code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
''' @FileName : data_parser.py @EditTime : 2021-11-29 13:59:47 @Author : <NAME> @Email : <EMAIL> @Description : ''' from __future__ import absolute_import from __future__ import print_function from __future__ import division import sys import os import os.path as osp import platform import json from collections import namedtuple import cv2 import numpy as np import torch from torch.utils.data import Dataset Keypoints = namedtuple('Keypoints', ['keypoints', 'gender_gt', 'gender_pd']) Keypoints.__new__.__defaults__ = (None,) * len(Keypoints._fields) def read_keypoints(keypoint_fn, num_people, num_joint): if not os.path.exists(keypoint_fn): keypoints = [np.zeros((num_joint, 3))] * num_people # keypoints may not exist flags = np.zeros((num_people,)) valid = 0 return keypoints, flags, valid with open(keypoint_fn) as keypoint_file: data = json.load(keypoint_file) valid = 1 keypoints = [] flags = np.zeros((len(data['people']))) for idx, person_data in enumerate(data['people']): if person_data is None: body_keypoints = np.zeros((num_joint, 3), dtype=np.float32) else: flags[idx] = 1 body_keypoints = np.array(person_data['pose_keypoints_2d'], dtype=np.float32) body_keypoints = body_keypoints.reshape([-1, 3]) keypoints.append(body_keypoints) return keypoints[:num_people], flags[:num_people], valid def read_joints(keypoint_fn, use_hands=True, use_face=True, use_face_contour=False): """ load 3D annotation """ with open(keypoint_fn) as keypoint_file: data = json.load(keypoint_file) keypoints = [] gender_pd = [] gender_gt = [] for idx, person_data in enumerate(data['people']): try: body_keypoints = np.array(person_data['pose_keypoints_3d'], dtype=np.float32) body_keypoints = body_keypoints.reshape([-1, 4]) if use_hands: left_hand_keyp = np.array( person_data['hand_left_keypoints_3d'], dtype=np.float32).reshape([-1, 4]) right_hand_keyp = np.array( person_data['hand_right_keypoints_3d'], dtype=np.float32).reshape([-1, 4]) body_keypoints = np.concatenate( [body_keypoints, left_hand_keyp, right_hand_keyp], axis=0) if use_face: # TODO: Make parameters, 17 is the offset for the eye brows, # etc. 51 is the total number of FLAME compatible landmarks face_keypoints = np.array( person_data['face_keypoints_3d'], dtype=np.float32).reshape([-1, 4])[17: 17 + 51, :] contour_keyps = np.array( [], dtype=body_keypoints.dtype).reshape(0, 4) if use_face_contour: contour_keyps = np.array( person_data['face_keypoints_3d'], dtype=np.float32).reshape([-1, 4])[:17, :] body_keypoints = np.concatenate( [body_keypoints, face_keypoints, contour_keyps], axis=0) keypoints.append(body_keypoints) except: keypoints = None if 'gender_pd' in person_data: gender_pd.append(person_data['gender_pd']) if 'gender_gt' in person_data: gender_gt.append(person_data['gender_gt']) return Keypoints(keypoints=keypoints, gender_pd=gender_pd, gender_gt=gender_gt) def smpl_to_annotation(model_type='smpl', use_hands=False, use_face=False, use_face_contour=False, pose_format='coco17'): if pose_format == 'halpe': if model_type == 'smplhalpe': # Halpe to SMPL return np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25], dtype=np.int32) else: raise ValueError('Unknown model type: {}'.format(model_type)) class FittingData(Dataset): NUM_BODY_JOINTS = 17 NUM_HAND_JOINTS = 20 def __init__(self, data_folder, img_folder='images', keyp_folder='keypoints', use_hands=False, use_face=False, dtype=torch.float32, model_type='smplx', joints_to_ign=None, use_face_contour=False, pose_format='coco17', use_3d=False, use_hip=True, frames=1, num_people=1, **kwargs): super(FittingData, self).__init__() self.use_hands = use_hands self.use_face = use_face self.model_type = model_type self.dtype = dtype self.use_3d = use_3d self.use_hip = use_hip self.joints_to_ign = joints_to_ign self.use_face_contour = use_face_contour self.pose_format = pose_format if self.pose_format == 'halpe': self.NUM_BODY_JOINTS = 26 self.num_joints = (self.NUM_BODY_JOINTS + 2 * self.NUM_HAND_JOINTS * use_hands) self.data_folder = data_folder self.img_folder = osp.join(data_folder, img_folder) self.keyp_folder = osp.join(data_folder, keyp_folder) img_serials = sorted(os.listdir(self.img_folder)) self.img_paths = [] for i_s in img_serials: i_s_dir = osp.join(self.img_folder, i_s) img_cameras = sorted(os.listdir(i_s_dir)) this_serials = [] for i_cam in img_cameras: i_c_dir = osp.join(i_s_dir, i_cam) cam_imgs = [osp.join(i_s, i_cam, img_fn) for img_fn in os.listdir(i_c_dir) if img_fn.endswith('.png') or img_fn.endswith('.jpg') and not img_fn.startswith('.')] cam_imgs = sorted(cam_imgs) this_serials.append(cam_imgs) self.img_paths.append(this_serials) self.cnt = 0 self.serial_cnt = 0 self.max_frames = frames self.min_frames = 13 self.num_people = num_people # if len(cam_imgs) < frames: # self.frames = len(cam_imgs) # else: self.frames = frames def get_model2data(self): # Map SMPL to Halpe return np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25], dtype=np.int32) def get_left_shoulder(self): return 2 def get_right_shoulder(self): return 5 def get_joint_weights(self): # The weights for the joint terms in the optimization optim_weights = np.ones(self.num_joints + 2 * self.use_hands + self.use_face * 51 + 17 * self.use_face_contour, dtype=np.float32) # Neck, Left and right hip # These joints are ignored because SMPL has no neck joint and the # annotation of the hips is ambiguous. # if self.joints_to_ign is not None and -1 not in self.joints_to_ign: # optim_weights[self.joints_to_ign] = 0. # return torch.tensor(optim_weights, dtype=self.dtype) if (self.pose_format != 'lsp14' and self.pose_format != 'halpe') or not self.use_hip: optim_weights[11] = 0. optim_weights[12] = 0. return torch.tensor(optim_weights, dtype=self.dtype) def __len__(self): return len(self.img_paths) def __getitem__(self, idx): img_path = self.img_paths[idx] return self.read_item(img_path) def read_item(self, img_paths): """Load keypoints according to img name""" keypoints = [] total_flags = [] count = 0 for imgs in img_paths: cam_keps = [] cam_flag = [] for img in imgs: if platform.system() == 'Windows': seq_name, cam_name, f_name = img.split('\\') else: seq_name, cam_name, f_name = img.split('/') index = f_name.split('.')[0] keypoint_fn = osp.join(self.keyp_folder, seq_name, cam_name, '%s_keypoints.json' %index) keypoints_, flags, valid = read_keypoints(keypoint_fn, self.num_people, self.NUM_BODY_JOINTS) count += valid cam_flag.append(flags) cam_keps.append(keypoints_) keypoints.append(cam_keps) total_flags.append(cam_flag) total_flags = np.array(total_flags, dtype=np.int) total_flags = np.max(total_flags, axis=0) camparam = os.path.join(self.data_folder, 'camparams', seq_name, 'camparams.txt') output_dict = { 'camparam': camparam, 'img_path': img_paths, 'keypoints': keypoints, 'flags':total_flags, 'count':count} return output_dict def __iter__(self): return self def __next__(self): return self.next() def next(self): if self.serial_cnt >= len(self.img_paths): raise StopIteration img_path = self.img_paths[self.serial_cnt] img_paths = [] for cam in img_path: if self.cnt+self.max_frames > len(cam): if len(cam) - self.cnt < self.min_frames: img_paths.append(cam[-self.min_frames:]) else: img_paths.append(cam[self.cnt:]) else: img_paths.append(cam[self.cnt:self.cnt+self.max_frames]) # self.frames = len(img_paths[0]) if self.cnt + self.max_frames >= len(cam): self.cnt = 0 self.serial_cnt += 1 else: self.cnt += self.frames return self.read_item(img_paths)
[ "os.path.exists", "collections.namedtuple", "os.listdir", "numpy.ones", "os.path.join", "numpy.max", "numpy.array", "numpy.zeros", "torch.tensor", "platform.system", "numpy.concatenate", "json.load" ]
[((452, 516), 'collections.namedtuple', 'namedtuple', (['"""Keypoints"""', "['keypoints', 'gender_gt', 'gender_pd']"], {}), "('Keypoints', ['keypoints', 'gender_gt', 'gender_pd'])\n", (462, 516), False, 'from collections import namedtuple\n'), ((676, 703), 'os.path.exists', 'os.path.exists', (['keypoint_fn'], {}), '(keypoint_fn)\n', (690, 703), False, 'import os\n'), ((807, 830), 'numpy.zeros', 'np.zeros', (['(num_people,)'], {}), '((num_people,))\n', (815, 830), True, 'import numpy as np\n'), ((949, 973), 'json.load', 'json.load', (['keypoint_file'], {}), '(keypoint_file)\n', (958, 973), False, 'import json\n'), ((1782, 1806), 'json.load', 'json.load', (['keypoint_file'], {}), '(keypoint_file)\n', (1791, 1806), False, 'import json\n'), ((5495, 5528), 'os.path.join', 'osp.join', (['data_folder', 'img_folder'], {}), '(data_folder, img_folder)\n', (5503, 5528), True, 'import os.path as osp\n'), ((5556, 5590), 'os.path.join', 'osp.join', (['data_folder', 'keyp_folder'], {}), '(data_folder, keyp_folder)\n', (5564, 5590), True, 'import os.path as osp\n'), ((6710, 6834), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, \n 21, 22, 23, 24, 25]'], {'dtype': 'np.int32'}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,\n 19, 20, 21, 22, 23, 24, 25], dtype=np.int32)\n', (6718, 6834), True, 'import numpy as np\n'), ((7057, 7174), 'numpy.ones', 'np.ones', (['(self.num_joints + 2 * self.use_hands + self.use_face * 51 + 17 * self.\n use_face_contour)'], {'dtype': 'np.float32'}), '(self.num_joints + 2 * self.use_hands + self.use_face * 51 + 17 *\n self.use_face_contour, dtype=np.float32)\n', (7064, 7174), True, 'import numpy as np\n'), ((7806, 7851), 'torch.tensor', 'torch.tensor', (['optim_weights'], {'dtype': 'self.dtype'}), '(optim_weights, dtype=self.dtype)\n', (7818, 7851), False, 'import torch\n'), ((8976, 9011), 'numpy.array', 'np.array', (['total_flags'], {'dtype': 'np.int'}), '(total_flags, dtype=np.int)\n', (8984, 9011), True, 'import numpy as np\n'), ((9034, 9061), 'numpy.max', 'np.max', (['total_flags'], {'axis': '(0)'}), '(total_flags, axis=0)\n', (9040, 9061), True, 'import numpy as np\n'), ((9082, 9152), 'os.path.join', 'os.path.join', (['self.data_folder', '"""camparams"""', 'seq_name', '"""camparams.txt"""'], {}), "(self.data_folder, 'camparams', seq_name, 'camparams.txt')\n", (9094, 9152), False, 'import os\n'), ((1167, 1209), 'numpy.zeros', 'np.zeros', (['(num_joint, 3)'], {'dtype': 'np.float32'}), '((num_joint, 3), dtype=np.float32)\n', (1175, 1209), True, 'import numpy as np\n'), ((1316, 1376), 'numpy.array', 'np.array', (["person_data['pose_keypoints_2d']"], {'dtype': 'np.float32'}), "(person_data['pose_keypoints_2d'], dtype=np.float32)\n", (1324, 1376), True, 'import numpy as np\n'), ((1963, 2023), 'numpy.array', 'np.array', (["person_data['pose_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['pose_keypoints_3d'], dtype=np.float32)\n", (1971, 2023), True, 'import numpy as np\n'), ((4028, 4152), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, \n 21, 22, 23, 24, 25]'], {'dtype': 'np.int32'}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,\n 19, 20, 21, 22, 23, 24, 25], dtype=np.int32)\n', (4036, 4152), True, 'import numpy as np\n'), ((5621, 5648), 'os.listdir', 'os.listdir', (['self.img_folder'], {}), '(self.img_folder)\n', (5631, 5648), False, 'import os\n'), ((5732, 5762), 'os.path.join', 'osp.join', (['self.img_folder', 'i_s'], {}), '(self.img_folder, i_s)\n', (5740, 5762), True, 'import os.path as osp\n'), ((726, 750), 'numpy.zeros', 'np.zeros', (['(num_joint, 3)'], {}), '((num_joint, 3))\n', (734, 750), True, 'import numpy as np\n'), ((2497, 2570), 'numpy.concatenate', 'np.concatenate', (['[body_keypoints, left_hand_keyp, right_hand_keyp]'], {'axis': '(0)'}), '([body_keypoints, left_hand_keyp, right_hand_keyp], axis=0)\n', (2511, 2570), True, 'import numpy as np\n'), ((3289, 3360), 'numpy.concatenate', 'np.concatenate', (['[body_keypoints, face_keypoints, contour_keyps]'], {'axis': '(0)'}), '([body_keypoints, face_keypoints, contour_keyps], axis=0)\n', (3303, 3360), True, 'import numpy as np\n'), ((5796, 5815), 'os.listdir', 'os.listdir', (['i_s_dir'], {}), '(i_s_dir)\n', (5806, 5815), False, 'import os\n'), ((5911, 5935), 'os.path.join', 'osp.join', (['i_s_dir', 'i_cam'], {}), '(i_s_dir, i_cam)\n', (5919, 5935), True, 'import os.path as osp\n'), ((8572, 8647), 'os.path.join', 'osp.join', (['self.keyp_folder', 'seq_name', 'cam_name', "('%s_keypoints.json' % index)"], {}), "(self.keyp_folder, seq_name, cam_name, '%s_keypoints.json' % index)\n", (8580, 8647), True, 'import os.path as osp\n'), ((5964, 5992), 'os.path.join', 'osp.join', (['i_s', 'i_cam', 'img_fn'], {}), '(i_s, i_cam, img_fn)\n', (5972, 5992), True, 'import os.path as osp\n'), ((8314, 8331), 'platform.system', 'platform.system', ([], {}), '()\n', (8329, 8331), False, 'import platform\n'), ((2180, 2245), 'numpy.array', 'np.array', (["person_data['hand_left_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['hand_left_keypoints_3d'], dtype=np.float32)\n", (2188, 2245), True, 'import numpy as np\n'), ((2338, 2404), 'numpy.array', 'np.array', (["person_data['hand_right_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['hand_right_keypoints_3d'], dtype=np.float32)\n", (2346, 2404), True, 'import numpy as np\n'), ((2971, 3011), 'numpy.array', 'np.array', (['[]'], {'dtype': 'body_keypoints.dtype'}), '([], dtype=body_keypoints.dtype)\n', (2979, 3011), True, 'import numpy as np\n'), ((6035, 6054), 'os.listdir', 'os.listdir', (['i_c_dir'], {}), '(i_c_dir)\n', (6045, 6054), False, 'import os\n'), ((2803, 2863), 'numpy.array', 'np.array', (["person_data['face_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['face_keypoints_3d'], dtype=np.float32)\n", (2811, 2863), True, 'import numpy as np\n'), ((3120, 3180), 'numpy.array', 'np.array', (["person_data['face_keypoints_3d']"], {'dtype': 'np.float32'}), "(person_data['face_keypoints_3d'], dtype=np.float32)\n", (3128, 3180), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt import math def log(list_name): for i in range(len(list_name)): list_name[i] = math.log10(list_name[i]) print(list_name[i]) return list_name size = 4 x = np.arange(size) video_file = [11132, 21164, 34452, 45208] # 每帧视频文件大小(byte) video_file = log(video_file) data_to_cloud = [127, 248, 365, 488] # 每帧所有edge上传的文件大小(byte)(2,2,3,4个摄像头) data_to_cloud = log(data_to_cloud) total_width, n = 0.8, 3 width = total_width / n x = x - (total_width - width) / 2 plt.xlabel('Total Camera Numbers', fontsize=20) plt.ylabel('Communication Cost (lg(Byte))', fontsize=20) plt.bar(x-0.45*width, video_file, fc='#036564', width=0.75*width, label='Input Data to Cloud (Cloud)') # plt.bar(x-0.45*width, data_to_cam, fc='#033649', width=0.75*width, bottom=video_file, label='Feedback (Cloud)') plt.bar(x+0.45*width, data_to_cloud, fc='#764D39', width=0.75*width, label='Input Data to Cloud (EATP)') # plt.bar(x+0.45*width, data_to_cam, fc='#250807', width=0.75*width, bottom=data_to_cloud, label='Feedback (EaOT)') plt.xticks(x, (2, 4, 6, 8), fontsize=18) plt.yticks(fontsize=18) plt.legend(loc='center', bbox_to_anchor=(0.62, 0.11), fontsize=17) plt.show()
[ "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.legend", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.bar", "matplotlib.pyplot.yticks", "math.log10", "numpy.arange", "matplotlib.pyplot.show" ]
[((232, 247), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (241, 247), True, 'import numpy as np\n'), ((533, 580), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Total Camera Numbers"""'], {'fontsize': '(20)'}), "('Total Camera Numbers', fontsize=20)\n", (543, 580), True, 'import matplotlib.pyplot as plt\n'), ((581, 637), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Communication Cost (lg(Byte))"""'], {'fontsize': '(20)'}), "('Communication Cost (lg(Byte))', fontsize=20)\n", (591, 637), True, 'import matplotlib.pyplot as plt\n'), ((638, 750), 'matplotlib.pyplot.bar', 'plt.bar', (['(x - 0.45 * width)', 'video_file'], {'fc': '"""#036564"""', 'width': '(0.75 * width)', 'label': '"""Input Data to Cloud (Cloud)"""'}), "(x - 0.45 * width, video_file, fc='#036564', width=0.75 * width,\n label='Input Data to Cloud (Cloud)')\n", (645, 750), True, 'import matplotlib.pyplot as plt\n'), ((855, 969), 'matplotlib.pyplot.bar', 'plt.bar', (['(x + 0.45 * width)', 'data_to_cloud'], {'fc': '"""#764D39"""', 'width': '(0.75 * width)', 'label': '"""Input Data to Cloud (EATP)"""'}), "(x + 0.45 * width, data_to_cloud, fc='#764D39', width=0.75 * width,\n label='Input Data to Cloud (EATP)')\n", (862, 969), True, 'import matplotlib.pyplot as plt\n'), ((1076, 1116), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x', '(2, 4, 6, 8)'], {'fontsize': '(18)'}), '(x, (2, 4, 6, 8), fontsize=18)\n', (1086, 1116), True, 'import matplotlib.pyplot as plt\n'), ((1117, 1140), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(18)'}), '(fontsize=18)\n', (1127, 1140), True, 'import matplotlib.pyplot as plt\n'), ((1141, 1207), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""center"""', 'bbox_to_anchor': '(0.62, 0.11)', 'fontsize': '(17)'}), "(loc='center', bbox_to_anchor=(0.62, 0.11), fontsize=17)\n", (1151, 1207), True, 'import matplotlib.pyplot as plt\n'), ((1208, 1218), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1216, 1218), True, 'import matplotlib.pyplot as plt\n'), ((144, 168), 'math.log10', 'math.log10', (['list_name[i]'], {}), '(list_name[i])\n', (154, 168), False, 'import math\n')]
import numpy from chainer import cuda import chainer.serializers as S import chainer.links as L from nltk.corpus import stopwords from context_models import CbowContext, BiLstmContext from defs import IN_TO_OUT_UNITS_RATIO, NEGATIVE_SAMPLING_NUM class ModelReader(object): ''' Reads a pre-trained model using a config file ''' def __init__(self, config_file): self.gpu = -1 # todo support gpu print('Reading config file: ' + config_file) params = self.read_config_file(config_file) print('Config: ', params) self.w, self.word2index, self.index2word, self.model = self.read_model(params) def read_config_file(self, filename): params = {} config_path = filename[:filename.rfind('/')+1] params['config_path'] = config_path with open(filename, 'r') as f: for line in f: if not line.startswith('#'): [param, val] = line.strip().split() params[param] = val return params def read_model(self, params, train=False): if 'model_type' in params: model_type = params['model_type'] else: model_type = 'lstm_context' if model_type == 'lstm_context': return self.read_lstm_model(params, train) elif model_type == 'bow_context': return self.read_bow_model(params) else: raise Exception("Unknown model type: " + model_type) def read_lstm_model(self, params, train): assert train == False # reading a model to continue training is currently not supported words_file = params['config_path'] + params['words_file'] model_file = params['config_path'] + params['model_file'] unit = int(params['unit']) deep = (params['deep'] == 'yes') drop_ratio = float(params['drop_ratio']) #read and normalize target word embeddings w, word2index, index2word = self.read_words(words_file) s = numpy.sqrt((w * w).sum(1)) s[s==0.] = 1. w /= s.reshape((s.shape[0], 1)) # normalize context_word_units = unit lstm_hidden_units = IN_TO_OUT_UNITS_RATIO*unit target_word_units = IN_TO_OUT_UNITS_RATIO*unit cs = [1 for _ in range(len(word2index))] # dummy word counts - not used for eval loss_func = L.NegativeSampling(target_word_units, cs, NEGATIVE_SAMPLING_NUM) # dummy loss func - not used for eval model = BiLstmContext(deep, self.gpu, word2index, context_word_units, lstm_hidden_units, target_word_units, loss_func, train, drop_ratio) S.load_npz(model_file, model,strict=False) return w, word2index, index2word, model def read_bow_model(self, params): words_file = params['config_path'] + params['words_file'] contexts_file = params['config_path'] + params['contexts_file'] if 'contexts_file' in params else None window_size = int(params['window_size']) use_stopwords = params['stopwords'] if 'word_counts_file' in params: word_counts_file = params['config_path'] + params['word_counts_file'] else: word_counts_file = None if use_stopwords == 'yes': stop = set(stopwords.words('english') + ['.',',','(',')','[',']',':','"',"'","'s","-",';','?','!','|','%','/','\\']) else: stop = set() word_counts = self.read_word_counts(word_counts_file) if word_counts_file is not None else None # read and normalize target words embeddings w, word2index, index2word = self.read_words(words_file) s = numpy.sqrt((w * w).sum(1)) s[s==0.] = 1. w /= s.reshape((s.shape[0], 1)) # normalize # read and normalize context words embeddings (if using different embeddings for context words) if contexts_file is not None: c, _, _ = self.read_words(words_file) # assuming words and contexts vocabs are identical s = numpy.sqrt((c * c).sum(1)) s[s==0.] = 1. c /= s.reshape((s.shape[0], 1)) # normalize else: c = None model = CbowContext(w, c, word2index, stop, window_size, word_counts) return w, word2index, index2word, model def read_words(self, filename): with open(filename, 'r') as f: ss = f.readline().split() n_vocab, n_units = int(ss[0]), int(ss[1]) word2index = {} index2word = [] w = numpy.empty((n_vocab, n_units), dtype=numpy.float32) for i, line in enumerate(f): ss = line.split() assert len(ss) == n_units + 1 word = ss[0] word2index[word] = i index2word.append(word) w[i] = numpy.array([float(s) for s in ss[1:]], dtype=numpy.float32) return w, word2index, index2word def read_word_counts(self, filename): counts = {} with open(filename) as f: for line in f: if len(line) > 0: tokens = line.split('\t') word = tokens[0].strip() count = int(tokens[1].strip()) counts[word] = count return counts
[ "nltk.corpus.stopwords.words", "context_models.CbowContext", "numpy.empty", "context_models.BiLstmContext", "chainer.links.NegativeSampling", "chainer.serializers.load_npz" ]
[((2480, 2544), 'chainer.links.NegativeSampling', 'L.NegativeSampling', (['target_word_units', 'cs', 'NEGATIVE_SAMPLING_NUM'], {}), '(target_word_units, cs, NEGATIVE_SAMPLING_NUM)\n', (2498, 2544), True, 'import chainer.links as L\n'), ((2608, 2741), 'context_models.BiLstmContext', 'BiLstmContext', (['deep', 'self.gpu', 'word2index', 'context_word_units', 'lstm_hidden_units', 'target_word_units', 'loss_func', 'train', 'drop_ratio'], {}), '(deep, self.gpu, word2index, context_word_units,\n lstm_hidden_units, target_word_units, loss_func, train, drop_ratio)\n', (2621, 2741), False, 'from context_models import CbowContext, BiLstmContext\n'), ((2746, 2789), 'chainer.serializers.load_npz', 'S.load_npz', (['model_file', 'model'], {'strict': '(False)'}), '(model_file, model, strict=False)\n', (2756, 2789), True, 'import chainer.serializers as S\n'), ((4353, 4414), 'context_models.CbowContext', 'CbowContext', (['w', 'c', 'word2index', 'stop', 'window_size', 'word_counts'], {}), '(w, c, word2index, stop, window_size, word_counts)\n', (4364, 4414), False, 'from context_models import CbowContext, BiLstmContext\n'), ((4713, 4765), 'numpy.empty', 'numpy.empty', (['(n_vocab, n_units)'], {'dtype': 'numpy.float32'}), '((n_vocab, n_units), dtype=numpy.float32)\n', (4724, 4765), False, 'import numpy\n'), ((3413, 3439), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (3428, 3439), False, 'from nltk.corpus import stopwords\n')]
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2012-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. """ Module exports :class:`ZhaoEtAl2006Asc`, :class:`ZhaoEtAl2006SInter`, :class:`ZhaoEtAl2006SSlab`, :class:`ZhaoEtAl2006SInterNSHMP2008` and :class:`ZhaoEtAl2006SSlabNSHMP2014` """ from __future__ import division import numpy as np # standard acceleration of gravity in m/s**2 from scipy.constants import g import copy from openquake.hazardlib.gsim.base import GMPE, CoeffsTable from openquake.hazardlib import const from openquake.hazardlib.imt import PGA, PGV, SA class ZhaoEtAl2006Asc(GMPE): """ Implements GMPE developed by <NAME> et al. and published as "Attenuation Relations of Strong Ground Motion in Japan Using Site Classification Based on Predominant Period" (2006, Bulletin of the Seismological Society of America, Volume 96, No. 3, pages 898-913). This class implements the equations for 'Active Shallow Crust' (that's why the class name ends with 'Asc'). """ #: Supported tectonic region type is active shallow crust, this means #: that factors SI, SS and SSL are assumed 0 in equation 1, p. 901. DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST #: Supported intensity measure types are spectral acceleration, #: and peak ground acceleration, see paragraph 'Development of Base Model' #: p. 901. DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([ PGA, SA ]) #: Supported intensity measure component is geometric mean #: of two horizontal components : #: attr:`~openquake.hazardlib.const.IMC.AVERAGE_HORIZONTAL`, see paragraph #: 'Development of Base Model', p. 901. DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.AVERAGE_HORIZONTAL #: Supported standard deviation types are inter-event, intra-event #: and total, see equation 3, p. 902. DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([ const.StdDev.TOTAL, const.StdDev.INTER_EVENT, const.StdDev.INTRA_EVENT ]) #: Required site parameters is Vs30. #: See table 2, p. 901. REQUIRES_SITES_PARAMETERS = set(('vs30', )) #: Required rupture parameters are magnitude, rake, and focal depth. #: See paragraph 'Development of Base Model', p. 901. REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'rake', 'hypo_depth')) #: Required distance measure is Rrup. #: See paragraph 'Development of Base Model', p. 902. REQUIRES_DISTANCES = set(('rrup', )) def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required # intensity measure type. C = self.COEFFS_ASC[imt] # mean value as given by equation 1, p. 901, without considering the # interface and intraslab terms (that is SI, SS, SSL = 0) and the # inter and intra event terms, plus the magnitude-squared term # correction factor (equation 5 p. 909). mean = self._compute_magnitude_term(C, rup.mag) +\ self._compute_distance_term(C, rup.mag, dists.rrup) +\ self._compute_focal_depth_term(C, rup.hypo_depth) +\ self._compute_faulting_style_term(C, rup.rake) +\ self._compute_site_class_term(C, sites.vs30) +\ self._compute_magnitude_squared_term(P=0.0, M=6.3, Q=C['QC'], W=C['WC'], mag=rup.mag) # convert from cm/s**2 to g mean = np.log(np.exp(mean) * 1e-2 / g) stddevs = self._get_stddevs(C['sigma'], C['tauC'], stddev_types, num_sites=len(sites.vs30)) return mean, stddevs def _get_stddevs(self, sigma, tau, stddev_types, num_sites): """ Return standard deviations as defined in equation 3 p. 902. """ stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: sigma_t = np.sqrt(sigma ** 2 + tau ** 2) stddevs.append(sigma_t + np.zeros(num_sites)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(sigma + np.zeros(num_sites)) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(tau + np.zeros(num_sites)) return stddevs def _compute_magnitude_term(self, C, mag): """ Compute first term in equation 1, p. 901. """ return C['a'] * mag def _compute_distance_term(self, C, mag, rrup): """ Compute second and third terms in equation 1, p. 901. """ term1 = C['b'] * rrup term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag)) return term1 + term2 def _compute_focal_depth_term(self, C, hypo_depth): """ Compute fourth term in equation 1, p. 901. """ # p. 901. "(i.e, depth is capped at 125 km)". focal_depth = hypo_depth if focal_depth > 125.0: focal_depth = 125.0 # p. 902. "We used the value of 15 km for the # depth coefficient hc ...". hc = 15.0 # p. 901. "When h is larger than hc, the depth terms takes # effect ...". The next sentence specifies h>=hc. return float(focal_depth >= hc) * C['e'] * (focal_depth - hc) def _compute_faulting_style_term(self, C, rake): """ Compute fifth term in equation 1, p. 901. """ # p. 900. "The differentiation in focal mechanism was # based on a rake angle criterion, with a rake of +/- 45 # as demarcation between dip-slip and strike-slip." return float(rake > 45.0 and rake < 135.0) * C['FR'] def _compute_site_class_term(self, C, vs30): """ Compute nine-th term in equation 1, p. 901. """ # map vs30 value to site class, see table 2, p. 901. site_term = np.zeros(len(vs30)) # hard rock site_term[vs30 > 1100.0] = C['CH'] # rock site_term[(vs30 > 600) & (vs30 <= 1100)] = C['C1'] # hard soil site_term[(vs30 > 300) & (vs30 <= 600)] = C['C2'] # medium soil site_term[(vs30 > 200) & (vs30 <= 300)] = C['C3'] # soft soil site_term[vs30 <= 200] = C['C4'] return site_term def _compute_magnitude_squared_term(self, P, M, Q, W, mag): """ Compute magnitude squared term, equation 5, p. 909. """ return P * (mag - M) + Q * (mag - M) ** 2 + W #: Coefficient table obtained by joining table 4 (except columns for #: SI, SS, SSL), table 5 (both at p. 903) and table 6 (only columns for #: QC WC TauC), p. 907. COEFFS_ASC = CoeffsTable(sa_damping=5, table="""\ IMT a b c d e FR CH C1 C2 C3 C4 sigma QC WC tauC pga 1.101 -0.00564 0.0055 1.080 0.01412 0.251 0.293 1.111 1.344 1.355 1.420 0.604 0.0 0.0 0.303 0.05 1.076 -0.00671 0.0075 1.060 0.01463 0.251 0.939 1.684 1.793 1.747 1.814 0.640 0.0 0.0 0.326 0.10 1.118 -0.00787 0.0090 1.083 0.01423 0.240 1.499 2.061 2.135 2.031 2.082 0.694 0.0 0.0 0.342 0.15 1.134 -0.00722 0.0100 1.053 0.01509 0.251 1.462 1.916 2.168 2.052 2.113 0.702 0.0 0.0 0.331 0.20 1.147 -0.00659 0.0120 1.014 0.01462 0.260 1.280 1.669 2.085 2.001 2.030 0.692 0.0 0.0 0.312 0.25 1.149 -0.00590 0.0140 0.966 0.01459 0.269 1.121 1.468 1.942 1.941 1.937 0.682 0.0 0.0 0.298 0.30 1.163 -0.00520 0.0150 0.934 0.01458 0.259 0.852 1.172 1.683 1.808 1.770 0.670 0.0 0.0 0.300 0.40 1.200 -0.00422 0.0100 0.959 0.01257 0.248 0.365 0.655 1.127 1.482 1.397 0.659 0.0 0.0 0.346 0.50 1.250 -0.00338 0.0060 1.008 0.01114 0.247 -0.207 0.071 0.515 0.934 0.955 0.653 -0.0126 0.0116 0.338 0.60 1.293 -0.00282 0.0030 1.088 0.01019 0.233 -0.705 -0.429 -0.003 0.394 0.559 0.653 -0.0329 0.0202 0.349 0.70 1.336 -0.00258 0.0025 1.084 0.00979 0.220 -1.144 -0.866 -0.449 -0.111 0.188 0.652 -0.0501 0.0274 0.351 0.80 1.386 -0.00242 0.0022 1.088 0.00944 0.232 -1.609 -1.325 -0.928 -0.620 -0.246 0.647 -0.0650 0.0336 0.356 0.90 1.433 -0.00232 0.0020 1.109 0.00972 0.220 -2.023 -1.732 -1.349 -1.066 -0.643 0.653 -0.0781 0.0391 0.348 1.00 1.479 -0.00220 0.0020 1.115 0.01005 0.211 -2.451 -2.152 -1.776 -1.523 -1.084 0.657 -0.0899 0.0440 0.338 1.25 1.551 -0.00207 0.0020 1.083 0.01003 0.251 -3.243 -2.923 -2.542 -2.327 -1.936 0.660 -0.1148 0.0545 0.313 1.50 1.621 -0.00224 0.0020 1.091 0.00928 0.248 -3.888 -3.548 -3.169 -2.979 -2.661 0.664 -0.1351 0.0630 0.306 2.00 1.694 -0.00201 0.0025 1.055 0.00833 0.263 -4.783 -4.410 -4.039 -3.871 -3.640 0.669 -0.1672 0.0764 0.283 2.50 1.748 -0.00187 0.0028 1.052 0.00776 0.262 -5.444 -5.049 -4.698 -4.496 -4.341 0.671 -0.1921 0.0869 0.287 3.00 1.759 -0.00147 0.0032 1.025 0.00644 0.307 -5.839 -5.431 -5.089 -4.893 -4.758 0.667 -0.2124 0.0954 0.278 4.00 1.826 -0.00195 0.0040 1.044 0.00590 0.353 -6.598 -6.181 -5.882 -5.698 -5.588 0.647 -0.2445 0.1088 0.273 5.00 1.825 -0.00237 0.0050 1.065 0.00510 0.248 -6.752 -6.347 -6.051 -5.873 -5.798 0.643 -0.2694 0.1193 0.275 """) class ZhaoEtAl2006SInter(ZhaoEtAl2006Asc): """ Implements GMPE developed by <NAME> et al and published as "Attenuation Relations of Strong Ground Motion in Japan Using Site Classification Based on Predominant Period" (2006, Bulletin of the Seismological Society of America, Volume 96, No. 3, pages 898-913). This class implements the equations for 'Subduction Interface' (that's why the class name ends with 'SInter'). This class extends the :class:`openquake.hazardlib.gsim.zhao_2006.ZhaoEtAl2006Asc` because the equation for subduction interface is obtained from the equation for active shallow crust, by removing the faulting style term and adding a subduction interface term. """ #: Supported tectonic region type is subduction interface, this means #: that factors FR, SS and SSL are assumed 0 in equation 1, p. 901. DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.SUBDUCTION_INTERFACE #: Required rupture parameters are magnitude and focal depth. REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'hypo_depth')) def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required # intensity measure type. C = self.COEFFS_ASC[imt] C_SINTER = self.COEFFS_SINTER[imt] # mean value as given by equation 1, p. 901, without considering the # faulting style and intraslab terms (that is FR, SS, SSL = 0) and the # inter and intra event terms, plus the magnitude-squared term # correction factor (equation 5 p. 909) mean = self._compute_magnitude_term(C, rup.mag) +\ self._compute_distance_term(C, rup.mag, dists.rrup) +\ self._compute_focal_depth_term(C, rup.hypo_depth) +\ self._compute_site_class_term(C, sites.vs30) + \ self._compute_magnitude_squared_term(P=0.0, M=6.3, Q=C_SINTER['QI'], W=C_SINTER['WI'], mag=rup.mag) +\ C_SINTER['SI'] # convert from cm/s**2 to g mean = np.log(np.exp(mean) * 1e-2 / g) stddevs = self._get_stddevs(C['sigma'], C_SINTER['tauI'], stddev_types, num_sites=len(sites.vs30)) return mean, stddevs #: Coefficient table containing subduction interface coefficients, #: taken from table 4, p. 903 (only column SI), and table 6, p. 907 #: (only columns QI, WI, TauI) COEFFS_SINTER = CoeffsTable(sa_damping=5, table="""\ IMT SI QI WI tauI pga 0.000 0.0 0.0 0.308 0.05 0.000 0.0 0.0 0.343 0.10 0.000 0.0 0.0 0.403 0.15 0.000 -0.0138 0.0286 0.367 0.20 0.000 -0.0256 0.0352 0.328 0.25 0.000 -0.0348 0.0403 0.289 0.30 0.000 -0.0423 0.0445 0.280 0.40 -0.041 -0.0541 0.0511 0.271 0.50 -0.053 -0.0632 0.0562 0.277 0.60 -0.103 -0.0707 0.0604 0.296 0.70 -0.146 -0.0771 0.0639 0.313 0.80 -0.164 -0.0825 0.0670 0.329 0.90 -0.206 -0.0874 0.0697 0.324 1.00 -0.239 -0.0917 0.0721 0.328 1.25 -0.256 -0.1009 0.0772 0.339 1.50 -0.306 -0.1083 0.0814 0.352 2.00 -0.321 -0.1202 0.0880 0.360 2.50 -0.337 -0.1293 0.0931 0.356 3.00 -0.331 -0.1368 0.0972 0.338 4.00 -0.390 -0.1486 0.1038 0.307 5.00 -0.498 -0.1578 0.1090 0.272 """) class ZhaoEtAl2006SSlab(ZhaoEtAl2006Asc): """ Implements GMPE developed by <NAME> et al and published as "Attenuation Relations of Strong Ground Motion in Japan Using Site Classification Based on Predominant Period" (2006, Bulletin of the Seismological Society of America, Volume 96, No. 3, pages 898-913). This class implements the equations for 'Subduction Slab'. (that's why the class name ends with 'SSlab'). This class extends the :class:`openquake.hazardlib.gsim.zhao_2006.ZhaoEtAl2006Asc` because the equation for subduction slab is obtained from the equation for active shallow crust, by removing the faulting style term and adding subduction slab terms. """ #: Supported tectonic region type is subduction interface, this means #: that factors FR, SS and SSL are assumed 0 in equation 1, p. 901. DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.SUBDUCTION_INTRASLAB #: Required rupture parameters are magnitude and focal depth. REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'hypo_depth')) def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required # intensity measure type. C = self.COEFFS_ASC[imt] C_SSLAB = self.COEFFS_SSLAB[imt] # to avoid singularity at 0.0 (in the calculation of the # slab correction term), replace 0 values with 0.1 d = dists.rrup d[d == 0.0] = 0.1 # mean value as given by equation 1, p. 901, without considering the # faulting style and intraslab terms (that is FR, SS, SSL = 0) and the # inter and intra event terms, plus the magnitude-squared term # correction factor (equation 5 p. 909) mean = self._compute_magnitude_term(C, rup.mag) +\ self._compute_distance_term(C, rup.mag, d) +\ self._compute_focal_depth_term(C, rup.hypo_depth) +\ self._compute_site_class_term(C, sites.vs30) +\ self._compute_magnitude_squared_term(P=C_SSLAB['PS'], M=6.5, Q=C_SSLAB['QS'], W=C_SSLAB['WS'], mag=rup.mag) +\ C_SSLAB['SS'] + self._compute_slab_correction_term(C_SSLAB, d) # convert from cm/s**2 to g mean = np.log(np.exp(mean) * 1e-2 / g) stddevs = self._get_stddevs(C['sigma'], C_SSLAB['tauS'], stddev_types, num_sites=len(sites.vs30)) return mean, stddevs def _compute_slab_correction_term(self, C, rrup): """ Compute path modification term for slab events, that is the 8-th term in equation 1, p. 901. """ slab_term = C['SSL'] * np.log(rrup) return slab_term #: Coefficient table containing subduction slab coefficients taken from #: table 4, p. 903 (only columns for SS and SSL), and table 6, p. 907 #: (only columns for PS, QS, WS, TauS) COEFFS_SSLAB = CoeffsTable(sa_damping=5, table="""\ IMT SS SSL PS QS WS tauS pga 2.607 -0.528 0.1392 0.1584 -0.0529 0.321 0.05 2.764 -0.551 0.1636 0.1932 -0.0841 0.378 0.10 2.156 -0.420 0.1690 0.2057 -0.0877 0.420 0.15 2.161 -0.431 0.1669 0.1984 -0.0773 0.372 0.20 1.901 -0.372 0.1631 0.1856 -0.0644 0.324 0.25 1.814 -0.360 0.1588 0.1714 -0.0515 0.294 0.30 2.181 -0.450 0.1544 0.1573 -0.0395 0.284 0.40 2.432 -0.506 0.1460 0.1309 -0.0183 0.278 0.50 2.629 -0.554 0.1381 0.1078 -0.0008 0.272 0.60 2.702 -0.575 0.1307 0.0878 0.0136 0.285 0.70 2.654 -0.572 0.1239 0.0705 0.0254 0.290 0.80 2.480 -0.540 0.1176 0.0556 0.0352 0.299 0.90 2.332 -0.522 0.1116 0.0426 0.0432 0.289 1.00 2.233 -0.509 0.1060 0.0314 0.0498 0.286 1.25 2.029 -0.469 0.0933 0.0093 0.0612 0.277 1.50 1.589 -0.379 0.0821 -0.0062 0.0674 0.282 2.00 0.966 -0.248 0.0628 -0.0235 0.0692 0.300 2.50 0.789 -0.221 0.0465 -0.0287 0.0622 0.292 3.00 1.037 -0.263 0.0322 -0.0261 0.0496 0.274 4.00 0.561 -0.169 0.0083 -0.0065 0.0150 0.281 5.00 0.225 -0.120 -0.0117 0.0246 -0.0268 0.296 """) class ZhaoEtAl2006SInterNSHMP2008(ZhaoEtAl2006SInter): """ Extend :class:`ZhaoEtAl2006SInter` and fix hypocentral depth at 20 km as defined the by National Seismic Hazard Mapping Project for the 2008 US hazard model. The calculation of the total standard deviation is done considering the inter-event standard deviation as defined in table 5, page 903 of Zhao's paper. The class implement the equation as coded in ``subroutine zhao`` in ``hazSUBXnga.f`` Fotran code available at: http://earthquake.usgs.gov/hazards/products/conterminous/2008/software/ """ def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. Call super class method with hypocentral depth fixed at 20 km """ # create new rupture context to avoid changing the original one new_rup = copy.deepcopy(rup) new_rup.hypo_depth = 20. mean, stddevs = super(ZhaoEtAl2006SInterNSHMP2008, self). \ get_mean_and_stddevs(sites, new_rup, dists, imt, stddev_types) return mean, stddevs COEFFS_SINTER = CoeffsTable(sa_damping=5, table="""\ IMT SI QI WI tauI pga 0.000 0.0 0.0 0.3976 0.05 0.000 0.0 0.0 0.4437 0.10 0.000 0.0 0.0 0.4903 0.15 0.000 -0.0138 0.0286 0.4603 0.20 0.000 -0.0256 0.0352 0.4233 0.25 0.000 -0.0348 0.0403 0.3908 0.30 0.000 -0.0423 0.0445 0.3790 0.40 -0.041 -0.0541 0.0511 0.3897 0.50 -0.053 -0.0632 0.0562 0.3890 0.60 -0.103 -0.0707 0.0604 0.4014 0.70 -0.146 -0.0771 0.0639 0.4079 0.80 -0.164 -0.0825 0.0670 0.4183 0.90 -0.206 -0.0874 0.0697 0.4106 1.00 -0.239 -0.0917 0.0721 0.4101 1.25 -0.256 -0.1009 0.0772 0.4021 1.50 -0.306 -0.1083 0.0814 0.4076 2.00 -0.321 -0.1202 0.0880 0.4138 2.50 -0.337 -0.1293 0.0931 0.4108 3.00 -0.331 -0.1368 0.0972 0.3961 4.00 -0.390 -0.1486 0.1038 0.3821 5.00 -0.498 -0.1578 0.1090 0.3766 """) class ZhaoEtAl2006SSlabNSHMP2014(ZhaoEtAl2006SSlab): """ For the 2014 US National Seismic Hazard Maps the magnitude of Zhao et al. (2006) for the subduction inslab events is capped at magnitude Mw 7.8 """ def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required # intensity measure type. C = self.COEFFS_ASC[imt] C_SSLAB = self.COEFFS_SSLAB[imt] # to avoid singularity at 0.0 (in the calculation of the # slab correction term), replace 0 values with 0.1 d = dists.rrup d[d == 0.0] = 0.1 if rup.mag > 7.8: rup_mag = 7.8 else: rup_mag = rup.mag # mean value as given by equation 1, p. 901, without considering the # faulting style and intraslab terms (that is FR, SS, SSL = 0) and the # inter and intra event terms, plus the magnitude-squared term # correction factor (equation 5 p. 909) mean = self._compute_magnitude_term(C, rup_mag) +\ self._compute_distance_term(C, rup_mag, d) +\ self._compute_focal_depth_term(C, rup.hypo_depth) +\ self._compute_site_class_term(C, sites.vs30) +\ self._compute_magnitude_squared_term(P=C_SSLAB['PS'], M=6.5, Q=C_SSLAB['QS'], W=C_SSLAB['WS'], mag=rup_mag) +\ C_SSLAB['SS'] + self._compute_slab_correction_term(C_SSLAB, d) # convert from cm/s**2 to g mean = np.log(np.exp(mean) * 1e-2 / g) stddevs = self._get_stddevs(C['sigma'], C_SSLAB['tauS'], stddev_types, num_sites=len(sites.vs30)) return mean, stddevs # Coefficient table taken from <NAME>'s "White paper on # Proposed Ground-motion Prediction Equations (GMPEs) for 2015 # National Seismic Hazard Maps" (2012, page 16). # Values were interpolated to include all listed periods. # MF is the linear multiplicative factor. COEFFS_SITE_FACTORS = CoeffsTable(sa_damping=5, table="""\ IMT MF pga 0.50 pgv 1.00 0.05 0.44 0.10 0.44 0.15 0.53 0.20 0.60 0.25 0.72 0.30 0.81 0.40 1.00 0.50 1.01 0.60 1.02 0.70 1.02 0.80 1.03 0.90 1.04 1.00 1.04 1.25 1.19 1.50 1.31 2.00 1.51 2.50 1.34 3.00 1.21 4.00 1.09 5.00 1.00 """) class ZhaoEtAl2006SInterCascadia(ZhaoEtAl2006SInter): """ Implements the interface GMPE developed by <NAME> et al modified by the Japan/Cascadia site factors as proposed by <NAME>. (2012). White paper on proposed ground-motion prediction equations (GMPEs) for 2015 National Seismic Hazard Maps Final Version, Nov. 2012, 50 pp. This class extends the :class:`openquake.hazardlib.gsim.zhao_2006.ZhaoEtAl2006Asc` because the equation for subduction interface is obtained from the equation for active shallow crust, by removing the faulting style term and adding a subduction interface term. """ def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required # intensity measure type. C = self.COEFFS_ASC[imt] C_SINTER = self.COEFFS_SINTER[imt] C_SF = COEFFS_SITE_FACTORS[imt] # mean value as given by equation 1, p. 901, without considering the # faulting style and intraslab terms (that is FR, SS, SSL = 0) and the # inter and intra event terms, plus the magnitude-squared term # correction factor (equation 5 p. 909) mean = self._compute_magnitude_term(C, rup.mag) +\ self._compute_distance_term(C, rup.mag, dists.rrup) +\ self._compute_focal_depth_term(C, rup.hypo_depth) +\ self._compute_site_class_term(C, sites.vs30) + \ self._compute_magnitude_squared_term(P=0.0, M=6.3, Q=C_SINTER['QI'], W=C_SINTER['WI'], mag=rup.mag) +\ C_SINTER['SI'] # multiply by site factor to "convert" Japan values to Cascadia values # then convert from cm/s**2 to g mean = np.log((np.exp(mean) * C_SF["MF"]) * 1e-2 / g) stddevs = self._get_stddevs(C['sigma'], C_SINTER['tauI'], stddev_types, num_sites=len(sites.vs30)) return mean, stddevs class ZhaoEtAl2006SSlabCascadia(ZhaoEtAl2006SSlab): """ Implements GMPE developed by <NAME> et al modified by the Japan/Cascadia site factors as proposed by <NAME>. (2012). White paper on proposed ground-motion prediction equations (GMPEs) for 2015 National Seismic Hazard Maps Final Version, Nov. 2012, 50 pp. This class extends the :class:`openquake.hazardlib.gsim.zhao_2006.ZhaoEtAl2006Asc` because the equation for subduction slab is obtained from the equation for active shallow crust, by removing the faulting style term and adding subduction slab terms. """ def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required # intensity measure type. C = self.COEFFS_ASC[imt] C_SSLAB = self.COEFFS_SSLAB[imt] C_SF = COEFFS_SITE_FACTORS[imt] # to avoid singularity at 0.0 (in the calculation of the # slab correction term), replace 0 values with 0.1 d = dists.rrup d[d == 0.0] = 0.1 # mean value as given by equation 1, p. 901, without considering the # faulting style and intraslab terms (that is FR, SS, SSL = 0) and the # inter and intra event terms, plus the magnitude-squared term # correction factor (equation 5 p. 909) mean = self._compute_magnitude_term(C, rup.mag) +\ self._compute_distance_term(C, rup.mag, d) +\ self._compute_focal_depth_term(C, rup.hypo_depth) +\ self._compute_site_class_term(C, sites.vs30) +\ self._compute_magnitude_squared_term(P=C_SSLAB['PS'], M=6.5, Q=C_SSLAB['QS'], W=C_SSLAB['WS'], mag=rup.mag) +\ C_SSLAB['SS'] + self._compute_slab_correction_term(C_SSLAB, d) # multiply by site factor to "convert" Japan values to Cascadia values # then convert from cm/s**2 to g mean = np.log((np.exp(mean) * C_SF["MF"]) * 1e-2 / g) stddevs = self._get_stddevs(C['sigma'], C_SSLAB['tauS'], stddev_types, num_sites=len(sites.vs30)) return mean, stddevs
[ "numpy.sqrt", "numpy.log", "numpy.exp", "openquake.hazardlib.gsim.base.CoeffsTable", "numpy.zeros", "copy.deepcopy" ]
[((23450, 23869), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT MF\n pga 0.50\n pgv 1.00\n 0.05 0.44\n 0.10 0.44\n 0.15 0.53\n 0.20 0.60\n 0.25 0.72\n 0.30 0.81\n 0.40 1.00\n 0.50 1.01\n 0.60 1.02\n 0.70 1.02\n 0.80 1.03\n 0.90 1.04\n 1.00 1.04\n 1.25 1.19\n 1.50 1.31\n 2.00 1.51\n 2.50 1.34\n 3.00 1.21\n 4.00 1.09\n 5.00 1.00\n """'}), '(sa_damping=5, table=\n """ IMT MF\n pga 0.50\n pgv 1.00\n 0.05 0.44\n 0.10 0.44\n 0.15 0.53\n 0.20 0.60\n 0.25 0.72\n 0.30 0.81\n 0.40 1.00\n 0.50 1.01\n 0.60 1.02\n 0.70 1.02\n 0.80 1.03\n 0.90 1.04\n 1.00 1.04\n 1.25 1.19\n 1.50 1.31\n 2.00 1.51\n 2.50 1.34\n 3.00 1.21\n 4.00 1.09\n 5.00 1.00\n """\n )\n', (23461, 23869), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((7631, 10389), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT a b c d e FR CH C1 C2 C3 C4 sigma QC WC tauC\n pga 1.101 -0.00564 0.0055 1.080 0.01412 0.251 0.293 1.111 1.344 1.355 1.420 0.604 0.0 0.0 0.303\n 0.05 1.076 -0.00671 0.0075 1.060 0.01463 0.251 0.939 1.684 1.793 1.747 1.814 0.640 0.0 0.0 0.326\n 0.10 1.118 -0.00787 0.0090 1.083 0.01423 0.240 1.499 2.061 2.135 2.031 2.082 0.694 0.0 0.0 0.342\n 0.15 1.134 -0.00722 0.0100 1.053 0.01509 0.251 1.462 1.916 2.168 2.052 2.113 0.702 0.0 0.0 0.331\n 0.20 1.147 -0.00659 0.0120 1.014 0.01462 0.260 1.280 1.669 2.085 2.001 2.030 0.692 0.0 0.0 0.312\n 0.25 1.149 -0.00590 0.0140 0.966 0.01459 0.269 1.121 1.468 1.942 1.941 1.937 0.682 0.0 0.0 0.298\n 0.30 1.163 -0.00520 0.0150 0.934 0.01458 0.259 0.852 1.172 1.683 1.808 1.770 0.670 0.0 0.0 0.300\n 0.40 1.200 -0.00422 0.0100 0.959 0.01257 0.248 0.365 0.655 1.127 1.482 1.397 0.659 0.0 0.0 0.346\n 0.50 1.250 -0.00338 0.0060 1.008 0.01114 0.247 -0.207 0.071 0.515 0.934 0.955 0.653 -0.0126 0.0116 0.338\n 0.60 1.293 -0.00282 0.0030 1.088 0.01019 0.233 -0.705 -0.429 -0.003 0.394 0.559 0.653 -0.0329 0.0202 0.349\n 0.70 1.336 -0.00258 0.0025 1.084 0.00979 0.220 -1.144 -0.866 -0.449 -0.111 0.188 0.652 -0.0501 0.0274 0.351\n 0.80 1.386 -0.00242 0.0022 1.088 0.00944 0.232 -1.609 -1.325 -0.928 -0.620 -0.246 0.647 -0.0650 0.0336 0.356\n 0.90 1.433 -0.00232 0.0020 1.109 0.00972 0.220 -2.023 -1.732 -1.349 -1.066 -0.643 0.653 -0.0781 0.0391 0.348\n 1.00 1.479 -0.00220 0.0020 1.115 0.01005 0.211 -2.451 -2.152 -1.776 -1.523 -1.084 0.657 -0.0899 0.0440 0.338\n 1.25 1.551 -0.00207 0.0020 1.083 0.01003 0.251 -3.243 -2.923 -2.542 -2.327 -1.936 0.660 -0.1148 0.0545 0.313\n 1.50 1.621 -0.00224 0.0020 1.091 0.00928 0.248 -3.888 -3.548 -3.169 -2.979 -2.661 0.664 -0.1351 0.0630 0.306\n 2.00 1.694 -0.00201 0.0025 1.055 0.00833 0.263 -4.783 -4.410 -4.039 -3.871 -3.640 0.669 -0.1672 0.0764 0.283\n 2.50 1.748 -0.00187 0.0028 1.052 0.00776 0.262 -5.444 -5.049 -4.698 -4.496 -4.341 0.671 -0.1921 0.0869 0.287\n 3.00 1.759 -0.00147 0.0032 1.025 0.00644 0.307 -5.839 -5.431 -5.089 -4.893 -4.758 0.667 -0.2124 0.0954 0.278\n 4.00 1.826 -0.00195 0.0040 1.044 0.00590 0.353 -6.598 -6.181 -5.882 -5.698 -5.588 0.647 -0.2445 0.1088 0.273\n 5.00 1.825 -0.00237 0.0050 1.065 0.00510 0.248 -6.752 -6.347 -6.051 -5.873 -5.798 0.643 -0.2694 0.1193 0.275\n """'}), '(sa_damping=5, table=\n """ IMT a b c d e FR CH C1 C2 C3 C4 sigma QC WC tauC\n pga 1.101 -0.00564 0.0055 1.080 0.01412 0.251 0.293 1.111 1.344 1.355 1.420 0.604 0.0 0.0 0.303\n 0.05 1.076 -0.00671 0.0075 1.060 0.01463 0.251 0.939 1.684 1.793 1.747 1.814 0.640 0.0 0.0 0.326\n 0.10 1.118 -0.00787 0.0090 1.083 0.01423 0.240 1.499 2.061 2.135 2.031 2.082 0.694 0.0 0.0 0.342\n 0.15 1.134 -0.00722 0.0100 1.053 0.01509 0.251 1.462 1.916 2.168 2.052 2.113 0.702 0.0 0.0 0.331\n 0.20 1.147 -0.00659 0.0120 1.014 0.01462 0.260 1.280 1.669 2.085 2.001 2.030 0.692 0.0 0.0 0.312\n 0.25 1.149 -0.00590 0.0140 0.966 0.01459 0.269 1.121 1.468 1.942 1.941 1.937 0.682 0.0 0.0 0.298\n 0.30 1.163 -0.00520 0.0150 0.934 0.01458 0.259 0.852 1.172 1.683 1.808 1.770 0.670 0.0 0.0 0.300\n 0.40 1.200 -0.00422 0.0100 0.959 0.01257 0.248 0.365 0.655 1.127 1.482 1.397 0.659 0.0 0.0 0.346\n 0.50 1.250 -0.00338 0.0060 1.008 0.01114 0.247 -0.207 0.071 0.515 0.934 0.955 0.653 -0.0126 0.0116 0.338\n 0.60 1.293 -0.00282 0.0030 1.088 0.01019 0.233 -0.705 -0.429 -0.003 0.394 0.559 0.653 -0.0329 0.0202 0.349\n 0.70 1.336 -0.00258 0.0025 1.084 0.00979 0.220 -1.144 -0.866 -0.449 -0.111 0.188 0.652 -0.0501 0.0274 0.351\n 0.80 1.386 -0.00242 0.0022 1.088 0.00944 0.232 -1.609 -1.325 -0.928 -0.620 -0.246 0.647 -0.0650 0.0336 0.356\n 0.90 1.433 -0.00232 0.0020 1.109 0.00972 0.220 -2.023 -1.732 -1.349 -1.066 -0.643 0.653 -0.0781 0.0391 0.348\n 1.00 1.479 -0.00220 0.0020 1.115 0.01005 0.211 -2.451 -2.152 -1.776 -1.523 -1.084 0.657 -0.0899 0.0440 0.338\n 1.25 1.551 -0.00207 0.0020 1.083 0.01003 0.251 -3.243 -2.923 -2.542 -2.327 -1.936 0.660 -0.1148 0.0545 0.313\n 1.50 1.621 -0.00224 0.0020 1.091 0.00928 0.248 -3.888 -3.548 -3.169 -2.979 -2.661 0.664 -0.1351 0.0630 0.306\n 2.00 1.694 -0.00201 0.0025 1.055 0.00833 0.263 -4.783 -4.410 -4.039 -3.871 -3.640 0.669 -0.1672 0.0764 0.283\n 2.50 1.748 -0.00187 0.0028 1.052 0.00776 0.262 -5.444 -5.049 -4.698 -4.496 -4.341 0.671 -0.1921 0.0869 0.287\n 3.00 1.759 -0.00147 0.0032 1.025 0.00644 0.307 -5.839 -5.431 -5.089 -4.893 -4.758 0.667 -0.2124 0.0954 0.278\n 4.00 1.826 -0.00195 0.0040 1.044 0.00590 0.353 -6.598 -6.181 -5.882 -5.698 -5.588 0.647 -0.2445 0.1088 0.273\n 5.00 1.825 -0.00237 0.0050 1.065 0.00510 0.248 -6.752 -6.347 -6.051 -5.873 -5.798 0.643 -0.2694 0.1193 0.275\n """\n )\n', (7642, 10389), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((13164, 14188), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT SI QI WI tauI\n pga 0.000 0.0 0.0 0.308\n 0.05 0.000 0.0 0.0 0.343\n 0.10 0.000 0.0 0.0 0.403\n 0.15 0.000 -0.0138 0.0286 0.367\n 0.20 0.000 -0.0256 0.0352 0.328\n 0.25 0.000 -0.0348 0.0403 0.289\n 0.30 0.000 -0.0423 0.0445 0.280\n 0.40 -0.041 -0.0541 0.0511 0.271\n 0.50 -0.053 -0.0632 0.0562 0.277\n 0.60 -0.103 -0.0707 0.0604 0.296\n 0.70 -0.146 -0.0771 0.0639 0.313\n 0.80 -0.164 -0.0825 0.0670 0.329\n 0.90 -0.206 -0.0874 0.0697 0.324\n 1.00 -0.239 -0.0917 0.0721 0.328\n 1.25 -0.256 -0.1009 0.0772 0.339\n 1.50 -0.306 -0.1083 0.0814 0.352\n 2.00 -0.321 -0.1202 0.0880 0.360\n 2.50 -0.337 -0.1293 0.0931 0.356\n 3.00 -0.331 -0.1368 0.0972 0.338\n 4.00 -0.390 -0.1486 0.1038 0.307\n 5.00 -0.498 -0.1578 0.1090 0.272\n """'}), '(sa_damping=5, table=\n """ IMT SI QI WI tauI\n pga 0.000 0.0 0.0 0.308\n 0.05 0.000 0.0 0.0 0.343\n 0.10 0.000 0.0 0.0 0.403\n 0.15 0.000 -0.0138 0.0286 0.367\n 0.20 0.000 -0.0256 0.0352 0.328\n 0.25 0.000 -0.0348 0.0403 0.289\n 0.30 0.000 -0.0423 0.0445 0.280\n 0.40 -0.041 -0.0541 0.0511 0.271\n 0.50 -0.053 -0.0632 0.0562 0.277\n 0.60 -0.103 -0.0707 0.0604 0.296\n 0.70 -0.146 -0.0771 0.0639 0.313\n 0.80 -0.164 -0.0825 0.0670 0.329\n 0.90 -0.206 -0.0874 0.0697 0.324\n 1.00 -0.239 -0.0917 0.0721 0.328\n 1.25 -0.256 -0.1009 0.0772 0.339\n 1.50 -0.306 -0.1083 0.0814 0.352\n 2.00 -0.321 -0.1202 0.0880 0.360\n 2.50 -0.337 -0.1293 0.0931 0.356\n 3.00 -0.331 -0.1368 0.0972 0.338\n 4.00 -0.390 -0.1486 0.1038 0.307\n 5.00 -0.498 -0.1578 0.1090 0.272\n """\n )\n', (13175, 14188), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((17435, 18833), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT SS SSL PS QS WS tauS\n pga 2.607 -0.528 0.1392 0.1584 -0.0529 0.321\n 0.05 2.764 -0.551 0.1636 0.1932 -0.0841 0.378\n 0.10 2.156 -0.420 0.1690 0.2057 -0.0877 0.420\n 0.15 2.161 -0.431 0.1669 0.1984 -0.0773 0.372\n 0.20 1.901 -0.372 0.1631 0.1856 -0.0644 0.324\n 0.25 1.814 -0.360 0.1588 0.1714 -0.0515 0.294\n 0.30 2.181 -0.450 0.1544 0.1573 -0.0395 0.284\n 0.40 2.432 -0.506 0.1460 0.1309 -0.0183 0.278\n 0.50 2.629 -0.554 0.1381 0.1078 -0.0008 0.272\n 0.60 2.702 -0.575 0.1307 0.0878 0.0136 0.285\n 0.70 2.654 -0.572 0.1239 0.0705 0.0254 0.290\n 0.80 2.480 -0.540 0.1176 0.0556 0.0352 0.299\n 0.90 2.332 -0.522 0.1116 0.0426 0.0432 0.289\n 1.00 2.233 -0.509 0.1060 0.0314 0.0498 0.286\n 1.25 2.029 -0.469 0.0933 0.0093 0.0612 0.277\n 1.50 1.589 -0.379 0.0821 -0.0062 0.0674 0.282\n 2.00 0.966 -0.248 0.0628 -0.0235 0.0692 0.300\n 2.50 0.789 -0.221 0.0465 -0.0287 0.0622 0.292\n 3.00 1.037 -0.263 0.0322 -0.0261 0.0496 0.274\n 4.00 0.561 -0.169 0.0083 -0.0065 0.0150 0.281\n 5.00 0.225 -0.120 -0.0117 0.0246 -0.0268 0.296\n """'}), '(sa_damping=5, table=\n """ IMT SS SSL PS QS WS tauS\n pga 2.607 -0.528 0.1392 0.1584 -0.0529 0.321\n 0.05 2.764 -0.551 0.1636 0.1932 -0.0841 0.378\n 0.10 2.156 -0.420 0.1690 0.2057 -0.0877 0.420\n 0.15 2.161 -0.431 0.1669 0.1984 -0.0773 0.372\n 0.20 1.901 -0.372 0.1631 0.1856 -0.0644 0.324\n 0.25 1.814 -0.360 0.1588 0.1714 -0.0515 0.294\n 0.30 2.181 -0.450 0.1544 0.1573 -0.0395 0.284\n 0.40 2.432 -0.506 0.1460 0.1309 -0.0183 0.278\n 0.50 2.629 -0.554 0.1381 0.1078 -0.0008 0.272\n 0.60 2.702 -0.575 0.1307 0.0878 0.0136 0.285\n 0.70 2.654 -0.572 0.1239 0.0705 0.0254 0.290\n 0.80 2.480 -0.540 0.1176 0.0556 0.0352 0.299\n 0.90 2.332 -0.522 0.1116 0.0426 0.0432 0.289\n 1.00 2.233 -0.509 0.1060 0.0314 0.0498 0.286\n 1.25 2.029 -0.469 0.0933 0.0093 0.0612 0.277\n 1.50 1.589 -0.379 0.0821 -0.0062 0.0674 0.282\n 2.00 0.966 -0.248 0.0628 -0.0235 0.0692 0.300\n 2.50 0.789 -0.221 0.0465 -0.0287 0.0622 0.292\n 3.00 1.037 -0.263 0.0322 -0.0261 0.0496 0.274\n 4.00 0.561 -0.169 0.0083 -0.0065 0.0150 0.281\n 5.00 0.225 -0.120 -0.0117 0.0246 -0.0268 0.296\n """\n )\n', (17446, 18833), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((20084, 21129), 'openquake.hazardlib.gsim.base.CoeffsTable', 'CoeffsTable', ([], {'sa_damping': '(5)', 'table': '""" IMT SI QI WI tauI\n pga 0.000 0.0 0.0 0.3976\n 0.05 0.000 0.0 0.0 0.4437\n 0.10 0.000 0.0 0.0 0.4903\n 0.15 0.000 -0.0138 0.0286 0.4603\n 0.20 0.000 -0.0256 0.0352 0.4233\n 0.25 0.000 -0.0348 0.0403 0.3908\n 0.30 0.000 -0.0423 0.0445 0.3790\n 0.40 -0.041 -0.0541 0.0511 0.3897\n 0.50 -0.053 -0.0632 0.0562 0.3890\n 0.60 -0.103 -0.0707 0.0604 0.4014\n 0.70 -0.146 -0.0771 0.0639 0.4079\n 0.80 -0.164 -0.0825 0.0670 0.4183\n 0.90 -0.206 -0.0874 0.0697 0.4106\n 1.00 -0.239 -0.0917 0.0721 0.4101\n 1.25 -0.256 -0.1009 0.0772 0.4021\n 1.50 -0.306 -0.1083 0.0814 0.4076\n 2.00 -0.321 -0.1202 0.0880 0.4138\n 2.50 -0.337 -0.1293 0.0931 0.4108\n 3.00 -0.331 -0.1368 0.0972 0.3961\n 4.00 -0.390 -0.1486 0.1038 0.3821\n 5.00 -0.498 -0.1578 0.1090 0.3766\n """'}), '(sa_damping=5, table=\n """ IMT SI QI WI tauI\n pga 0.000 0.0 0.0 0.3976\n 0.05 0.000 0.0 0.0 0.4437\n 0.10 0.000 0.0 0.0 0.4903\n 0.15 0.000 -0.0138 0.0286 0.4603\n 0.20 0.000 -0.0256 0.0352 0.4233\n 0.25 0.000 -0.0348 0.0403 0.3908\n 0.30 0.000 -0.0423 0.0445 0.3790\n 0.40 -0.041 -0.0541 0.0511 0.3897\n 0.50 -0.053 -0.0632 0.0562 0.3890\n 0.60 -0.103 -0.0707 0.0604 0.4014\n 0.70 -0.146 -0.0771 0.0639 0.4079\n 0.80 -0.164 -0.0825 0.0670 0.4183\n 0.90 -0.206 -0.0874 0.0697 0.4106\n 1.00 -0.239 -0.0917 0.0721 0.4101\n 1.25 -0.256 -0.1009 0.0772 0.4021\n 1.50 -0.306 -0.1083 0.0814 0.4076\n 2.00 -0.321 -0.1202 0.0880 0.4138\n 2.50 -0.337 -0.1293 0.0931 0.4108\n 3.00 -0.331 -0.1368 0.0972 0.3961\n 4.00 -0.390 -0.1486 0.1038 0.3821\n 5.00 -0.498 -0.1578 0.1090 0.3766\n """\n )\n', (20095, 21129), False, 'from openquake.hazardlib.gsim.base import GMPE, CoeffsTable\n'), ((19837, 19855), 'copy.deepcopy', 'copy.deepcopy', (['rup'], {}), '(rup)\n', (19850, 19855), False, 'import copy\n'), ((17183, 17195), 'numpy.log', 'np.log', (['rrup'], {}), '(rrup)\n', (17189, 17195), True, 'import numpy as np\n'), ((4892, 4922), 'numpy.sqrt', 'np.sqrt', (['(sigma ** 2 + tau ** 2)'], {}), '(sigma ** 2 + tau ** 2)\n', (4899, 4922), True, 'import numpy as np\n'), ((4328, 4340), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (4334, 4340), True, 'import numpy as np\n'), ((12766, 12778), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (12772, 12778), True, 'import numpy as np\n'), ((16766, 16778), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (16772, 16778), True, 'import numpy as np\n'), ((22960, 22972), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (22966, 22972), True, 'import numpy as np\n'), ((4964, 4983), 'numpy.zeros', 'np.zeros', (['num_sites'], {}), '(num_sites)\n', (4972, 4983), True, 'import numpy as np\n'), ((5602, 5622), 'numpy.exp', 'np.exp', (["(C['d'] * mag)"], {}), "(C['d'] * mag)\n", (5608, 5622), True, 'import numpy as np\n'), ((25926, 25938), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (25932, 25938), True, 'import numpy as np\n'), ((28395, 28407), 'numpy.exp', 'np.exp', (['mean'], {}), '(mean)\n', (28401, 28407), True, 'import numpy as np\n'), ((5082, 5101), 'numpy.zeros', 'np.zeros', (['num_sites'], {}), '(num_sites)\n', (5090, 5101), True, 'import numpy as np\n'), ((5198, 5217), 'numpy.zeros', 'np.zeros', (['num_sites'], {}), '(num_sites)\n', (5206, 5217), True, 'import numpy as np\n')]
# PRISM CONVERSION FROM ASCII GRIDS -- TASMIN / TASMAX # header info # ncols 2015 # nrows 1320 # xllcorner -2301787.7731349 # yllcorner 108069.7858797 # cellsize 2000 # NODATA_value -9999 import rasterio, glob, os from rasterio import Affine import numpy as np from pathos import multiprocessing as mp # input_path = '/Data/Base_Data/Climate/AK_CAN_2km/historical/singleBand/pr' # #'/Data/Base_Data/Climate/AK_CAN_2km/historical/singleBand/prism/AK_2KM_PRISM/Temperature/2km/older' # output_path = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2' # groups = ['min_temp', 'max_temp'] # # # STEP 1 -- CONVERT TO GTIFF FROM ASC AND TXT # list the data we want variables = [ 'tmin', 'tmax' ] input_path_ak = '/Data/Base_Data/Climate/AK_CAN_2km/historical/singleBand/prism/AK_2KM_PRISM/Temperature/2km/older' input_path_can = '/Data/Base_Data/Climate/AK_CAN_2km/historical/singleBand/prism/AK_CAN_2km_PRISM/CAN_originals/older' for variable in variables: for ak_test, input_path in zip( [True,False], [input_path_ak,input_path_can] ): output_path = os.path.join( '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2', variable,'raw_converted' ) if not os.path.exists( output_path ): os.makedirs( output_path ) if ak_test: input_path = input_path_ak if variable == 'tmin': v = 'min_temp' elif variable == 'tmax': v = 'max_temp' else: NotImplemented( 'only tmax / tmin currently supported' ) files = glob.glob( os.path.join( input_path, v, '*'+variable+'*.txt' ) ) else: input_path = input_path_can files = glob.glob( os.path.join( input_path, '*'+variable+'*.asc' ) ) ext = files[0].split('.')[1] output_filenames = [ os.path.join( output_path, os.path.basename( fn ).replace( '.'+ext, '.tif' ) ) for fn in files ] crs = {'init':'epsg:4326'} args = [ (i,j,crs) for i,j in zip(files, output_filenames) ] def bounds_to_extent( bounds ): ''' take input rasterio bounds object and return an extent ''' l,b,r,t = bounds return [ (l,b), (r,b), (r,t), (l,t), (l,b) ] def convert_to_gtiff( fn, output_filename, crs={'init':'epsg:3338'} ): ''' convert the ascii rasters from PRISM to gtiff ''' print( fn ) rst = rasterio.open( fn ) arr = rst.read( 1 ) # get the first and only band meta = rst.meta meta.update( compress='lzw', driver='GTiff', crs=crs ) # drop the transform to overcome rasterio warnings if 'transform' in meta.keys(): meta.pop( 'transform' ) # write them out with rasterio.open( output_filename, 'w', **meta ) as out: out.write( arr, 1 ) return output_filename if __name__ == '__main__': pool = mp.Pool( 32 ) pool.map( lambda x: convert_to_gtiff( *x ), args ) pool.close() pool.join() # # # STEP 2 -- MERGE IT WITH GDAL TOOLS # list the data caw = sorted( glob.glob( os.path.join( '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2',variable,'raw_converted', 'caw*.tif' ) ) ) ak = sorted( glob.glob( os.path.join( '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2',variable,'raw_converted', 'ak_*.tif' ) ) ) grouped = zip( ak, caw ) # merge these files: # log = open( '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2/batch_run.bat', 'w' ) for ak,ca in grouped: out = ak.replace( 'ak_', 'akcan_') ca_out = ca.replace( '.tif', '_3338.tif' ) os.system( 'gdalwarp -overwrite -r near -t_srs EPSG:3338 -s_srs EPSG:4326 -ot Float32 ' + ca + ' ' + ca_out ) ca_scale = ca_out.replace( '.tif', '_scaled.tif' ) os.system( 'gdal_calc.py --overwrite -A ' + ca_out + ' --outfile=' + ca_scale + ' --calc="A*(0.1)" --NoDataValue=-9999 --type=Float32' ) os.system( 'gdal_merge.py -init -9999 -n -9999 -a_nodata -9999 -ot Float32 -o ' + out + ' ' + ak + ' ' + ca_scale ) final = ca.replace( '.tif', '_merged.tif' ).replace( 'raw_converted', 'merged' ).replace( 'caw_', 'akcan_' ) if not os.path.exists( os.path.dirname(final) ): os.makedirs(os.path.dirname(final)) os.system( 'gdal_translate -co "COMPRESS=LZW" ' + out + ' ' + final ) # # DUE TO SOME WEIRDNESS WITH VIRTUALENV AND GDAL_MERGE.PY I am writing this out to a text file and running it when not in virtualenv # out = ak.replace( 'ak_', 'akcan_') # ca_out = ca.replace( '.tif', '_3338.tif' ) # log.write( 'gdalwarp -overwrite -r near -t_srs EPSG:3338 -s_srs EPSG:4326 -ot Float32 ' + ca + ' ' + ca_out + '\n' ) # ca_scale = ca_out.replace( '.tif', '_scaled.tif' ) # log.write( 'gdal_calc.py --overwrite -A ' + ca_out + ' --outfile=' + ca_scale + ' --calc="A*(0.1)" --NoDataValue=-9999 --type=Float32' + '\n' ) # log.write( 'gdal_merge.py -init -9999 -n -9999 -a_nodata -9999 -ot Float32 -o ' + out + ' ' + ak + ' ' + ca_scale + '\n' ) # final = ca.replace( '.tif', '_merged.tif' ) # log.write( 'gdal_translate -co "COMPRESS=LZW" ' + out + ' ' + final + '\n' ) # # # STEP 3 -- INTERPOLATE / REGRID / MASK to match existing SNAP resources def coordinates( fn=None, meta=None, numpy_array=None, input_crs=None, to_latlong=False ): ''' take a raster file as input and return the centroid coords for each of the grid cells as a pair of numpy 2d arrays (longitude, latitude) ''' import rasterio import numpy as np from affine import Affine from pyproj import Proj, transform if fn: # Read raster with rasterio.open( fn ) as r: T0 = r.affine # upper-left pixel corner affine transform p1 = Proj( r.crs ) A = r.read( 1 ) # pixel values elif (meta is not None) & (numpy_array is not None): A = numpy_array if input_crs != None: p1 = Proj( input_crs ) T0 = meta[ 'affine' ] else: p1 = None T0 = meta[ 'affine' ] else: BaseException( 'check inputs' ) # All rows and columns cols, rows = np.meshgrid(np.arange(A.shape[1]), np.arange(A.shape[0])) # Get affine transform for pixel centres T1 = T0 * Affine.translation( 0.5, 0.5 ) # Function to convert pixel row/column index (from 0) to easting/northing at centre rc2en = lambda r, c: ( c, r ) * T1 # All eastings and northings (there is probably a faster way to do this) eastings, northings = np.vectorize(rc2en, otypes=[np.float, np.float])(rows, cols) if to_latlong == False: return eastings, northings elif (to_latlong == True) & (input_crs != None): # Project all longitudes, latitudes longs, lats = transform(p1, p1.to_latlong(), eastings, northings) return longs, lats else: BaseException( 'cant reproject to latlong without an input_crs' ) def xyz_to_grid( x, y, z, grid, method='cubic', output_dtype=np.float32, *args, **kwargs ): ''' interpolate points to a grid. simple wrapper around scipy.interpolate.griddata. Points and grid must be in the same coordinate system x = 1-D np.array of x coordinates / x,y,z must be same length y = 1-D np.array of y coordinates / x,y,z must be same length z = 1-D np.array of z coordinates / x,y,z must be same length grid = tuple of meshgrid as made using numpy.meshgrid() order (xi, yi) method = one of 'cubic', 'near', 'linear' ''' from scipy.interpolate import griddata zi = griddata( (x, y), z, grid, method=method ) zi = np.flipud( zi ).astype( output_dtype ) return zi import glob, os, rasterio import numpy as np from rasterio.warp import reproject, RESAMPLING import pandas as pd # ORIG_AK_RAW = '/Data/Base_Data/Climate/AK_CAN_2km/historical/singleBand/prism/AK_2KM_PRISM/Temperature/2km/older' # TEMPLATE: template_fn = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/akcan_template/tas_mean_C_AR5_CCSM4_rcp26_01_2006.tif' rst = rasterio.open( template_fn ) mask = rst.read_masks() input_dir = os.path.join( '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2', variable, 'merged' ) files = glob.glob( os.path.join( input_dir, 'akcan_*.tif' ) ) # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * # make an empty raster to hold the new output for fn in files: template = rasterio.open( template_fn ) meta = template.meta meta.update( compress='lzw' ) output_filename = os.path.join( '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2', variable, os.path.basename( fn ).replace( 'merged', 'final' ) ) with rasterio.open( output_filename, 'w', **meta ) as out: out.write( np.empty_like( template.read( 1 ) ), 1 ) # run it with gdalwarp command = 'gdalwarp ' + fn + ' ' + output_filename os.system( command ) # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * # for fn in files: # cur = rasterio.open( fn ) # # GET THE COORDS AND THE DATA IN A WAY THAT IS INTEPOLATABLE # lons, lats = coordinates( fn ) # df = pd.DataFrame( {'lons':lons.ravel(), 'lats':lats.ravel(), 'dat':cur.read(1).ravel() } ) # new_df = df[df.dat != -9999] # new_grid = xyz_to_grid( new_df.lons.tolist(), new_df.lats.tolist(), new_df.dat.tolist(), (lons,lats), method='cubic', output_dtype=np.float32 ) # # new_grid[ np.isnan( new_grid ) ] = -9999 # output_arr = np.empty_like( rst.read( 1 ) ) # # now reproject the new_grid to the extent/resolution/crs of the ALF data -- idiotic crs we use here # reproject( new_grid, output_arr, src_transform=cur.affine, src_crs={ 'init':'epsg:3338' }, src_nodata=None, \ # dst_transform=rst.affine, dst_crs=rst.crs,\ # dst_nodata=None, resampling=RESAMPLING.cubic_spline, SOURCE_EXTRA=1000 ) # output_arr[ mask == 0 ] = rst.nodata # new_path = os.path.join( '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2', variable, 'prepped' ) # output_filename = os.path.join( new_path, os.path.basename( fn ) ) # meta = rst.meta # meta.update( compress='lzw' ) # meta.pop( 'transform' ) # with rasterio.open( output_filename, 'w', **meta ) as out: # out.write( output_arr, 1 ) # # # # END PREP # THIS IS HOW IT WAS CONVERTED FROM THE TXT/ASC FORMATS # for group in groups: # # list the data we want to convert to GTiff # # remember that month 14 is the annual average # files = glob.glob( os.path.join( input_path, group, '*.txt' ) ) # for fn in files: # # print fn # rst = rasterio.open( fn ) # arr = rst.read( 1 ) # get the first and only band # output_filename = os.path.join( output_path, os.path.basename(fn).replace( '.txt', '.tif' ) ) # meta = rst.meta # meta.update( compress='lzw', driver='GTiff', crs={'init':'epsg:3338'} ) # # drop the transform to overcome rasterio warnings # if 'transform' in meta.keys(): # meta.pop( 'transform' ) # # write them out # with rasterio.open( output_filename, 'w', **meta ) as out: # out.write( arr, 1 )
[ "os.path.exists", "os.makedirs", "pathos.multiprocessing.Pool", "numpy.flipud", "rasterio.open", "scipy.interpolate.griddata", "os.path.join", "os.path.dirname", "affine.Affine.translation", "os.path.basename", "pyproj.Proj", "os.system", "numpy.vectorize", "numpy.arange" ]
[((7696, 7722), 'rasterio.open', 'rasterio.open', (['template_fn'], {}), '(template_fn)\n', (7709, 7722), False, 'import rasterio\n'), ((7764, 7883), 'os.path.join', 'os.path.join', (['"""/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2"""', 'variable', '"""merged"""'], {}), "(\n '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2'\n , variable, 'merged')\n", (7776, 7883), False, 'import glob, os, rasterio\n'), ((1110, 1236), 'os.path.join', 'os.path.join', (['"""/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2"""', 'variable', '"""raw_converted"""'], {}), "(\n '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2'\n , variable, 'raw_converted')\n", (1122, 1236), False, 'import glob, os, rasterio\n'), ((3456, 3573), 'os.system', 'os.system', (["(\n 'gdalwarp -overwrite -r near -t_srs EPSG:3338 -s_srs EPSG:4326 -ot Float32 '\n + ca + ' ' + ca_out)"], {}), "(\n 'gdalwarp -overwrite -r near -t_srs EPSG:3338 -s_srs EPSG:4326 -ot Float32 '\n + ca + ' ' + ca_out)\n", (3465, 3573), False, 'import glob, os, rasterio\n'), ((3621, 3759), 'os.system', 'os.system', (['(\'gdal_calc.py --overwrite -A \' + ca_out + \' --outfile=\' + ca_scale +\n \' --calc="A*(0.1)" --NoDataValue=-9999 --type=Float32\')'], {}), '(\'gdal_calc.py --overwrite -A \' + ca_out + \' --outfile=\' +\n ca_scale + \' --calc="A*(0.1)" --NoDataValue=-9999 --type=Float32\')\n', (3630, 3759), False, 'import glob, os, rasterio\n'), ((3760, 3882), 'os.system', 'os.system', (["('gdal_merge.py -init -9999 -n -9999 -a_nodata -9999 -ot Float32 -o ' + out +\n ' ' + ak + ' ' + ca_scale)"], {}), "(\n 'gdal_merge.py -init -9999 -n -9999 -a_nodata -9999 -ot Float32 -o ' +\n out + ' ' + ak + ' ' + ca_scale)\n", (3769, 3882), False, 'import glob, os, rasterio\n'), ((4079, 4146), 'os.system', 'os.system', (['(\'gdal_translate -co "COMPRESS=LZW" \' + out + \' \' + final)'], {}), '(\'gdal_translate -co "COMPRESS=LZW" \' + out + \' \' + final)\n', (4088, 4146), False, 'import glob, os, rasterio\n'), ((7202, 7242), 'scipy.interpolate.griddata', 'griddata', (['(x, y)', 'z', 'grid'], {'method': 'method'}), '((x, y), z, grid, method=method)\n', (7210, 7242), False, 'from scipy.interpolate import griddata\n'), ((7896, 7934), 'os.path.join', 'os.path.join', (['input_dir', '"""akcan_*.tif"""'], {}), "(input_dir, 'akcan_*.tif')\n", (7908, 7934), False, 'import glob, os, rasterio\n'), ((8134, 8160), 'rasterio.open', 'rasterio.open', (['template_fn'], {}), '(template_fn)\n', (8147, 8160), False, 'import rasterio\n'), ((8590, 8608), 'os.system', 'os.system', (['command'], {}), '(command)\n', (8599, 8608), False, 'import glob, os, rasterio\n'), ((1238, 1265), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (1252, 1265), False, 'import glob, os, rasterio\n'), ((1272, 1296), 'os.makedirs', 'os.makedirs', (['output_path'], {}), '(output_path)\n', (1283, 1296), False, 'import glob, os, rasterio\n'), ((2274, 2291), 'rasterio.open', 'rasterio.open', (['fn'], {}), '(fn)\n', (2287, 2291), False, 'import rasterio\n'), ((2712, 2723), 'pathos.multiprocessing.Pool', 'mp.Pool', (['(32)'], {}), '(32)\n', (2719, 2723), True, 'from pathos import multiprocessing as mp\n'), ((2897, 3035), 'os.path.join', 'os.path.join', (['"""/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2"""', 'variable', '"""raw_converted"""', '"""caw*.tif"""'], {}), "(\n '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2'\n , variable, 'raw_converted', 'caw*.tif')\n", (2909, 3035), False, 'import glob, os, rasterio\n'), ((3055, 3193), 'os.path.join', 'os.path.join', (['"""/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2"""', 'variable', '"""raw_converted"""', '"""ak_*.tif"""'], {}), "(\n '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/prism_v2'\n , variable, 'raw_converted', 'ak_*.tif')\n", (3067, 3193), False, 'import glob, os, rasterio\n'), ((5863, 5884), 'numpy.arange', 'np.arange', (['A.shape[1]'], {}), '(A.shape[1])\n', (5872, 5884), True, 'import numpy as np\n'), ((5886, 5907), 'numpy.arange', 'np.arange', (['A.shape[0]'], {}), '(A.shape[0])\n', (5895, 5907), True, 'import numpy as np\n'), ((5964, 5992), 'affine.Affine.translation', 'Affine.translation', (['(0.5)', '(0.5)'], {}), '(0.5, 0.5)\n', (5982, 5992), False, 'from affine import Affine\n'), ((6217, 6265), 'numpy.vectorize', 'np.vectorize', (['rc2en'], {'otypes': '[np.float, np.float]'}), '(rc2en, otypes=[np.float, np.float])\n', (6229, 6265), True, 'import numpy as np\n'), ((8400, 8443), 'rasterio.open', 'rasterio.open', (['output_filename', '"""w"""'], {}), "(output_filename, 'w', **meta)\n", (8413, 8443), False, 'import rasterio\n'), ((1529, 1582), 'os.path.join', 'os.path.join', (['input_path', 'v', "('*' + variable + '*.txt')"], {}), "(input_path, v, '*' + variable + '*.txt')\n", (1541, 1582), False, 'import glob, os, rasterio\n'), ((1644, 1694), 'os.path.join', 'os.path.join', (['input_path', "('*' + variable + '*.asc')"], {}), "(input_path, '*' + variable + '*.asc')\n", (1656, 1694), False, 'import glob, os, rasterio\n'), ((2568, 2611), 'rasterio.open', 'rasterio.open', (['output_filename', '"""w"""'], {}), "(output_filename, 'w', **meta)\n", (2581, 2611), False, 'import rasterio\n'), ((4012, 4034), 'os.path.dirname', 'os.path.dirname', (['final'], {}), '(final)\n', (4027, 4034), False, 'import glob, os, rasterio\n'), ((4053, 4075), 'os.path.dirname', 'os.path.dirname', (['final'], {}), '(final)\n', (4068, 4075), False, 'import glob, os, rasterio\n'), ((5418, 5435), 'rasterio.open', 'rasterio.open', (['fn'], {}), '(fn)\n', (5431, 5435), False, 'import rasterio\n'), ((5515, 5526), 'pyproj.Proj', 'Proj', (['r.crs'], {}), '(r.crs)\n', (5519, 5526), False, 'from pyproj import Proj, transform\n'), ((7252, 7265), 'numpy.flipud', 'np.flipud', (['zi'], {}), '(zi)\n', (7261, 7265), True, 'import numpy as np\n'), ((5674, 5689), 'pyproj.Proj', 'Proj', (['input_crs'], {}), '(input_crs)\n', (5678, 5689), False, 'from pyproj import Proj, transform\n'), ((8339, 8359), 'os.path.basename', 'os.path.basename', (['fn'], {}), '(fn)\n', (8355, 8359), False, 'import glob, os, rasterio\n'), ((1777, 1797), 'os.path.basename', 'os.path.basename', (['fn'], {}), '(fn)\n', (1793, 1797), False, 'import glob, os, rasterio\n')]
#!/usr/bin/py2 import cv2 import imutils import numpy as np from solver import Solver from Recognizer import OCR from skimage.segmentation import clear_border from imutils.perspective import four_point_transform class Sudoku(object): def __init__(self, image): self.image = image self.gray = None def initialize_image(self): self.image = cv2.imread(self.image) self.image = imutils.resize(self.image, width=600) return def fetch_rectangle(self): self.gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(self.gray, (7, 7), 3) thresh = cv2.adaptiveThreshold(blurred, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) thresh = cv2.bitwise_not(thresh) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cnts = sorted(cnts, key=cv2.contourArea, reverse=True) puzzleCnt = None for c in cnts: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) if len(approx) == 4: puzzleCnt = approx break return puzzleCnt def extract_sudoku_board(self,board): original_image = four_point_transform(self.image, board.reshape(4, 2)) gray_image = four_point_transform(self.gray, board.reshape(4, 2)) return gray_image def split_board(self,board): return board.shape[1] // 9, board.shape[0] // 9 def extract_digit(self,cell): thresh = cv2.threshold(cell, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] thresh = clear_border(thresh) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) if len(cnts) == 0: return None c = max(cnts, key=cv2.contourArea) mask = np.zeros(thresh.shape, dtype="uint8") cv2.drawContours(mask, [c], -1, 255, -1) (h, w) = thresh.shape percentFilled = cv2.countNonZero(mask) / float(w * h) if percentFilled < 0.03: return None digit = cv2.bitwise_and(thresh, thresh, mask=mask) return digit def process_cells(self,stepX,stepY,board): ocr = OCR() sudoku_array = np.zeros((9, 9), dtype="int") cellLocs = [] boolean = True for y in range(0, 9): row = [] for x in range(0, 9): startX = x * stepX startY = y * stepY endX = (x + 1) * stepX endY = (y + 1) * stepY row.append((startX, startY, endX, endY)) cell = board[startY:endY, startX:endX] digit = self.extract_digit(cell) if (digit is not None): cv2.imwrite("img-"+str(y)+str(x)+".png",digit) sudoku_array[y][x] = ocr.prediction(digit) return sudoku_array def solve(self): self.initialize_image() board = self.fetch_rectangle() if board is None: return board = self.extract_sudoku_board(board) x,y = self.split_board(board) final_board = self.process_cells(x,y,board) return final_board def manipulate(board): canShow = True while (canShow): decision = raw_input("\nWanna make any corrections to the board? Press y if yes:-") if (decision and decision[0].lower() == "y"): canShow = False break values = raw_input("\nEnter Row,Column and Value. Ex: 2,2,3: ").split(",") try: row,col,val = list(map(int,values[:3])) check = lambda x: x>0 and x<10 if (all([check(i) for i in [row,col,val]])): board[row-1][col-1] = val print("\nUpdated Board\n") print(board) else: print("\nInvalid input") except: print("\nInvalid input") return board sudoku_board = Sudoku("Images/sudoku.jpg").solve() print(sudoku_board) updated_board = manipulate(sudoku_board) Solver().solution(updated_board)
[ "Recognizer.OCR", "cv2.drawContours", "cv2.countNonZero", "cv2.threshold", "solver.Solver", "cv2.arcLength", "cv2.bitwise_and", "skimage.segmentation.clear_border", "imutils.resize", "cv2.adaptiveThreshold", "imutils.grab_contours", "numpy.zeros", "cv2.approxPolyDP", "cv2.cvtColor", "cv2.bitwise_not", "cv2.GaussianBlur", "cv2.imread" ]
[((354, 376), 'cv2.imread', 'cv2.imread', (['self.image'], {}), '(self.image)\n', (364, 376), False, 'import cv2\n'), ((392, 429), 'imutils.resize', 'imutils.resize', (['self.image'], {'width': '(600)'}), '(self.image, width=600)\n', (406, 429), False, 'import imutils\n'), ((486, 530), 'cv2.cvtColor', 'cv2.cvtColor', (['self.image', 'cv2.COLOR_BGR2GRAY'], {}), '(self.image, cv2.COLOR_BGR2GRAY)\n', (498, 530), False, 'import cv2\n'), ((543, 581), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['self.gray', '(7, 7)', '(3)'], {}), '(self.gray, (7, 7), 3)\n', (559, 581), False, 'import cv2\n'), ((594, 692), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['blurred', '(255)', 'cv2.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv2.THRESH_BINARY', '(11)', '(2)'], {}), '(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.\n THRESH_BINARY, 11, 2)\n', (615, 692), False, 'import cv2\n'), ((698, 721), 'cv2.bitwise_not', 'cv2.bitwise_not', (['thresh'], {}), '(thresh)\n', (713, 721), False, 'import cv2\n'), ((817, 844), 'imutils.grab_contours', 'imutils.grab_contours', (['cnts'], {}), '(cnts)\n', (838, 844), False, 'import imutils\n'), ((1521, 1541), 'skimage.segmentation.clear_border', 'clear_border', (['thresh'], {}), '(thresh)\n', (1533, 1541), False, 'from skimage.segmentation import clear_border\n'), ((1641, 1668), 'imutils.grab_contours', 'imutils.grab_contours', (['cnts'], {}), '(cnts)\n', (1662, 1668), False, 'import imutils\n'), ((1753, 1790), 'numpy.zeros', 'np.zeros', (['thresh.shape'], {'dtype': '"""uint8"""'}), "(thresh.shape, dtype='uint8')\n", (1761, 1790), True, 'import numpy as np\n'), ((1793, 1833), 'cv2.drawContours', 'cv2.drawContours', (['mask', '[c]', '(-1)', '(255)', '(-1)'], {}), '(mask, [c], -1, 255, -1)\n', (1809, 1833), False, 'import cv2\n'), ((1969, 2011), 'cv2.bitwise_and', 'cv2.bitwise_and', (['thresh', 'thresh'], {'mask': 'mask'}), '(thresh, thresh, mask=mask)\n', (1984, 2011), False, 'import cv2\n'), ((2082, 2087), 'Recognizer.OCR', 'OCR', ([], {}), '()\n', (2085, 2087), False, 'from Recognizer import OCR\n'), ((2106, 2135), 'numpy.zeros', 'np.zeros', (['(9, 9)'], {'dtype': '"""int"""'}), "((9, 9), dtype='int')\n", (2114, 2135), True, 'import numpy as np\n'), ((3596, 3604), 'solver.Solver', 'Solver', ([], {}), '()\n', (3602, 3604), False, 'from solver import Solver\n'), ((952, 974), 'cv2.arcLength', 'cv2.arcLength', (['c', '(True)'], {}), '(c, True)\n', (965, 974), False, 'import cv2\n'), ((987, 1025), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['c', '(0.02 * peri)', '(True)'], {}), '(c, 0.02 * peri, True)\n', (1003, 1025), False, 'import cv2\n'), ((1435, 1503), 'cv2.threshold', 'cv2.threshold', (['cell', '(0)', '(255)', '(cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)'], {}), '(cell, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n', (1448, 1503), False, 'import cv2\n'), ((1877, 1899), 'cv2.countNonZero', 'cv2.countNonZero', (['mask'], {}), '(mask)\n', (1893, 1899), False, 'import cv2\n')]
import numpy as np from public_tool.form_index import form_index from XGB_HMM.form_B_matrix_by_XGB import form_B_matrix_by_XGB from XGB_HMM.predict import self_pred def pred_proba_XGB(A, model, pi, O, allow_flag, lengths): # 对dataset形成pred_proba,注意这里的dataset是solve_on_raw_data后的结果,即附带allow_flag的数据 # output: # pred_proba:数组类型 n_states = len(pi) pred_proba = np.zeros((O.shape[0], n_states)) for i in range(len(lengths)): begin_index, end_index = form_index(lengths, i) now_O = O[begin_index:end_index, :] now_allow_flag = allow_flag[begin_index:end_index] now_pred_proba = np.zeros((now_O.shape[0], n_states)) now_allow_B = form_B_matrix_by_XGB(model, now_O[now_allow_flag == 1], pi) _, now_allow_pred_proba, _ = self_pred(now_allow_B, [now_allow_B.shape[0]], A, pi) now_pred_proba[now_allow_flag == 1] = now_allow_pred_proba pred_proba[begin_index:end_index] = now_pred_proba return pred_proba
[ "XGB_HMM.form_B_matrix_by_XGB.form_B_matrix_by_XGB", "numpy.zeros", "XGB_HMM.predict.self_pred", "public_tool.form_index.form_index" ]
[((397, 429), 'numpy.zeros', 'np.zeros', (['(O.shape[0], n_states)'], {}), '((O.shape[0], n_states))\n', (405, 429), True, 'import numpy as np\n'), ((501, 523), 'public_tool.form_index.form_index', 'form_index', (['lengths', 'i'], {}), '(lengths, i)\n', (511, 523), False, 'from public_tool.form_index import form_index\n'), ((657, 693), 'numpy.zeros', 'np.zeros', (['(now_O.shape[0], n_states)'], {}), '((now_O.shape[0], n_states))\n', (665, 693), True, 'import numpy as np\n'), ((719, 778), 'XGB_HMM.form_B_matrix_by_XGB.form_B_matrix_by_XGB', 'form_B_matrix_by_XGB', (['model', 'now_O[now_allow_flag == 1]', 'pi'], {}), '(model, now_O[now_allow_flag == 1], pi)\n', (739, 778), False, 'from XGB_HMM.form_B_matrix_by_XGB import form_B_matrix_by_XGB\n'), ((817, 870), 'XGB_HMM.predict.self_pred', 'self_pred', (['now_allow_B', '[now_allow_B.shape[0]]', 'A', 'pi'], {}), '(now_allow_B, [now_allow_B.shape[0]], A, pi)\n', (826, 870), False, 'from XGB_HMM.predict import self_pred\n')]
""" Software that detects each of the yellow shapes on the video frames and classifies the shapes into classes: circle, rectangle, triangle. USAGE: python3 shape_detection.py <video path> <output video path> """ import sys import cv2 import imutils import numpy as np from tqdm import tqdm BOX_COLORS = { "triangle": (255, 0, 0), "rectangle": (0, 255, 0), "circle" : (0, 0, 255) } def get_contours(image: np.ndarray) -> (np.ndarray, np.ndarray): """ Gets edge and yellow contours from an image. Parameters ---------- image: np.ndarray Target image. Returns ------- edges_filled: np.ndarray Detected edges in an image as a boolean 2D map. yellow_contours: np.ndarray Detected yellow contours in an image. """ # get edges edges = cv2.Canny(image, 10, 255) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) edges_thresh = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel) edges_filled = np.zeros_like(edges_thresh) edges_contours = cv2.findContours(edges_thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) edges_contours = imutils.grab_contours(edges_contours) for cont in edges_contours: cv2.drawContours(edges_filled, [cont], 0, 255, -1) # select yellow color hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) yellow_lower = np.array([30, 10, 10]) yellow_upper = np.array([90, 255, 255]) mask_yellow = cv2.inRange(hsv, yellow_lower, yellow_upper) yellow_output = cv2.bitwise_and(image, image, mask=mask_yellow) gray = cv2.cvtColor(yellow_output, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[1] yellow_contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) yellow_contours = imutils.grab_contours(yellow_contours) return edges_filled, yellow_contours def detect(tcontour: np.ndarray) -> str: """ Detects shape by a contour. Parameters ---------- tcontour: np.ndarray Target contour. Returns ------- shape: str Detected shape of a contour. """ shape = "unidentified" peri = cv2.arcLength(tcontour, True) approx = cv2.approxPolyDP(tcontour, 0.04 * peri, True) if len(approx) == 3: shape = "triangle" elif len(approx) == 4: shape = "rectangle" else: shape = "circle" return shape if __name__ == "__main__": if len(sys.argv) != 3: print(f'USAGE: python3 {sys.argv[0]} <video path> <output video path>') sys.exit() VIDEO_PATH = sys.argv[1] OUTPUT_PATH = sys.argv[2] # open input and output videos cap = cv2.VideoCapture(VIDEO_PATH) width = int(cap.get(3)) height = int(cap.get(4)) fps = cap.get(5) frame_count = int(cap.get(7)) out = cv2.VideoWriter(OUTPUT_PATH, -1, fps, (width, height)) if not cap.isOpened() or not out.isOpened(): raise RuntimeError("video file cannot be opened") print(f'\nVideo "{VIDEO_PATH}" opened for processing\n') for i in tqdm(range(frame_count), desc="Processing video"): ret, frame = cap.read() if ret is True: # preprocess frame resized = imutils.resize(frame, width=300) ratio = frame.shape[0] / float(resized.shape[0]) blurred = cv2.GaussianBlur(resized, (3, 3), 0) edges_map, contours = get_contours(blurred) for contour in contours: if cv2.contourArea(contour) > 50: # get contour's center M = cv2.moments(contour) rel_cX = int(M["m10"] / M["m00"]) rel_cY = int(M["m01"] / M["m00"]) if edges_map[rel_cY, rel_cX]: SHAPE = detect(contour) # get exact coordinates contour = contour.astype("float") contour *= ratio cX = int((M["m10"] / M["m00"]) * ratio) cY = int((M["m01"] / M["m00"]) * ratio) contour = contour.astype("int") # draw contour and shape name cv2.drawContours(frame, [contour], -1, BOX_COLORS[SHAPE], 2) cv2.putText(frame, SHAPE, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) out.write(frame) else: break cap.release() out.release() print(f'\nVideo "{OUTPUT_PATH}" successfully saved')
[ "numpy.array", "cv2.approxPolyDP", "sys.exit", "cv2.threshold", "cv2.arcLength", "numpy.zeros_like", "cv2.VideoWriter", "cv2.contourArea", "imutils.grab_contours", "cv2.drawContours", "cv2.putText", "cv2.morphologyEx", "cv2.cvtColor", "cv2.moments", "cv2.Canny", "cv2.GaussianBlur", "cv2.inRange", "cv2.bitwise_and", "imutils.resize", "cv2.VideoCapture", "cv2.getStructuringElement" ]
[((821, 846), 'cv2.Canny', 'cv2.Canny', (['image', '(10)', '(255)'], {}), '(image, 10, 255)\n', (830, 846), False, 'import cv2\n'), ((860, 912), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(3, 3)'], {}), '(cv2.MORPH_ELLIPSE, (3, 3))\n', (885, 912), False, 'import cv2\n'), ((932, 980), 'cv2.morphologyEx', 'cv2.morphologyEx', (['edges', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(edges, cv2.MORPH_CLOSE, kernel)\n', (948, 980), False, 'import cv2\n'), ((1000, 1027), 'numpy.zeros_like', 'np.zeros_like', (['edges_thresh'], {}), '(edges_thresh)\n', (1013, 1027), True, 'import numpy as np\n'), ((1190, 1227), 'imutils.grab_contours', 'imutils.grab_contours', (['edges_contours'], {}), '(edges_contours)\n', (1211, 1227), False, 'import imutils\n'), ((1356, 1394), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2HSV'], {}), '(image, cv2.COLOR_BGR2HSV)\n', (1368, 1394), False, 'import cv2\n'), ((1414, 1436), 'numpy.array', 'np.array', (['[30, 10, 10]'], {}), '([30, 10, 10])\n', (1422, 1436), True, 'import numpy as np\n'), ((1456, 1480), 'numpy.array', 'np.array', (['[90, 255, 255]'], {}), '([90, 255, 255])\n', (1464, 1480), True, 'import numpy as np\n'), ((1499, 1543), 'cv2.inRange', 'cv2.inRange', (['hsv', 'yellow_lower', 'yellow_upper'], {}), '(hsv, yellow_lower, yellow_upper)\n', (1510, 1543), False, 'import cv2\n'), ((1564, 1611), 'cv2.bitwise_and', 'cv2.bitwise_and', (['image', 'image'], {'mask': 'mask_yellow'}), '(image, image, mask=mask_yellow)\n', (1579, 1611), False, 'import cv2\n'), ((1623, 1670), 'cv2.cvtColor', 'cv2.cvtColor', (['yellow_output', 'cv2.COLOR_BGR2GRAY'], {}), '(yellow_output, cv2.COLOR_BGR2GRAY)\n', (1635, 1670), False, 'import cv2\n'), ((1894, 1932), 'imutils.grab_contours', 'imutils.grab_contours', (['yellow_contours'], {}), '(yellow_contours)\n', (1915, 1932), False, 'import imutils\n'), ((2259, 2288), 'cv2.arcLength', 'cv2.arcLength', (['tcontour', '(True)'], {}), '(tcontour, True)\n', (2272, 2288), False, 'import cv2\n'), ((2302, 2347), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['tcontour', '(0.04 * peri)', '(True)'], {}), '(tcontour, 0.04 * peri, True)\n', (2318, 2347), False, 'import cv2\n'), ((2767, 2795), 'cv2.VideoCapture', 'cv2.VideoCapture', (['VIDEO_PATH'], {}), '(VIDEO_PATH)\n', (2783, 2795), False, 'import cv2\n'), ((2918, 2972), 'cv2.VideoWriter', 'cv2.VideoWriter', (['OUTPUT_PATH', '(-1)', 'fps', '(width, height)'], {}), '(OUTPUT_PATH, -1, fps, (width, height))\n', (2933, 2972), False, 'import cv2\n'), ((1268, 1318), 'cv2.drawContours', 'cv2.drawContours', (['edges_filled', '[cont]', '(0)', '(255)', '(-1)'], {}), '(edges_filled, [cont], 0, 255, -1)\n', (1284, 1318), False, 'import cv2\n'), ((1684, 1731), 'cv2.threshold', 'cv2.threshold', (['gray', '(60)', '(255)', 'cv2.THRESH_BINARY'], {}), '(gray, 60, 255, cv2.THRESH_BINARY)\n', (1697, 1731), False, 'import cv2\n'), ((2651, 2661), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2659, 2661), False, 'import sys\n'), ((3316, 3348), 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(300)'}), '(frame, width=300)\n', (3330, 3348), False, 'import imutils\n'), ((3432, 3468), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['resized', '(3, 3)', '(0)'], {}), '(resized, (3, 3), 0)\n', (3448, 3468), False, 'import cv2\n'), ((3581, 3605), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (3596, 3605), False, 'import cv2\n'), ((3680, 3700), 'cv2.moments', 'cv2.moments', (['contour'], {}), '(contour)\n', (3691, 3700), False, 'import cv2\n'), ((4318, 4378), 'cv2.drawContours', 'cv2.drawContours', (['frame', '[contour]', '(-1)', 'BOX_COLORS[SHAPE]', '(2)'], {}), '(frame, [contour], -1, BOX_COLORS[SHAPE], 2)\n', (4334, 4378), False, 'import cv2\n'), ((4403, 4494), 'cv2.putText', 'cv2.putText', (['frame', 'SHAPE', '(cX, cY)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', '(255, 255, 255)', '(2)'], {}), '(frame, SHAPE, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, \n 255, 255), 2)\n', (4414, 4494), False, 'import cv2\n')]
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=invalid-name,missing-docstring from test.python.common import QiskitTestCase import json import unittest import numpy as np from numpy.linalg import norm import qiskit import qiskit._compiler from qiskit import ClassicalRegister from qiskit import QuantumCircuit from qiskit import QuantumJob from qiskit import QuantumRegister from qiskit.backends.local.qasm_simulator_cpp import (QasmSimulatorCpp, cx_error_matrix, x90_error_matrix) class TestLocalQasmSimulatorCpp(QiskitTestCase): """ Test job_processor module. """ def setUp(self): self.seed = 88 self.qasm_filename = self._get_resource_path('qasm/example.qasm') with open(self.qasm_filename, 'r') as qasm_file: self.qasm_text = qasm_file.read() self.qasm_ast = qiskit.qasm.Qasm(data=self.qasm_text).parse() self.qasm_be = qiskit.unroll.CircuitBackend(['u1', 'u2', 'u3', 'id', 'cx']) self.qasm_circ = qiskit.unroll.Unroller(self.qasm_ast, self.qasm_be).execute() qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qc = qc # create qobj compiled_circuit1 = qiskit._compiler.compile_circuit(self.qc, format='json') compiled_circuit2 = qiskit._compiler.compile_circuit(self.qasm_circ, format='json') self.qobj = {'id': 'test_qobj', 'config': { 'max_credits': 3, 'shots': 2000, 'backend_name': 'local_qasm_simulator_cpp', 'seed': 1111 }, 'circuits': [ { 'name': 'test_circuit1', 'compiled_circuit': compiled_circuit1, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, }, { 'name': 'test_circuit2', 'compiled_circuit': compiled_circuit2, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, } ]} # Simulator backend try: self.backend = QasmSimulatorCpp() except FileNotFoundError as fnferr: raise unittest.SkipTest( 'cannot find {} in path'.format(fnferr)) self.q_job = QuantumJob(self.qobj, backend=self.backend, preformatted=True) def test_x90_coherent_error_matrix(self): X90 = np.array([[1, -1j], [-1j, 1]]) / np.sqrt(2) U = x90_error_matrix(0., 0.).dot(X90) target = X90 self.assertAlmostEqual(norm(U - target), 0.0, places=10, msg="identity error matrix") U = x90_error_matrix(np.pi / 2., 0.).dot(X90) target = -1j * np.array([[0, 1], [1, 0]]) self.assertAlmostEqual(norm(U - target), 0.0, places=10) U = x90_error_matrix(0., np.pi / 2.).dot(X90) target = np.array([[1., -1], [1, 1.]]) / np.sqrt(2.) self.assertAlmostEqual(norm(U - target), 0.0, places=10) U = x90_error_matrix(np.pi / 2, np.pi / 2.).dot(X90) target = np.array([[0., -1], [1, 0.]]) self.assertAlmostEqual(norm(U - target), 0.0, places=10) U = x90_error_matrix(0.02, -0.03) self.assertAlmostEqual(norm(U.dot(U.conj().T) - np.eye(2)), 0.0, places=10, msg="Test error matrix is unitary") def test_cx_coherent_error_matrix(self): CX = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]) U = cx_error_matrix(0., 0.).dot(CX) target = CX self.assertAlmostEqual(norm(U - target), 0.0, places=10, msg="identity error matrix") U = cx_error_matrix(np.pi / 2., 0.).dot(CX) target = np.array([[1, 0, 1j, 0], [0, -1j, 0, 1], [1j, 0, 1, 0], [0, 1, 0, -1j]]) / np.sqrt(2) self.assertAlmostEqual(norm(U - target), 0.0, places=10) U = cx_error_matrix(0.03, -0.04) self.assertAlmostEqual(norm(U.dot(U.conj().T) - np.eye(4)), 0.0, places=10, msg="Test error matrix is unitary") def test_run_qobj(self): result = self.backend.run(self.q_job).result() shots = self.qobj['config']['shots'] threshold = 0.04 * shots counts = result.get_counts('test_circuit2') target = {'100 100': shots / 8, '011 011': shots / 8, '101 101': shots / 8, '111 111': shots / 8, '000 000': shots / 8, '010 010': shots / 8, '110 110': shots / 8, '001 001': shots / 8} self.assertDictAlmostEqual(counts, target, threshold) def test_qobj_measure_opt(self): filename = self._get_resource_path('qobj/cpp_measure_opt.json') with open(filename, 'r') as file: q_job = QuantumJob(json.load(file), backend=self.backend, preformatted=True) result = self.backend.run(q_job).result() shots = q_job.qobj['config']['shots'] expected_data = { 'measure (opt)': { 'deterministic': True, 'counts': {'00': shots}, 'statevector': np.array([1, 0, 0, 0])}, 'x0 measure (opt)': { 'deterministic': True, 'counts': {'01': shots}, 'statevector': np.array([0, 1, 0, 0])}, 'x1 measure (opt)': { 'deterministic': True, 'counts': {'10': shots}, 'statevector': np.array([0, 0, 1, 0])}, 'x0 x1 measure (opt)': { 'deterministic': True, 'counts': {'11': shots}, 'statevector': np.array([0, 0, 0, 1])}, 'y0 measure (opt)': { 'deterministic': True, 'counts': {'01': shots}, 'statevector': np.array([0, 1j, 0, 0])}, 'y1 measure (opt)': { 'deterministic': True, 'counts': {'10': shots}, 'statevector': np.array([0, 0, 1j, 0])}, 'y0 y1 measure (opt)': { 'deterministic': True, 'counts': {'11': shots}, 'statevector': np.array([0, 0, 0, -1j])}, 'h0 measure (opt)': { 'deterministic': False, 'counts': {'00': shots / 2, '01': shots / 2}, 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h1 measure (opt)': { 'deterministic': False, 'counts': {'00': shots / 2, '10': shots / 2}, 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h0 h1 measure (opt)': { 'deterministic': False, 'counts': {'00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4}, 'statevector': np.array([0.5, 0.5, 0.5, 0.5])}, 'bell measure (opt)': { 'deterministic': False, 'counts': {'00': shots / 2, '11': shots / 2}, 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])} } for name in expected_data: # Check counts: counts = result.get_counts(name) expected_counts = expected_data[name]['counts'] if expected_data[name].get('deterministic', False): self.assertEqual(counts, expected_counts, msg=name + ' counts') else: threshold = 0.04 * shots self.assertDictAlmostEqual(counts, expected_counts, threshold, msg=name + 'counts') # Check snapshot snapshots = result.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 3, msg=name + ' snapshot length') state = snapshots['0']['statevector'][0] expected_state = expected_data[name]['statevector'] fidelity = np.abs(expected_state.dot(state.conj())) ** 2 self.assertAlmostEqual(fidelity, 1.0, places=10, msg=name + ' snapshot fidelity') rho = snapshots['0']['density_matrix'] self.assertAlmostEqual(np.trace(rho), 1) prob = snapshots['0']['probabilities'] self.assertAlmostEqual(np.sum(prob), 1) def test_qobj_measure_opt_flag(self): filename = self._get_resource_path('qobj/cpp_measure_opt_flag.json') with open(filename, 'r') as file: q_job = QuantumJob(json.load(file), backend=self.backend, preformatted=True) result = self.backend.run(q_job).result() shots = q_job.qobj['config']['shots'] sampled_measurements = { 'measure (sampled)': True, 'trivial (sampled)': True, 'reset1 (shots)': False, 'reset2 (shots)': False, 'reset3 (shots)': False, 'gate1 (shots)': False, 'gate2 (shots)': False, 'gate3 (shots)': False, 'gate4 (shots)': False } for name in sampled_measurements: snapshots = result.get_snapshots(name) # Check snapshot keys self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') # Check number of snapshots # there should be 1 for measurement sampling optimization # and there should be >1 for each shot beign simulated. num_snapshots = len(snapshots['0'].get('statevector', [])) if sampled_measurements[name] is True: self.assertEqual(num_snapshots, 1, msg=name + ' snapshot length') else: self.assertEqual(num_snapshots, shots, msg=name + ' snapshot length') def test_qobj_reset(self): filename = self._get_resource_path('qobj/cpp_reset.json') with open(filename, 'r') as file: q_job = QuantumJob(json.load(file), backend=self.backend, preformatted=True) result = self.backend.run(q_job).result() expected_data = { 'reset': {'statevector': np.array([1, 0])}, 'x reset': {'statevector': np.array([1, 0])}, 'y reset': {'statevector': np.array([1, 0])}, 'h reset': {'statevector': np.array([1, 0])} } for name in expected_data: # Check snapshot is |0> state snapshots = result.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = snapshots['0']['statevector'][0] expected_state = expected_data[name]['statevector'] fidelity = np.abs(expected_state.dot(state.conj())) ** 2 self.assertAlmostEqual(fidelity, 1.0, places=10, msg=name + ' snapshot fidelity') def test_qobj_save_load(self): filename = self._get_resource_path('qobj/cpp_save_load.json') with open(filename, 'r') as file: q_job = QuantumJob(json.load(file), backend=self.backend, preformatted=True) result = self.backend.run(q_job).result() snapshots = result.get_snapshots('save_command') self.assertEqual(set(snapshots), {'0', '1', '10', '11'}, msg='snapshot keys') state0 = snapshots['0']['statevector'][0] state10 = snapshots['10']['statevector'][0] state1 = snapshots['1']['statevector'][0] state11 = snapshots['11']['statevector'][0] expected_state0 = np.array([1, 0]) expected_state10 = np.array([1 / np.sqrt(2), 1 / np.sqrt(2)]) fidelity0 = np.abs(expected_state0.dot(state0.conj())) ** 2 fidelity1 = np.abs(expected_state0.dot(state1.conj())) ** 2 fidelity10 = np.abs(expected_state10.dot(state10.conj())) ** 2 fidelity11 = np.abs(expected_state10.dot(state11.conj())) ** 2 self.assertAlmostEqual(fidelity0, 1.0, places=10, msg='snapshot 0') self.assertAlmostEqual(fidelity10, 1.0, places=10, msg='snapshot 0') self.assertAlmostEqual(fidelity1, 1.0, places=10, msg='snapshot 0') self.assertAlmostEqual(fidelity11, 1.0, places=10, msg='snapshot 0') def test_qobj_single_qubit_gates(self): filename = self._get_resource_path('qobj/cpp_single_qubit_gates.json') with open(filename, 'r') as file: q_job = QuantumJob(json.load(file), backend=self.backend, preformatted=True) result = self.backend.run(q_job).result() expected_data = { 'snapshot': { 'statevector': np.array([1, 0])}, 'id(U)': { 'statevector': np.array([1, 0])}, 'id(u3)': { 'statevector': np.array([1, 0])}, 'id(u1)': { 'statevector': np.array([1, 0])}, 'id(direct)': { 'statevector': np.array([1, 0])}, 'x(U)': { 'statevector': np.array([0, 1])}, 'x(u3)': { 'statevector': np.array([0, 1])}, 'x(direct)': { 'statevector': np.array([0, 1])}, 'y(U)': { 'statevector': np.array([0, 1j])}, 'y(u3)': { 'statevector': np.array([0, 1j])}, 'y(direct)': { 'statevector': np.array([0, 1j])}, 'h(U)': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])}, 'h(u3)': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])}, 'h(u2)': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])}, 'h(direct)': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])}, 'h(direct) z(U)': { 'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])}, 'h(direct) z(u3)': { 'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])}, 'h(direct) z(u1)': { 'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])}, 'h(direct) z(direct)': { 'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])}, 'h(direct) s(U)': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])}, 'h(direct) s(u3)': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])}, 'h(direct) s(u1)': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])}, 'h(direct) s(direct)': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])}, 'h(direct) sdg(U)': { 'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])}, 'h(direct) sdg(u3)': { 'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])}, 'h(direct) sdg(u1)': { 'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])}, 'h(direct) sdg(direct)': { 'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])}, 'h(direct) t(U)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])}, 'h(direct) t(u3)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])}, 'h(direct) t(u1)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])}, 'h(direct) t(direct)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])}, 'h(direct) tdg(U)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])}, 'h(direct) tdg(u3)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])}, 'h(direct) tdg(u1)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])}, 'h(direct) tdg(direct)': { 'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])} } for name in expected_data: # Check snapshot snapshots = result.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = snapshots['0']['statevector'][0] expected_state = expected_data[name]['statevector'] inner_product = expected_state.dot(state.conj()) self.assertAlmostEqual(inner_product, 1.0, places=10, msg=name + ' snapshot fidelity') def test_qobj_two_qubit_gates(self): filename = self._get_resource_path('qobj/cpp_two_qubit_gates.json') with open(filename, 'r') as file: q_job = QuantumJob(json.load(file), backend=self.backend, preformatted=True) result = self.backend.run(q_job).result() expected_data = { 'h0 CX01': { 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])}, 'h0 CX10': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h1 CX01': { 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h1 CX10': { 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])}, 'h0 cx01': { 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])}, 'h0 cx10': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h1 cx01': { 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h1 cx10': { 'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])}, 'h0 cz01': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h0 cz10': { 'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])}, 'h1 cz01': { 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h1 cz10': { 'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])}, 'h0 h1 cz01': {'statevector': np.array([0.5, 0.5, 0.5, -0.5])}, 'h0 h1 cz10': {'statevector': np.array([0.5, 0.5, 0.5, -0.5])}, 'h0 rzz01': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2), 0, 0])}, 'h0 rzz10': { 'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2), 0, 0])}, 'h1 rzz01': { 'statevector': np.array([1 / np.sqrt(2), 0, 1j / np.sqrt(2), 0])}, 'h1 rzz10': { 'statevector': np.array([1 / np.sqrt(2), 0, 1j / np.sqrt(2), 0])}, 'h0 h1 rzz01': {'statevector': np.array([0.5, 0.5j, 0.5j, 0.5])}, 'h0 h1 rzz10': {'statevector': np.array([0.5, 0.5j, 0.5j, 0.5])} } for name in expected_data: # Check snapshot snapshots = result.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = snapshots['0']['statevector'][0] expected_state = expected_data[name]['statevector'] fidelity = np.abs(expected_state.dot(state.conj())) ** 2 self.assertAlmostEqual(fidelity, 1.0, places=10, msg=name + ' snapshot fidelity') def test_conditionals(self): filename = self._get_resource_path('qobj/cpp_conditionals.json') with open(filename, 'r') as file: q_job = QuantumJob(json.load(file), backend=self.backend, preformatted=True) result = self.backend.run(q_job).result() expected_data = { 'single creg (c0=0)': { 'statevector': np.array([1, 0, 0, 0])}, 'single creg (c0=1)': { 'statevector': np.array([0, 0, 0, 1])}, 'two creg (c1=0)': { 'statevector': np.array([1, 0, 0, 0])}, 'two creg (c1=1)': { 'statevector': np.array([0, 0, 0, 1])} } for name in expected_data: # Check snapshot snapshots = result.get_snapshots(name) self.assertEqual(set(snapshots), {'0'}, msg=name + ' snapshot keys') self.assertEqual(len(snapshots['0']), 1, msg=name + ' snapshot length') state = snapshots['0']['statevector'][0] expected_state = expected_data[name]['statevector'] fidelity = np.abs(expected_state.dot(state.conj())) ** 2 self.assertAlmostEqual(fidelity, 1.0, places=10, msg=name + ' snapshot fidelity') if __name__ == '__main__': unittest.main(verbosity=2)
[ "numpy.trace", "numpy.sqrt", "numpy.array", "qiskit.qasm.Qasm", "numpy.linalg.norm", "unittest.main", "qiskit.QuantumJob", "qiskit.backends.local.qasm_simulator_cpp.x90_error_matrix", "qiskit.QuantumCircuit", "qiskit.backends.local.qasm_simulator_cpp.cx_error_matrix", "numpy.eye", "qiskit._compiler.compile_circuit", "qiskit.unroll.CircuitBackend", "qiskit.ClassicalRegister", "qiskit.backends.local.qasm_simulator_cpp.QasmSimulatorCpp", "json.load", "numpy.sum", "qiskit.unroll.Unroller", "qiskit.QuantumRegister" ]
[((22521, 22547), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (22534, 22547), False, 'import unittest\n'), ((1345, 1368), 'qiskit.QuantumRegister', 'QuantumRegister', (['(2)', '"""q"""'], {}), "(2, 'q')\n", (1360, 1368), False, 'from qiskit import QuantumRegister\n'), ((1382, 1407), 'qiskit.ClassicalRegister', 'ClassicalRegister', (['(2)', '"""c"""'], {}), "(2, 'c')\n", (1399, 1407), False, 'from qiskit import ClassicalRegister\n'), ((1421, 1443), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qr', 'cr'], {}), '(qr, cr)\n', (1435, 1443), False, 'from qiskit import QuantumCircuit\n'), ((1568, 1624), 'qiskit._compiler.compile_circuit', 'qiskit._compiler.compile_circuit', (['self.qc'], {'format': '"""json"""'}), "(self.qc, format='json')\n", (1600, 1624), False, 'import qiskit\n'), ((1653, 1716), 'qiskit._compiler.compile_circuit', 'qiskit._compiler.compile_circuit', (['self.qasm_circ'], {'format': '"""json"""'}), "(self.qasm_circ, format='json')\n", (1685, 1716), False, 'import qiskit\n'), ((2877, 2939), 'qiskit.QuantumJob', 'QuantumJob', (['self.qobj'], {'backend': 'self.backend', 'preformatted': '(True)'}), '(self.qobj, backend=self.backend, preformatted=True)\n', (2887, 2939), False, 'from qiskit import QuantumJob\n'), ((3728, 3759), 'numpy.array', 'np.array', (['[[0.0, -1], [1, 0.0]]'], {}), '([[0.0, -1], [1, 0.0]])\n', (3736, 3759), True, 'import numpy as np\n'), ((3835, 3864), 'qiskit.backends.local.qasm_simulator_cpp.x90_error_matrix', 'x90_error_matrix', (['(0.02)', '(-0.03)'], {}), '(0.02, -0.03)\n', (3851, 3864), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((4075, 4141), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]'], {}), '([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])\n', (4083, 4141), True, 'import numpy as np\n'), ((4644, 4672), 'qiskit.backends.local.qasm_simulator_cpp.cx_error_matrix', 'cx_error_matrix', (['(0.03)', '(-0.04)'], {}), '(0.03, -0.04)\n', (4659, 4672), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((12868, 12884), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (12876, 12884), True, 'import numpy as np\n'), ((1180, 1240), 'qiskit.unroll.CircuitBackend', 'qiskit.unroll.CircuitBackend', (["['u1', 'u2', 'u3', 'id', 'cx']"], {}), "(['u1', 'u2', 'u3', 'id', 'cx'])\n", (1208, 1240), False, 'import qiskit\n'), ((2698, 2716), 'qiskit.backends.local.qasm_simulator_cpp.QasmSimulatorCpp', 'QasmSimulatorCpp', ([], {}), '()\n', (2714, 2716), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((3065, 3099), 'numpy.array', 'np.array', (['[[1, -1.0j], [-1.0j, 1]]'], {}), '([[1, -1.0j], [-1.0j, 1]])\n', (3073, 3099), True, 'import numpy as np\n'), ((3098, 3108), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (3105, 3108), True, 'import numpy as np\n'), ((3207, 3223), 'numpy.linalg.norm', 'norm', (['(U - target)'], {}), '(U - target)\n', (3211, 3223), False, 'from numpy.linalg import norm\n'), ((3378, 3404), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (3386, 3404), True, 'import numpy as np\n'), ((3436, 3452), 'numpy.linalg.norm', 'norm', (['(U - target)'], {}), '(U - target)\n', (3440, 3452), False, 'from numpy.linalg import norm\n'), ((3541, 3572), 'numpy.array', 'np.array', (['[[1.0, -1], [1, 1.0]]'], {}), '([[1.0, -1], [1, 1.0]])\n', (3549, 3572), True, 'import numpy as np\n'), ((3573, 3585), 'numpy.sqrt', 'np.sqrt', (['(2.0)'], {}), '(2.0)\n', (3580, 3585), True, 'import numpy as np\n'), ((3616, 3632), 'numpy.linalg.norm', 'norm', (['(U - target)'], {}), '(U - target)\n', (3620, 3632), False, 'from numpy.linalg import norm\n'), ((3789, 3805), 'numpy.linalg.norm', 'norm', (['(U - target)'], {}), '(U - target)\n', (3793, 3805), False, 'from numpy.linalg import norm\n'), ((4237, 4253), 'numpy.linalg.norm', 'norm', (['(U - target)'], {}), '(U - target)\n', (4241, 4253), False, 'from numpy.linalg import norm\n'), ((4400, 4485), 'numpy.array', 'np.array', (['[[1, 0, 1.0j, 0], [0, -1.0j, 0, 1], [1.0j, 0, 1, 0], [0, 1, 0, -1.0j]]'], {}), '([[1, 0, 1.0j, 0], [0, -1.0j, 0, 1], [1.0j, 0, 1, 0], [0, 1, 0, -1.0j]]\n )\n', (4408, 4485), True, 'import numpy as np\n'), ((4556, 4566), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4563, 4566), True, 'import numpy as np\n'), ((4598, 4614), 'numpy.linalg.norm', 'norm', (['(U - target)'], {}), '(U - target)\n', (4602, 4614), False, 'from numpy.linalg import norm\n'), ((3121, 3147), 'qiskit.backends.local.qasm_simulator_cpp.x90_error_matrix', 'x90_error_matrix', (['(0.0)', '(0.0)'], {}), '(0.0, 0.0)\n', (3137, 3147), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((3313, 3347), 'qiskit.backends.local.qasm_simulator_cpp.x90_error_matrix', 'x90_error_matrix', (['(np.pi / 2.0)', '(0.0)'], {}), '(np.pi / 2.0, 0.0)\n', (3329, 3347), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((3482, 3516), 'qiskit.backends.local.qasm_simulator_cpp.x90_error_matrix', 'x90_error_matrix', (['(0.0)', '(np.pi / 2.0)'], {}), '(0.0, np.pi / 2.0)\n', (3498, 3516), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((3662, 3702), 'qiskit.backends.local.qasm_simulator_cpp.x90_error_matrix', 'x90_error_matrix', (['(np.pi / 2)', '(np.pi / 2.0)'], {}), '(np.pi / 2, np.pi / 2.0)\n', (3678, 3702), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((4154, 4179), 'qiskit.backends.local.qasm_simulator_cpp.cx_error_matrix', 'cx_error_matrix', (['(0.0)', '(0.0)'], {}), '(0.0, 0.0)\n', (4169, 4179), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((4343, 4376), 'qiskit.backends.local.qasm_simulator_cpp.cx_error_matrix', 'cx_error_matrix', (['(np.pi / 2.0)', '(0.0)'], {}), '(np.pi / 2.0, 0.0)\n', (4358, 4376), False, 'from qiskit.backends.local.qasm_simulator_cpp import QasmSimulatorCpp, cx_error_matrix, x90_error_matrix\n'), ((5532, 5547), 'json.load', 'json.load', (['file'], {}), '(file)\n', (5541, 5547), False, 'import json\n'), ((5916, 5938), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (5924, 5938), True, 'import numpy as np\n'), ((6086, 6108), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (6094, 6108), True, 'import numpy as np\n'), ((6256, 6278), 'numpy.array', 'np.array', (['[0, 0, 1, 0]'], {}), '([0, 0, 1, 0])\n', (6264, 6278), True, 'import numpy as np\n'), ((6429, 6451), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (6437, 6451), True, 'import numpy as np\n'), ((6599, 6624), 'numpy.array', 'np.array', (['[0, 1.0j, 0, 0]'], {}), '([0, 1.0j, 0, 0])\n', (6607, 6624), True, 'import numpy as np\n'), ((6770, 6795), 'numpy.array', 'np.array', (['[0, 0, 1.0j, 0]'], {}), '([0, 0, 1.0j, 0])\n', (6778, 6795), True, 'import numpy as np\n'), ((6944, 6970), 'numpy.array', 'np.array', (['[0, 0, 0, -1.0j]'], {}), '([0, 0, 0, -1.0j])\n', (6952, 6970), True, 'import numpy as np\n'), ((7638, 7668), 'numpy.array', 'np.array', (['[0.5, 0.5, 0.5, 0.5]'], {}), '([0.5, 0.5, 0.5, 0.5])\n', (7646, 7668), True, 'import numpy as np\n'), ((9152, 9165), 'numpy.trace', 'np.trace', (['rho'], {}), '(rho)\n', (9160, 9165), True, 'import numpy as np\n'), ((9256, 9268), 'numpy.sum', 'np.sum', (['prob'], {}), '(prob)\n', (9262, 9268), True, 'import numpy as np\n'), ((9466, 9481), 'json.load', 'json.load', (['file'], {}), '(file)\n', (9475, 9481), False, 'import json\n'), ((11018, 11033), 'json.load', 'json.load', (['file'], {}), '(file)\n', (11027, 11033), False, 'import json\n'), ((11251, 11267), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (11259, 11267), True, 'import numpy as np\n'), ((11309, 11325), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (11317, 11325), True, 'import numpy as np\n'), ((11367, 11383), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (11375, 11383), True, 'import numpy as np\n'), ((11425, 11441), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (11433, 11441), True, 'import numpy as np\n'), ((12298, 12313), 'json.load', 'json.load', (['file'], {}), '(file)\n', (12307, 12313), False, 'import json\n'), ((13737, 13752), 'json.load', 'json.load', (['file'], {}), '(file)\n', (13746, 13752), False, 'import json\n'), ((13990, 14006), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (13998, 14006), True, 'import numpy as np\n'), ((14063, 14079), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (14071, 14079), True, 'import numpy as np\n'), ((14137, 14153), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (14145, 14153), True, 'import numpy as np\n'), ((14211, 14227), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (14219, 14227), True, 'import numpy as np\n'), ((14289, 14305), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (14297, 14305), True, 'import numpy as np\n'), ((14361, 14377), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (14369, 14377), True, 'import numpy as np\n'), ((14434, 14450), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (14442, 14450), True, 'import numpy as np\n'), ((14511, 14527), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (14519, 14527), True, 'import numpy as np\n'), ((14583, 14602), 'numpy.array', 'np.array', (['[0, 1.0j]'], {}), '([0, 1.0j])\n', (14591, 14602), True, 'import numpy as np\n'), ((14657, 14676), 'numpy.array', 'np.array', (['[0, 1.0j]'], {}), '([0, 1.0j])\n', (14665, 14676), True, 'import numpy as np\n'), ((14735, 14754), 'numpy.array', 'np.array', (['[0, 1.0j]'], {}), '([0, 1.0j])\n', (14743, 14754), True, 'import numpy as np\n'), ((18200, 18215), 'json.load', 'json.load', (['file'], {}), '(file)\n', (18209, 18215), False, 'import json\n'), ((19722, 19753), 'numpy.array', 'np.array', (['[0.5, 0.5, 0.5, -0.5]'], {}), '([0.5, 0.5, 0.5, -0.5])\n', (19730, 19753), True, 'import numpy as np\n'), ((19798, 19829), 'numpy.array', 'np.array', (['[0.5, 0.5, 0.5, -0.5]'], {}), '([0.5, 0.5, 0.5, -0.5])\n', (19806, 19829), True, 'import numpy as np\n'), ((20311, 20343), 'numpy.array', 'np.array', (['[0.5, 0.5j, 0.5j, 0.5]'], {}), '([0.5, 0.5j, 0.5j, 0.5])\n', (20319, 20343), True, 'import numpy as np\n'), ((20389, 20421), 'numpy.array', 'np.array', (['[0.5, 0.5j, 0.5j, 0.5]'], {}), '([0.5, 0.5j, 0.5j, 0.5])\n', (20397, 20421), True, 'import numpy as np\n'), ((21267, 21282), 'json.load', 'json.load', (['file'], {}), '(file)\n', (21276, 21282), False, 'import json\n'), ((21530, 21552), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (21538, 21552), True, 'import numpy as np\n'), ((21622, 21644), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (21630, 21644), True, 'import numpy as np\n'), ((21711, 21733), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (21719, 21733), True, 'import numpy as np\n'), ((21800, 21822), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (21808, 21822), True, 'import numpy as np\n'), ((1107, 1144), 'qiskit.qasm.Qasm', 'qiskit.qasm.Qasm', ([], {'data': 'self.qasm_text'}), '(data=self.qasm_text)\n', (1123, 1144), False, 'import qiskit\n'), ((1270, 1321), 'qiskit.unroll.Unroller', 'qiskit.unroll.Unroller', (['self.qasm_ast', 'self.qasm_be'], {}), '(self.qasm_ast, self.qasm_be)\n', (1292, 1321), False, 'import qiskit\n'), ((3921, 3930), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (3927, 3930), True, 'import numpy as np\n'), ((4729, 4738), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (4735, 4738), True, 'import numpy as np\n'), ((12926, 12936), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (12933, 12936), True, 'import numpy as np\n'), ((12942, 12952), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (12949, 12952), True, 'import numpy as np\n'), ((7152, 7162), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7159, 7162), True, 'import numpy as np\n'), ((7168, 7178), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7175, 7178), True, 'import numpy as np\n'), ((7370, 7380), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7377, 7380), True, 'import numpy as np\n'), ((7389, 7399), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7396, 7399), True, 'import numpy as np\n'), ((7854, 7864), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7861, 7864), True, 'import numpy as np\n'), ((7876, 7886), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7883, 7886), True, 'import numpy as np\n'), ((14822, 14832), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (14829, 14832), True, 'import numpy as np\n'), ((14838, 14848), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (14845, 14848), True, 'import numpy as np\n'), ((14921, 14931), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (14928, 14931), True, 'import numpy as np\n'), ((14937, 14947), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (14944, 14947), True, 'import numpy as np\n'), ((15020, 15030), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15027, 15030), True, 'import numpy as np\n'), ((15036, 15046), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15043, 15046), True, 'import numpy as np\n'), ((15123, 15133), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15130, 15133), True, 'import numpy as np\n'), ((15139, 15149), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15146, 15149), True, 'import numpy as np\n'), ((15231, 15241), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15238, 15241), True, 'import numpy as np\n'), ((15248, 15258), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15255, 15258), True, 'import numpy as np\n'), ((15341, 15351), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15348, 15351), True, 'import numpy as np\n'), ((15358, 15368), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15365, 15368), True, 'import numpy as np\n'), ((15451, 15461), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15458, 15461), True, 'import numpy as np\n'), ((15468, 15478), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15475, 15478), True, 'import numpy as np\n'), ((15565, 15575), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15572, 15575), True, 'import numpy as np\n'), ((15582, 15592), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15589, 15592), True, 'import numpy as np\n'), ((15674, 15684), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15681, 15684), True, 'import numpy as np\n'), ((15691, 15701), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15698, 15701), True, 'import numpy as np\n'), ((15784, 15794), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15791, 15794), True, 'import numpy as np\n'), ((15801, 15811), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15808, 15811), True, 'import numpy as np\n'), ((15894, 15904), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15901, 15904), True, 'import numpy as np\n'), ((15911, 15921), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15918, 15921), True, 'import numpy as np\n'), ((16008, 16018), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16015, 16018), True, 'import numpy as np\n'), ((16025, 16035), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16032, 16035), True, 'import numpy as np\n'), ((16119, 16129), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16126, 16129), True, 'import numpy as np\n'), ((16137, 16147), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16144, 16147), True, 'import numpy as np\n'), ((16232, 16242), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16239, 16242), True, 'import numpy as np\n'), ((16250, 16260), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16257, 16260), True, 'import numpy as np\n'), ((16345, 16355), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16352, 16355), True, 'import numpy as np\n'), ((16363, 16373), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16370, 16373), True, 'import numpy as np\n'), ((16462, 16472), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16469, 16472), True, 'import numpy as np\n'), ((16480, 16490), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16487, 16490), True, 'import numpy as np\n'), ((16572, 16582), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16579, 16582), True, 'import numpy as np\n'), ((16677, 16687), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16684, 16687), True, 'import numpy as np\n'), ((16782, 16792), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16789, 16792), True, 'import numpy as np\n'), ((16891, 16901), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16898, 16901), True, 'import numpy as np\n'), ((16997, 17007), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (17004, 17007), True, 'import numpy as np\n'), ((17104, 17114), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (17111, 17114), True, 'import numpy as np\n'), ((17211, 17221), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (17218, 17221), True, 'import numpy as np\n'), ((17322, 17332), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (17329, 17332), True, 'import numpy as np\n'), ((18466, 18476), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18473, 18476), True, 'import numpy as np\n'), ((18488, 18498), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18495, 18498), True, 'import numpy as np\n'), ((18573, 18583), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18580, 18583), True, 'import numpy as np\n'), ((18589, 18599), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18596, 18599), True, 'import numpy as np\n'), ((18680, 18690), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18687, 18690), True, 'import numpy as np\n'), ((18699, 18709), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18706, 18709), True, 'import numpy as np\n'), ((18787, 18797), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18794, 18797), True, 'import numpy as np\n'), ((18809, 18819), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18816, 18819), True, 'import numpy as np\n'), ((18894, 18904), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18901, 18904), True, 'import numpy as np\n'), ((18916, 18926), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18923, 18926), True, 'import numpy as np\n'), ((19001, 19011), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19008, 19011), True, 'import numpy as np\n'), ((19017, 19027), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19024, 19027), True, 'import numpy as np\n'), ((19108, 19118), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19115, 19118), True, 'import numpy as np\n'), ((19127, 19137), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19134, 19137), True, 'import numpy as np\n'), ((19215, 19225), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19222, 19225), True, 'import numpy as np\n'), ((19237, 19247), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19244, 19247), True, 'import numpy as np\n'), ((19322, 19332), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19329, 19332), True, 'import numpy as np\n'), ((19338, 19348), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19345, 19348), True, 'import numpy as np\n'), ((19429, 19439), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19436, 19439), True, 'import numpy as np\n'), ((19445, 19455), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19452, 19455), True, 'import numpy as np\n'), ((19536, 19546), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19543, 19546), True, 'import numpy as np\n'), ((19555, 19565), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19562, 19565), True, 'import numpy as np\n'), ((19643, 19653), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19650, 19653), True, 'import numpy as np\n'), ((19662, 19672), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19669, 19672), True, 'import numpy as np\n'), ((19903, 19913), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19910, 19913), True, 'import numpy as np\n'), ((19920, 19930), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (19927, 19930), True, 'import numpy as np\n'), ((20012, 20022), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (20019, 20022), True, 'import numpy as np\n'), ((20029, 20039), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (20036, 20039), True, 'import numpy as np\n'), ((20121, 20131), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (20128, 20131), True, 'import numpy as np\n'), ((20141, 20151), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (20148, 20151), True, 'import numpy as np\n'), ((20230, 20240), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (20237, 20240), True, 'import numpy as np\n'), ((20250, 20260), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (20257, 20260), True, 'import numpy as np\n')]
import json import random from typing import NamedTuple, Any import numpy from numpy.testing import assert_array_almost_equal, assert_almost_equal import torch import pytest from flaky import flaky from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.common.util import sanitize from allennlp.nn import util from allennlp.models import load_archive class TestNnUtil(AllenNlpTestCase): def test_get_sequence_lengths_from_binary_mask(self): binary_mask = torch.tensor( [ [True, True, True, False, False, False], [True, True, False, False, False, False], [True, True, True, True, True, True], [True, False, False, False, False, False], ] ) lengths = util.get_lengths_from_binary_sequence_mask(binary_mask) numpy.testing.assert_array_equal(lengths.numpy(), numpy.array([3, 2, 6, 1])) def test_get_mask_from_sequence_lengths(self): sequence_lengths = torch.LongTensor([4, 3, 1, 4, 2]) mask = util.get_mask_from_sequence_lengths(sequence_lengths, 5).data.numpy() assert_almost_equal( mask, [[1, 1, 1, 1, 0], [1, 1, 1, 0, 0], [1, 0, 0, 0, 0], [1, 1, 1, 1, 0], [1, 1, 0, 0, 0]], ) def test_get_sequence_lengths_converts_to_long_tensor_and_avoids_variable_overflow(self): # Tests the following weird behaviour in Pytorch 0.1.12 # doesn't happen for our sequence masks: # # mask = torch.ones([260]).bool() # mask.sum() # equals 260. # var_mask = t.a.V(mask) # var_mask.sum() # equals 4, due to 8 bit precision - the sum overflows. binary_mask = torch.ones(2, 260).bool() lengths = util.get_lengths_from_binary_sequence_mask(binary_mask) numpy.testing.assert_array_equal(lengths.data.numpy(), numpy.array([260, 260])) def test_clamp_tensor(self): # Test on uncoalesced sparse tensor i = torch.LongTensor([[0, 1, 1, 0], [2, 0, 2, 2]]) v = torch.FloatTensor([3, 4, -5, 3]) tensor = torch.sparse.FloatTensor(i, v, torch.Size([2, 3])) clamped_tensor = util.clamp_tensor(tensor, minimum=-3, maximum=3).to_dense() assert_almost_equal(clamped_tensor, [[0, 0, 3], [3, 0, -3]]) # Test on coalesced sparse tensor i = torch.LongTensor([[0, 1, 1], [2, 0, 2]]) v = torch.FloatTensor([3, 4, -5]) tensor = torch.sparse.FloatTensor(i, v, torch.Size([2, 3])) clamped_tensor = util.clamp_tensor(tensor, minimum=-3, maximum=3).to_dense() assert_almost_equal(clamped_tensor, [[0, 0, 3], [3, 0, -3]]) # Test on dense tensor tensor = torch.tensor([[5, -4, 3], [-3, 0, -30]]) clamped_tensor = util.clamp_tensor(tensor, minimum=-3, maximum=3) assert_almost_equal(clamped_tensor, [[3, -3, 3], [-3, 0, -3]]) def test_sort_tensor_by_length(self): tensor = torch.rand([5, 7, 9]) tensor[0, 3:, :] = 0 tensor[1, 4:, :] = 0 tensor[2, 1:, :] = 0 tensor[3, 5:, :] = 0 sequence_lengths = torch.LongTensor([3, 4, 1, 5, 7]) sorted_tensor, sorted_lengths, reverse_indices, _ = util.sort_batch_by_length( tensor, sequence_lengths ) # Test sorted indices are padded correctly. numpy.testing.assert_array_equal(sorted_tensor[1, 5:, :].data.numpy(), 0.0) numpy.testing.assert_array_equal(sorted_tensor[2, 4:, :].data.numpy(), 0.0) numpy.testing.assert_array_equal(sorted_tensor[3, 3:, :].data.numpy(), 0.0) numpy.testing.assert_array_equal(sorted_tensor[4, 1:, :].data.numpy(), 0.0) assert sorted_lengths.data.equal(torch.LongTensor([7, 5, 4, 3, 1])) # Test restoration indices correctly recover the original tensor. assert sorted_tensor.index_select(0, reverse_indices).data.equal(tensor.data) def test_get_final_encoder_states(self): encoder_outputs = torch.Tensor( [ [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]], ] ) mask = torch.tensor([[True, True, True], [True, True, False]]) final_states = util.get_final_encoder_states(encoder_outputs, mask, bidirectional=False) assert_almost_equal(final_states.data.numpy(), [[9, 10, 11, 12], [17, 18, 19, 20]]) final_states = util.get_final_encoder_states(encoder_outputs, mask, bidirectional=True) assert_almost_equal(final_states.data.numpy(), [[9, 10, 3, 4], [17, 18, 15, 16]]) def test_masked_softmax_no_mask(self): # Testing the general unmasked 1D case. vector_1d = torch.FloatTensor([[1.0, 2.0, 3.0]]) vector_1d_softmaxed = util.masked_softmax(vector_1d, None).data.numpy() assert_array_almost_equal( vector_1d_softmaxed, numpy.array([[0.090031, 0.244728, 0.665241]]) ) assert_almost_equal(1.0, numpy.sum(vector_1d_softmaxed), decimal=6) vector_1d = torch.FloatTensor([[1.0, 2.0, 5.0]]) vector_1d_softmaxed = util.masked_softmax(vector_1d, None).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.017148, 0.046613, 0.93624]])) # Testing the unmasked 1D case where the input is all 0s. vector_zero = torch.FloatTensor([[0.0, 0.0, 0.0]]) vector_zero_softmaxed = util.masked_softmax(vector_zero, None).data.numpy() assert_array_almost_equal( vector_zero_softmaxed, numpy.array([[0.33333334, 0.33333334, 0.33333334]]) ) # Testing the general unmasked batched case. matrix = torch.FloatTensor([[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]]) masked_matrix_softmaxed = util.masked_softmax(matrix, None).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array( [[0.01714783, 0.04661262, 0.93623955], [0.09003057, 0.24472847, 0.66524096]] ), ) # Testing the unmasked batched case where one of the inputs are all 0s. matrix = torch.FloatTensor([[1.0, 2.0, 5.0], [0.0, 0.0, 0.0]]) masked_matrix_softmaxed = util.masked_softmax(matrix, None).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array( [[0.01714783, 0.04661262, 0.93623955], [0.33333334, 0.33333334, 0.33333334]] ), ) def test_masked_softmax_masked(self): # Testing the general masked 1D case. vector_1d = torch.FloatTensor([[1.0, 2.0, 5.0]]) mask_1d = torch.tensor([[True, False, True]]) vector_1d_softmaxed = util.masked_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.01798621, 0.0, 0.98201382]])) vector_1d = torch.FloatTensor([[0.0, 2.0, 3.0, 4.0]]) mask_1d = torch.tensor([[True, False, True, True]]) vector_1d_softmaxed = util.masked_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal( vector_1d_softmaxed, numpy.array([[0.01321289, 0.0, 0.26538793, 0.72139918]]) ) # Testing the masked 1D case where the input is all 0s and the mask # is not all 0s. vector_1d = torch.FloatTensor([[0.0, 0.0, 0.0, 0.0]]) mask_1d = torch.tensor([[False, False, False, True]]) vector_1d_softmaxed = util.masked_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0, 0, 0, 1]])) # Testing the masked 1D case where the input is not all 0s # and the mask is all 0s. vector_1d = torch.FloatTensor([[0.0, 2.0, 3.0, 4.0]]) mask_1d = torch.tensor([[False, False, False, False]]) vector_1d_softmaxed = util.masked_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.0, 0.0, 0.0, 0.0]])) # Testing the masked 1D case where the input is all 0s and # the mask is all 0s. vector_1d = torch.FloatTensor([[0.0, 0.0, 0.0, 0.0]]) mask_1d = torch.tensor([[False, False, False, False]]) vector_1d_softmaxed = util.masked_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.0, 0.0, 0.0, 0.0]])) # Testing the masked 1D case where there are large elements in the # padding. vector_1d = torch.FloatTensor([[1.0, 1.0, 1e5]]) mask_1d = torch.tensor([[True, True, False]]) vector_1d_softmaxed = util.masked_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.5, 0.5, 0]])) # Testing the general masked batched case. matrix = torch.FloatTensor([[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]]) mask = torch.tensor([[True, False, True], [True, True, True]]) masked_matrix_softmaxed = util.masked_softmax(matrix, mask).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array([[0.01798621, 0.0, 0.98201382], [0.090031, 0.244728, 0.665241]]), ) # Testing the masked batch case where one of the inputs is all 0s but # none of the masks are all 0. matrix = torch.FloatTensor([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]) mask = torch.tensor([[True, False, True], [True, True, True]]) masked_matrix_softmaxed = util.masked_softmax(matrix, mask).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array([[0.5, 0.0, 0.5], [0.090031, 0.244728, 0.665241]]) ) # Testing the masked batch case where one of the inputs is all 0s and # one of the masks are all 0. matrix = torch.FloatTensor([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]) mask = torch.tensor([[True, False, True], [False, False, False]]) masked_matrix_softmaxed = util.masked_softmax(matrix, mask).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array([[0.5, 0.0, 0.5], [0.0, 0.0, 0.0]]) ) matrix = torch.FloatTensor([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]) mask = torch.tensor([[False, False, False], [True, False, True]]) masked_matrix_softmaxed = util.masked_softmax(matrix, mask).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array([[0.0, 0.0, 0.0], [0.11920292, 0.0, 0.88079708]]) ) def test_masked_softmax_memory_efficient_masked(self): # Testing the general masked 1D case. vector_1d = torch.FloatTensor([[1.0, 2.0, 5.0]]) mask_1d = torch.tensor([[True, False, True]]) vector_1d_softmaxed = util.masked_softmax( vector_1d, mask_1d, memory_efficient=True ).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.01798621, 0.0, 0.98201382]])) vector_1d = torch.FloatTensor([[0.0, 2.0, 3.0, 4.0]]) mask_1d = torch.tensor([[True, False, True, True]]) vector_1d_softmaxed = util.masked_softmax( vector_1d, mask_1d, memory_efficient=True ).data.numpy() assert_array_almost_equal( vector_1d_softmaxed, numpy.array([[0.01321289, 0.0, 0.26538793, 0.72139918]]) ) # Testing the masked 1D case where the input is all 0s and the mask # is not all 0s. vector_1d = torch.FloatTensor([[0.0, 0.0, 0.0, 0.0]]) mask_1d = torch.tensor([[False, False, False, True]]) vector_1d_softmaxed = util.masked_softmax( vector_1d, mask_1d, memory_efficient=True ).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0, 0, 0, 1]])) # Testing the masked 1D case where the input is not all 0s # and the mask is all 0s. vector_1d = torch.FloatTensor([[0.0, 2.0, 3.0, 4.0]]) mask_1d = torch.tensor([[False, False, False, False]]) vector_1d_softmaxed = util.masked_softmax( vector_1d, mask_1d, memory_efficient=True ).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.25, 0.25, 0.25, 0.25]])) # Testing the masked 1D case where the input is all 0s and # the mask is all 0s. vector_1d = torch.FloatTensor([[0.0, 0.0, 0.0, 0.0]]) mask_1d = torch.tensor([[False, False, False, False]]) vector_1d_softmaxed = util.masked_softmax( vector_1d, mask_1d, memory_efficient=True ).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.25, 0.25, 0.25, 0.25]])) # Testing the masked 1D case where there are large elements in the # padding. vector_1d = torch.FloatTensor([[1.0, 1.0, 1e5]]) mask_1d = torch.tensor([[True, True, False]]) vector_1d_softmaxed = util.masked_softmax( vector_1d, mask_1d, memory_efficient=True ).data.numpy() assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.5, 0.5, 0]])) # Testing the general masked batched case. matrix = torch.FloatTensor([[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]]) mask = torch.tensor([[True, False, True], [True, True, True]]) masked_matrix_softmaxed = util.masked_softmax( matrix, mask, memory_efficient=True ).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array([[0.01798621, 0.0, 0.98201382], [0.090031, 0.244728, 0.665241]]), ) # Testing the masked batch case where one of the inputs is all 0s but # none of the masks are all 0. matrix = torch.FloatTensor([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]) mask = torch.tensor([[True, False, True], [True, True, True]]) masked_matrix_softmaxed = util.masked_softmax( matrix, mask, memory_efficient=True ).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array([[0.5, 0.0, 0.5], [0.090031, 0.244728, 0.665241]]) ) # Testing the masked batch case where one of the inputs is all 0s and # one of the masks are all 0. matrix = torch.FloatTensor([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]) mask = torch.tensor([[True, False, True], [False, False, False]]) masked_matrix_softmaxed = util.masked_softmax( matrix, mask, memory_efficient=True ).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array([[0.5, 0.0, 0.5], [0.33333333, 0.33333333, 0.33333333]]), ) matrix = torch.FloatTensor([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]) mask = torch.tensor([[False, False, False], [True, False, True]]) masked_matrix_softmaxed = util.masked_softmax( matrix, mask, memory_efficient=True ).data.numpy() assert_array_almost_equal( masked_matrix_softmaxed, numpy.array([[0.33333333, 0.33333333, 0.33333333], [0.11920292, 0.0, 0.88079708]]), ) def test_masked_log_softmax_masked(self): # Tests replicated from test_softmax_masked - we test that exponentiated, # the log softmax contains the correct elements (masked elements should be == 1). # Testing the general masked 1D case. vector_1d = torch.FloatTensor([[1.0, 2.0, 5.0]]) mask_1d = torch.tensor([[True, False, True]]) vector_1d_softmaxed = util.masked_log_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal( numpy.exp(vector_1d_softmaxed), numpy.array([[0.01798621, 0.0, 0.98201382]]) ) vector_1d = torch.FloatTensor([[0.0, 2.0, 3.0, 4.0]]) mask_1d = torch.tensor([[True, False, True, True]]) vector_1d_softmaxed = util.masked_log_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal( numpy.exp(vector_1d_softmaxed), numpy.array([[0.01321289, 0.0, 0.26538793, 0.72139918]]) ) # Testing the masked 1D case where the input is all 0s and the mask # is not all 0s. vector_1d = torch.FloatTensor([[0.0, 0.0, 0.0, 0.0]]) mask_1d = torch.tensor([[False, False, False, True]]) vector_1d_softmaxed = util.masked_log_softmax(vector_1d, mask_1d).data.numpy() assert_array_almost_equal( numpy.exp(vector_1d_softmaxed), numpy.array([[0.0, 0.0, 0.0, 1.0]]) ) # Testing the masked 1D case where the input is not all 0s # and the mask is all 0s. The output here will be arbitrary, but it should not be nan. vector_1d = torch.FloatTensor([[0.0, 2.0, 3.0, 4.0]]) mask_1d = torch.tensor([[False, False, False, False]]) vector_1d_softmaxed = util.masked_log_softmax(vector_1d, mask_1d).data.numpy() assert not numpy.isnan(vector_1d_softmaxed).any() def test_masked_max(self): # Testing the general masked 1D case. vector_1d = torch.FloatTensor([1.0, 12.0, 5.0]) mask_1d = torch.tensor([True, False, True]) vector_1d_maxed = util.masked_max(vector_1d, mask_1d, dim=0).data.numpy() assert_array_almost_equal(vector_1d_maxed, 5.0) # Testing if all masks are zero, the output will be arbitrary, but it should not be nan. vector_1d = torch.FloatTensor([1.0, 12.0, 5.0]) mask_1d = torch.tensor([False, False, False]) vector_1d_maxed = util.masked_max(vector_1d, mask_1d, dim=0).data.numpy() assert not numpy.isnan(vector_1d_maxed).any() # Testing batch value and batch masks matrix = torch.FloatTensor([[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]]) mask = torch.tensor([[True, False, True], [True, True, False]]) matrix_maxed = util.masked_max(matrix, mask, dim=-1).data.numpy() assert_array_almost_equal(matrix_maxed, numpy.array([5.0, -1.0])) # Testing keepdim for batch value and batch masks matrix = torch.FloatTensor([[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]]) mask = torch.tensor([[True, False, True], [True, True, False]]) matrix_maxed = util.masked_max(matrix, mask, dim=-1, keepdim=True).data.numpy() assert_array_almost_equal(matrix_maxed, numpy.array([[5.0], [-1.0]])) # Testing broadcast matrix = torch.FloatTensor( [[[1.0, 2.0], [12.0, 3.0], [5.0, -1.0]], [[-1.0, -3.0], [-2.0, -0.5], [3.0, 8.0]]] ) mask = torch.tensor([[True, False, True], [True, True, False]]).unsqueeze(-1) matrix_maxed = util.masked_max(matrix, mask, dim=1).data.numpy() assert_array_almost_equal(matrix_maxed, numpy.array([[5.0, 2.0], [-1.0, -0.5]])) def test_masked_mean(self): # Testing the general masked 1D case. vector_1d = torch.FloatTensor([1.0, 12.0, 5.0]) mask_1d = torch.tensor([True, False, True]) vector_1d_mean = util.masked_mean(vector_1d, mask_1d, dim=0).data.numpy() assert_array_almost_equal(vector_1d_mean, 3.0) # Testing if all masks are zero, the output will be arbitrary, but it should not be nan. vector_1d = torch.FloatTensor([1.0, 12.0, 5.0]) mask_1d = torch.tensor([False, False, False]) vector_1d_mean = util.masked_mean(vector_1d, mask_1d, dim=0).data.numpy() assert not numpy.isnan(vector_1d_mean).any() # Testing batch value and batch masks matrix = torch.FloatTensor([[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]]) mask = torch.tensor([[True, False, True], [True, True, False]]) matrix_mean = util.masked_mean(matrix, mask, dim=-1).data.numpy() assert_array_almost_equal(matrix_mean, numpy.array([3.0, -1.5])) # Testing keepdim for batch value and batch masks matrix = torch.FloatTensor([[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]]) mask = torch.tensor([[True, False, True], [True, True, False]]) matrix_mean = util.masked_mean(matrix, mask, dim=-1, keepdim=True).data.numpy() assert_array_almost_equal(matrix_mean, numpy.array([[3.0], [-1.5]])) # Testing broadcast matrix = torch.FloatTensor( [[[1.0, 2.0], [12.0, 3.0], [5.0, -1.0]], [[-1.0, -3.0], [-2.0, -0.5], [3.0, 8.0]]] ) mask = torch.tensor([[True, False, True], [True, True, False]]).unsqueeze(-1) matrix_mean = util.masked_mean(matrix, mask, dim=1).data.numpy() assert_array_almost_equal(matrix_mean, numpy.array([[3.0, 0.5], [-1.5, -1.75]])) def test_masked_flip(self): tensor = torch.FloatTensor( [[[6, 6, 6], [1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4], [5, 5, 5]]] ) solution = [[[6, 6, 6], [0, 0, 0]], [[4, 4, 4], [3, 3, 3]]] response = util.masked_flip(tensor, [1, 2]) assert_almost_equal(response, solution) tensor = torch.FloatTensor( [ [[6, 6, 6], [1, 1, 1], [2, 2, 2], [0, 0, 0]], [[3, 3, 3], [4, 4, 4], [5, 5, 5], [1, 2, 3]], ] ) solution = [ [[2, 2, 2], [1, 1, 1], [6, 6, 6], [0, 0, 0]], [[1, 2, 3], [5, 5, 5], [4, 4, 4], [3, 3, 3]], ] response = util.masked_flip(tensor, [3, 4]) assert_almost_equal(response, solution) tensor = torch.FloatTensor( [ [[6, 6, 6], [1, 1, 1], [2, 2, 2], [0, 0, 0]], [[3, 3, 3], [4, 4, 4], [5, 5, 5], [1, 2, 3]], [[1, 1, 1], [2, 2, 2], [0, 0, 0], [0, 0, 0]], ] ) solution = [ [[2, 2, 2], [1, 1, 1], [6, 6, 6], [0, 0, 0]], [[1, 2, 3], [5, 5, 5], [4, 4, 4], [3, 3, 3]], [[2, 2, 2], [1, 1, 1], [0, 0, 0], [0, 0, 0]], ] response = util.masked_flip(tensor, [3, 4, 2]) assert_almost_equal(response, solution) def test_get_text_field_mask_returns_a_correct_mask(self): text_field_tensors = { "indexer_name": { "tokens": torch.LongTensor([[3, 4, 5, 0, 0], [1, 2, 0, 0, 0]]), "token_characters": torch.LongTensor( [ [[1, 2], [3, 0], [2, 0], [0, 0], [0, 0]], [[5, 0], [4, 6], [0, 0], [0, 0], [0, 0]], ] ), } } assert_almost_equal( util.get_text_field_mask(text_field_tensors).long().numpy(), [[1, 1, 1, 0, 0], [1, 1, 0, 0, 0]], ) def test_get_text_field_mask_returns_a_correct_mask_character_only_input(self): text_field_tensors = { "indexer_name": { "token_characters": torch.LongTensor( [ [[1, 2, 3], [3, 0, 1], [2, 1, 0], [0, 0, 0]], [[5, 5, 5], [4, 6, 0], [0, 0, 0], [0, 0, 0]], ] ) } } assert_almost_equal( util.get_text_field_mask(text_field_tensors).long().numpy(), [[1, 1, 1, 0], [1, 1, 0, 0]], ) def test_get_text_field_mask_returns_a_correct_mask_list_field(self): text_field_tensors = { "indexer_name": { "list_tokens": torch.LongTensor( [ [[1, 2], [3, 0], [2, 0], [0, 0], [0, 0]], [[5, 0], [4, 6], [0, 0], [0, 0], [0, 0]], ] ) } } actual_mask = ( util.get_text_field_mask(text_field_tensors, num_wrapping_dims=1).long().numpy() ) expected_mask = (text_field_tensors["indexer_name"]["list_tokens"].numpy() > 0).astype( "int32" ) assert_almost_equal(actual_mask, expected_mask) def test_get_text_field_mask_returns_mask_key(self): text_field_tensors = { "indexer_name": { "tokens": torch.LongTensor([[3, 4, 5, 0, 0], [1, 2, 0, 0, 0]]), "mask": torch.tensor([[False, False, True]]), } } assert_almost_equal( util.get_text_field_mask(text_field_tensors).long().numpy(), [[0, 0, 1]] ) def test_weighted_sum_works_on_simple_input(self): batch_size = 1 sentence_length = 5 embedding_dim = 4 sentence_array = numpy.random.rand(batch_size, sentence_length, embedding_dim) sentence_tensor = torch.from_numpy(sentence_array).float() attention_tensor = torch.FloatTensor([[0.3, 0.4, 0.1, 0, 1.2]]) aggregated_array = util.weighted_sum(sentence_tensor, attention_tensor).data.numpy() assert aggregated_array.shape == (batch_size, embedding_dim) expected_array = ( 0.3 * sentence_array[0, 0] + 0.4 * sentence_array[0, 1] + 0.1 * sentence_array[0, 2] + 0.0 * sentence_array[0, 3] + 1.2 * sentence_array[0, 4] ) numpy.testing.assert_almost_equal(aggregated_array, [expected_array], decimal=5) def test_weighted_sum_handles_higher_order_input(self): batch_size = 1 length_1 = 5 length_2 = 6 length_3 = 2 embedding_dim = 4 sentence_array = numpy.random.rand(batch_size, length_1, length_2, length_3, embedding_dim) attention_array = numpy.random.rand(batch_size, length_1, length_2, length_3) sentence_tensor = torch.from_numpy(sentence_array).float() attention_tensor = torch.from_numpy(attention_array).float() aggregated_array = util.weighted_sum(sentence_tensor, attention_tensor).data.numpy() assert aggregated_array.shape == (batch_size, length_1, length_2, embedding_dim) expected_array = ( attention_array[0, 3, 2, 0] * sentence_array[0, 3, 2, 0] + attention_array[0, 3, 2, 1] * sentence_array[0, 3, 2, 1] ) numpy.testing.assert_almost_equal(aggregated_array[0, 3, 2], expected_array, decimal=5) def test_weighted_sum_handles_uneven_higher_order_input(self): batch_size = 1 length_1 = 5 length_2 = 6 length_3 = 2 embedding_dim = 4 sentence_array = numpy.random.rand(batch_size, length_3, embedding_dim) attention_array = numpy.random.rand(batch_size, length_1, length_2, length_3) sentence_tensor = torch.from_numpy(sentence_array).float() attention_tensor = torch.from_numpy(attention_array).float() aggregated_array = util.weighted_sum(sentence_tensor, attention_tensor).data.numpy() assert aggregated_array.shape == (batch_size, length_1, length_2, embedding_dim) for i in range(length_1): for j in range(length_2): expected_array = ( attention_array[0, i, j, 0] * sentence_array[0, 0] + attention_array[0, i, j, 1] * sentence_array[0, 1] ) numpy.testing.assert_almost_equal( aggregated_array[0, i, j], expected_array, decimal=5 ) def test_weighted_sum_handles_3d_attention_with_3d_matrix(self): batch_size = 1 length_1 = 5 length_2 = 2 embedding_dim = 4 sentence_array = numpy.random.rand(batch_size, length_2, embedding_dim) attention_array = numpy.random.rand(batch_size, length_1, length_2) sentence_tensor = torch.from_numpy(sentence_array).float() attention_tensor = torch.from_numpy(attention_array).float() aggregated_array = util.weighted_sum(sentence_tensor, attention_tensor).data.numpy() assert aggregated_array.shape == (batch_size, length_1, embedding_dim) for i in range(length_1): expected_array = ( attention_array[0, i, 0] * sentence_array[0, 0] + attention_array[0, i, 1] * sentence_array[0, 1] ) numpy.testing.assert_almost_equal(aggregated_array[0, i], expected_array, decimal=5) def test_viterbi_decode(self): # Test Viterbi decoding is equal to greedy decoding with no pairwise potentials. sequence_logits = torch.nn.functional.softmax(torch.rand([5, 9]), dim=-1) transition_matrix = torch.zeros([9, 9]) indices, _ = util.viterbi_decode(sequence_logits.data, transition_matrix) _, argmax_indices = torch.max(sequence_logits, 1) assert indices == argmax_indices.data.squeeze().tolist() # Test Viterbi decoding works with start and end transitions sequence_logits = torch.nn.functional.softmax(torch.rand([5, 9]), dim=-1) transition_matrix = torch.zeros([9, 9]) allowed_start_transitions = torch.zeros([9]) # Force start tag to be an 8 allowed_start_transitions[:8] = float("-inf") allowed_end_transitions = torch.zeros([9]) # Force end tag to be a 0 allowed_end_transitions[1:] = float("-inf") indices, _ = util.viterbi_decode( sequence_logits.data, transition_matrix, allowed_end_transitions=allowed_end_transitions, allowed_start_transitions=allowed_start_transitions, ) assert indices[0] == 8 assert indices[-1] == 0 # Test that pairwise potentials affect the sequence correctly and that # viterbi_decode can handle -inf values. sequence_logits = torch.FloatTensor( [ [0, 0, 0, 3, 5], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], ] ) # The same tags shouldn't appear sequentially. transition_matrix = torch.zeros([5, 5]) for i in range(5): transition_matrix[i, i] = float("-inf") indices, _ = util.viterbi_decode(sequence_logits, transition_matrix) assert indices == [4, 3, 4, 3, 4, 3] # Test that unbalanced pairwise potentials break ties # between paths with equal unary potentials. sequence_logits = torch.FloatTensor( [ [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], ] ) # The 5th tag has a penalty for appearing sequentially # or for transitioning to the 4th tag, making the best # path uniquely to take the 4th tag only. transition_matrix = torch.zeros([5, 5]) transition_matrix[4, 4] = -10 transition_matrix[4, 3] = -10 transition_matrix[3, 4] = -10 indices, _ = util.viterbi_decode(sequence_logits, transition_matrix) assert indices == [3, 3, 3, 3, 3, 3] sequence_logits = torch.FloatTensor([[1, 0, 0, 4], [1, 0, 6, 2], [0, 3, 0, 4]]) # Best path would normally be [3, 2, 3] but we add a # potential from 2 -> 1, making [3, 2, 1] the best path. transition_matrix = torch.zeros([4, 4]) transition_matrix[0, 0] = 1 transition_matrix[2, 1] = 5 indices, value = util.viterbi_decode(sequence_logits, transition_matrix) assert indices == [3, 2, 1] assert value.numpy() == 18 # Test that providing evidence results in paths containing specified tags. sequence_logits = torch.FloatTensor( [ [0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0, 0, 7, 7], ] ) # The 5th tag has a penalty for appearing sequentially # or for transitioning to the 4th tag, making the best # path to take the 4th tag for every label. transition_matrix = torch.zeros([5, 5]) transition_matrix[4, 4] = -10 transition_matrix[4, 3] = -2 transition_matrix[3, 4] = -2 # The 1st, 4th and 5th sequence elements are observed - they should be # equal to 2, 0 and 4. The last tag should be equal to 3, because although # the penalty for transitioning to the 4th tag is -2, the unary potential # is 7, which is greater than the combination for any of the other labels. observations = [2, -1, -1, 0, 4, -1] indices, _ = util.viterbi_decode(sequence_logits, transition_matrix, observations) assert indices == [2, 3, 3, 0, 4, 3] def test_viterbi_decode_top_k(self): # Test cases taken from: https://gist.github.com/PetrochukM/afaa3613a99a8e7213d2efdd02ae4762 # Test Viterbi decoding is equal to greedy decoding with no pairwise potentials. sequence_logits = torch.autograd.Variable(torch.rand([5, 9])) transition_matrix = torch.zeros([9, 9]) indices, _ = util.viterbi_decode(sequence_logits.data, transition_matrix, top_k=5) _, argmax_indices = torch.max(sequence_logits, 1) assert indices[0] == argmax_indices.data.squeeze().tolist() # Test that pairwise potentials effect the sequence correctly and that # viterbi_decode can handle -inf values. sequence_logits = torch.FloatTensor( [ [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], ] ) # The same tags shouldn't appear sequentially. transition_matrix = torch.zeros([5, 5]) for i in range(5): transition_matrix[i, i] = float("-inf") indices, _ = util.viterbi_decode(sequence_logits, transition_matrix, top_k=5) assert indices[0] == [3, 4, 3, 4, 3, 4] # Test that unbalanced pairwise potentials break ties # between paths with equal unary potentials. sequence_logits = torch.FloatTensor( [ [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 0], ] ) # The 5th tag has a penalty for appearing sequentially # or for transitioning to the 4th tag, making the best # path uniquely to take the 4th tag only. transition_matrix = torch.zeros([5, 5]) transition_matrix[4, 4] = -10 transition_matrix[4, 3] = -10 indices, _ = util.viterbi_decode(sequence_logits, transition_matrix, top_k=5) assert indices[0] == [3, 3, 3, 3, 3, 3] sequence_logits = torch.FloatTensor([[1, 0, 0, 4], [1, 0, 6, 2], [0, 3, 0, 4]]) # Best path would normally be [3, 2, 3] but we add a # potential from 2 -> 1, making [3, 2, 1] the best path. transition_matrix = torch.zeros([4, 4]) transition_matrix[0, 0] = 1 transition_matrix[2, 1] = 5 indices, value = util.viterbi_decode(sequence_logits, transition_matrix, top_k=5) assert indices[0] == [3, 2, 1] assert value[0] == 18 def _brute_decode( tag_sequence: torch.Tensor, transition_matrix: torch.Tensor, top_k: int = 5 ) -> Any: """ Top-k decoder that uses brute search instead of the Viterbi Decode dynamic programing algorithm """ # Create all possible sequences sequences = [[]] # type: ignore for i in range(len(tag_sequence)): new_sequences = [] # type: ignore for j in range(len(tag_sequence[i])): for sequence in sequences: new_sequences.append(sequence[:] + [j]) sequences = new_sequences # Score scored_sequences = [] # type: ignore for sequence in sequences: emission_score = sum(tag_sequence[i, j] for i, j in enumerate(sequence)) transition_score = sum( transition_matrix[sequence[i - 1], sequence[i]] for i in range(1, len(sequence)) ) score = emission_score + transition_score scored_sequences.append((score, sequence)) # Get the top k scores / paths top_k_sequences = sorted(scored_sequences, key=lambda r: r[0], reverse=True)[:top_k] scores, paths = zip(*top_k_sequences) return paths, scores # type: ignore # Run 100 randomly generated parameters and compare the outputs. for i in range(100): num_tags = random.randint(1, 5) seq_len = random.randint(1, 5) k = random.randint(1, 5) sequence_logits = torch.rand([seq_len, num_tags]) transition_matrix = torch.rand([num_tags, num_tags]) viterbi_paths_v1, viterbi_scores_v1 = util.viterbi_decode( sequence_logits, transition_matrix, top_k=k ) viterbi_path_brute, viterbi_score_brute = _brute_decode( sequence_logits, transition_matrix, top_k=k ) numpy.testing.assert_almost_equal( list(viterbi_score_brute), viterbi_scores_v1.tolist(), decimal=3 ) numpy.testing.assert_equal(sanitize(viterbi_paths_v1), viterbi_path_brute) def test_sequence_cross_entropy_with_logits_masks_loss_correctly(self): # test weight masking by checking that a tensor with non-zero values in # masked positions returns the same loss as a tensor with zeros in those # positions. tensor = torch.rand([5, 7, 4]) tensor[0, 3:, :] = 0 tensor[1, 4:, :] = 0 tensor[2, 2:, :] = 0 tensor[3, :, :] = 0 weights = (tensor != 0.0)[:, :, 0].long().squeeze(-1) tensor2 = tensor.clone() tensor2[0, 3:, :] = 2 tensor2[1, 4:, :] = 13 tensor2[2, 2:, :] = 234 tensor2[3, :, :] = 65 targets = torch.LongTensor(numpy.random.randint(0, 3, [5, 7])) targets *= weights loss = util.sequence_cross_entropy_with_logits(tensor, targets, weights) loss2 = util.sequence_cross_entropy_with_logits(tensor2, targets, weights) assert loss.data.numpy() == loss2.data.numpy() def test_sequence_cross_entropy_with_logits_smooths_labels_correctly(self): tensor = torch.rand([1, 3, 4]) targets = torch.LongTensor(numpy.random.randint(0, 3, [1, 3])) weights = torch.ones([2, 3]) loss = util.sequence_cross_entropy_with_logits( tensor, targets, weights, label_smoothing=0.1 ) correct_loss = 0.0 for prediction, label in zip(tensor.squeeze(0), targets.squeeze(0)): prediction = torch.nn.functional.log_softmax(prediction, dim=-1) correct_loss += prediction[label] * 0.9 # incorrect elements correct_loss += prediction.sum() * 0.1 / 4 # Average over sequence. correct_loss = -correct_loss / 3 numpy.testing.assert_array_almost_equal(loss.data.numpy(), correct_loss.data.numpy()) def test_sequence_cross_entropy_with_logits_averages_batch_correctly(self): # test batch average is the same as dividing the batch averaged # loss by the number of batches containing any non-padded tokens. tensor = torch.rand([5, 7, 4]) tensor[0, 3:, :] = 0 tensor[1, 4:, :] = 0 tensor[2, 2:, :] = 0 tensor[3, :, :] = 0 weights = (tensor != 0.0)[:, :, 0].long().squeeze(-1) targets = torch.LongTensor(numpy.random.randint(0, 3, [5, 7])) targets *= weights loss = util.sequence_cross_entropy_with_logits(tensor, targets, weights) vector_loss = util.sequence_cross_entropy_with_logits( tensor, targets, weights, average=None ) # Batch has one completely padded row, so divide by 4. assert loss.data.numpy() == vector_loss.sum().item() / 4 @flaky(max_runs=3, min_passes=1) def test_sequence_cross_entropy_with_logits_averages_token_correctly(self): # test token average is the same as multiplying the per-batch loss # with the per-batch weights and dividing by the total weight tensor = torch.rand([5, 7, 4]) tensor[0, 3:, :] = 0 tensor[1, 4:, :] = 0 tensor[2, 2:, :] = 0 tensor[3, :, :] = 0 weights = (tensor != 0.0)[:, :, 0].long().squeeze(-1) targets = torch.LongTensor(numpy.random.randint(0, 3, [5, 7])) targets *= weights loss = util.sequence_cross_entropy_with_logits(tensor, targets, weights, average="token") vector_loss = util.sequence_cross_entropy_with_logits( tensor, targets, weights, average=None ) total_token_loss = (vector_loss * weights.float().sum(dim=-1)).sum() average_token_loss = (total_token_loss / weights.float().sum()).detach() assert_almost_equal(loss.detach().item(), average_token_loss.item(), decimal=5) def test_sequence_cross_entropy_with_logits_gamma_correctly(self): batch = 1 length = 3 classes = 4 gamma = abs(numpy.random.randn()) # [0, +inf) tensor = torch.rand([batch, length, classes]) targets = torch.LongTensor(numpy.random.randint(0, classes, [batch, length])) weights = torch.ones([batch, length]) loss = util.sequence_cross_entropy_with_logits(tensor, targets, weights, gamma=gamma) correct_loss = 0.0 for logit, label in zip(tensor.squeeze(0), targets.squeeze(0)): p = torch.nn.functional.softmax(logit, dim=-1) pt = p[label] ft = (1 - pt) ** gamma correct_loss += -pt.log() * ft # Average over sequence. correct_loss = correct_loss / length numpy.testing.assert_array_almost_equal(loss.data.numpy(), correct_loss.data.numpy()) def test_sequence_cross_entropy_with_logits_alpha_float_correctly(self): batch = 1 length = 3 classes = 2 # alpha float for binary class only alpha = ( numpy.random.rand() if numpy.random.rand() > 0.5 else (1.0 - numpy.random.rand()) ) # [0, 1] tensor = torch.rand([batch, length, classes]) targets = torch.LongTensor(numpy.random.randint(0, classes, [batch, length])) weights = torch.ones([batch, length]) loss = util.sequence_cross_entropy_with_logits(tensor, targets, weights, alpha=alpha) correct_loss = 0.0 for logit, label in zip(tensor.squeeze(0), targets.squeeze(0)): logp = torch.nn.functional.log_softmax(logit, dim=-1) logpt = logp[label] if label: at = alpha else: at = 1 - alpha correct_loss += -logpt * at # Average over sequence. correct_loss = correct_loss / length numpy.testing.assert_array_almost_equal(loss.data.numpy(), correct_loss.data.numpy()) def test_sequence_cross_entropy_with_logits_alpha_single_float_correctly(self): batch = 1 length = 3 classes = 2 # alpha float for binary class only alpha = ( numpy.random.rand() if numpy.random.rand() > 0.5 else (1.0 - numpy.random.rand()) ) # [0, 1] alpha = torch.tensor(alpha) tensor = torch.rand([batch, length, classes]) targets = torch.LongTensor(numpy.random.randint(0, classes, [batch, length])) weights = torch.ones([batch, length]) loss = util.sequence_cross_entropy_with_logits(tensor, targets, weights, alpha=alpha) correct_loss = 0.0 for logit, label in zip(tensor.squeeze(0), targets.squeeze(0)): logp = torch.nn.functional.log_softmax(logit, dim=-1) logpt = logp[label] if label: at = alpha else: at = 1 - alpha correct_loss += -logpt * at # Average over sequence. correct_loss = correct_loss / length numpy.testing.assert_array_almost_equal(loss.data.numpy(), correct_loss.data.numpy()) def test_sequence_cross_entropy_with_logits_alpha_list_correctly(self): batch = 1 length = 3 classes = 4 # alpha float for binary class only alpha = abs(numpy.random.randn(classes)) # [0, +inf) tensor = torch.rand([batch, length, classes]) targets = torch.LongTensor(numpy.random.randint(0, classes, [batch, length])) weights = torch.ones([batch, length]) loss = util.sequence_cross_entropy_with_logits(tensor, targets, weights, alpha=alpha) correct_loss = 0.0 for logit, label in zip(tensor.squeeze(0), targets.squeeze(0)): logp = torch.nn.functional.log_softmax(logit, dim=-1) logpt = logp[label] at = alpha[label] correct_loss += -logpt * at # Average over sequence. correct_loss = correct_loss / length numpy.testing.assert_array_almost_equal(loss.data.numpy(), correct_loss.data.numpy()) def test_replace_masked_values_replaces_masked_values_with_finite_value(self): tensor = torch.FloatTensor([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]]) mask = torch.tensor([[True, True, False]]) replaced = util.replace_masked_values(tensor, mask.unsqueeze(-1), 2).data.numpy() assert_almost_equal(replaced, [[[1, 2, 3, 4], [5, 6, 7, 8], [2, 2, 2, 2]]]) def test_logsumexp(self): # First a simple example where we add probabilities in log space. tensor = torch.FloatTensor([[0.4, 0.1, 0.2]]) log_tensor = tensor.log() log_summed = util.logsumexp(log_tensor, dim=-1, keepdim=False) assert_almost_equal(log_summed.exp().data.numpy(), [0.7]) log_summed = util.logsumexp(log_tensor, dim=-1, keepdim=True) assert_almost_equal(log_summed.exp().data.numpy(), [[0.7]]) # Then some more atypical examples, and making sure this will work with how we handle # log masks. tensor = torch.FloatTensor([[float("-inf"), 20.0]]) assert_almost_equal(util.logsumexp(tensor).data.numpy(), [20.0]) tensor = torch.FloatTensor([[-200.0, 20.0]]) assert_almost_equal(util.logsumexp(tensor).data.numpy(), [20.0]) tensor = torch.FloatTensor([[20.0, 20.0], [-200.0, 200.0]]) assert_almost_equal(util.logsumexp(tensor, dim=0).data.numpy(), [20.0, 200.0]) def test_flatten_and_batch_shift_indices(self): indices = numpy.array( [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 9, 9, 9]], [[2, 1, 0, 7], [7, 7, 2, 3], [0, 0, 4, 2]]] ) indices = torch.tensor(indices, dtype=torch.long) shifted_indices = util.flatten_and_batch_shift_indices(indices, 10) numpy.testing.assert_array_equal( shifted_indices.data.numpy(), numpy.array( [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 12, 11, 10, 17, 17, 17, 12, 13, 10, 10, 14, 12] ), ) def test_batched_index_select(self): indices = numpy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # Each element is a vector of its index. targets = torch.ones([2, 10, 3]).cumsum(1) - 1 # Make the second batch double its index so they're different. targets[1, :, :] *= 2 indices = torch.tensor(indices, dtype=torch.long) selected = util.batched_index_select(targets, indices) assert list(selected.size()) == [2, 2, 2, 3] ones = numpy.ones([3]) numpy.testing.assert_array_equal(selected[0, 0, 0, :].data.numpy(), ones) numpy.testing.assert_array_equal(selected[0, 0, 1, :].data.numpy(), ones * 2) numpy.testing.assert_array_equal(selected[0, 1, 0, :].data.numpy(), ones * 3) numpy.testing.assert_array_equal(selected[0, 1, 1, :].data.numpy(), ones * 4) numpy.testing.assert_array_equal(selected[1, 0, 0, :].data.numpy(), ones * 10) numpy.testing.assert_array_equal(selected[1, 0, 1, :].data.numpy(), ones * 12) numpy.testing.assert_array_equal(selected[1, 1, 0, :].data.numpy(), ones * 14) numpy.testing.assert_array_equal(selected[1, 1, 1, :].data.numpy(), ones * 16) indices = numpy.array([[[1, 11], [3, 4]], [[5, 6], [7, 8]]]) indices = torch.tensor(indices, dtype=torch.long) with pytest.raises(ConfigurationError): util.batched_index_select(targets, indices) indices = numpy.array([[[1, -1], [3, 4]], [[5, 6], [7, 8]]]) indices = torch.tensor(indices, dtype=torch.long) with pytest.raises(ConfigurationError): util.batched_index_select(targets, indices) def test_batched_span_select(self): # Each element is a vector of its index. targets = torch.ones([3, 12, 2]).cumsum(1) - 1 spans = torch.LongTensor( [ [[0, 0], [1, 2], [5, 8], [10, 10]], [[i, i] for i in range(3, -1, -1)], [[0, 3], [1, 4], [2, 5], [10, 11]], ] ) selected, mask = util.batched_span_select(targets, spans) selected = torch.where(mask.unsqueeze(-1), selected, torch.empty_like(selected).fill_(-1)) numpy.testing.assert_array_equal( selected, [ [ [[0, 0], [-1, -1], [-1, -1], [-1, -1]], [[2, 2], [1, 1], [-1, -1], [-1, -1]], [[8, 8], [7, 7], [6, 6], [5, 5]], [[10, 10], [-1, -1], [-1, -1], [-1, -1]], ], [[[i, i], [-1, -1], [-1, -1], [-1, -1]] for i in range(3, -1, -1)], [ [[3, 3], [2, 2], [1, 1], [0, 0]], [[4, 4], [3, 3], [2, 2], [1, 1]], [[5, 5], [4, 4], [3, 3], [2, 2]], [[11, 11], [10, 10], [-1, -1], [-1, -1]], ], ], ) def test_flattened_index_select(self): indices = numpy.array([[1, 2], [3, 4]]) targets = torch.ones([2, 6, 3]).cumsum(1) - 1 # Make the second batch double its index so they're different. targets[1, :, :] *= 2 indices = torch.tensor(indices, dtype=torch.long) selected = util.flattened_index_select(targets, indices) assert list(selected.size()) == [2, 2, 2, 3] ones = numpy.ones([3]) numpy.testing.assert_array_equal(selected[0, 0, 0, :].data.numpy(), ones) numpy.testing.assert_array_equal(selected[0, 0, 1, :].data.numpy(), ones * 2) numpy.testing.assert_array_equal(selected[0, 1, 0, :].data.numpy(), ones * 3) numpy.testing.assert_array_equal(selected[0, 1, 1, :].data.numpy(), ones * 4) numpy.testing.assert_array_equal(selected[1, 0, 0, :].data.numpy(), ones * 2) numpy.testing.assert_array_equal(selected[1, 0, 1, :].data.numpy(), ones * 4) numpy.testing.assert_array_equal(selected[1, 1, 0, :].data.numpy(), ones * 6) numpy.testing.assert_array_equal(selected[1, 1, 1, :].data.numpy(), ones * 8) # Check we only accept 2D indices. with pytest.raises(ConfigurationError): util.flattened_index_select(targets, torch.ones([3, 4, 5])) def test_bucket_values(self): indices = torch.LongTensor([1, 2, 7, 1, 56, 900]) bucketed_distances = util.bucket_values(indices) numpy.testing.assert_array_equal( bucketed_distances.numpy(), numpy.array([1, 2, 5, 1, 8, 9]) ) def test_add_sentence_boundary_token_ids_handles_2D_input(self): tensor = torch.from_numpy(numpy.array([[1, 2, 3], [4, 5, 0]])) mask = tensor > 0 bos = 9 eos = 10 new_tensor, new_mask = util.add_sentence_boundary_token_ids(tensor, mask, bos, eos) expected_new_tensor = numpy.array([[9, 1, 2, 3, 10], [9, 4, 5, 10, 0]]) assert (new_tensor.data.numpy() == expected_new_tensor).all() assert (new_mask.data.numpy() == (expected_new_tensor > 0)).all() def test_add_sentence_boundary_token_ids_handles_3D_input(self): tensor = torch.from_numpy( numpy.array( [ [[1, 2, 3, 4], [5, 5, 5, 5], [6, 8, 1, 2]], [[4, 3, 2, 1], [8, 7, 6, 5], [0, 0, 0, 0]], ] ) ) mask = (tensor > 0).sum(dim=-1) > 0 bos = torch.from_numpy(numpy.array([9, 9, 9, 9])) eos = torch.from_numpy(numpy.array([10, 10, 10, 10])) new_tensor, new_mask = util.add_sentence_boundary_token_ids(tensor, mask, bos, eos) expected_new_tensor = numpy.array( [ [[9, 9, 9, 9], [1, 2, 3, 4], [5, 5, 5, 5], [6, 8, 1, 2], [10, 10, 10, 10]], [[9, 9, 9, 9], [4, 3, 2, 1], [8, 7, 6, 5], [10, 10, 10, 10], [0, 0, 0, 0]], ] ) assert (new_tensor.data.numpy() == expected_new_tensor).all() assert (new_mask.data.numpy() == ((expected_new_tensor > 0).sum(axis=-1) > 0)).all() def test_remove_sentence_boundaries(self): tensor = torch.from_numpy(numpy.random.rand(3, 5, 7)) mask = torch.from_numpy( # The mask with two elements is to test the corner case # of an empty sequence, so here we are removing boundaries # from "<S> </S>" numpy.array([[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0]]) ).bool() new_tensor, new_mask = util.remove_sentence_boundaries(tensor, mask) expected_new_tensor = torch.zeros(3, 3, 7) expected_new_tensor[1, 0:3, :] = tensor[1, 1:4, :] expected_new_tensor[2, 0:2, :] = tensor[2, 1:3, :] assert_array_almost_equal(new_tensor.data.numpy(), expected_new_tensor.data.numpy()) expected_new_mask = torch.from_numpy(numpy.array([[0, 0, 0], [1, 1, 1], [1, 1, 0]])).bool() assert (new_mask.data.numpy() == expected_new_mask.data.numpy()).all() def test_add_positional_features(self): # This is hard to test, so we check that we get the same result as the # original tensorflow implementation: # https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/layers/common_attention.py#L270 tensor2tensor_result = numpy.asarray( [ [0.00000000e00, 0.00000000e00, 1.00000000e00, 1.00000000e00], [8.41470957e-01, 9.99999902e-05, 5.40302277e-01, 1.00000000e00], [9.09297407e-01, 1.99999980e-04, -4.16146845e-01, 1.00000000e00], ] ) tensor = torch.zeros([2, 3, 4]) result = util.add_positional_features(tensor, min_timescale=1.0, max_timescale=1.0e4) numpy.testing.assert_almost_equal(result[0].detach().cpu().numpy(), tensor2tensor_result) numpy.testing.assert_almost_equal(result[1].detach().cpu().numpy(), tensor2tensor_result) # Check case with odd number of dimensions. tensor2tensor_result = numpy.asarray( [ [ 0.00000000e00, 0.00000000e00, 0.00000000e00, 1.00000000e00, 1.00000000e00, 1.00000000e00, 0.00000000e00, ], [ 8.41470957e-01, 9.99983307e-03, 9.99999902e-05, 5.40302277e-01, 9.99949992e-01, 1.00000000e00, 0.00000000e00, ], [ 9.09297407e-01, 1.99986659e-02, 1.99999980e-04, -4.16146815e-01, 9.99800026e-01, 1.00000000e00, 0.00000000e00, ], ] ) tensor = torch.zeros([2, 3, 7]) result = util.add_positional_features(tensor, min_timescale=1.0, max_timescale=1.0e4) numpy.testing.assert_almost_equal(result[0].detach().cpu().numpy(), tensor2tensor_result) numpy.testing.assert_almost_equal(result[1].detach().cpu().numpy(), tensor2tensor_result) def test_combine_tensors_and_multiply(self): tensors = [torch.Tensor([[[2, 3]]]), torch.Tensor([[[5, 5]]])] weight = torch.Tensor([4, 5]) combination = "x" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[8 + 15]] ) combination = "y" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[20 + 25]] ) combination = "x,y" weight2 = torch.Tensor([4, 5, 4, 5]) assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight2), [[8 + 20 + 15 + 25]] ) combination = "x-y" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[-3 * 4 + -2 * 5]] ) combination = "y-x" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[3 * 4 + 2 * 5]] ) combination = "y+x" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[7 * 4 + 8 * 5]] ) combination = "y*x" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[10 * 4 + 15 * 5]] ) combination = "y/x" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[(5 / 2) * 4 + (5 / 3) * 5]], decimal=4, ) combination = "x/y" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[(2 / 5) * 4 + (3 / 5) * 5]], decimal=4, ) with pytest.raises(ConfigurationError): util.combine_tensors_and_multiply("x+y+y", tensors, weight) with pytest.raises(ConfigurationError): util.combine_tensors_and_multiply("x%y", tensors, weight) def test_combine_tensors_and_multiply_with_same_batch_size_and_embedding_dim(self): # This test just makes sure we handle some potential edge cases where the lengths of all # dimensions are the same, making sure that the multiplication with the weight vector # happens along the right dimension (it should be the last one). tensors = [torch.Tensor([[[5, 5], [4, 4]], [[2, 3], [1, 1]]])] # (2, 2, 2) weight = torch.Tensor([4, 5]) # (2,) combination = "x" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [[20 + 25, 16 + 20], [8 + 15, 4 + 5]], ) tensors = [ torch.Tensor([[[5, 5], [2, 2]], [[4, 4], [3, 3]]]), torch.Tensor([[[2, 3]], [[1, 1]]]), ] weight = torch.Tensor([4, 5]) combination = "x*y" assert_almost_equal( util.combine_tensors_and_multiply(combination, tensors, weight), [ [5 * 2 * 4 + 5 * 3 * 5, 2 * 2 * 4 + 2 * 3 * 5], [4 * 1 * 4 + 4 * 1 * 5, 3 * 1 * 4 + 3 * 1 * 5], ], ) def test_combine_tensors_and_multiply_with_batch_size_one(self): seq_len_1 = 10 seq_len_2 = 5 embedding_dim = 8 combination = "x,y,x*y" t1 = torch.randn(1, seq_len_1, embedding_dim) t2 = torch.randn(1, seq_len_2, embedding_dim) combined_dim = util.get_combined_dim(combination, [embedding_dim, embedding_dim]) weight = torch.Tensor(combined_dim) result = util.combine_tensors_and_multiply( combination, [t1.unsqueeze(2), t2.unsqueeze(1)], weight ) assert_almost_equal(result.size(), [1, seq_len_1, seq_len_2]) def test_combine_tensors_and_multiply_with_batch_size_one_and_seq_len_one(self): seq_len_1 = 10 seq_len_2 = 1 embedding_dim = 8 combination = "x,y,x*y" t1 = torch.randn(1, seq_len_1, embedding_dim) t2 = torch.randn(1, seq_len_2, embedding_dim) combined_dim = util.get_combined_dim(combination, [embedding_dim, embedding_dim]) weight = torch.Tensor(combined_dim) result = util.combine_tensors_and_multiply( combination, [t1.unsqueeze(2), t2.unsqueeze(1)], weight ) assert_almost_equal(result.size(), [1, seq_len_1, seq_len_2]) def test_has_tensor(self): has_tensor = util.has_tensor tensor = torch.tensor([1, 2, 3]) assert has_tensor(["a", 10, tensor]) assert not has_tensor(["a", 10]) assert has_tensor(("a", 10, tensor)) assert not has_tensor(("a", 10)) assert has_tensor({"a": tensor, "b": 1}) assert not has_tensor({"a": 10, "b": 1}) assert has_tensor(tensor) assert not has_tensor(3) assert has_tensor({"x": [0, {"inside": {"double_inside": [3, [10, tensor]]}}]}) def test_combine_initial_dims(self): tensor = torch.randn(4, 10, 20, 17, 5) tensor2d = util.combine_initial_dims(tensor) assert list(tensor2d.size()) == [4 * 10 * 20 * 17, 5] def test_uncombine_initial_dims(self): embedding2d = torch.randn(4 * 10 * 20 * 17 * 5, 12) embedding = util.uncombine_initial_dims(embedding2d, torch.Size((4, 10, 20, 17, 5))) assert list(embedding.size()) == [4, 10, 20, 17, 5, 12] def test_inspect_model_parameters(self): model_archive = str( self.FIXTURES_ROOT / "decomposable_attention" / "serialization" / "model.tar.gz" ) parameters_inspection = str( self.FIXTURES_ROOT / "decomposable_attention" / "parameters_inspection.json" ) model = load_archive(model_archive).model with open(parameters_inspection) as file: parameters_inspection_dict = json.load(file) assert parameters_inspection_dict == util.inspect_parameters(model) def test_move_to_device(self): # We're faking the tensor here so that we can test the calls to .cuda() without actually # needing a GPU. class FakeTensor(torch.Tensor): def __init__(self): self._device = None def cuda(self, device): self._device = device return self class A(NamedTuple): a: int b: torch.Tensor structured_obj = { "a": [A(1, FakeTensor()), A(2, FakeTensor())], "b": FakeTensor(), "c": (1, FakeTensor()), } new_device = 4 moved_obj = util.move_to_device(structured_obj, new_device) assert moved_obj["a"][0].a == 1 assert moved_obj["a"][0].b._device == new_device assert moved_obj["a"][1].b._device == new_device assert moved_obj["b"]._device == new_device assert moved_obj["c"][0] == 1 assert moved_obj["c"][1]._device == new_device def test_extend_layer(self): lin_layer = torch.nn.Linear(10, 5) new_dim = 8 old_weights = lin_layer.weight.data.clone() old_bias = lin_layer.bias.data.clone() util.extend_layer(lin_layer, new_dim) assert lin_layer.weight.data.shape == (8, 10) assert lin_layer.bias.data.shape == (8,) assert (lin_layer.weight.data[:5] == old_weights).all() assert (lin_layer.bias.data[:5] == old_bias).all() assert lin_layer.out_features == new_dim def test_masked_topk_selects_top_scored_items_and_respects_masking(self): items = torch.randn([3, 4, 5]).clamp(min=0.0, max=1.0) items[0, :2, :] = 1 items[1, 2:, :] = 1 items[2, 2:, :] = 1 scores = items.sum(-1) mask = torch.ones([3, 4]).bool() mask[1, 0] = 0 mask[1, 3] = 0 pruned_scores, pruned_mask, pruned_indices = util.masked_topk(scores, mask, 2) # Second element in the batch would have indices 2, 3, but # 3 and 0 are masked, so instead it has 1, 2. numpy.testing.assert_array_equal( pruned_indices.data.numpy(), numpy.array([[0, 1], [1, 2], [2, 3]]) ) numpy.testing.assert_array_equal(pruned_mask.data.numpy(), numpy.ones([3, 2])) # scores should be the result of index_selecting the pruned_indices. correct_scores = util.batched_index_select(scores.unsqueeze(-1), pruned_indices).squeeze(-1) self.assert_array_equal_with_mask(correct_scores, pruned_scores, pruned_mask) def test_masked_topk_works_for_completely_masked_rows(self): items = torch.randn([3, 4, 5]).clamp(min=0.0, max=1.0) items[0, :2, :] = 1 items[1, 2:, :] = 1 items[2, 2:, :] = 1 scores = items.sum(-1) mask = torch.ones([3, 4]).bool() mask[1, 0] = 0 mask[1, 3] = 0 mask[2, :] = 0 # fully masked last batch element. pruned_scores, pruned_mask, pruned_indices = util.masked_topk(scores, mask, 2) # We can't check the last row here, because it's completely masked. # Instead we'll check that the scores for these elements are very small. numpy.testing.assert_array_equal( pruned_indices[:2].data.numpy(), numpy.array([[0, 1], [1, 2]]) ) numpy.testing.assert_array_equal( pruned_mask.data.numpy(), numpy.array([[1, 1], [1, 1], [0, 0]]) ) # scores should be the result of index_selecting the pruned_indices. correct_scores = util.batched_index_select(scores.unsqueeze(-1), pruned_indices).squeeze(-1) self.assert_array_equal_with_mask(correct_scores, pruned_scores, pruned_mask) def test_masked_topk_selects_top_scored_items_and_respects_masking_different_num_items(self): items = torch.randn([3, 4, 5]).clamp(min=0.0, max=1.0) items[0, 0, :] = 1.5 items[0, 1, :] = 2 items[0, 3, :] = 1 items[1, 1:3, :] = 1 items[2, 0, :] = 1 items[2, 1, :] = 2 items[2, 2, :] = 1.5 scores = items.sum(-1) mask = torch.ones([3, 4]).bool() mask[1, 3] = 0 k = torch.tensor([3, 2, 1], dtype=torch.long) pruned_scores, pruned_mask, pruned_indices = util.masked_topk(scores, mask, k) # Second element in the batch would have indices 2, 3, but # 3 and 0 are masked, so instead it has 1, 2. numpy.testing.assert_array_equal( pruned_indices.data.numpy(), numpy.array([[0, 1, 3], [1, 2, 2], [1, 2, 2]]) ) numpy.testing.assert_array_equal( pruned_mask.data.numpy(), numpy.array([[1, 1, 1], [1, 1, 0], [1, 0, 0]]) ) # scores should be the result of index_selecting the pruned_indices. correct_scores = util.batched_index_select(scores.unsqueeze(-1), pruned_indices).squeeze(-1) self.assert_array_equal_with_mask(correct_scores, pruned_scores, pruned_mask) def test_masked_topk_works_for_row_with_no_items_requested(self): # Case where `num_items_to_keep` is a tensor rather than an int. Make sure it does the right # thing when no items are requested for one of the rows. items = torch.randn([3, 4, 5]).clamp(min=0.0, max=1.0) items[0, :3, :] = 1 items[1, 2:, :] = 1 items[2, 2:, :] = 1 scores = items.sum(-1) mask = torch.ones([3, 4]).bool() mask[1, 0] = 0 mask[1, 3] = 0 k = torch.tensor([3, 2, 0], dtype=torch.long) pruned_scores, pruned_mask, pruned_indices = util.masked_topk(scores, mask, k) # First element just picks top three entries. Second would pick entries 2 and 3, but 0 and 3 # are masked, so it takes 1 and 2 (repeating the second index). The third element is # entirely masked and just repeats the largest index with a top-3 score. numpy.testing.assert_array_equal( pruned_indices.data.numpy(), numpy.array([[0, 1, 2], [1, 2, 2], [3, 3, 3]]) ) numpy.testing.assert_array_equal( pruned_mask.data.numpy(), numpy.array([[1, 1, 1], [1, 1, 0], [0, 0, 0]]) ) # scores should be the result of index_selecting the pruned_indices. correct_scores = util.batched_index_select(scores.unsqueeze(-1), pruned_indices).squeeze(-1) self.assert_array_equal_with_mask(correct_scores, pruned_scores, pruned_mask) def test_masked_topk_works_for_multiple_dimensions(self): # fmt: off items = torch.FloatTensor([ # (3, 2, 5) [[4, 2, 9, 9, 7], [-4, -2, -9, -9, -7]], [[5, 4, 1, 8, 8], [9, 1, 7, 4, 1]], [[9, 8, 9, 6, 0], [2, 2, 2, 2, 2]], ]).unsqueeze(-1).expand(3, 2, 5, 4) mask = torch.tensor([ [[False, False, False, False, False], [True, True, True, True, True]], [[True, True, True, True, False], [False, True, True, True, True]], [[True, False, True, True, True], [False, True, False, True, True]], ]).unsqueeze(-1).expand(3, 2, 5, 4) # This is the same as just specifying a scalar int, but we want to test this behavior k = torch.ones(3, 5, 4, dtype=torch.long) k[1, 3, :] = 2 target_items = torch.FloatTensor([ [[-4, -2, -9, -9, -7], [0, 0, 0, 0, 0]], [[5, 4, 7, 8, 1], [0, 0, 0, 4, 0]], [[9, 2, 9, 6, 2], [0, 0, 0, 0, 0]], ]).unsqueeze(-1).expand(3, 2, 5, 4) target_mask = torch.ones(3, 2, 5, 4, dtype=torch.bool) target_mask[:, 1, :, :] = 0 target_mask[1, 1, 3, :] = 1 target_indices = torch.LongTensor([ [[1, 1, 1, 1, 1], [0, 0, 0, 0, 0]], [[0, 0, 1, 0, 1], [0, 0, 0, 1, 0]], [[0, 1, 0, 0, 1], [0, 0, 0, 0, 0]], ]).unsqueeze(-1).expand(3, 2, 5, 4) # fmt: on pruned_items, pruned_mask, pruned_indices = util.masked_topk(items, mask, k, dim=1) numpy.testing.assert_array_equal(pruned_mask.data.numpy(), target_mask.data.numpy()) self.assert_array_equal_with_mask(pruned_items, target_items, pruned_mask) self.assert_array_equal_with_mask(pruned_indices, target_indices, pruned_mask) def assert_array_equal_with_mask(self, a, b, mask): numpy.testing.assert_array_equal((a * mask).data.numpy(), (b * mask).data.numpy()) def test_tensors_equal(self): # Basic assert util.tensors_equal(torch.tensor([1]), torch.tensor([1])) assert not util.tensors_equal(torch.tensor([1]), torch.tensor([2])) # Bool assert util.tensors_equal(torch.tensor([True]), torch.tensor([True])) # Cross dtype assert util.tensors_equal(torch.tensor([1]), torch.tensor([1.0])) assert util.tensors_equal(torch.tensor([1]), torch.tensor([True])) # Containers assert util.tensors_equal([torch.tensor([1])], [torch.tensor([1])]) assert not util.tensors_equal([torch.tensor([1])], [torch.tensor([2])]) assert util.tensors_equal({"key": torch.tensor([1])}, {"key": torch.tensor([1])})
[ "allennlp.nn.util.bucket_values", "allennlp.nn.util.masked_topk", "numpy.random.rand", "torch.LongTensor", "allennlp.nn.util.get_text_field_mask", "torch.max", "allennlp.nn.util.get_combined_dim", "torch.from_numpy", "allennlp.nn.util.add_sentence_boundary_token_ids", "numpy.array", "allennlp.nn.util.logsumexp", "allennlp.nn.util.inspect_parameters", "allennlp.nn.util.clamp_tensor", "allennlp.nn.util.masked_max", "allennlp.nn.util.flattened_index_select", "torch.nn.functional.softmax", "allennlp.nn.util.sequence_cross_entropy_with_logits", "numpy.testing.assert_array_almost_equal", "allennlp.nn.util.viterbi_decode", "allennlp.nn.util.combine_initial_dims", "flaky.flaky", "numpy.asarray", "allennlp.nn.util.get_mask_from_sequence_lengths", "numpy.exp", "numpy.testing.assert_almost_equal", "allennlp.nn.util.weighted_sum", "allennlp.nn.util.get_final_encoder_states", "allennlp.nn.util.masked_mean", "torch.randn", "random.randint", "numpy.ones", "allennlp.nn.util.flatten_and_batch_shift_indices", "torch.Tensor", "torch.empty_like", "allennlp.nn.util.remove_sentence_boundaries", "pytest.raises", "numpy.isnan", "torch.nn.functional.log_softmax", "allennlp.nn.util.masked_log_softmax", "torch.Size", "numpy.random.randn", "allennlp.nn.util.get_lengths_from_binary_sequence_mask", "allennlp.common.util.sanitize", "allennlp.models.load_archive", "allennlp.nn.util.sort_batch_by_length", "allennlp.nn.util.masked_softmax", "allennlp.nn.util.move_to_device", "allennlp.nn.util.combine_tensors_and_multiply", "torch.FloatTensor", "json.load", "torch.tensor", "allennlp.nn.util.add_positional_features", "allennlp.nn.util.extend_layer", "allennlp.nn.util.masked_flip", "numpy.sum", "torch.nn.Linear", "allennlp.nn.util.batched_index_select", "numpy.random.randint", "allennlp.nn.util.batched_span_select", "torch.zeros", "torch.rand", "torch.ones" ]
[((40211, 40242), 'flaky.flaky', 'flaky', ([], {'max_runs': '(3)', 'min_passes': '(1)'}), '(max_runs=3, min_passes=1)\n', (40216, 40242), False, 'from flaky import flaky\n'), ((537, 725), 'torch.tensor', 'torch.tensor', (['[[True, True, True, False, False, False], [True, True, False, False, False,\n False], [True, True, True, True, True, True], [True, False, False, \n False, False, False]]'], {}), '([[True, True, True, False, False, False], [True, True, False, \n False, False, False], [True, True, True, True, True, True], [True, \n False, False, False, False, False]])\n', (549, 725), False, 'import torch\n'), ((835, 890), 'allennlp.nn.util.get_lengths_from_binary_sequence_mask', 'util.get_lengths_from_binary_sequence_mask', (['binary_mask'], {}), '(binary_mask)\n', (877, 890), False, 'from allennlp.nn import util\n'), ((1055, 1088), 'torch.LongTensor', 'torch.LongTensor', (['[4, 3, 1, 4, 2]'], {}), '([4, 3, 1, 4, 2])\n', (1071, 1088), False, 'import torch\n'), ((1182, 1299), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['mask', '[[1, 1, 1, 1, 0], [1, 1, 1, 0, 0], [1, 0, 0, 0, 0], [1, 1, 1, 1, 0], [1, 1,\n 0, 0, 0]]'], {}), '(mask, [[1, 1, 1, 1, 0], [1, 1, 1, 0, 0], [1, 0, 0, 0, 0\n ], [1, 1, 1, 1, 0], [1, 1, 0, 0, 0]])\n', (1201, 1299), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((1805, 1860), 'allennlp.nn.util.get_lengths_from_binary_sequence_mask', 'util.get_lengths_from_binary_sequence_mask', (['binary_mask'], {}), '(binary_mask)\n', (1847, 1860), False, 'from allennlp.nn import util\n'), ((2039, 2085), 'torch.LongTensor', 'torch.LongTensor', (['[[0, 1, 1, 0], [2, 0, 2, 2]]'], {}), '([[0, 1, 1, 0], [2, 0, 2, 2]])\n', (2055, 2085), False, 'import torch\n'), ((2098, 2130), 'torch.FloatTensor', 'torch.FloatTensor', (['[3, 4, -5, 3]'], {}), '([3, 4, -5, 3])\n', (2115, 2130), False, 'import torch\n'), ((2292, 2352), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['clamped_tensor', '[[0, 0, 3], [3, 0, -3]]'], {}), '(clamped_tensor, [[0, 0, 3], [3, 0, -3]])\n', (2311, 2352), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((2408, 2448), 'torch.LongTensor', 'torch.LongTensor', (['[[0, 1, 1], [2, 0, 2]]'], {}), '([[0, 1, 1], [2, 0, 2]])\n', (2424, 2448), False, 'import torch\n'), ((2461, 2490), 'torch.FloatTensor', 'torch.FloatTensor', (['[3, 4, -5]'], {}), '([3, 4, -5])\n', (2478, 2490), False, 'import torch\n'), ((2652, 2712), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['clamped_tensor', '[[0, 0, 3], [3, 0, -3]]'], {}), '(clamped_tensor, [[0, 0, 3], [3, 0, -3]])\n', (2671, 2712), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((2762, 2802), 'torch.tensor', 'torch.tensor', (['[[5, -4, 3], [-3, 0, -30]]'], {}), '([[5, -4, 3], [-3, 0, -30]])\n', (2774, 2802), False, 'import torch\n'), ((2828, 2876), 'allennlp.nn.util.clamp_tensor', 'util.clamp_tensor', (['tensor'], {'minimum': '(-3)', 'maximum': '(3)'}), '(tensor, minimum=-3, maximum=3)\n', (2845, 2876), False, 'from allennlp.nn import util\n'), ((2885, 2947), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['clamped_tensor', '[[3, -3, 3], [-3, 0, -3]]'], {}), '(clamped_tensor, [[3, -3, 3], [-3, 0, -3]])\n', (2904, 2947), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((3008, 3029), 'torch.rand', 'torch.rand', (['[5, 7, 9]'], {}), '([5, 7, 9])\n', (3018, 3029), False, 'import torch\n'), ((3174, 3207), 'torch.LongTensor', 'torch.LongTensor', (['[3, 4, 1, 5, 7]'], {}), '([3, 4, 1, 5, 7])\n', (3190, 3207), False, 'import torch\n'), ((3268, 3319), 'allennlp.nn.util.sort_batch_by_length', 'util.sort_batch_by_length', (['tensor', 'sequence_lengths'], {}), '(tensor, sequence_lengths)\n', (3293, 3319), False, 'from allennlp.nn import util\n'), ((4041, 4163), 'torch.Tensor', 'torch.Tensor', (['[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18,\n 19, 20], [21, 22, 23, 24]]]'], {}), '([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, \n 16], [17, 18, 19, 20], [21, 22, 23, 24]]])\n', (4053, 4163), False, 'import torch\n'), ((4243, 4298), 'torch.tensor', 'torch.tensor', (['[[True, True, True], [True, True, False]]'], {}), '([[True, True, True], [True, True, False]])\n', (4255, 4298), False, 'import torch\n'), ((4322, 4395), 'allennlp.nn.util.get_final_encoder_states', 'util.get_final_encoder_states', (['encoder_outputs', 'mask'], {'bidirectional': '(False)'}), '(encoder_outputs, mask, bidirectional=False)\n', (4351, 4395), False, 'from allennlp.nn import util\n'), ((4511, 4583), 'allennlp.nn.util.get_final_encoder_states', 'util.get_final_encoder_states', (['encoder_outputs', 'mask'], {'bidirectional': '(True)'}), '(encoder_outputs, mask, bidirectional=True)\n', (4540, 4583), False, 'from allennlp.nn import util\n'), ((4786, 4822), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 3.0]]'], {}), '([[1.0, 2.0, 3.0]])\n', (4803, 4822), False, 'import torch\n'), ((5124, 5160), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 5.0]]'], {}), '([[1.0, 2.0, 5.0]])\n', (5141, 5160), False, 'import torch\n'), ((5431, 5467), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0]])\n', (5448, 5467), False, 'import torch\n'), ((5755, 5808), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]]'], {}), '([[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]])\n', (5772, 5808), False, 'import torch\n'), ((6203, 6256), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 5.0], [0.0, 0.0, 0.0]]'], {}), '([[1.0, 2.0, 5.0], [0.0, 0.0, 0.0]])\n', (6220, 6256), False, 'import torch\n'), ((6662, 6698), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 5.0]]'], {}), '([[1.0, 2.0, 5.0]])\n', (6679, 6698), False, 'import torch\n'), ((6717, 6752), 'torch.tensor', 'torch.tensor', (['[[True, False, True]]'], {}), '([[True, False, True]])\n', (6729, 6752), False, 'import torch\n'), ((6958, 6999), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 2.0, 3.0, 4.0]]'], {}), '([[0.0, 2.0, 3.0, 4.0]])\n', (6975, 6999), False, 'import torch\n'), ((7018, 7059), 'torch.tensor', 'torch.tensor', (['[[True, False, True, True]]'], {}), '([[True, False, True, True]])\n', (7030, 7059), False, 'import torch\n'), ((7400, 7441), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0]])\n', (7417, 7441), False, 'import torch\n'), ((7460, 7503), 'torch.tensor', 'torch.tensor', (['[[False, False, False, True]]'], {}), '([[False, False, False, True]])\n', (7472, 7503), False, 'import torch\n'), ((7793, 7834), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 2.0, 3.0, 4.0]]'], {}), '([[0.0, 2.0, 3.0, 4.0]])\n', (7810, 7834), False, 'import torch\n'), ((7853, 7897), 'torch.tensor', 'torch.tensor', (['[[False, False, False, False]]'], {}), '([[False, False, False, False]])\n', (7865, 7897), False, 'import torch\n'), ((8191, 8232), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0]])\n', (8208, 8232), False, 'import torch\n'), ((8251, 8295), 'torch.tensor', 'torch.tensor', (['[[False, False, False, False]]'], {}), '([[False, False, False, False]])\n', (8263, 8295), False, 'import torch\n'), ((8586, 8627), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 1.0, 100000.0]]'], {}), '([[1.0, 1.0, 100000.0]])\n', (8603, 8627), False, 'import torch\n'), ((8641, 8676), 'torch.tensor', 'torch.tensor', (['[[True, True, False]]'], {}), '([[True, True, False]])\n', (8653, 8676), False, 'import torch\n'), ((8914, 8967), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]]'], {}), '([[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]])\n', (8931, 8967), False, 'import torch\n'), ((8983, 9038), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, True]]'], {}), '([[True, False, True], [True, True, True]])\n', (8995, 9038), False, 'import torch\n'), ((9427, 9480), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]])\n', (9444, 9480), False, 'import torch\n'), ((9496, 9551), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, True]]'], {}), '([[True, False, True], [True, True, True]])\n', (9508, 9551), False, 'import torch\n'), ((9912, 9965), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]])\n', (9929, 9965), False, 'import torch\n'), ((9981, 10039), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [False, False, False]]'], {}), '([[True, False, True], [False, False, False]])\n', (9993, 10039), False, 'import torch\n'), ((10269, 10322), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]])\n', (10286, 10322), False, 'import torch\n'), ((10338, 10396), 'torch.tensor', 'torch.tensor', (['[[False, False, False], [True, False, True]]'], {}), '([[False, False, False], [True, False, True]])\n', (10350, 10396), False, 'import torch\n'), ((10748, 10784), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 5.0]]'], {}), '([[1.0, 2.0, 5.0]])\n', (10765, 10784), False, 'import torch\n'), ((10803, 10838), 'torch.tensor', 'torch.tensor', (['[[True, False, True]]'], {}), '([[True, False, True]])\n', (10815, 10838), False, 'import torch\n'), ((11089, 11130), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 2.0, 3.0, 4.0]]'], {}), '([[0.0, 2.0, 3.0, 4.0]])\n', (11106, 11130), False, 'import torch\n'), ((11149, 11190), 'torch.tensor', 'torch.tensor', (['[[True, False, True, True]]'], {}), '([[True, False, True, True]])\n', (11161, 11190), False, 'import torch\n'), ((11576, 11617), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0]])\n', (11593, 11617), False, 'import torch\n'), ((11636, 11679), 'torch.tensor', 'torch.tensor', (['[[False, False, False, True]]'], {}), '([[False, False, False, True]])\n', (11648, 11679), False, 'import torch\n'), ((12014, 12055), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 2.0, 3.0, 4.0]]'], {}), '([[0.0, 2.0, 3.0, 4.0]])\n', (12031, 12055), False, 'import torch\n'), ((12074, 12118), 'torch.tensor', 'torch.tensor', (['[[False, False, False, False]]'], {}), '([[False, False, False, False]])\n', (12086, 12118), False, 'import torch\n'), ((12461, 12502), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0]])\n', (12478, 12502), False, 'import torch\n'), ((12521, 12565), 'torch.tensor', 'torch.tensor', (['[[False, False, False, False]]'], {}), '([[False, False, False, False]])\n', (12533, 12565), False, 'import torch\n'), ((12905, 12946), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 1.0, 100000.0]]'], {}), '([[1.0, 1.0, 100000.0]])\n', (12922, 12946), False, 'import torch\n'), ((12960, 12995), 'torch.tensor', 'torch.tensor', (['[[True, True, False]]'], {}), '([[True, True, False]])\n', (12972, 12995), False, 'import torch\n'), ((13278, 13331), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]]'], {}), '([[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]])\n', (13295, 13331), False, 'import torch\n'), ((13347, 13402), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, True]]'], {}), '([[True, False, True], [True, True, True]])\n', (13359, 13402), False, 'import torch\n'), ((13836, 13889), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]])\n', (13853, 13889), False, 'import torch\n'), ((13905, 13960), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, True]]'], {}), '([[True, False, True], [True, True, True]])\n', (13917, 13960), False, 'import torch\n'), ((14366, 14419), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]])\n', (14383, 14419), False, 'import torch\n'), ((14435, 14493), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [False, False, False]]'], {}), '([[True, False, True], [False, False, False]])\n', (14447, 14493), False, 'import torch\n'), ((14802, 14855), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0], [1.0, 2.0, 3.0]])\n', (14819, 14855), False, 'import torch\n'), ((14871, 14929), 'torch.tensor', 'torch.tensor', (['[[False, False, False], [True, False, True]]'], {}), '([[False, False, False], [True, False, True]])\n', (14883, 14929), False, 'import torch\n'), ((15520, 15556), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 2.0, 5.0]]'], {}), '([[1.0, 2.0, 5.0]])\n', (15537, 15556), False, 'import torch\n'), ((15575, 15610), 'torch.tensor', 'torch.tensor', (['[[True, False, True]]'], {}), '([[True, False, True]])\n', (15587, 15610), False, 'import torch\n'), ((15853, 15894), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 2.0, 3.0, 4.0]]'], {}), '([[0.0, 2.0, 3.0, 4.0]])\n', (15870, 15894), False, 'import torch\n'), ((15913, 15954), 'torch.tensor', 'torch.tensor', (['[[True, False, True, True]]'], {}), '([[True, False, True, True]])\n', (15925, 15954), False, 'import torch\n'), ((16310, 16351), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0]])\n', (16327, 16351), False, 'import torch\n'), ((16370, 16413), 'torch.tensor', 'torch.tensor', (['[[False, False, False, True]]'], {}), '([[False, False, False, True]])\n', (16382, 16413), False, 'import torch\n'), ((16810, 16851), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.0, 2.0, 3.0, 4.0]]'], {}), '([[0.0, 2.0, 3.0, 4.0]])\n', (16827, 16851), False, 'import torch\n'), ((16870, 16914), 'torch.tensor', 'torch.tensor', (['[[False, False, False, False]]'], {}), '([[False, False, False, False]])\n', (16882, 16914), False, 'import torch\n'), ((17158, 17193), 'torch.FloatTensor', 'torch.FloatTensor', (['[1.0, 12.0, 5.0]'], {}), '([1.0, 12.0, 5.0])\n', (17175, 17193), False, 'import torch\n'), ((17212, 17245), 'torch.tensor', 'torch.tensor', (['[True, False, True]'], {}), '([True, False, True])\n', (17224, 17245), False, 'import torch\n'), ((17336, 17383), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_1d_maxed', '(5.0)'], {}), '(vector_1d_maxed, 5.0)\n', (17361, 17383), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((17502, 17537), 'torch.FloatTensor', 'torch.FloatTensor', (['[1.0, 12.0, 5.0]'], {}), '([1.0, 12.0, 5.0])\n', (17519, 17537), False, 'import torch\n'), ((17556, 17591), 'torch.tensor', 'torch.tensor', (['[False, False, False]'], {}), '([False, False, False])\n', (17568, 17591), False, 'import torch\n'), ((17792, 17848), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]]'], {}), '([[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]])\n', (17809, 17848), False, 'import torch\n'), ((17864, 17920), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, False]]'], {}), '([[True, False, True], [True, True, False]])\n', (17876, 17920), False, 'import torch\n'), ((18145, 18201), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]]'], {}), '([[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]])\n', (18162, 18201), False, 'import torch\n'), ((18217, 18273), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, False]]'], {}), '([[True, False, True], [True, True, False]])\n', (18229, 18273), False, 'import torch\n'), ((18486, 18592), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[1.0, 2.0], [12.0, 3.0], [5.0, -1.0]], [[-1.0, -3.0], [-2.0, -0.5], [3.0,\n 8.0]]]'], {}), '([[[1.0, 2.0], [12.0, 3.0], [5.0, -1.0]], [[-1.0, -3.0], [\n -2.0, -0.5], [3.0, 8.0]]])\n', (18503, 18592), False, 'import torch\n'), ((18957, 18992), 'torch.FloatTensor', 'torch.FloatTensor', (['[1.0, 12.0, 5.0]'], {}), '([1.0, 12.0, 5.0])\n', (18974, 18992), False, 'import torch\n'), ((19011, 19044), 'torch.tensor', 'torch.tensor', (['[True, False, True]'], {}), '([True, False, True])\n', (19023, 19044), False, 'import torch\n'), ((19135, 19181), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['vector_1d_mean', '(3.0)'], {}), '(vector_1d_mean, 3.0)\n', (19160, 19181), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((19300, 19335), 'torch.FloatTensor', 'torch.FloatTensor', (['[1.0, 12.0, 5.0]'], {}), '([1.0, 12.0, 5.0])\n', (19317, 19335), False, 'import torch\n'), ((19354, 19389), 'torch.tensor', 'torch.tensor', (['[False, False, False]'], {}), '([False, False, False])\n', (19366, 19389), False, 'import torch\n'), ((19589, 19645), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]]'], {}), '([[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]])\n', (19606, 19645), False, 'import torch\n'), ((19661, 19717), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, False]]'], {}), '([[True, False, True], [True, True, False]])\n', (19673, 19717), False, 'import torch\n'), ((19941, 19997), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]]'], {}), '([[1.0, 12.0, 5.0], [-1.0, -2.0, 3.0]])\n', (19958, 19997), False, 'import torch\n'), ((20013, 20069), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, False]]'], {}), '([[True, False, True], [True, True, False]])\n', (20025, 20069), False, 'import torch\n'), ((20281, 20387), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[1.0, 2.0], [12.0, 3.0], [5.0, -1.0]], [[-1.0, -3.0], [-2.0, -0.5], [3.0,\n 8.0]]]'], {}), '([[[1.0, 2.0], [12.0, 3.0], [5.0, -1.0]], [[-1.0, -3.0], [\n -2.0, -0.5], [3.0, 8.0]]])\n', (20298, 20387), False, 'import torch\n'), ((20703, 20796), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[6, 6, 6], [1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4], [5, 5, 5]]]'], {}), '([[[6, 6, 6], [1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4],\n [5, 5, 5]]])\n', (20720, 20796), False, 'import torch\n'), ((20902, 20934), 'allennlp.nn.util.masked_flip', 'util.masked_flip', (['tensor', '[1, 2]'], {}), '(tensor, [1, 2])\n', (20918, 20934), False, 'from allennlp.nn import util\n'), ((20943, 20982), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['response', 'solution'], {}), '(response, solution)\n', (20962, 20982), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((21001, 21116), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[6, 6, 6], [1, 1, 1], [2, 2, 2], [0, 0, 0]], [[3, 3, 3], [4, 4, 4], [5, 5,\n 5], [1, 2, 3]]]'], {}), '([[[6, 6, 6], [1, 1, 1], [2, 2, 2], [0, 0, 0]], [[3, 3, 3],\n [4, 4, 4], [5, 5, 5], [1, 2, 3]]])\n', (21018, 21116), False, 'import torch\n'), ((21348, 21380), 'allennlp.nn.util.masked_flip', 'util.masked_flip', (['tensor', '[3, 4]'], {}), '(tensor, [3, 4])\n', (21364, 21380), False, 'from allennlp.nn import util\n'), ((21389, 21428), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['response', 'solution'], {}), '(response, solution)\n', (21408, 21428), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((21447, 21612), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[6, 6, 6], [1, 1, 1], [2, 2, 2], [0, 0, 0]], [[3, 3, 3], [4, 4, 4], [5, 5,\n 5], [1, 2, 3]], [[1, 1, 1], [2, 2, 2], [0, 0, 0], [0, 0, 0]]]'], {}), '([[[6, 6, 6], [1, 1, 1], [2, 2, 2], [0, 0, 0]], [[3, 3, 3],\n [4, 4, 4], [5, 5, 5], [1, 2, 3]], [[1, 1, 1], [2, 2, 2], [0, 0, 0], [0,\n 0, 0]]])\n', (21464, 21612), False, 'import torch\n'), ((21914, 21949), 'allennlp.nn.util.masked_flip', 'util.masked_flip', (['tensor', '[3, 4, 2]'], {}), '(tensor, [3, 4, 2])\n', (21930, 21949), False, 'from allennlp.nn import util\n'), ((21958, 21997), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['response', 'solution'], {}), '(response, solution)\n', (21977, 21997), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((23880, 23927), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['actual_mask', 'expected_mask'], {}), '(actual_mask, expected_mask)\n', (23899, 23927), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((24495, 24556), 'numpy.random.rand', 'numpy.random.rand', (['batch_size', 'sentence_length', 'embedding_dim'], {}), '(batch_size, sentence_length, embedding_dim)\n', (24512, 24556), False, 'import numpy\n'), ((24651, 24695), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.3, 0.4, 0.1, 0, 1.2]]'], {}), '([[0.3, 0.4, 0.1, 0, 1.2]])\n', (24668, 24695), False, 'import torch\n'), ((25106, 25191), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['aggregated_array', '[expected_array]'], {'decimal': '(5)'}), '(aggregated_array, [expected_array], decimal=5\n )\n', (25139, 25191), False, 'import numpy\n'), ((25385, 25459), 'numpy.random.rand', 'numpy.random.rand', (['batch_size', 'length_1', 'length_2', 'length_3', 'embedding_dim'], {}), '(batch_size, length_1, length_2, length_3, embedding_dim)\n', (25402, 25459), False, 'import numpy\n'), ((25486, 25545), 'numpy.random.rand', 'numpy.random.rand', (['batch_size', 'length_1', 'length_2', 'length_3'], {}), '(batch_size, length_1, length_2, length_3)\n', (25503, 25545), False, 'import numpy\n'), ((26049, 26140), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['aggregated_array[0, 3, 2]', 'expected_array'], {'decimal': '(5)'}), '(aggregated_array[0, 3, 2], expected_array,\n decimal=5)\n', (26082, 26140), False, 'import numpy\n'), ((26342, 26396), 'numpy.random.rand', 'numpy.random.rand', (['batch_size', 'length_3', 'embedding_dim'], {}), '(batch_size, length_3, embedding_dim)\n', (26359, 26396), False, 'import numpy\n'), ((26423, 26482), 'numpy.random.rand', 'numpy.random.rand', (['batch_size', 'length_1', 'length_2', 'length_3'], {}), '(batch_size, length_1, length_2, length_3)\n', (26440, 26482), False, 'import numpy\n'), ((27398, 27452), 'numpy.random.rand', 'numpy.random.rand', (['batch_size', 'length_2', 'embedding_dim'], {}), '(batch_size, length_2, embedding_dim)\n', (27415, 27452), False, 'import numpy\n'), ((27479, 27528), 'numpy.random.rand', 'numpy.random.rand', (['batch_size', 'length_1', 'length_2'], {}), '(batch_size, length_1, length_2)\n', (27496, 27528), False, 'import numpy\n'), ((28378, 28397), 'torch.zeros', 'torch.zeros', (['[9, 9]'], {}), '([9, 9])\n', (28389, 28397), False, 'import torch\n'), ((28419, 28479), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits.data', 'transition_matrix'], {}), '(sequence_logits.data, transition_matrix)\n', (28438, 28479), False, 'from allennlp.nn import util\n'), ((28508, 28537), 'torch.max', 'torch.max', (['sequence_logits', '(1)'], {}), '(sequence_logits, 1)\n', (28517, 28537), False, 'import torch\n'), ((28783, 28802), 'torch.zeros', 'torch.zeros', (['[9, 9]'], {}), '([9, 9])\n', (28794, 28802), False, 'import torch\n'), ((28839, 28855), 'torch.zeros', 'torch.zeros', (['[9]'], {}), '([9])\n', (28850, 28855), False, 'import torch\n'), ((28981, 28997), 'torch.zeros', 'torch.zeros', (['[9]'], {}), '([9])\n', (28992, 28997), False, 'import torch\n'), ((29105, 29275), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits.data', 'transition_matrix'], {'allowed_end_transitions': 'allowed_end_transitions', 'allowed_start_transitions': 'allowed_start_transitions'}), '(sequence_logits.data, transition_matrix,\n allowed_end_transitions=allowed_end_transitions,\n allowed_start_transitions=allowed_start_transitions)\n', (29124, 29275), False, 'from allennlp.nn import util\n'), ((29545, 29670), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 0, 3, 5], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0,\n 0, 3, 4], [0, 0, 0, 3, 4]]'], {}), '([[0, 0, 0, 3, 5], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0,\n 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4]])\n', (29562, 29670), False, 'import torch\n'), ((29883, 29902), 'torch.zeros', 'torch.zeros', (['[5, 5]'], {}), '([5, 5])\n', (29894, 29902), False, 'import torch\n'), ((30003, 30058), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits', 'transition_matrix'], {}), '(sequence_logits, transition_matrix)\n', (30022, 30058), False, 'from allennlp.nn import util\n'), ((30246, 30371), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0,\n 0, 4, 4], [0, 0, 0, 4, 4]]'], {}), '([[0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0,\n 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4]])\n', (30263, 30371), False, 'import torch\n'), ((30705, 30724), 'torch.zeros', 'torch.zeros', (['[5, 5]'], {}), '([5, 5])\n', (30716, 30724), False, 'import torch\n'), ((30860, 30915), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits', 'transition_matrix'], {}), '(sequence_logits, transition_matrix)\n', (30879, 30915), False, 'from allennlp.nn import util\n'), ((30988, 31049), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1, 0, 0, 4], [1, 0, 6, 2], [0, 3, 0, 4]]'], {}), '([[1, 0, 0, 4], [1, 0, 6, 2], [0, 3, 0, 4]])\n', (31005, 31049), False, 'import torch\n'), ((31204, 31223), 'torch.zeros', 'torch.zeros', (['[4, 4]'], {}), '([4, 4])\n', (31215, 31223), False, 'import torch\n'), ((31321, 31376), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits', 'transition_matrix'], {}), '(sequence_logits, transition_matrix)\n', (31340, 31376), False, 'from allennlp.nn import util\n'), ((31558, 31683), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0,\n 0, 7, 7], [0, 0, 0, 7, 7]]'], {}), '([[0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0, 0, 7, 7], [0, 0,\n 0, 7, 7], [0, 0, 0, 7, 7], [0, 0, 0, 7, 7]])\n', (31575, 31683), False, 'import torch\n'), ((32019, 32038), 'torch.zeros', 'torch.zeros', (['[5, 5]'], {}), '([5, 5])\n', (32030, 32038), False, 'import torch\n'), ((32544, 32613), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits', 'transition_matrix', 'observations'], {}), '(sequence_logits, transition_matrix, observations)\n', (32563, 32613), False, 'from allennlp.nn import util\n'), ((32990, 33009), 'torch.zeros', 'torch.zeros', (['[9, 9]'], {}), '([9, 9])\n', (33001, 33009), False, 'import torch\n'), ((33032, 33101), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits.data', 'transition_matrix'], {'top_k': '(5)'}), '(sequence_logits.data, transition_matrix, top_k=5)\n', (33051, 33101), False, 'from allennlp.nn import util\n'), ((33131, 33160), 'torch.max', 'torch.max', (['sequence_logits', '(1)'], {}), '(sequence_logits, 1)\n', (33140, 33160), False, 'import torch\n'), ((33384, 33509), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0,\n 0, 3, 4], [0, 0, 0, 3, 4]]'], {}), '([[0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4], [0, 0,\n 0, 3, 4], [0, 0, 0, 3, 4], [0, 0, 0, 3, 4]])\n', (33401, 33509), False, 'import torch\n'), ((33722, 33741), 'torch.zeros', 'torch.zeros', (['[5, 5]'], {}), '([5, 5])\n', (33733, 33741), False, 'import torch\n'), ((33842, 33906), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits', 'transition_matrix'], {'top_k': '(5)'}), '(sequence_logits, transition_matrix, top_k=5)\n', (33861, 33906), False, 'from allennlp.nn import util\n'), ((34097, 34222), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0,\n 0, 4, 4], [0, 0, 0, 4, 0]]'], {}), '([[0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 4], [0, 0,\n 0, 4, 4], [0, 0, 0, 4, 4], [0, 0, 0, 4, 0]])\n', (34114, 34222), False, 'import torch\n'), ((34556, 34575), 'torch.zeros', 'torch.zeros', (['[5, 5]'], {}), '([5, 5])\n', (34567, 34575), False, 'import torch\n'), ((34673, 34737), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits', 'transition_matrix'], {'top_k': '(5)'}), '(sequence_logits, transition_matrix, top_k=5)\n', (34692, 34737), False, 'from allennlp.nn import util\n'), ((34813, 34874), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1, 0, 0, 4], [1, 0, 6, 2], [0, 3, 0, 4]]'], {}), '([[1, 0, 0, 4], [1, 0, 6, 2], [0, 3, 0, 4]])\n', (34830, 34874), False, 'import torch\n'), ((35029, 35048), 'torch.zeros', 'torch.zeros', (['[4, 4]'], {}), '([4, 4])\n', (35040, 35048), False, 'import torch\n'), ((35146, 35210), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits', 'transition_matrix'], {'top_k': '(5)'}), '(sequence_logits, transition_matrix, top_k=5)\n', (35165, 35210), False, 'from allennlp.nn import util\n'), ((37813, 37834), 'torch.rand', 'torch.rand', (['[5, 7, 4]'], {}), '([5, 7, 4])\n', (37823, 37834), False, 'import torch\n'), ((38282, 38347), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {}), '(tensor, targets, weights)\n', (38321, 38347), False, 'from allennlp.nn import util\n'), ((38364, 38430), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor2', 'targets', 'weights'], {}), '(tensor2, targets, weights)\n', (38403, 38430), False, 'from allennlp.nn import util\n'), ((38584, 38605), 'torch.rand', 'torch.rand', (['[1, 3, 4]'], {}), '([1, 3, 4])\n', (38594, 38605), False, 'import torch\n'), ((38696, 38714), 'torch.ones', 'torch.ones', (['[2, 3]'], {}), '([2, 3])\n', (38706, 38714), False, 'import torch\n'), ((38730, 38820), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {'label_smoothing': '(0.1)'}), '(tensor, targets, weights,\n label_smoothing=0.1)\n', (38769, 38820), False, 'from allennlp.nn import util\n'), ((39573, 39594), 'torch.rand', 'torch.rand', (['[5, 7, 4]'], {}), '([5, 7, 4])\n', (39583, 39594), False, 'import torch\n'), ((39886, 39951), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {}), '(tensor, targets, weights)\n', (39925, 39951), False, 'from allennlp.nn import util\n'), ((39975, 40054), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {'average': 'None'}), '(tensor, targets, weights, average=None)\n', (40014, 40054), False, 'from allennlp.nn import util\n'), ((40485, 40506), 'torch.rand', 'torch.rand', (['[5, 7, 4]'], {}), '([5, 7, 4])\n', (40495, 40506), False, 'import torch\n'), ((40798, 40885), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {'average': '"""token"""'}), "(tensor, targets, weights, average=\n 'token')\n", (40837, 40885), False, 'from allennlp.nn import util\n'), ((40904, 40983), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {'average': 'None'}), '(tensor, targets, weights, average=None)\n', (40943, 40983), False, 'from allennlp.nn import util\n'), ((41454, 41490), 'torch.rand', 'torch.rand', (['[batch, length, classes]'], {}), '([batch, length, classes])\n', (41464, 41490), False, 'import torch\n'), ((41595, 41622), 'torch.ones', 'torch.ones', (['[batch, length]'], {}), '([batch, length])\n', (41605, 41622), False, 'import torch\n'), ((41639, 41717), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {'gamma': 'gamma'}), '(tensor, targets, weights, gamma=gamma)\n', (41678, 41717), False, 'from allennlp.nn import util\n'), ((42475, 42511), 'torch.rand', 'torch.rand', (['[batch, length, classes]'], {}), '([batch, length, classes])\n', (42485, 42511), False, 'import torch\n'), ((42616, 42643), 'torch.ones', 'torch.ones', (['[batch, length]'], {}), '([batch, length])\n', (42626, 42643), False, 'import torch\n'), ((42660, 42738), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {'alpha': 'alpha'}), '(tensor, targets, weights, alpha=alpha)\n', (42699, 42738), False, 'from allennlp.nn import util\n'), ((43574, 43593), 'torch.tensor', 'torch.tensor', (['alpha'], {}), '(alpha)\n', (43586, 43593), False, 'import torch\n'), ((43612, 43648), 'torch.rand', 'torch.rand', (['[batch, length, classes]'], {}), '([batch, length, classes])\n', (43622, 43648), False, 'import torch\n'), ((43753, 43780), 'torch.ones', 'torch.ones', (['[batch, length]'], {}), '([batch, length])\n', (43763, 43780), False, 'import torch\n'), ((43797, 43875), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {'alpha': 'alpha'}), '(tensor, targets, weights, alpha=alpha)\n', (43836, 43875), False, 'from allennlp.nn import util\n'), ((44635, 44671), 'torch.rand', 'torch.rand', (['[batch, length, classes]'], {}), '([batch, length, classes])\n', (44645, 44671), False, 'import torch\n'), ((44776, 44803), 'torch.ones', 'torch.ones', (['[batch, length]'], {}), '([batch, length])\n', (44786, 44803), False, 'import torch\n'), ((44820, 44898), 'allennlp.nn.util.sequence_cross_entropy_with_logits', 'util.sequence_cross_entropy_with_logits', (['tensor', 'targets', 'weights'], {'alpha': 'alpha'}), '(tensor, targets, weights, alpha=alpha)\n', (44859, 44898), False, 'from allennlp.nn import util\n'), ((45440, 45506), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]]'], {}), '([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]])\n', (45457, 45506), False, 'import torch\n'), ((45522, 45557), 'torch.tensor', 'torch.tensor', (['[[True, True, False]]'], {}), '([[True, True, False]])\n', (45534, 45557), False, 'import torch\n'), ((45656, 45731), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['replaced', '[[[1, 2, 3, 4], [5, 6, 7, 8], [2, 2, 2, 2]]]'], {}), '(replaced, [[[1, 2, 3, 4], [5, 6, 7, 8], [2, 2, 2, 2]]])\n', (45675, 45731), False, 'from numpy.testing import assert_array_almost_equal, assert_almost_equal\n'), ((45854, 45890), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0.4, 0.1, 0.2]]'], {}), '([[0.4, 0.1, 0.2]])\n', (45871, 45890), False, 'import torch\n'), ((45946, 45995), 'allennlp.nn.util.logsumexp', 'util.logsumexp', (['log_tensor'], {'dim': '(-1)', 'keepdim': '(False)'}), '(log_tensor, dim=-1, keepdim=False)\n', (45960, 45995), False, 'from allennlp.nn import util\n'), ((46083, 46131), 'allennlp.nn.util.logsumexp', 'util.logsumexp', (['log_tensor'], {'dim': '(-1)', 'keepdim': '(True)'}), '(log_tensor, dim=-1, keepdim=True)\n', (46097, 46131), False, 'from allennlp.nn import util\n'), ((46466, 46501), 'torch.FloatTensor', 'torch.FloatTensor', (['[[-200.0, 20.0]]'], {}), '([[-200.0, 20.0]])\n', (46483, 46501), False, 'import torch\n'), ((46592, 46642), 'torch.FloatTensor', 'torch.FloatTensor', (['[[20.0, 20.0], [-200.0, 200.0]]'], {}), '([[20.0, 20.0], [-200.0, 200.0]])\n', (46609, 46642), False, 'import torch\n'), ((46801, 46906), 'numpy.array', 'numpy.array', (['[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 9, 9, 9]], [[2, 1, 0, 7], [7, 7, 2, 3], [\n 0, 0, 4, 2]]]'], {}), '([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 9, 9, 9]], [[2, 1, 0, 7], [7,\n 7, 2, 3], [0, 0, 4, 2]]])\n', (46812, 46906), False, 'import numpy\n'), ((46943, 46982), 'torch.tensor', 'torch.tensor', (['indices'], {'dtype': 'torch.long'}), '(indices, dtype=torch.long)\n', (46955, 46982), False, 'import torch\n'), ((47009, 47058), 'allennlp.nn.util.flatten_and_batch_shift_indices', 'util.flatten_and_batch_shift_indices', (['indices', '(10)'], {}), '(indices, 10)\n', (47045, 47058), False, 'from allennlp.nn import util\n'), ((47354, 47403), 'numpy.array', 'numpy.array', (['[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]'], {}), '([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])\n', (47365, 47403), False, 'import numpy\n'), ((47627, 47666), 'torch.tensor', 'torch.tensor', (['indices'], {'dtype': 'torch.long'}), '(indices, dtype=torch.long)\n', (47639, 47666), False, 'import torch\n'), ((47686, 47729), 'allennlp.nn.util.batched_index_select', 'util.batched_index_select', (['targets', 'indices'], {}), '(targets, indices)\n', (47711, 47729), False, 'from allennlp.nn import util\n'), ((47799, 47814), 'numpy.ones', 'numpy.ones', (['[3]'], {}), '([3])\n', (47809, 47814), False, 'import numpy\n'), ((48523, 48573), 'numpy.array', 'numpy.array', (['[[[1, 11], [3, 4]], [[5, 6], [7, 8]]]'], {}), '([[[1, 11], [3, 4]], [[5, 6], [7, 8]]])\n', (48534, 48573), False, 'import numpy\n'), ((48592, 48631), 'torch.tensor', 'torch.tensor', (['indices'], {'dtype': 'torch.long'}), '(indices, dtype=torch.long)\n', (48604, 48631), False, 'import torch\n'), ((48755, 48805), 'numpy.array', 'numpy.array', (['[[[1, -1], [3, 4]], [[5, 6], [7, 8]]]'], {}), '([[[1, -1], [3, 4]], [[5, 6], [7, 8]]])\n', (48766, 48805), False, 'import numpy\n'), ((48824, 48863), 'torch.tensor', 'torch.tensor', (['indices'], {'dtype': 'torch.long'}), '(indices, dtype=torch.long)\n', (48836, 48863), False, 'import torch\n'), ((49366, 49406), 'allennlp.nn.util.batched_span_select', 'util.batched_span_select', (['targets', 'spans'], {}), '(targets, spans)\n', (49390, 49406), False, 'from allennlp.nn import util\n'), ((50289, 50318), 'numpy.array', 'numpy.array', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (50300, 50318), False, 'import numpy\n'), ((50492, 50531), 'torch.tensor', 'torch.tensor', (['indices'], {'dtype': 'torch.long'}), '(indices, dtype=torch.long)\n', (50504, 50531), False, 'import torch\n'), ((50552, 50597), 'allennlp.nn.util.flattened_index_select', 'util.flattened_index_select', (['targets', 'indices'], {}), '(targets, indices)\n', (50579, 50597), False, 'from allennlp.nn import util\n'), ((50668, 50683), 'numpy.ones', 'numpy.ones', (['[3]'], {}), '([3])\n', (50678, 50683), False, 'import numpy\n'), ((51586, 51625), 'torch.LongTensor', 'torch.LongTensor', (['[1, 2, 7, 1, 56, 900]'], {}), '([1, 2, 7, 1, 56, 900])\n', (51602, 51625), False, 'import torch\n'), ((51655, 51682), 'allennlp.nn.util.bucket_values', 'util.bucket_values', (['indices'], {}), '(indices)\n', (51673, 51682), False, 'from allennlp.nn import util\n'), ((52038, 52098), 'allennlp.nn.util.add_sentence_boundary_token_ids', 'util.add_sentence_boundary_token_ids', (['tensor', 'mask', 'bos', 'eos'], {}), '(tensor, mask, bos, eos)\n', (52074, 52098), False, 'from allennlp.nn import util\n'), ((52129, 52178), 'numpy.array', 'numpy.array', (['[[9, 1, 2, 3, 10], [9, 4, 5, 10, 0]]'], {}), '([[9, 1, 2, 3, 10], [9, 4, 5, 10, 0]])\n', (52140, 52178), False, 'import numpy\n'), ((52836, 52896), 'allennlp.nn.util.add_sentence_boundary_token_ids', 'util.add_sentence_boundary_token_ids', (['tensor', 'mask', 'bos', 'eos'], {}), '(tensor, mask, bos, eos)\n', (52872, 52896), False, 'from allennlp.nn import util\n'), ((52927, 53102), 'numpy.array', 'numpy.array', (['[[[9, 9, 9, 9], [1, 2, 3, 4], [5, 5, 5, 5], [6, 8, 1, 2], [10, 10, 10, 10]],\n [[9, 9, 9, 9], [4, 3, 2, 1], [8, 7, 6, 5], [10, 10, 10, 10], [0, 0, 0, 0]]]'], {}), '([[[9, 9, 9, 9], [1, 2, 3, 4], [5, 5, 5, 5], [6, 8, 1, 2], [10, \n 10, 10, 10]], [[9, 9, 9, 9], [4, 3, 2, 1], [8, 7, 6, 5], [10, 10, 10, \n 10], [0, 0, 0, 0]]])\n', (52938, 53102), False, 'import numpy\n'), ((53763, 53808), 'allennlp.nn.util.remove_sentence_boundaries', 'util.remove_sentence_boundaries', (['tensor', 'mask'], {}), '(tensor, mask)\n', (53794, 53808), False, 'from allennlp.nn import util\n'), ((53840, 53860), 'torch.zeros', 'torch.zeros', (['(3)', '(3)', '(7)'], {}), '(3, 3, 7)\n', (53851, 53860), False, 'import torch\n'), ((54565, 54705), 'numpy.asarray', 'numpy.asarray', (['[[0.0, 0.0, 1.0, 1.0], [0.841470957, 9.99999902e-05, 0.540302277, 1.0], [\n 0.909297407, 0.00019999998, -0.416146845, 1.0]]'], {}), '([[0.0, 0.0, 1.0, 1.0], [0.841470957, 9.99999902e-05, \n 0.540302277, 1.0], [0.909297407, 0.00019999998, -0.416146845, 1.0]])\n', (54578, 54705), False, 'import numpy\n'), ((54877, 54899), 'torch.zeros', 'torch.zeros', (['[2, 3, 4]'], {}), '([2, 3, 4])\n', (54888, 54899), False, 'import torch\n'), ((54917, 54995), 'allennlp.nn.util.add_positional_features', 'util.add_positional_features', (['tensor'], {'min_timescale': '(1.0)', 'max_timescale': '(10000.0)'}), '(tensor, min_timescale=1.0, max_timescale=10000.0)\n', (54945, 54995), False, 'from allennlp.nn import util\n'), ((55274, 55504), 'numpy.asarray', 'numpy.asarray', (['[[0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0], [0.841470957, 0.00999983307, \n 9.99999902e-05, 0.540302277, 0.999949992, 1.0, 0.0], [0.909297407, \n 0.0199986659, 0.00019999998, -0.416146815, 0.999800026, 1.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0], [0.841470957, \n 0.00999983307, 9.99999902e-05, 0.540302277, 0.999949992, 1.0, 0.0], [\n 0.909297407, 0.0199986659, 0.00019999998, -0.416146815, 0.999800026, \n 1.0, 0.0]])\n', (55287, 55504), False, 'import numpy\n'), ((56202, 56224), 'torch.zeros', 'torch.zeros', (['[2, 3, 7]'], {}), '([2, 3, 7])\n', (56213, 56224), False, 'import torch\n'), ((56242, 56320), 'allennlp.nn.util.add_positional_features', 'util.add_positional_features', (['tensor'], {'min_timescale': '(1.0)', 'max_timescale': '(10000.0)'}), '(tensor, min_timescale=1.0, max_timescale=10000.0)\n', (56270, 56320), False, 'from allennlp.nn import util\n'), ((56653, 56673), 'torch.Tensor', 'torch.Tensor', (['[4, 5]'], {}), '([4, 5])\n', (56665, 56673), False, 'import torch\n'), ((57030, 57056), 'torch.Tensor', 'torch.Tensor', (['[4, 5, 4, 5]'], {}), '([4, 5, 4, 5])\n', (57042, 57056), False, 'import torch\n'), ((58967, 58987), 'torch.Tensor', 'torch.Tensor', (['[4, 5]'], {}), '([4, 5])\n', (58979, 58987), False, 'import torch\n'), ((59350, 59370), 'torch.Tensor', 'torch.Tensor', (['[4, 5]'], {}), '([4, 5])\n', (59362, 59370), False, 'import torch\n'), ((59859, 59899), 'torch.randn', 'torch.randn', (['(1)', 'seq_len_1', 'embedding_dim'], {}), '(1, seq_len_1, embedding_dim)\n', (59870, 59899), False, 'import torch\n'), ((59913, 59953), 'torch.randn', 'torch.randn', (['(1)', 'seq_len_2', 'embedding_dim'], {}), '(1, seq_len_2, embedding_dim)\n', (59924, 59953), False, 'import torch\n'), ((59977, 60043), 'allennlp.nn.util.get_combined_dim', 'util.get_combined_dim', (['combination', '[embedding_dim, embedding_dim]'], {}), '(combination, [embedding_dim, embedding_dim])\n', (59998, 60043), False, 'from allennlp.nn import util\n'), ((60061, 60087), 'torch.Tensor', 'torch.Tensor', (['combined_dim'], {}), '(combined_dim)\n', (60073, 60087), False, 'import torch\n'), ((60493, 60533), 'torch.randn', 'torch.randn', (['(1)', 'seq_len_1', 'embedding_dim'], {}), '(1, seq_len_1, embedding_dim)\n', (60504, 60533), False, 'import torch\n'), ((60547, 60587), 'torch.randn', 'torch.randn', (['(1)', 'seq_len_2', 'embedding_dim'], {}), '(1, seq_len_2, embedding_dim)\n', (60558, 60587), False, 'import torch\n'), ((60611, 60677), 'allennlp.nn.util.get_combined_dim', 'util.get_combined_dim', (['combination', '[embedding_dim, embedding_dim]'], {}), '(combination, [embedding_dim, embedding_dim])\n', (60632, 60677), False, 'from allennlp.nn import util\n'), ((60695, 60721), 'torch.Tensor', 'torch.Tensor', (['combined_dim'], {}), '(combined_dim)\n', (60707, 60721), False, 'import torch\n'), ((61011, 61034), 'torch.tensor', 'torch.tensor', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (61023, 61034), False, 'import torch\n'), ((61524, 61553), 'torch.randn', 'torch.randn', (['(4)', '(10)', '(20)', '(17)', '(5)'], {}), '(4, 10, 20, 17, 5)\n', (61535, 61553), False, 'import torch\n'), ((61574, 61607), 'allennlp.nn.util.combine_initial_dims', 'util.combine_initial_dims', (['tensor'], {}), '(tensor)\n', (61599, 61607), False, 'from allennlp.nn import util\n'), ((61736, 61773), 'torch.randn', 'torch.randn', (['(4 * 10 * 20 * 17 * 5)', '(12)'], {}), '(4 * 10 * 20 * 17 * 5, 12)\n', (61747, 61773), False, 'import torch\n'), ((63132, 63179), 'allennlp.nn.util.move_to_device', 'util.move_to_device', (['structured_obj', 'new_device'], {}), '(structured_obj, new_device)\n', (63151, 63179), False, 'from allennlp.nn import util\n'), ((63533, 63555), 'torch.nn.Linear', 'torch.nn.Linear', (['(10)', '(5)'], {}), '(10, 5)\n', (63548, 63555), False, 'import torch\n'), ((63685, 63722), 'allennlp.nn.util.extend_layer', 'util.extend_layer', (['lin_layer', 'new_dim'], {}), '(lin_layer, new_dim)\n', (63702, 63722), False, 'from allennlp.nn import util\n'), ((64401, 64434), 'allennlp.nn.util.masked_topk', 'util.masked_topk', (['scores', 'mask', '(2)'], {}), '(scores, mask, 2)\n', (64417, 64434), False, 'from allennlp.nn import util\n'), ((65486, 65519), 'allennlp.nn.util.masked_topk', 'util.masked_topk', (['scores', 'mask', '(2)'], {}), '(scores, mask, 2)\n', (65502, 65519), False, 'from allennlp.nn import util\n'), ((66665, 66706), 'torch.tensor', 'torch.tensor', (['[3, 2, 1]'], {'dtype': 'torch.long'}), '([3, 2, 1], dtype=torch.long)\n', (66677, 66706), False, 'import torch\n'), ((66761, 66794), 'allennlp.nn.util.masked_topk', 'util.masked_topk', (['scores', 'mask', 'k'], {}), '(scores, mask, k)\n', (66777, 66794), False, 'from allennlp.nn import util\n'), ((67977, 68018), 'torch.tensor', 'torch.tensor', (['[3, 2, 0]'], {'dtype': 'torch.long'}), '([3, 2, 0], dtype=torch.long)\n', (67989, 68018), False, 'import torch\n'), ((68073, 68106), 'allennlp.nn.util.masked_topk', 'util.masked_topk', (['scores', 'mask', 'k'], {}), '(scores, mask, k)\n', (68089, 68106), False, 'from allennlp.nn import util\n'), ((69675, 69712), 'torch.ones', 'torch.ones', (['(3)', '(5)', '(4)'], {'dtype': 'torch.long'}), '(3, 5, 4, dtype=torch.long)\n', (69685, 69712), False, 'import torch\n'), ((69996, 70036), 'torch.ones', 'torch.ones', (['(3)', '(2)', '(5)', '(4)'], {'dtype': 'torch.bool'}), '(3, 2, 5, 4, dtype=torch.bool)\n', (70006, 70036), False, 'import torch\n'), ((70413, 70452), 'allennlp.nn.util.masked_topk', 'util.masked_topk', (['items', 'mask', 'k'], {'dim': '(1)'}), '(items, mask, k, dim=1)\n', (70429, 70452), False, 'from allennlp.nn import util\n'), ((949, 974), 'numpy.array', 'numpy.array', (['[3, 2, 6, 1]'], {}), '([3, 2, 6, 1])\n', (960, 974), False, 'import numpy\n'), ((1924, 1947), 'numpy.array', 'numpy.array', (['[260, 260]'], {}), '([260, 260])\n', (1935, 1947), False, 'import numpy\n'), ((2179, 2197), 'torch.Size', 'torch.Size', (['[2, 3]'], {}), '([2, 3])\n', (2189, 2197), False, 'import torch\n'), ((2539, 2557), 'torch.Size', 'torch.Size', (['[2, 3]'], {}), '([2, 3])\n', (2549, 2557), False, 'import torch\n'), ((3773, 3806), 'torch.LongTensor', 'torch.LongTensor', (['[7, 5, 4, 3, 1]'], {}), '([7, 5, 4, 3, 1])\n', (3789, 3806), False, 'import torch\n'), ((4971, 5016), 'numpy.array', 'numpy.array', (['[[0.090031, 0.244728, 0.665241]]'], {}), '([[0.090031, 0.244728, 0.665241]])\n', (4982, 5016), False, 'import numpy\n'), ((5060, 5090), 'numpy.sum', 'numpy.sum', (['vector_1d_softmaxed'], {}), '(vector_1d_softmaxed)\n', (5069, 5090), False, 'import numpy\n'), ((5296, 5340), 'numpy.array', 'numpy.array', (['[[0.017148, 0.046613, 0.93624]]'], {}), '([[0.017148, 0.046613, 0.93624]])\n', (5307, 5340), False, 'import numpy\n'), ((5622, 5673), 'numpy.array', 'numpy.array', (['[[0.33333334, 0.33333334, 0.33333334]]'], {}), '([[0.33333334, 0.33333334, 0.33333334]])\n', (5633, 5673), False, 'import numpy\n'), ((5974, 6067), 'numpy.array', 'numpy.array', (['[[0.01714783, 0.04661262, 0.93623955], [0.09003057, 0.24472847, 0.66524096]]'], {}), '([[0.01714783, 0.04661262, 0.93623955], [0.09003057, 0.24472847,\n 0.66524096]])\n', (5985, 6067), False, 'import numpy\n'), ((6422, 6515), 'numpy.array', 'numpy.array', (['[[0.01714783, 0.04661262, 0.93623955], [0.33333334, 0.33333334, 0.33333334]]'], {}), '([[0.01714783, 0.04661262, 0.93623955], [0.33333334, 0.33333334,\n 0.33333334]])\n', (6433, 6515), False, 'import numpy\n'), ((6891, 6935), 'numpy.array', 'numpy.array', (['[[0.01798621, 0.0, 0.98201382]]'], {}), '([[0.01798621, 0.0, 0.98201382]])\n', (6902, 6935), False, 'import numpy\n'), ((7211, 7267), 'numpy.array', 'numpy.array', (['[[0.01321289, 0.0, 0.26538793, 0.72139918]]'], {}), '([[0.01321289, 0.0, 0.26538793, 0.72139918]])\n', (7222, 7267), False, 'import numpy\n'), ((7642, 7669), 'numpy.array', 'numpy.array', (['[[0, 0, 0, 1]]'], {}), '([[0, 0, 0, 1]])\n', (7653, 7669), False, 'import numpy\n'), ((8036, 8071), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0]])\n', (8047, 8071), False, 'import numpy\n'), ((8434, 8469), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0]])\n', (8445, 8469), False, 'import numpy\n'), ((8815, 8843), 'numpy.array', 'numpy.array', (['[[0.5, 0.5, 0]]'], {}), '([[0.5, 0.5, 0]])\n', (8826, 8843), False, 'import numpy\n'), ((9204, 9280), 'numpy.array', 'numpy.array', (['[[0.01798621, 0.0, 0.98201382], [0.090031, 0.244728, 0.665241]]'], {}), '([[0.01798621, 0.0, 0.98201382], [0.090031, 0.244728, 0.665241]])\n', (9215, 9280), False, 'import numpy\n'), ((9705, 9767), 'numpy.array', 'numpy.array', (['[[0.5, 0.0, 0.5], [0.090031, 0.244728, 0.665241]]'], {}), '([[0.5, 0.0, 0.5], [0.090031, 0.244728, 0.665241]])\n', (9716, 9767), False, 'import numpy\n'), ((10193, 10240), 'numpy.array', 'numpy.array', (['[[0.5, 0.0, 0.5], [0.0, 0.0, 0.0]]'], {}), '([[0.5, 0.0, 0.5], [0.0, 0.0, 0.0]])\n', (10204, 10240), False, 'import numpy\n'), ((10550, 10611), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, 0.0], [0.11920292, 0.0, 0.88079708]]'], {}), '([[0.0, 0.0, 0.0], [0.11920292, 0.0, 0.88079708]])\n', (10561, 10611), False, 'import numpy\n'), ((11022, 11066), 'numpy.array', 'numpy.array', (['[[0.01798621, 0.0, 0.98201382]]'], {}), '([[0.01798621, 0.0, 0.98201382]])\n', (11033, 11066), False, 'import numpy\n'), ((11387, 11443), 'numpy.array', 'numpy.array', (['[[0.01321289, 0.0, 0.26538793, 0.72139918]]'], {}), '([[0.01321289, 0.0, 0.26538793, 0.72139918]])\n', (11398, 11443), False, 'import numpy\n'), ((11863, 11890), 'numpy.array', 'numpy.array', (['[[0, 0, 0, 1]]'], {}), '([[0, 0, 0, 1]])\n', (11874, 11890), False, 'import numpy\n'), ((12302, 12341), 'numpy.array', 'numpy.array', (['[[0.25, 0.25, 0.25, 0.25]]'], {}), '([[0.25, 0.25, 0.25, 0.25]])\n', (12313, 12341), False, 'import numpy\n'), ((12749, 12788), 'numpy.array', 'numpy.array', (['[[0.25, 0.25, 0.25, 0.25]]'], {}), '([[0.25, 0.25, 0.25, 0.25]])\n', (12760, 12788), False, 'import numpy\n'), ((13179, 13207), 'numpy.array', 'numpy.array', (['[[0.5, 0.5, 0]]'], {}), '([[0.5, 0.5, 0]])\n', (13190, 13207), False, 'import numpy\n'), ((13613, 13689), 'numpy.array', 'numpy.array', (['[[0.01798621, 0.0, 0.98201382], [0.090031, 0.244728, 0.665241]]'], {}), '([[0.01798621, 0.0, 0.98201382], [0.090031, 0.244728, 0.665241]])\n', (13624, 13689), False, 'import numpy\n'), ((14159, 14221), 'numpy.array', 'numpy.array', (['[[0.5, 0.0, 0.5], [0.090031, 0.244728, 0.665241]]'], {}), '([[0.5, 0.0, 0.5], [0.090031, 0.244728, 0.665241]])\n', (14170, 14221), False, 'import numpy\n'), ((14704, 14772), 'numpy.array', 'numpy.array', (['[[0.5, 0.0, 0.5], [0.33333333, 0.33333333, 0.33333333]]'], {}), '([[0.5, 0.0, 0.5], [0.33333333, 0.33333333, 0.33333333]])\n', (14715, 14772), False, 'import numpy\n'), ((15140, 15227), 'numpy.array', 'numpy.array', (['[[0.33333333, 0.33333333, 0.33333333], [0.11920292, 0.0, 0.88079708]]'], {}), '([[0.33333333, 0.33333333, 0.33333333], [0.11920292, 0.0, \n 0.88079708]])\n', (15151, 15227), False, 'import numpy\n'), ((15745, 15775), 'numpy.exp', 'numpy.exp', (['vector_1d_softmaxed'], {}), '(vector_1d_softmaxed)\n', (15754, 15775), False, 'import numpy\n'), ((15777, 15821), 'numpy.array', 'numpy.array', (['[[0.01798621, 0.0, 0.98201382]]'], {}), '([[0.01798621, 0.0, 0.98201382]])\n', (15788, 15821), False, 'import numpy\n'), ((16089, 16119), 'numpy.exp', 'numpy.exp', (['vector_1d_softmaxed'], {}), '(vector_1d_softmaxed)\n', (16098, 16119), False, 'import numpy\n'), ((16121, 16177), 'numpy.array', 'numpy.array', (['[[0.01321289, 0.0, 0.26538793, 0.72139918]]'], {}), '([[0.01321289, 0.0, 0.26538793, 0.72139918]])\n', (16132, 16177), False, 'import numpy\n'), ((16548, 16578), 'numpy.exp', 'numpy.exp', (['vector_1d_softmaxed'], {}), '(vector_1d_softmaxed)\n', (16557, 16578), False, 'import numpy\n'), ((16580, 16615), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, 0.0, 1.0]]'], {}), '([[0.0, 0.0, 0.0, 1.0]])\n', (16591, 16615), False, 'import numpy\n'), ((18043, 18067), 'numpy.array', 'numpy.array', (['[5.0, -1.0]'], {}), '([5.0, -1.0])\n', (18054, 18067), False, 'import numpy\n'), ((18410, 18438), 'numpy.array', 'numpy.array', (['[[5.0], [-1.0]]'], {}), '([[5.0], [-1.0]])\n', (18421, 18438), False, 'import numpy\n'), ((18817, 18856), 'numpy.array', 'numpy.array', (['[[5.0, 2.0], [-1.0, -0.5]]'], {}), '([[5.0, 2.0], [-1.0, -0.5]])\n', (18828, 18856), False, 'import numpy\n'), ((19839, 19863), 'numpy.array', 'numpy.array', (['[3.0, -1.5]'], {}), '([3.0, -1.5])\n', (19850, 19863), False, 'import numpy\n'), ((20205, 20233), 'numpy.array', 'numpy.array', (['[[3.0], [-1.5]]'], {}), '([[3.0], [-1.5]])\n', (20216, 20233), False, 'import numpy\n'), ((20611, 20651), 'numpy.array', 'numpy.array', (['[[3.0, 0.5], [-1.5, -1.75]]'], {}), '([[3.0, 0.5], [-1.5, -1.75]])\n', (20622, 20651), False, 'import numpy\n'), ((28058, 28146), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['aggregated_array[0, i]', 'expected_array'], {'decimal': '(5)'}), '(aggregated_array[0, i], expected_array,\n decimal=5)\n', (28091, 28146), False, 'import numpy\n'), ((28322, 28340), 'torch.rand', 'torch.rand', (['[5, 9]'], {}), '([5, 9])\n', (28332, 28340), False, 'import torch\n'), ((28727, 28745), 'torch.rand', 'torch.rand', (['[5, 9]'], {}), '([5, 9])\n', (28737, 28745), False, 'import torch\n'), ((32942, 32960), 'torch.rand', 'torch.rand', (['[5, 9]'], {}), '([5, 9])\n', (32952, 32960), False, 'import torch\n'), ((36791, 36811), 'random.randint', 'random.randint', (['(1)', '(5)'], {}), '(1, 5)\n', (36805, 36811), False, 'import random\n'), ((36834, 36854), 'random.randint', 'random.randint', (['(1)', '(5)'], {}), '(1, 5)\n', (36848, 36854), False, 'import random\n'), ((36871, 36891), 'random.randint', 'random.randint', (['(1)', '(5)'], {}), '(1, 5)\n', (36885, 36891), False, 'import random\n'), ((36922, 36953), 'torch.rand', 'torch.rand', (['[seq_len, num_tags]'], {}), '([seq_len, num_tags])\n', (36932, 36953), False, 'import torch\n'), ((36986, 37018), 'torch.rand', 'torch.rand', (['[num_tags, num_tags]'], {}), '([num_tags, num_tags])\n', (36996, 37018), False, 'import torch\n'), ((37069, 37133), 'allennlp.nn.util.viterbi_decode', 'util.viterbi_decode', (['sequence_logits', 'transition_matrix'], {'top_k': 'k'}), '(sequence_logits, transition_matrix, top_k=k)\n', (37088, 37133), False, 'from allennlp.nn import util\n'), ((38203, 38237), 'numpy.random.randint', 'numpy.random.randint', (['(0)', '(3)', '[5, 7]'], {}), '(0, 3, [5, 7])\n', (38223, 38237), False, 'import numpy\n'), ((38641, 38675), 'numpy.random.randint', 'numpy.random.randint', (['(0)', '(3)', '[1, 3]'], {}), '(0, 3, [1, 3])\n', (38661, 38675), False, 'import numpy\n'), ((38969, 39020), 'torch.nn.functional.log_softmax', 'torch.nn.functional.log_softmax', (['prediction'], {'dim': '(-1)'}), '(prediction, dim=-1)\n', (39000, 39020), False, 'import torch\n'), ((39807, 39841), 'numpy.random.randint', 'numpy.random.randint', (['(0)', '(3)', '[5, 7]'], {}), '(0, 3, [5, 7])\n', (39827, 39841), False, 'import numpy\n'), ((40719, 40753), 'numpy.random.randint', 'numpy.random.randint', (['(0)', '(3)', '[5, 7]'], {}), '(0, 3, [5, 7])\n', (40739, 40753), False, 'import numpy\n'), ((41401, 41421), 'numpy.random.randn', 'numpy.random.randn', ([], {}), '()\n', (41419, 41421), False, 'import numpy\n'), ((41526, 41575), 'numpy.random.randint', 'numpy.random.randint', (['(0)', 'classes', '[batch, length]'], {}), '(0, classes, [batch, length])\n', (41546, 41575), False, 'import numpy\n'), ((41834, 41876), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['logit'], {'dim': '(-1)'}), '(logit, dim=-1)\n', (41861, 41876), False, 'import torch\n'), ((42355, 42374), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (42372, 42374), False, 'import numpy\n'), ((42547, 42596), 'numpy.random.randint', 'numpy.random.randint', (['(0)', 'classes', '[batch, length]'], {}), '(0, classes, [batch, length])\n', (42567, 42596), False, 'import numpy\n'), ((42858, 42904), 'torch.nn.functional.log_softmax', 'torch.nn.functional.log_softmax', (['logit'], {'dim': '(-1)'}), '(logit, dim=-1)\n', (42889, 42904), False, 'import torch\n'), ((43456, 43475), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (43473, 43475), False, 'import numpy\n'), ((43684, 43733), 'numpy.random.randint', 'numpy.random.randint', (['(0)', 'classes', '[batch, length]'], {}), '(0, classes, [batch, length])\n', (43704, 43733), False, 'import numpy\n'), ((43995, 44041), 'torch.nn.functional.log_softmax', 'torch.nn.functional.log_softmax', (['logit'], {'dim': '(-1)'}), '(logit, dim=-1)\n', (44026, 44041), False, 'import torch\n'), ((44575, 44602), 'numpy.random.randn', 'numpy.random.randn', (['classes'], {}), '(classes)\n', (44593, 44602), False, 'import numpy\n'), ((44707, 44756), 'numpy.random.randint', 'numpy.random.randint', (['(0)', 'classes', '[batch, length]'], {}), '(0, classes, [batch, length])\n', (44727, 44756), False, 'import numpy\n'), ((45018, 45064), 'torch.nn.functional.log_softmax', 'torch.nn.functional.log_softmax', (['logit'], {'dim': '(-1)'}), '(logit, dim=-1)\n', (45049, 45064), False, 'import torch\n'), ((47155, 47256), 'numpy.array', 'numpy.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 12, 11, 10, 17, 17, 17, 12, 13, 10, 10,\n 14, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 12, 11, 10, 17, 17, 17, 12,\n 13, 10, 10, 14, 12])\n', (47166, 47256), False, 'import numpy\n'), ((48645, 48678), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (48658, 48678), False, 'import pytest\n'), ((48692, 48735), 'allennlp.nn.util.batched_index_select', 'util.batched_index_select', (['targets', 'indices'], {}), '(targets, indices)\n', (48717, 48735), False, 'from allennlp.nn import util\n'), ((48877, 48910), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (48890, 48910), False, 'import pytest\n'), ((48924, 48967), 'allennlp.nn.util.batched_index_select', 'util.batched_index_select', (['targets', 'indices'], {}), '(targets, indices)\n', (48949, 48967), False, 'from allennlp.nn import util\n'), ((51426, 51459), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (51439, 51459), False, 'import pytest\n'), ((51765, 51796), 'numpy.array', 'numpy.array', (['[1, 2, 5, 1, 8, 9]'], {}), '([1, 2, 5, 1, 8, 9])\n', (51776, 51796), False, 'import numpy\n'), ((51911, 51946), 'numpy.array', 'numpy.array', (['[[1, 2, 3], [4, 5, 0]]'], {}), '([[1, 2, 3], [4, 5, 0]])\n', (51922, 51946), False, 'import numpy\n'), ((52440, 52545), 'numpy.array', 'numpy.array', (['[[[1, 2, 3, 4], [5, 5, 5, 5], [6, 8, 1, 2]], [[4, 3, 2, 1], [8, 7, 6, 5], [\n 0, 0, 0, 0]]]'], {}), '([[[1, 2, 3, 4], [5, 5, 5, 5], [6, 8, 1, 2]], [[4, 3, 2, 1], [8,\n 7, 6, 5], [0, 0, 0, 0]]])\n', (52451, 52545), False, 'import numpy\n'), ((52716, 52741), 'numpy.array', 'numpy.array', (['[9, 9, 9, 9]'], {}), '([9, 9, 9, 9])\n', (52727, 52741), False, 'import numpy\n'), ((52774, 52803), 'numpy.array', 'numpy.array', (['[10, 10, 10, 10]'], {}), '([10, 10, 10, 10])\n', (52785, 52803), False, 'import numpy\n'), ((53407, 53433), 'numpy.random.rand', 'numpy.random.rand', (['(3)', '(5)', '(7)'], {}), '(3, 5, 7)\n', (53424, 53433), False, 'import numpy\n'), ((56584, 56608), 'torch.Tensor', 'torch.Tensor', (['[[[2, 3]]]'], {}), '([[[2, 3]]])\n', (56596, 56608), False, 'import torch\n'), ((56610, 56634), 'torch.Tensor', 'torch.Tensor', (['[[[5, 5]]]'], {}), '([[[5, 5]]])\n', (56622, 56634), False, 'import torch\n'), ((56742, 56805), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (56775, 56805), False, 'from allennlp.nn import util\n'), ((56896, 56959), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (56929, 56959), False, 'from allennlp.nn import util\n'), ((57098, 57162), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight2'], {}), '(combination, tensors, weight2)\n', (57131, 57162), False, 'from allennlp.nn import util\n'), ((57265, 57328), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (57298, 57328), False, 'from allennlp.nn import util\n'), ((57430, 57493), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (57463, 57493), False, 'from allennlp.nn import util\n'), ((57593, 57656), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (57626, 57656), False, 'from allennlp.nn import util\n'), ((57756, 57819), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (57789, 57819), False, 'from allennlp.nn import util\n'), ((57921, 57984), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (57954, 57984), False, 'from allennlp.nn import util\n'), ((58132, 58195), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (58165, 58195), False, 'from allennlp.nn import util\n'), ((58287, 58320), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (58300, 58320), False, 'import pytest\n'), ((58334, 58393), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['"""x+y+y"""', 'tensors', 'weight'], {}), "('x+y+y', tensors, weight)\n", (58367, 58393), False, 'from allennlp.nn import util\n'), ((58408, 58441), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (58421, 58441), False, 'import pytest\n'), ((58455, 58512), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['"""x%y"""', 'tensors', 'weight'], {}), "('x%y', tensors, weight)\n", (58488, 58512), False, 'from allennlp.nn import util\n'), ((58885, 58935), 'torch.Tensor', 'torch.Tensor', (['[[[5, 5], [4, 4]], [[2, 3], [1, 1]]]'], {}), '([[[5, 5], [4, 4]], [[2, 3], [1, 1]]])\n', (58897, 58935), False, 'import torch\n'), ((59064, 59127), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (59097, 59127), False, 'from allennlp.nn import util\n'), ((59223, 59273), 'torch.Tensor', 'torch.Tensor', (['[[[5, 5], [2, 2]], [[4, 4], [3, 3]]]'], {}), '([[[5, 5], [2, 2]], [[4, 4], [3, 3]]])\n', (59235, 59273), False, 'import torch\n'), ((59287, 59321), 'torch.Tensor', 'torch.Tensor', (['[[[2, 3]], [[1, 1]]]'], {}), '([[[2, 3]], [[1, 1]]])\n', (59299, 59321), False, 'import torch\n'), ((59440, 59503), 'allennlp.nn.util.combine_tensors_and_multiply', 'util.combine_tensors_and_multiply', (['combination', 'tensors', 'weight'], {}), '(combination, tensors, weight)\n', (59473, 59503), False, 'from allennlp.nn import util\n'), ((61836, 61866), 'torch.Size', 'torch.Size', (['(4, 10, 20, 17, 5)'], {}), '((4, 10, 20, 17, 5))\n', (61846, 61866), False, 'import torch\n'), ((62262, 62289), 'allennlp.models.load_archive', 'load_archive', (['model_archive'], {}), '(model_archive)\n', (62274, 62289), False, 'from allennlp.models import load_archive\n'), ((62387, 62402), 'json.load', 'json.load', (['file'], {}), '(file)\n', (62396, 62402), False, 'import json\n'), ((62448, 62478), 'allennlp.nn.util.inspect_parameters', 'util.inspect_parameters', (['model'], {}), '(model)\n', (62471, 62478), False, 'from allennlp.nn import util\n'), ((64640, 64677), 'numpy.array', 'numpy.array', (['[[0, 1], [1, 2], [2, 3]]'], {}), '([[0, 1], [1, 2], [2, 3]])\n', (64651, 64677), False, 'import numpy\n'), ((64755, 64773), 'numpy.ones', 'numpy.ones', (['[3, 2]'], {}), '([3, 2])\n', (64765, 64773), False, 'import numpy\n'), ((65765, 65794), 'numpy.array', 'numpy.array', (['[[0, 1], [1, 2]]'], {}), '([[0, 1], [1, 2]])\n', (65776, 65794), False, 'import numpy\n'), ((65885, 65922), 'numpy.array', 'numpy.array', (['[[1, 1], [1, 1], [0, 0]]'], {}), '([[1, 1], [1, 1], [0, 0]])\n', (65896, 65922), False, 'import numpy\n'), ((67000, 67046), 'numpy.array', 'numpy.array', (['[[0, 1, 3], [1, 2, 2], [1, 2, 2]]'], {}), '([[0, 1, 3], [1, 2, 2], [1, 2, 2]])\n', (67011, 67046), False, 'import numpy\n'), ((67137, 67183), 'numpy.array', 'numpy.array', (['[[1, 1, 1], [1, 1, 0], [1, 0, 0]]'], {}), '([[1, 1, 1], [1, 1, 0], [1, 0, 0]])\n', (67148, 67183), False, 'import numpy\n'), ((68466, 68512), 'numpy.array', 'numpy.array', (['[[0, 1, 2], [1, 2, 2], [3, 3, 3]]'], {}), '([[0, 1, 2], [1, 2, 2], [3, 3, 3]])\n', (68477, 68512), False, 'import numpy\n'), ((68603, 68649), 'numpy.array', 'numpy.array', (['[[1, 1, 1], [1, 1, 0], [0, 0, 0]]'], {}), '([[1, 1, 1], [1, 1, 0], [0, 0, 0]])\n', (68614, 68649), False, 'import numpy\n'), ((70950, 70967), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (70962, 70967), False, 'import torch\n'), ((70969, 70986), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (70981, 70986), False, 'import torch\n'), ((71114, 71134), 'torch.tensor', 'torch.tensor', (['[True]'], {}), '([True])\n', (71126, 71134), False, 'import torch\n'), ((71136, 71156), 'torch.tensor', 'torch.tensor', (['[True]'], {}), '([True])\n', (71148, 71156), False, 'import torch\n'), ((71215, 71232), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (71227, 71232), False, 'import torch\n'), ((71234, 71253), 'torch.tensor', 'torch.tensor', (['[1.0]'], {}), '([1.0])\n', (71246, 71253), False, 'import torch\n'), ((71289, 71306), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (71301, 71306), False, 'import torch\n'), ((71308, 71328), 'torch.tensor', 'torch.tensor', (['[True]'], {}), '([True])\n', (71320, 71328), False, 'import torch\n'), ((1761, 1779), 'torch.ones', 'torch.ones', (['(2)', '(260)'], {}), '(2, 260)\n', (1771, 1779), False, 'import torch\n'), ((2224, 2272), 'allennlp.nn.util.clamp_tensor', 'util.clamp_tensor', (['tensor'], {'minimum': '(-3)', 'maximum': '(3)'}), '(tensor, minimum=-3, maximum=3)\n', (2241, 2272), False, 'from allennlp.nn import util\n'), ((2584, 2632), 'allennlp.nn.util.clamp_tensor', 'util.clamp_tensor', (['tensor'], {'minimum': '(-3)', 'maximum': '(3)'}), '(tensor, minimum=-3, maximum=3)\n', (2601, 2632), False, 'from allennlp.nn import util\n'), ((18625, 18681), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, False]]'], {}), '([[True, False, True], [True, True, False]])\n', (18637, 18681), False, 'import torch\n'), ((20420, 20476), 'torch.tensor', 'torch.tensor', (['[[True, False, True], [True, True, False]]'], {}), '([[True, False, True], [True, True, False]])\n', (20432, 20476), False, 'import torch\n'), ((22149, 22201), 'torch.LongTensor', 'torch.LongTensor', (['[[3, 4, 5, 0, 0], [1, 2, 0, 0, 0]]'], {}), '([[3, 4, 5, 0, 0], [1, 2, 0, 0, 0]])\n', (22165, 22201), False, 'import torch\n'), ((22239, 22345), 'torch.LongTensor', 'torch.LongTensor', (['[[[1, 2], [3, 0], [2, 0], [0, 0], [0, 0]], [[5, 0], [4, 6], [0, 0], [0, 0],\n [0, 0]]]'], {}), '([[[1, 2], [3, 0], [2, 0], [0, 0], [0, 0]], [[5, 0], [4, 6],\n [0, 0], [0, 0], [0, 0]]])\n', (22255, 22345), False, 'import torch\n'), ((22818, 22932), 'torch.LongTensor', 'torch.LongTensor', (['[[[1, 2, 3], [3, 0, 1], [2, 1, 0], [0, 0, 0]], [[5, 5, 5], [4, 6, 0], [0, 0,\n 0], [0, 0, 0]]]'], {}), '([[[1, 2, 3], [3, 0, 1], [2, 1, 0], [0, 0, 0]], [[5, 5, 5],\n [4, 6, 0], [0, 0, 0], [0, 0, 0]]])\n', (22834, 22932), False, 'import torch\n'), ((23383, 23489), 'torch.LongTensor', 'torch.LongTensor', (['[[[1, 2], [3, 0], [2, 0], [0, 0], [0, 0]], [[5, 0], [4, 6], [0, 0], [0, 0],\n [0, 0]]]'], {}), '([[[1, 2], [3, 0], [2, 0], [0, 0], [0, 0]], [[5, 0], [4, 6],\n [0, 0], [0, 0], [0, 0]]])\n', (23399, 23489), False, 'import torch\n'), ((24073, 24125), 'torch.LongTensor', 'torch.LongTensor', (['[[3, 4, 5, 0, 0], [1, 2, 0, 0, 0]]'], {}), '([[3, 4, 5, 0, 0], [1, 2, 0, 0, 0]])\n', (24089, 24125), False, 'import torch\n'), ((24151, 24187), 'torch.tensor', 'torch.tensor', (['[[False, False, True]]'], {}), '([[False, False, True]])\n', (24163, 24187), False, 'import torch\n'), ((24583, 24615), 'torch.from_numpy', 'torch.from_numpy', (['sentence_array'], {}), '(sentence_array)\n', (24599, 24615), False, 'import torch\n'), ((25572, 25604), 'torch.from_numpy', 'torch.from_numpy', (['sentence_array'], {}), '(sentence_array)\n', (25588, 25604), False, 'import torch\n'), ((25640, 25673), 'torch.from_numpy', 'torch.from_numpy', (['attention_array'], {}), '(attention_array)\n', (25656, 25673), False, 'import torch\n'), ((26509, 26541), 'torch.from_numpy', 'torch.from_numpy', (['sentence_array'], {}), '(sentence_array)\n', (26525, 26541), False, 'import torch\n'), ((26577, 26610), 'torch.from_numpy', 'torch.from_numpy', (['attention_array'], {}), '(attention_array)\n', (26593, 26610), False, 'import torch\n'), ((27086, 27177), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['aggregated_array[0, i, j]', 'expected_array'], {'decimal': '(5)'}), '(aggregated_array[0, i, j], expected_array,\n decimal=5)\n', (27119, 27177), False, 'import numpy\n'), ((27555, 27587), 'torch.from_numpy', 'torch.from_numpy', (['sentence_array'], {}), '(sentence_array)\n', (27571, 27587), False, 'import torch\n'), ((27623, 27656), 'torch.from_numpy', 'torch.from_numpy', (['attention_array'], {}), '(attention_array)\n', (27639, 27656), False, 'import torch\n'), ((37488, 37514), 'allennlp.common.util.sanitize', 'sanitize', (['viterbi_paths_v1'], {}), '(viterbi_paths_v1)\n', (37496, 37514), False, 'from allennlp.common.util import sanitize\n'), ((42378, 42397), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (42395, 42397), False, 'import numpy\n'), ((42416, 42435), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (42433, 42435), False, 'import numpy\n'), ((43479, 43498), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (43496, 43498), False, 'import numpy\n'), ((43517, 43536), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (43534, 43536), False, 'import numpy\n'), ((51510, 51531), 'torch.ones', 'torch.ones', (['[3, 4, 5]'], {}), '([3, 4, 5])\n', (51520, 51531), False, 'import torch\n'), ((64096, 64118), 'torch.randn', 'torch.randn', (['[3, 4, 5]'], {}), '([3, 4, 5])\n', (64107, 64118), False, 'import torch\n'), ((64275, 64293), 'torch.ones', 'torch.ones', (['[3, 4]'], {}), '([3, 4])\n', (64285, 64293), False, 'import torch\n'), ((65122, 65144), 'torch.randn', 'torch.randn', (['[3, 4, 5]'], {}), '([3, 4, 5])\n', (65133, 65144), False, 'import torch\n'), ((65301, 65319), 'torch.ones', 'torch.ones', (['[3, 4]'], {}), '([3, 4])\n', (65311, 65319), False, 'import torch\n'), ((66313, 66335), 'torch.randn', 'torch.randn', (['[3, 4, 5]'], {}), '([3, 4, 5])\n', (66324, 66335), False, 'import torch\n'), ((66603, 66621), 'torch.ones', 'torch.ones', (['[3, 4]'], {}), '([3, 4])\n', (66613, 66621), False, 'import torch\n'), ((67713, 67735), 'torch.randn', 'torch.randn', (['[3, 4, 5]'], {}), '([3, 4, 5])\n', (67724, 67735), False, 'import torch\n'), ((67892, 67910), 'torch.ones', 'torch.ones', (['[3, 4]'], {}), '([3, 4])\n', (67902, 67910), False, 'import torch\n'), ((71026, 71043), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (71038, 71043), False, 'import torch\n'), ((71045, 71062), 'torch.tensor', 'torch.tensor', (['[2]'], {}), '([2])\n', (71057, 71062), False, 'import torch\n'), ((71387, 71404), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (71399, 71404), False, 'import torch\n'), ((71408, 71425), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (71420, 71425), False, 'import torch\n'), ((71550, 71567), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (71562, 71567), False, 'import torch\n'), ((71578, 71595), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (71590, 71595), False, 'import torch\n'), ((1104, 1160), 'allennlp.nn.util.get_mask_from_sequence_lengths', 'util.get_mask_from_sequence_lengths', (['sequence_lengths', '(5)'], {}), '(sequence_lengths, 5)\n', (1139, 1160), False, 'from allennlp.nn import util\n'), ((4853, 4889), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'None'], {}), '(vector_1d, None)\n', (4872, 4889), False, 'from allennlp.nn import util\n'), ((5191, 5227), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'None'], {}), '(vector_1d, None)\n', (5210, 5227), False, 'from allennlp.nn import util\n'), ((5500, 5538), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_zero', 'None'], {}), '(vector_zero, None)\n', (5519, 5538), False, 'from allennlp.nn import util\n'), ((5843, 5876), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'None'], {}), '(matrix, None)\n', (5862, 5876), False, 'from allennlp.nn import util\n'), ((6291, 6324), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'None'], {}), '(matrix, None)\n', (6310, 6324), False, 'from allennlp.nn import util\n'), ((6783, 6822), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (6802, 6822), False, 'from allennlp.nn import util\n'), ((7090, 7129), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (7109, 7129), False, 'from allennlp.nn import util\n'), ((7534, 7573), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (7553, 7573), False, 'from allennlp.nn import util\n'), ((7928, 7967), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (7947, 7967), False, 'from allennlp.nn import util\n'), ((8326, 8365), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (8345, 8365), False, 'from allennlp.nn import util\n'), ((8707, 8746), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (8726, 8746), False, 'from allennlp.nn import util\n'), ((9073, 9106), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'mask'], {}), '(matrix, mask)\n', (9092, 9106), False, 'from allennlp.nn import util\n'), ((9586, 9619), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'mask'], {}), '(matrix, mask)\n', (9605, 9619), False, 'from allennlp.nn import util\n'), ((10074, 10107), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'mask'], {}), '(matrix, mask)\n', (10093, 10107), False, 'from allennlp.nn import util\n'), ((10431, 10464), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'mask'], {}), '(matrix, mask)\n', (10450, 10464), False, 'from allennlp.nn import util\n'), ((10869, 10931), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {'memory_efficient': '(True)'}), '(vector_1d, mask_1d, memory_efficient=True)\n', (10888, 10931), False, 'from allennlp.nn import util\n'), ((11221, 11283), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {'memory_efficient': '(True)'}), '(vector_1d, mask_1d, memory_efficient=True)\n', (11240, 11283), False, 'from allennlp.nn import util\n'), ((11710, 11772), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {'memory_efficient': '(True)'}), '(vector_1d, mask_1d, memory_efficient=True)\n', (11729, 11772), False, 'from allennlp.nn import util\n'), ((12149, 12211), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {'memory_efficient': '(True)'}), '(vector_1d, mask_1d, memory_efficient=True)\n', (12168, 12211), False, 'from allennlp.nn import util\n'), ((12596, 12658), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {'memory_efficient': '(True)'}), '(vector_1d, mask_1d, memory_efficient=True)\n', (12615, 12658), False, 'from allennlp.nn import util\n'), ((13026, 13088), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['vector_1d', 'mask_1d'], {'memory_efficient': '(True)'}), '(vector_1d, mask_1d, memory_efficient=True)\n', (13045, 13088), False, 'from allennlp.nn import util\n'), ((13437, 13493), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'mask'], {'memory_efficient': '(True)'}), '(matrix, mask, memory_efficient=True)\n', (13456, 13493), False, 'from allennlp.nn import util\n'), ((13995, 14051), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'mask'], {'memory_efficient': '(True)'}), '(matrix, mask, memory_efficient=True)\n', (14014, 14051), False, 'from allennlp.nn import util\n'), ((14528, 14584), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'mask'], {'memory_efficient': '(True)'}), '(matrix, mask, memory_efficient=True)\n', (14547, 14584), False, 'from allennlp.nn import util\n'), ((14964, 15020), 'allennlp.nn.util.masked_softmax', 'util.masked_softmax', (['matrix', 'mask'], {'memory_efficient': '(True)'}), '(matrix, mask, memory_efficient=True)\n', (14983, 15020), False, 'from allennlp.nn import util\n'), ((15641, 15684), 'allennlp.nn.util.masked_log_softmax', 'util.masked_log_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (15664, 15684), False, 'from allennlp.nn import util\n'), ((15985, 16028), 'allennlp.nn.util.masked_log_softmax', 'util.masked_log_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (16008, 16028), False, 'from allennlp.nn import util\n'), ((16444, 16487), 'allennlp.nn.util.masked_log_softmax', 'util.masked_log_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (16467, 16487), False, 'from allennlp.nn import util\n'), ((16945, 16988), 'allennlp.nn.util.masked_log_softmax', 'util.masked_log_softmax', (['vector_1d', 'mask_1d'], {}), '(vector_1d, mask_1d)\n', (16968, 16988), False, 'from allennlp.nn import util\n'), ((17021, 17053), 'numpy.isnan', 'numpy.isnan', (['vector_1d_softmaxed'], {}), '(vector_1d_softmaxed)\n', (17032, 17053), False, 'import numpy\n'), ((17272, 17314), 'allennlp.nn.util.masked_max', 'util.masked_max', (['vector_1d', 'mask_1d'], {'dim': '(0)'}), '(vector_1d, mask_1d, dim=0)\n', (17287, 17314), False, 'from allennlp.nn import util\n'), ((17618, 17660), 'allennlp.nn.util.masked_max', 'util.masked_max', (['vector_1d', 'mask_1d'], {'dim': '(0)'}), '(vector_1d, mask_1d, dim=0)\n', (17633, 17660), False, 'from allennlp.nn import util\n'), ((17693, 17721), 'numpy.isnan', 'numpy.isnan', (['vector_1d_maxed'], {}), '(vector_1d_maxed)\n', (17704, 17721), False, 'import numpy\n'), ((17944, 17981), 'allennlp.nn.util.masked_max', 'util.masked_max', (['matrix', 'mask'], {'dim': '(-1)'}), '(matrix, mask, dim=-1)\n', (17959, 17981), False, 'from allennlp.nn import util\n'), ((18297, 18348), 'allennlp.nn.util.masked_max', 'util.masked_max', (['matrix', 'mask'], {'dim': '(-1)', 'keepdim': '(True)'}), '(matrix, mask, dim=-1, keepdim=True)\n', (18312, 18348), False, 'from allennlp.nn import util\n'), ((18719, 18755), 'allennlp.nn.util.masked_max', 'util.masked_max', (['matrix', 'mask'], {'dim': '(1)'}), '(matrix, mask, dim=1)\n', (18734, 18755), False, 'from allennlp.nn import util\n'), ((19070, 19113), 'allennlp.nn.util.masked_mean', 'util.masked_mean', (['vector_1d', 'mask_1d'], {'dim': '(0)'}), '(vector_1d, mask_1d, dim=0)\n', (19086, 19113), False, 'from allennlp.nn import util\n'), ((19415, 19458), 'allennlp.nn.util.masked_mean', 'util.masked_mean', (['vector_1d', 'mask_1d'], {'dim': '(0)'}), '(vector_1d, mask_1d, dim=0)\n', (19431, 19458), False, 'from allennlp.nn import util\n'), ((19491, 19518), 'numpy.isnan', 'numpy.isnan', (['vector_1d_mean'], {}), '(vector_1d_mean)\n', (19502, 19518), False, 'import numpy\n'), ((19740, 19778), 'allennlp.nn.util.masked_mean', 'util.masked_mean', (['matrix', 'mask'], {'dim': '(-1)'}), '(matrix, mask, dim=-1)\n', (19756, 19778), False, 'from allennlp.nn import util\n'), ((20092, 20144), 'allennlp.nn.util.masked_mean', 'util.masked_mean', (['matrix', 'mask'], {'dim': '(-1)', 'keepdim': '(True)'}), '(matrix, mask, dim=-1, keepdim=True)\n', (20108, 20144), False, 'from allennlp.nn import util\n'), ((20513, 20550), 'allennlp.nn.util.masked_mean', 'util.masked_mean', (['matrix', 'mask'], {'dim': '(1)'}), '(matrix, mask, dim=1)\n', (20529, 20550), False, 'from allennlp.nn import util\n'), ((24723, 24775), 'allennlp.nn.util.weighted_sum', 'util.weighted_sum', (['sentence_tensor', 'attention_tensor'], {}), '(sentence_tensor, attention_tensor)\n', (24740, 24775), False, 'from allennlp.nn import util\n'), ((25709, 25761), 'allennlp.nn.util.weighted_sum', 'util.weighted_sum', (['sentence_tensor', 'attention_tensor'], {}), '(sentence_tensor, attention_tensor)\n', (25726, 25761), False, 'from allennlp.nn import util\n'), ((26646, 26698), 'allennlp.nn.util.weighted_sum', 'util.weighted_sum', (['sentence_tensor', 'attention_tensor'], {}), '(sentence_tensor, attention_tensor)\n', (26663, 26698), False, 'from allennlp.nn import util\n'), ((27692, 27744), 'allennlp.nn.util.weighted_sum', 'util.weighted_sum', (['sentence_tensor', 'attention_tensor'], {}), '(sentence_tensor, attention_tensor)\n', (27709, 27744), False, 'from allennlp.nn import util\n'), ((47471, 47493), 'torch.ones', 'torch.ones', (['[2, 10, 3]'], {}), '([2, 10, 3])\n', (47481, 47493), False, 'import torch\n'), ((49076, 49098), 'torch.ones', 'torch.ones', (['[3, 12, 2]'], {}), '([3, 12, 2])\n', (49086, 49098), False, 'import torch\n'), ((49469, 49495), 'torch.empty_like', 'torch.empty_like', (['selected'], {}), '(selected)\n', (49485, 49495), False, 'import torch\n'), ((50337, 50358), 'torch.ones', 'torch.ones', (['[2, 6, 3]'], {}), '([2, 6, 3])\n', (50347, 50358), False, 'import torch\n'), ((53650, 53714), 'numpy.array', 'numpy.array', (['[[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0]]'], {}), '([[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0]])\n', (53661, 53714), False, 'import numpy\n'), ((54118, 54164), 'numpy.array', 'numpy.array', (['[[0, 0, 0], [1, 1, 1], [1, 1, 0]]'], {}), '([[0, 0, 0], [1, 1, 1], [1, 1, 0]])\n', (54129, 54164), False, 'import numpy\n'), ((71467, 71484), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (71479, 71484), False, 'import torch\n'), ((71488, 71505), 'torch.tensor', 'torch.tensor', (['[2]'], {}), '([2])\n', (71500, 71505), False, 'import torch\n'), ((23655, 23720), 'allennlp.nn.util.get_text_field_mask', 'util.get_text_field_mask', (['text_field_tensors'], {'num_wrapping_dims': '(1)'}), '(text_field_tensors, num_wrapping_dims=1)\n', (23679, 23720), False, 'from allennlp.nn import util\n'), ((46404, 46426), 'allennlp.nn.util.logsumexp', 'util.logsumexp', (['tensor'], {}), '(tensor)\n', (46418, 46426), False, 'from allennlp.nn import util\n'), ((46530, 46552), 'allennlp.nn.util.logsumexp', 'util.logsumexp', (['tensor'], {}), '(tensor)\n', (46544, 46552), False, 'from allennlp.nn import util\n'), ((46671, 46700), 'allennlp.nn.util.logsumexp', 'util.logsumexp', (['tensor'], {'dim': '(0)'}), '(tensor, dim=0)\n', (46685, 46700), False, 'from allennlp.nn import util\n'), ((69023, 69160), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[4, 2, 9, 9, 7], [-4, -2, -9, -9, -7]], [[5, 4, 1, 8, 8], [9, 1, 7, 4, 1]\n ], [[9, 8, 9, 6, 0], [2, 2, 2, 2, 2]]]'], {}), '([[[4, 2, 9, 9, 7], [-4, -2, -9, -9, -7]], [[5, 4, 1, 8, 8\n ], [9, 1, 7, 4, 1]], [[9, 8, 9, 6, 0], [2, 2, 2, 2, 2]]])\n', (69040, 69160), False, 'import torch\n'), ((69265, 69501), 'torch.tensor', 'torch.tensor', (['[[[False, False, False, False, False], [True, True, True, True, True]], [[\n True, True, True, True, False], [False, True, True, True, True]], [[\n True, False, True, True, True], [False, True, False, True, True]]]'], {}), '([[[False, False, False, False, False], [True, True, True, True,\n True]], [[True, True, True, True, False], [False, True, True, True, \n True]], [[True, False, True, True, True], [False, True, False, True, \n True]]])\n', (69277, 69501), False, 'import torch\n'), ((69760, 69897), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[-4, -2, -9, -9, -7], [0, 0, 0, 0, 0]], [[5, 4, 7, 8, 1], [0, 0, 0, 4, 0]\n ], [[9, 2, 9, 6, 2], [0, 0, 0, 0, 0]]]'], {}), '([[[-4, -2, -9, -9, -7], [0, 0, 0, 0, 0]], [[5, 4, 7, 8, 1\n ], [0, 0, 0, 4, 0]], [[9, 2, 9, 6, 2], [0, 0, 0, 0, 0]]])\n', (69777, 69897), False, 'import torch\n'), ((70135, 70265), 'torch.LongTensor', 'torch.LongTensor', (['[[[1, 1, 1, 1, 1], [0, 0, 0, 0, 0]], [[0, 0, 1, 0, 1], [0, 0, 0, 1, 0]], [[\n 0, 1, 0, 0, 1], [0, 0, 0, 0, 0]]]'], {}), '([[[1, 1, 1, 1, 1], [0, 0, 0, 0, 0]], [[0, 0, 1, 0, 1], [0,\n 0, 0, 1, 0]], [[0, 1, 0, 0, 1], [0, 0, 0, 0, 0]]])\n', (70151, 70265), False, 'import torch\n'), ((22517, 22561), 'allennlp.nn.util.get_text_field_mask', 'util.get_text_field_mask', (['text_field_tensors'], {}), '(text_field_tensors)\n', (22541, 22561), False, 'from allennlp.nn import util\n'), ((23103, 23147), 'allennlp.nn.util.get_text_field_mask', 'util.get_text_field_mask', (['text_field_tensors'], {}), '(text_field_tensors)\n', (23127, 23147), False, 'from allennlp.nn import util\n'), ((24254, 24298), 'allennlp.nn.util.get_text_field_mask', 'util.get_text_field_mask', (['text_field_tensors'], {}), '(text_field_tensors)\n', (24278, 24298), False, 'from allennlp.nn import util\n')]
"""PyMC3-ArviZ conversion code.""" import logging import warnings from typing import ( # pylint: disable=unused-import TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, ) import numpy as np import xarray as xr from aesara.graph.basic import Constant from aesara.tensor.sharedvar import SharedVariable from aesara.tensor.subtensor import AdvancedIncSubtensor from arviz import InferenceData, concat, rcParams from arviz.data.base import CoordSpec, DimSpec from arviz.data.base import dict_to_dataset as _dict_to_dataset from arviz.data.base import generate_dims_coords, make_attrs, requires import pymc3 from pymc3.aesaraf import extract_obs_data from pymc3.distributions import logpt from pymc3.model import modelcontext from pymc3.util import get_default_varnames if TYPE_CHECKING: from typing import Set # pylint: disable=ungrouped-imports from pymc3.backends.base import MultiTrace # pylint: disable=invalid-name from pymc3.model import Model ___all__ = [""] _log = logging.getLogger("pymc3") # random variable object ... Var = Any # pylint: disable=invalid-name class _DefaultTrace: """ Utility for collecting samples into a dictionary. Name comes from its similarity to ``defaultdict``: entries are lazily created. Parameters ---------- samples : int The number of samples that will be collected, per variable, into the trace. Attributes ---------- trace_dict : Dict[str, np.ndarray] A dictionary constituting a trace. Should be extracted after a procedure has filled the `_DefaultTrace` using the `insert()` method """ trace_dict: Dict[str, np.ndarray] = {} _len: Optional[int] = None def __init__(self, samples: int): self._len = samples self.trace_dict = {} def insert(self, k: str, v, idx: int): """ Insert `v` as the value of the `idx`th sample for the variable `k`. Parameters ---------- k: str Name of the variable. v: anything that can go into a numpy array (including a numpy array) The value of the `idx`th sample from variable `k` ids: int The index of the sample we are inserting into the trace. """ value_shape = np.shape(v) # initialize if necessary if k not in self.trace_dict: array_shape = (self._len,) + value_shape self.trace_dict[k] = np.empty(array_shape, dtype=np.array(v).dtype) # do the actual insertion if value_shape == (): self.trace_dict[k][idx] = v else: self.trace_dict[k][idx, :] = v def dict_to_dataset( data, library=None, coords=None, dims=None, attrs=None, default_dims=None, skip_event_dims=None, index_origin=None, ): """Temporal workaround for dict_to_dataset. Once ArviZ>0.11.2 release is available, only two changes are needed for everything to work. 1) this should be deleted, 2) dict_to_dataset should be imported as is from arviz, no underscore, also remove unnecessary imports """ if default_dims is None: return _dict_to_dataset( data, library=library, coords=coords, dims=dims, skip_event_dims=skip_event_dims ) else: out_data = {} for name, vals in data.items(): vals = np.atleast_1d(vals) val_dims = dims.get(name) val_dims, coords = generate_dims_coords(vals.shape, name, dims=val_dims, coords=coords) coords = {key: xr.IndexVariable((key,), data=coords[key]) for key in val_dims} out_data[name] = xr.DataArray(vals, dims=val_dims, coords=coords) return xr.Dataset(data_vars=out_data, attrs=make_attrs(library=library)) class InferenceDataConverter: # pylint: disable=too-many-instance-attributes """Encapsulate InferenceData specific logic.""" model = None # type: Optional[Model] nchains = None # type: int ndraws = None # type: int posterior_predictive = None # Type: Optional[Mapping[str, np.ndarray]] predictions = None # Type: Optional[Mapping[str, np.ndarray]] prior = None # Type: Optional[Mapping[str, np.ndarray]] def __init__( self, *, trace=None, prior=None, posterior_predictive=None, log_likelihood=True, predictions=None, coords: Optional[CoordSpec] = None, dims: Optional[DimSpec] = None, model=None, save_warmup: Optional[bool] = None, density_dist_obs: bool = True, index_origin: Optional[int] = None, ): self.save_warmup = rcParams["data.save_warmup"] if save_warmup is None else save_warmup self.trace = trace # this permits us to get the model from command-line argument or from with model: self.model = modelcontext(model) self.attrs = None if trace is not None: self.nchains = trace.nchains if hasattr(trace, "nchains") else 1 if hasattr(trace.report, "n_draws") and trace.report.n_draws is not None: self.ndraws = trace.report.n_draws self.attrs = { "sampling_time": trace.report.t_sampling, "tuning_steps": trace.report.n_tune, } else: self.ndraws = len(trace) if self.save_warmup: warnings.warn( "Warmup samples will be stored in posterior group and will not be" " excluded from stats and diagnostics." " Do not slice the trace manually before conversion", UserWarning, ) self.ntune = len(self.trace) - self.ndraws self.posterior_trace, self.warmup_trace = self.split_trace() else: self.nchains = self.ndraws = 0 self.prior = prior self.posterior_predictive = posterior_predictive self.log_likelihood = log_likelihood self.predictions = predictions self.index_origin = rcParams["data.index_origin"] if index_origin is None else index_origin def arbitrary_element(dct: Dict[Any, np.ndarray]) -> np.ndarray: return next(iter(dct.values())) if trace is None: # if you have a posterior_predictive built with keep_dims, # you'll lose here, but there's nothing I can do about that. self.nchains = 1 get_from = None if predictions is not None: get_from = predictions elif posterior_predictive is not None: get_from = posterior_predictive elif prior is not None: get_from = prior if get_from is None: # pylint: disable=line-too-long raise ValueError( "When constructing InferenceData must have at least" " one of trace, prior, posterior_predictive or predictions." ) aelem = arbitrary_element(get_from) self.ndraws = aelem.shape[0] self.coords = {} if coords is None else coords if hasattr(self.model, "coords"): self.coords = {**self.model.coords, **self.coords} self.coords = {key: value for key, value in self.coords.items() if value is not None} self.dims = {} if dims is None else dims if hasattr(self.model, "RV_dims"): model_dims = { var_name: [dim for dim in dims if dim is not None] for var_name, dims in self.model.RV_dims.items() } self.dims = {**model_dims, **self.dims} self.density_dist_obs = density_dist_obs self.observations = self.find_observations() def find_observations(self) -> Optional[Dict[str, Var]]: """If there are observations available, return them as a dictionary.""" if self.model is None: return None observations = {} for obs in self.model.observed_RVs: aux_obs = getattr(obs.tag, "observations", None) if aux_obs is not None: try: obs_data = extract_obs_data(aux_obs) observations[obs.name] = obs_data except TypeError: warnings.warn(f"Could not extract data from symbolic observation {obs}") else: warnings.warn(f"No data for observation {obs}") return observations def split_trace(self) -> Tuple[Union[None, "MultiTrace"], Union[None, "MultiTrace"]]: """Split MultiTrace object into posterior and warmup. Returns ------- trace_posterior: MultiTrace or None The slice of the trace corresponding to the posterior. If the posterior trace is empty, None is returned trace_warmup: MultiTrace or None The slice of the trace corresponding to the warmup. If the warmup trace is empty or ``save_warmup=False``, None is returned """ trace_posterior = None trace_warmup = None if self.save_warmup and self.ntune > 0: trace_warmup = self.trace[: self.ntune] if self.ndraws > 0: trace_posterior = self.trace[self.ntune :] return trace_posterior, trace_warmup def log_likelihood_vals_point(self, point, var, log_like_fun): """Compute log likelihood for each observed point.""" # TODO: This is a cheap hack; we should filter-out the correct # variables some other way point = {i.name: point[i.name] for i in log_like_fun.f.maker.inputs if i.name in point} log_like_val = np.atleast_1d(log_like_fun(point)) if isinstance(var.owner.op, AdvancedIncSubtensor): try: obs_data = extract_obs_data(var.tag.observations) except TypeError: warnings.warn(f"Could not extract data from symbolic observation {var}") mask = obs_data.mask if np.ndim(mask) > np.ndim(log_like_val): mask = np.any(mask, axis=-1) log_like_val = np.where(mask, np.nan, log_like_val) return log_like_val def _extract_log_likelihood(self, trace): """Compute log likelihood of each observation.""" if self.trace is None: return None if self.model is None: return None if self.log_likelihood is True: cached = [(var, self.model.fn(logpt(var))) for var in self.model.observed_RVs] else: cached = [ (var, self.model.fn(logpt(var))) for var in self.model.observed_RVs if var.name in self.log_likelihood ] log_likelihood_dict = _DefaultTrace(len(trace.chains)) for var, log_like_fun in cached: for k, chain in enumerate(trace.chains): log_like_chain = [ self.log_likelihood_vals_point(point, var, log_like_fun) for point in trace.points([chain]) ] log_likelihood_dict.insert(var.name, np.stack(log_like_chain), k) return log_likelihood_dict.trace_dict @requires("trace") def posterior_to_xarray(self): """Convert the posterior to an xarray dataset.""" var_names = get_default_varnames(self.trace.varnames, include_transformed=False) data = {} data_warmup = {} for var_name in var_names: if self.warmup_trace: data_warmup[var_name] = np.array( self.warmup_trace.get_values(var_name, combine=False, squeeze=False) ) if self.posterior_trace: data[var_name] = np.array( self.posterior_trace.get_values(var_name, combine=False, squeeze=False) ) return ( dict_to_dataset( data, library=pymc3, coords=self.coords, dims=self.dims, attrs=self.attrs, index_origin=self.index_origin, ), dict_to_dataset( data_warmup, library=pymc3, coords=self.coords, dims=self.dims, attrs=self.attrs, index_origin=self.index_origin, ), ) @requires("trace") def sample_stats_to_xarray(self): """Extract sample_stats from PyMC3 trace.""" data = {} rename_key = { "model_logp": "lp", "mean_tree_accept": "acceptance_rate", "depth": "tree_depth", "tree_size": "n_steps", } data = {} data_warmup = {} for stat in self.trace.stat_names: name = rename_key.get(stat, stat) if name == "tune": continue if self.warmup_trace: data_warmup[name] = np.array( self.warmup_trace.get_sampler_stats(stat, combine=False) ) if self.posterior_trace: data[name] = np.array(self.posterior_trace.get_sampler_stats(stat, combine=False)) return ( dict_to_dataset( data, library=pymc3, dims=None, coords=self.coords, attrs=self.attrs, index_origin=self.index_origin, ), dict_to_dataset( data_warmup, library=pymc3, dims=None, coords=self.coords, attrs=self.attrs, index_origin=self.index_origin, ), ) @requires("trace") @requires("model") def log_likelihood_to_xarray(self): """Extract log likelihood and log_p data from PyMC3 trace.""" if self.predictions or not self.log_likelihood: return None data_warmup = {} data = {} warn_msg = ( "Could not compute log_likelihood, it will be omitted. " "Check your model object or set log_likelihood=False" ) if self.posterior_trace: try: data = self._extract_log_likelihood(self.posterior_trace) except TypeError: warnings.warn(warn_msg) if self.warmup_trace: try: data_warmup = self._extract_log_likelihood(self.warmup_trace) except TypeError: warnings.warn(warn_msg) return ( dict_to_dataset( data, library=pymc3, dims=self.dims, coords=self.coords, skip_event_dims=True, index_origin=self.index_origin, ), dict_to_dataset( data_warmup, library=pymc3, dims=self.dims, coords=self.coords, skip_event_dims=True, index_origin=self.index_origin, ), ) def translate_posterior_predictive_dict_to_xarray(self, dct) -> xr.Dataset: """Take Dict of variables to numpy ndarrays (samples) and translate into dataset.""" data = {} for k, ary in dct.items(): shape = ary.shape if shape[0] == self.nchains and shape[1] == self.ndraws: data[k] = ary elif shape[0] == self.nchains * self.ndraws: data[k] = ary.reshape((self.nchains, self.ndraws, *shape[1:])) else: data[k] = np.expand_dims(ary, 0) # pylint: disable=line-too-long _log.warning( "posterior predictive variable %s's shape not compatible with number of chains and draws. " "This can mean that some draws or even whole chains are not represented.", k, ) return dict_to_dataset( data, library=pymc3, coords=self.coords, dims=self.dims, index_origin=self.index_origin ) @requires(["posterior_predictive"]) def posterior_predictive_to_xarray(self): """Convert posterior_predictive samples to xarray.""" return self.translate_posterior_predictive_dict_to_xarray(self.posterior_predictive) @requires(["predictions"]) def predictions_to_xarray(self): """Convert predictions (out of sample predictions) to xarray.""" return self.translate_posterior_predictive_dict_to_xarray(self.predictions) def priors_to_xarray(self): """Convert prior samples (and if possible prior predictive too) to xarray.""" if self.prior is None: return {"prior": None, "prior_predictive": None} if self.observations is not None: prior_predictive_vars = list(self.observations.keys()) prior_vars = [key for key in self.prior.keys() if key not in prior_predictive_vars] else: prior_vars = list(self.prior.keys()) prior_predictive_vars = None priors_dict = {} for group, var_names in zip( ("prior", "prior_predictive"), (prior_vars, prior_predictive_vars) ): priors_dict[group] = ( None if var_names is None else dict_to_dataset( {k: np.expand_dims(self.prior[k], 0) for k in var_names}, library=pymc3, coords=self.coords, dims=self.dims, index_origin=self.index_origin, ) ) return priors_dict @requires("observations") @requires("model") def observed_data_to_xarray(self): """Convert observed data to xarray.""" if self.predictions: return None return dict_to_dataset( self.observations, library=pymc3, coords=self.coords, dims=self.dims, default_dims=[], index_origin=self.index_origin, ) @requires(["trace", "predictions"]) @requires("model") def constant_data_to_xarray(self): """Convert constant data to xarray.""" # For constant data, we are concerned only with deterministics and # data. The constant data vars must be either pm.Data # (TensorSharedVariable) or pm.Deterministic constant_data_vars = {} # type: Dict[str, Var] def is_data(name, var) -> bool: assert self.model is not None return ( var not in self.model.deterministics and var not in self.model.observed_RVs and var not in self.model.free_RVs and var not in self.model.potentials and (self.observations is None or name not in self.observations) and isinstance(var, (Constant, SharedVariable)) ) # I don't know how to find pm.Data, except that they are named # variables that aren't observed or free RVs, nor are they # deterministics, and then we eliminate observations. for name, var in self.model.named_vars.items(): if is_data(name, var): constant_data_vars[name] = var if not constant_data_vars: return None constant_data = {} for name, vals in constant_data_vars.items(): if hasattr(vals, "get_value"): vals = vals.get_value() elif hasattr(vals, "data"): vals = vals.data constant_data[name] = vals return dict_to_dataset( constant_data, library=pymc3, coords=self.coords, dims=self.dims, default_dims=[], index_origin=self.index_origin, ) def to_inference_data(self): """Convert all available data to an InferenceData object. Note that if groups can not be created (e.g., there is no `trace`, so the `posterior` and `sample_stats` can not be extracted), then the InferenceData will not have those groups. """ id_dict = { "posterior": self.posterior_to_xarray(), "sample_stats": self.sample_stats_to_xarray(), "log_likelihood": self.log_likelihood_to_xarray(), "posterior_predictive": self.posterior_predictive_to_xarray(), "predictions": self.predictions_to_xarray(), **self.priors_to_xarray(), "observed_data": self.observed_data_to_xarray(), } if self.predictions: id_dict["predictions_constant_data"] = self.constant_data_to_xarray() else: id_dict["constant_data"] = self.constant_data_to_xarray() return InferenceData(save_warmup=self.save_warmup, **id_dict) def to_inference_data( trace: Optional["MultiTrace"] = None, *, prior: Optional[Dict[str, Any]] = None, posterior_predictive: Optional[Dict[str, Any]] = None, log_likelihood: Union[bool, Iterable[str]] = True, coords: Optional[CoordSpec] = None, dims: Optional[DimSpec] = None, model: Optional["Model"] = None, save_warmup: Optional[bool] = None, density_dist_obs: bool = True, ) -> InferenceData: """Convert pymc3 data into an InferenceData object. All three of them are optional arguments, but at least one of ``trace``, ``prior`` and ``posterior_predictive`` must be present. For a usage example read the :ref:`Creating InferenceData section on from_pymc3 <creating_InferenceData>` Parameters ---------- trace : MultiTrace, optional Trace generated from MCMC sampling. Output of :func:`~pymc3.sampling.sample`. prior : dict, optional Dictionary with the variable names as keys, and values numpy arrays containing prior and prior predictive samples. posterior_predictive : dict, optional Dictionary with the variable names as keys, and values numpy arrays containing posterior predictive samples. log_likelihood : bool or array_like of str, optional List of variables to calculate `log_likelihood`. Defaults to True which calculates `log_likelihood` for all observed variables. If set to False, log_likelihood is skipped. coords : dict of {str: array-like}, optional Map of coordinate names to coordinate values dims : dict of {str: list of str}, optional Map of variable names to the coordinate names to use to index its dimensions. model : Model, optional Model used to generate ``trace``. It is not necessary to pass ``model`` if in ``with`` context. save_warmup : bool, optional Save warmup iterations InferenceData object. If not defined, use default defined by the rcParams. density_dist_obs : bool, default True Store variables passed with ``observed`` arg to :class:`~pymc.distributions.DensityDist` in the generated InferenceData. Returns ------- arviz.InferenceData """ if isinstance(trace, InferenceData): return trace return InferenceDataConverter( trace=trace, prior=prior, posterior_predictive=posterior_predictive, log_likelihood=log_likelihood, coords=coords, dims=dims, model=model, save_warmup=save_warmup, density_dist_obs=density_dist_obs, ).to_inference_data() ### Later I could have this return ``None`` if the ``idata_orig`` argument is supplied. But ### perhaps we should have an inplace argument? def predictions_to_inference_data( predictions, posterior_trace: Optional["MultiTrace"] = None, model: Optional["Model"] = None, coords: Optional[CoordSpec] = None, dims: Optional[DimSpec] = None, idata_orig: Optional[InferenceData] = None, inplace: bool = False, ) -> InferenceData: """Translate out-of-sample predictions into ``InferenceData``. Parameters ---------- predictions: Dict[str, np.ndarray] The predictions are the return value of :func:`~pymc3.sample_posterior_predictive`, a dictionary of strings (variable names) to numpy ndarrays (draws). posterior_trace: MultiTrace This should be a trace that has been thinned appropriately for ``pymc3.sample_posterior_predictive``. Specifically, any variable whose shape is a deterministic function of the shape of any predictor (explanatory, independent, etc.) variables must be *removed* from this trace. model: Model The pymc3 model. It can be ommited if within a model context. coords: Dict[str, array-like[Any]] Coordinates for the variables. Map from coordinate names to coordinate values. dims: Dict[str, array-like[str]] Map from variable name to ordered set of coordinate names. idata_orig: InferenceData, optional If supplied, then modify this inference data in place, adding ``predictions`` and (if available) ``predictions_constant_data`` groups. If this is not supplied, make a fresh InferenceData inplace: boolean, optional If idata_orig is supplied and inplace is True, merge the predictions into idata_orig, rather than returning a fresh InferenceData object. Returns ------- InferenceData: May be modified ``idata_orig``. """ if inplace and not idata_orig: raise ValueError( "Do not pass True for inplace unless passing" "an existing InferenceData as idata_orig" ) new_idata = InferenceDataConverter( trace=posterior_trace, predictions=predictions, model=model, coords=coords, dims=dims, log_likelihood=False, ).to_inference_data() if idata_orig is None: return new_idata elif inplace: concat([idata_orig, new_idata], dim=None, inplace=True) return idata_orig else: # if we are not returning in place, then merge the old groups into the new inference # data and return that. concat([new_idata, idata_orig], dim=None, copy=True, inplace=True) return new_idata
[ "logging.getLogger", "xarray.IndexVariable", "arviz.data.base.dict_to_dataset", "numpy.array", "pymc3.aesaraf.extract_obs_data", "numpy.where", "numpy.ndim", "numpy.stack", "warnings.warn", "pymc3.util.get_default_varnames", "numpy.any", "numpy.shape", "arviz.data.base.generate_dims_coords", "numpy.atleast_1d", "pymc3.distributions.logpt", "pymc3.model.modelcontext", "arviz.InferenceData", "xarray.DataArray", "arviz.concat", "arviz.data.base.make_attrs", "numpy.expand_dims", "arviz.data.base.requires" ]
[((1054, 1080), 'logging.getLogger', 'logging.getLogger', (['"""pymc3"""'], {}), "('pymc3')\n", (1071, 1080), False, 'import logging\n'), ((11415, 11432), 'arviz.data.base.requires', 'requires', (['"""trace"""'], {}), "('trace')\n", (11423, 11432), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((12608, 12625), 'arviz.data.base.requires', 'requires', (['"""trace"""'], {}), "('trace')\n", (12616, 12625), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((13946, 13963), 'arviz.data.base.requires', 'requires', (['"""trace"""'], {}), "('trace')\n", (13954, 13963), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((13969, 13986), 'arviz.data.base.requires', 'requires', (['"""model"""'], {}), "('model')\n", (13977, 13986), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((16344, 16378), 'arviz.data.base.requires', 'requires', (["['posterior_predictive']"], {}), "(['posterior_predictive'])\n", (16352, 16378), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((16586, 16611), 'arviz.data.base.requires', 'requires', (["['predictions']"], {}), "(['predictions'])\n", (16594, 16611), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((17916, 17940), 'arviz.data.base.requires', 'requires', (['"""observations"""'], {}), "('observations')\n", (17924, 17940), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((17946, 17963), 'arviz.data.base.requires', 'requires', (['"""model"""'], {}), "('model')\n", (17954, 17963), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((18342, 18376), 'arviz.data.base.requires', 'requires', (["['trace', 'predictions']"], {}), "(['trace', 'predictions'])\n", (18350, 18376), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((18382, 18399), 'arviz.data.base.requires', 'requires', (['"""model"""'], {}), "('model')\n", (18390, 18399), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((2352, 2363), 'numpy.shape', 'np.shape', (['v'], {}), '(v)\n', (2360, 2363), True, 'import numpy as np\n'), ((3240, 3342), 'arviz.data.base.dict_to_dataset', '_dict_to_dataset', (['data'], {'library': 'library', 'coords': 'coords', 'dims': 'dims', 'skip_event_dims': 'skip_event_dims'}), '(data, library=library, coords=coords, dims=dims,\n skip_event_dims=skip_event_dims)\n', (3256, 3342), True, 'from arviz.data.base import dict_to_dataset as _dict_to_dataset\n'), ((4950, 4969), 'pymc3.model.modelcontext', 'modelcontext', (['model'], {}), '(model)\n', (4962, 4969), False, 'from pymc3.model import modelcontext\n'), ((11546, 11614), 'pymc3.util.get_default_varnames', 'get_default_varnames', (['self.trace.varnames'], {'include_transformed': '(False)'}), '(self.trace.varnames, include_transformed=False)\n', (11566, 11614), False, 'from pymc3.util import get_default_varnames\n'), ((21077, 21131), 'arviz.InferenceData', 'InferenceData', ([], {'save_warmup': 'self.save_warmup'}), '(save_warmup=self.save_warmup, **id_dict)\n', (21090, 21131), False, 'from arviz import InferenceData, concat, rcParams\n'), ((3452, 3471), 'numpy.atleast_1d', 'np.atleast_1d', (['vals'], {}), '(vals)\n', (3465, 3471), True, 'import numpy as np\n'), ((3541, 3609), 'arviz.data.base.generate_dims_coords', 'generate_dims_coords', (['vals.shape', 'name'], {'dims': 'val_dims', 'coords': 'coords'}), '(vals.shape, name, dims=val_dims, coords=coords)\n', (3561, 3609), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((3730, 3778), 'xarray.DataArray', 'xr.DataArray', (['vals'], {'dims': 'val_dims', 'coords': 'coords'}), '(vals, dims=val_dims, coords=coords)\n', (3742, 3778), True, 'import xarray as xr\n'), ((10325, 10361), 'numpy.where', 'np.where', (['mask', 'np.nan', 'log_like_val'], {}), '(mask, np.nan, log_like_val)\n', (10333, 10361), True, 'import numpy as np\n'), ((26181, 26236), 'arviz.concat', 'concat', (['[idata_orig, new_idata]'], {'dim': 'None', 'inplace': '(True)'}), '([idata_orig, new_idata], dim=None, inplace=True)\n', (26187, 26236), False, 'from arviz import InferenceData, concat, rcParams\n'), ((26406, 26472), 'arviz.concat', 'concat', (['[new_idata, idata_orig]'], {'dim': 'None', 'copy': '(True)', 'inplace': '(True)'}), '([new_idata, idata_orig], dim=None, copy=True, inplace=True)\n', (26412, 26472), False, 'from arviz import InferenceData, concat, rcParams\n'), ((3637, 3679), 'xarray.IndexVariable', 'xr.IndexVariable', (['(key,)'], {'data': 'coords[key]'}), '((key,), data=coords[key])\n', (3653, 3679), True, 'import xarray as xr\n'), ((3831, 3858), 'arviz.data.base.make_attrs', 'make_attrs', ([], {'library': 'library'}), '(library=library)\n', (3841, 3858), False, 'from arviz.data.base import generate_dims_coords, make_attrs, requires\n'), ((8589, 8636), 'warnings.warn', 'warnings.warn', (['f"""No data for observation {obs}"""'], {}), "(f'No data for observation {obs}')\n", (8602, 8636), False, 'import warnings\n'), ((10007, 10045), 'pymc3.aesaraf.extract_obs_data', 'extract_obs_data', (['var.tag.observations'], {}), '(var.tag.observations)\n', (10023, 10045), False, 'from pymc3.aesaraf import extract_obs_data\n'), ((10214, 10227), 'numpy.ndim', 'np.ndim', (['mask'], {}), '(mask)\n', (10221, 10227), True, 'import numpy as np\n'), ((10230, 10251), 'numpy.ndim', 'np.ndim', (['log_like_val'], {}), '(log_like_val)\n', (10237, 10251), True, 'import numpy as np\n'), ((10276, 10297), 'numpy.any', 'np.any', (['mask'], {'axis': '(-1)'}), '(mask, axis=-1)\n', (10282, 10297), True, 'import numpy as np\n'), ((5525, 5716), 'warnings.warn', 'warnings.warn', (['"""Warmup samples will be stored in posterior group and will not be excluded from stats and diagnostics. Do not slice the trace manually before conversion"""', 'UserWarning'], {}), "(\n 'Warmup samples will be stored in posterior group and will not be excluded from stats and diagnostics. Do not slice the trace manually before conversion'\n , UserWarning)\n", (5538, 5716), False, 'import warnings\n'), ((8348, 8373), 'pymc3.aesaraf.extract_obs_data', 'extract_obs_data', (['aux_obs'], {}), '(aux_obs)\n', (8364, 8373), False, 'from pymc3.aesaraf import extract_obs_data\n'), ((10092, 10164), 'warnings.warn', 'warnings.warn', (['f"""Could not extract data from symbolic observation {var}"""'], {}), "(f'Could not extract data from symbolic observation {var}')\n", (10105, 10164), False, 'import warnings\n'), ((11334, 11358), 'numpy.stack', 'np.stack', (['log_like_chain'], {}), '(log_like_chain)\n', (11342, 11358), True, 'import numpy as np\n'), ((14556, 14579), 'warnings.warn', 'warnings.warn', (['warn_msg'], {}), '(warn_msg)\n', (14569, 14579), False, 'import warnings\n'), ((14751, 14774), 'warnings.warn', 'warnings.warn', (['warn_msg'], {}), '(warn_msg)\n', (14764, 14774), False, 'import warnings\n'), ((15847, 15869), 'numpy.expand_dims', 'np.expand_dims', (['ary', '(0)'], {}), '(ary, 0)\n', (15861, 15869), True, 'import numpy as np\n'), ((2550, 2561), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (2558, 2561), True, 'import numpy as np\n'), ((8482, 8554), 'warnings.warn', 'warnings.warn', (['f"""Could not extract data from symbolic observation {obs}"""'], {}), "(f'Could not extract data from symbolic observation {obs}')\n", (8495, 8554), False, 'import warnings\n'), ((10688, 10698), 'pymc3.distributions.logpt', 'logpt', (['var'], {}), '(var)\n', (10693, 10698), False, 'from pymc3.distributions import logpt\n'), ((10810, 10820), 'pymc3.distributions.logpt', 'logpt', (['var'], {}), '(var)\n', (10815, 10820), False, 'from pymc3.distributions import logpt\n'), ((17634, 17666), 'numpy.expand_dims', 'np.expand_dims', (['self.prior[k]', '(0)'], {}), '(self.prior[k], 0)\n', (17648, 17666), True, 'import numpy as np\n')]
from __future__ import print_function import json import os import requests from datetime import datetime import pandas as pd import numpy as np import matplotlib.pyplot as plt DEMO_UID = 0 PREDICTION_RESPONSE_KEY_QUERY_ID = "query_id" PREDICTION_RESPONSE_KEY_OUTPUT = "output" PREDICTION_RESPONSE_KEY_USED_DEFAULT = "default" PREDICTION_ERROR_RESPONSE_KEY_ERROR = "error" PREDICTION_ERROR_RESPONSE_KEY_CAUSE = "cause" classes = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck' ] positive_class = classes.index('airplane') negative_class = classes.index('bird') def recover_pixels(x): return np.transpose(x.reshape(3, 32, 32), (1, 2, 0)) def show_example_images(images, labels, num_rows): imgs_per_row = 6 num_images = imgs_per_row * num_rows idxs = np.random.randint(0, len(labels), num_images) f, axes = plt.subplots( nrows=num_rows, ncols=imgs_per_row, figsize=(1.5 * imgs_per_row, 1.5 * num_rows)) f.tight_layout() for i, idx in enumerate(idxs): image = recover_pixels(images[idx]) label = labels[idx] cur_ax = axes[i / imgs_per_row][i % imgs_per_row] cur_ax.imshow(image.astype(np.ubyte), interpolation="nearest") cur_ax.axis('off') if label == 0: title = classes[negative_class] else: title = classes[positive_class] cur_ax.set_title(title) def load_cifar(cifar_location, cifar_filename="cifar_train.data", norm=True): cifar_path = os.path.join(cifar_location, cifar_filename) # print("Source file: %s" % cifar_path) df = pd.read_csv(cifar_path, sep=",", header=None) data = df.values print("Number of image files: %d" % len(data)) y = data[:, 0] X = data[:, 1:] Z = X if norm: mu = np.mean(X.T, 0) sigma = np.var(X.T, 0) Z = (X.T - mu) / np.array([np.sqrt(z) if z > 0 else 1. for z in sigma]) Z = Z.T return Z, y def filter_data(X, y): X_train, y_train = [], [] for (example, label) in zip(X, y): if label == positive_class: X_train.append(example) y_train.append(1.0) elif label == negative_class: X_train.append(example) y_train.append(0.0) X_train = np.array(X_train) y_train = np.array(y_train) return X_train, y_train def cifar_update(host, app, uid, x, y, print_result=False): url = "http://%s:1337/%s/update" % (host, app) req_json = json.dumps({ 'uid': uid, 'input': list(x), 'label': float(y), # These updates aren't coming from predictions made by a particular # model, so we can ignore the model name and version fields. 'model_name': 'NA', 'model_version': 1 }) headers = {'Content-type': 'application/json'} start = datetime.now() r = requests.post(url, headers=headers, data=req_json) end = datetime.now() latency = (end - start).total_seconds() * 1000.0 if print_result: print("'%s', %f ms" % (r.text, latency)) def parse_pred(p): json_prediction = json.loads(p) if PREDICTION_RESPONSE_KEY_OUTPUT in json_prediction: # Prediction was successful, return parsed data qid = int(json_prediction[PREDICTION_RESPONSE_KEY_QUERY_ID]) pred = int(json_prediction[PREDICTION_RESPONSE_KEY_OUTPUT]) return qid, pred elif PREDICTION_ERROR_RESPONSE_KEY_ERROR in json_prediction: # Prediction is an error, log the issue error_name = str(json_prediction[PREDICTION_ERROR_RESPONSE_KEY_ERROR]) print(error_name) error_cause = str(json_prediction[PREDICTION_ERROR_RESPONSE_KEY_CAUSE]) print("Error executing prediction!") print("{}: {}".format(error_name, error_cause)) return None def cifar_prediction(host, app, uid, x): url = "http://%s/%s/predict" % (host, app) req_json = json.dumps({'uid': uid, 'input': list(x)}) headers = {'Content-type': 'application/json'} start = datetime.now() r = requests.post(url, headers=headers, data=req_json) end = datetime.now() latency = (end - start).total_seconds() * 1000.0 parsed_prediction = parse_pred(r.text) if parsed_prediction: qid, pred = parsed_prediction if pred == -1.0: pred = 0.0 assert pred == 1.0 or pred == 0.0 return (pred, latency) else: return None def run_iteration(host, app, uid, test_x, test_y): correct = 0 false_pos = 0 false_neg = 0 latencies = [] true_pos = 0 true_neg = 0 total = 100 for i in range(total): example_num = np.random.randint(0, len(test_y)) correct_y = float(test_y[example_num]) prediction = cifar_prediction(host, app, uid, test_x[example_num]) if not prediction: continue pred_y, latency = prediction if correct_y == pred_y: if correct_y == 0: true_neg += 1 elif correct_y == 1: true_pos += 1 correct += 1 elif correct_y == 0 and pred_y == 1: false_pos += 1 elif correct_y == 1 and pred_y == 0: false_neg += 1 else: print("predicted: {p}, correct: {c}".format(p=pred_y, c=correct_y)) latencies.append(latency) total = float(total) return (float(correct) / total, float(false_pos) / total, float(false_neg) / total, float(true_pos) / total, float(true_neg) / total, np.mean(latencies)) def run_serving_workload(host, app, test_x, test_y): fig, (ax_acc) = plt.subplots(1, 1, sharex=True) ax_acc.set_ylabel("application accuracy") ax_acc.set_xlabel("iterations") ax_acc.set_ylim(0, 1.0) xs = [] accs = [] lats = [] j = 0 uid = DEMO_UID while True: correct, fp, fn, tp, tn, mean_lat, = run_iteration( host, app, uid, test_x, test_y) xs.append(j) accs.append(correct) lats.append(mean_lat) j += 1 ax_acc.set_xlim(0, j + 1) ax_acc.plot(xs, accs, 'b') fig.tight_layout() fig.canvas.draw() def run_serving_workload_show_latency(host, app, test_x, test_y): fig, (ax_acc, ax_lat) = plt.subplots(2, 1, sharex=True) ax_acc.set_ylabel("accuracy") ax_lat.set_xlabel("time") ax_lat.set_ylabel("latency") ax_acc.set_ylim(0, 1.0) xs = [] accs = [] lats = [] j = 0 uid = DEMO_UID while True: correct, fp, fn, tp, tn, mean_lat, = run_iteration( host, app, uid, test_x, test_y) xs.append(j) accs.append(correct) lats.append(mean_lat) j += 1 ax_acc.set_xlim(0, j + 1) ax_lat.set_xlim(0, j + 1) ax_acc.plot(xs, accs, 'b') ax_lat.plot(xs, lats, 'r') ax_lat.set_ylim(0, 300) fig.canvas.draw() print(("Accuracy: {cor}, false positives: {fp}, " "false negatives: {fn}, true positives: {tp}, " "true negatives: {tn}").format( cor=correct, fp=fp, fn=fn, tp=tp, tn=tn)) print("Mean latency: {lat} ms".format(lat=mean_lat)) def enable_feedback(host, app, test_x, test_y, num_updates): uid = DEMO_UID for i in range(num_updates): example_num = np.random.randint(0, len(test_y)) cifar_update(host, app, uid, test_x[example_num], float(test_y[example_num]))
[ "numpy.mean", "json.loads", "requests.post", "numpy.sqrt", "pandas.read_csv", "os.path.join", "numpy.array", "datetime.datetime.now", "matplotlib.pyplot.subplots", "numpy.var" ]
[((883, 981), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': 'num_rows', 'ncols': 'imgs_per_row', 'figsize': '(1.5 * imgs_per_row, 1.5 * num_rows)'}), '(nrows=num_rows, ncols=imgs_per_row, figsize=(1.5 *\n imgs_per_row, 1.5 * num_rows))\n', (895, 981), True, 'import matplotlib.pyplot as plt\n'), ((1542, 1586), 'os.path.join', 'os.path.join', (['cifar_location', 'cifar_filename'], {}), '(cifar_location, cifar_filename)\n', (1554, 1586), False, 'import os\n'), ((1640, 1685), 'pandas.read_csv', 'pd.read_csv', (['cifar_path'], {'sep': '""","""', 'header': 'None'}), "(cifar_path, sep=',', header=None)\n", (1651, 1685), True, 'import pandas as pd\n'), ((2310, 2327), 'numpy.array', 'np.array', (['X_train'], {}), '(X_train)\n', (2318, 2327), True, 'import numpy as np\n'), ((2342, 2359), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (2350, 2359), True, 'import numpy as np\n'), ((2872, 2886), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2884, 2886), False, 'from datetime import datetime\n'), ((2895, 2945), 'requests.post', 'requests.post', (['url'], {'headers': 'headers', 'data': 'req_json'}), '(url, headers=headers, data=req_json)\n', (2908, 2945), False, 'import requests\n'), ((2956, 2970), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2968, 2970), False, 'from datetime import datetime\n'), ((3137, 3150), 'json.loads', 'json.loads', (['p'], {}), '(p)\n', (3147, 3150), False, 'import json\n'), ((4058, 4072), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4070, 4072), False, 'from datetime import datetime\n'), ((4081, 4131), 'requests.post', 'requests.post', (['url'], {'headers': 'headers', 'data': 'req_json'}), '(url, headers=headers, data=req_json)\n', (4094, 4131), False, 'import requests\n'), ((4142, 4156), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4154, 4156), False, 'from datetime import datetime\n'), ((5667, 5698), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'sharex': '(True)'}), '(1, 1, sharex=True)\n', (5679, 5698), True, 'import matplotlib.pyplot as plt\n'), ((6311, 6342), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'sharex': '(True)'}), '(2, 1, sharex=True)\n', (6323, 6342), True, 'import matplotlib.pyplot as plt\n'), ((1833, 1848), 'numpy.mean', 'np.mean', (['X.T', '(0)'], {}), '(X.T, 0)\n', (1840, 1848), True, 'import numpy as np\n'), ((1865, 1879), 'numpy.var', 'np.var', (['X.T', '(0)'], {}), '(X.T, 0)\n', (1871, 1879), True, 'import numpy as np\n'), ((5572, 5590), 'numpy.mean', 'np.mean', (['latencies'], {}), '(latencies)\n', (5579, 5590), True, 'import numpy as np\n'), ((1915, 1925), 'numpy.sqrt', 'np.sqrt', (['z'], {}), '(z)\n', (1922, 1925), True, 'import numpy as np\n')]
""" Module contains tools for processing files into DataFrames or other objects """ from __future__ import annotations from collections import abc import csv import sys from textwrap import fill from typing import Any import warnings import numpy as np import pandas._libs.lib as lib from pandas._libs.parsers import STR_NA_VALUES from pandas._typing import ( ArrayLike, DtypeArg, FilePathOrBuffer, StorageOptions, ) from pandas.errors import ( AbstractMethodError, ParserWarning, ) from pandas.util._decorators import ( Appender, deprecate_nonkeyword_arguments, ) from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.common import ( is_file_like, is_float, is_integer, is_list_like, ) from pandas.core import generic from pandas.core.frame import DataFrame from pandas.core.indexes.api import RangeIndex from pandas.io.common import validate_header_arg from pandas.io.parsers.base_parser import ( ParserBase, is_index_col, parser_defaults, ) from pandas.io.parsers.c_parser_wrapper import CParserWrapper from pandas.io.parsers.python_parser import ( FixedWidthFieldParser, PythonParser, ) _doc_read_csv_and_table = ( r""" {summary} Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the online docs for `IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_. Parameters ---------- filepath_or_buffer : str, path object or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.csv. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. sep : str, default {_default_sep} Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator by Python's builtin sniffer tool, ``csv.Sniffer``. In addition, separators longer than 1 character and different from ``'\s+'`` will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: ``'\r\t'``. delimiter : str, default ``None`` Alias for sep. header : int, list of int, default 'infer' Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to ``header=0`` and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to ``header=None``. Explicitly pass ``header=0`` to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if ``skip_blank_lines=True``, so ``header=0`` denotes the first line of data rather than the first line of the file. names : array-like, optional List of column names to use. If the file contains a header row, then you should explicitly pass ``header=0`` to override the column names. Duplicates in this list are not allowed. index_col : int, str, sequence of int / str, or False, default ``None`` Column(s) to use as the row labels of the ``DataFrame``, either given as string name or column index. If a sequence of int / str is given, a MultiIndex is used. Note: ``index_col=False`` can be used to force pandas to *not* use the first column as the index, e.g. when you have a malformed file with delimiters at the end of each line. usecols : list-like or callable, optional Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in `names` or inferred from the document header row(s). For example, a valid list-like `usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``. Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``. To instantiate a DataFrame from ``data`` with element order preserved use ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns in ``['foo', 'bar']`` order or ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]`` for ``['bar', 'foo']`` order. If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. An example of a valid callable argument would be ``lambda x: x.upper() in ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster parsing time and lower memory usage. squeeze : bool, default False If the parsed data only contains one column then return a Series. prefix : str, optional Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ... mangle_dupe_cols : bool, default True Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than 'X'...'X'. Passing in False will cause data to be overwritten if there are duplicate names in the columns. dtype : Type name or dict of column -> type, optional Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32, 'c': 'Int64'}} Use `str` or `object` together with suitable `na_values` settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion. engine : {{'c', 'python'}}, optional Parser engine to use. The C engine is faster while the python engine is currently more feature-complete. converters : dict, optional Dict of functions for converting values in certain columns. Keys can either be integers or column labels. true_values : list, optional Values to consider as True. false_values : list, optional Values to consider as False. skipinitialspace : bool, default False Skip spaces after delimiter. skiprows : list-like, int or callable, optional Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be ``lambda x: x in [0, 2]``. skipfooter : int, default 0 Number of lines at bottom of file to skip (Unsupported with engine='c'). nrows : int, optional Number of rows of file to read. Useful for reading pieces of large files. na_values : scalar, str, list-like, or dict, optional Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: '""" + fill("', '".join(sorted(STR_NA_VALUES)), 70, subsequent_indent=" ") + """'. keep_default_na : bool, default True Whether or not to include the default NaN values when parsing the data. Depending on whether `na_values` is passed in, the behavior is as follows: * If `keep_default_na` is True, and `na_values` are specified, `na_values` is appended to the default NaN values used for parsing. * If `keep_default_na` is True, and `na_values` are not specified, only the default NaN values are used for parsing. * If `keep_default_na` is False, and `na_values` are specified, only the NaN values specified `na_values` are used for parsing. * If `keep_default_na` is False, and `na_values` are not specified, no strings will be parsed as NaN. Note that if `na_filter` is passed in as False, the `keep_default_na` and `na_values` parameters will be ignored. na_filter : bool, default True Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file. verbose : bool, default False Indicate number of NA values placed in non-numeric columns. skip_blank_lines : bool, default True If True, skip over blank lines rather than interpreting as NaN values. parse_dates : bool or list of int or names or list of lists or dict, \ default False The behavior is as follows: * boolean. If True -> try parsing the index. * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. * dict, e.g. {{'foo' : [1, 3]}} -> parse columns 1, 3 as date and call result 'foo' If a column or index cannot be represented as an array of datetimes, say because of an unparsable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use ``pd.to_datetime`` after ``pd.read_csv``. To parse an index or column with a mixture of timezones, specify ``date_parser`` to be a partially-applied :func:`pandas.to_datetime` with ``utc=True``. See :ref:`io.csv.mixed_timezones` for more. Note: A fast-path exists for iso8601-formatted dates. infer_datetime_format : bool, default False If True and `parse_dates` is enabled, pandas will attempt to infer the format of the datetime strings in the columns, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by 5-10x. keep_date_col : bool, default False If True and `parse_dates` specifies combining multiple columns then keep the original columns. date_parser : function, optional Function to use for converting a sequence of string columns to an array of datetime instances. The default uses ``dateutil.parser.parser`` to do the conversion. Pandas will try to call `date_parser` in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the string values from the columns defined by `parse_dates` into a single array and pass that; and 3) call `date_parser` once for each row using one or more strings (corresponding to the columns defined by `parse_dates`) as arguments. dayfirst : bool, default False DD/MM format dates, international and European format. cache_dates : bool, default True If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. .. versionadded:: 0.25.0 iterator : bool, default False Return TextFileReader object for iteration or getting chunks with ``get_chunk()``. .. versionchanged:: 1.2 ``TextFileReader`` is a context manager. chunksize : int, optional Return TextFileReader object for iteration. See the `IO Tools docs <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_ for more information on ``iterator`` and ``chunksize``. .. versionchanged:: 1.2 ``TextFileReader`` is a context manager. compression : {{'infer', 'gzip', 'bz2', 'zip', 'xz', None}}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no decompression). If using 'zip', the ZIP file must contain only one data file to be read in. Set to None for no decompression. thousands : str, optional Thousands separator. decimal : str, default '.' Character to recognize as decimal point (e.g. use ',' for European data). lineterminator : str (length 1), optional Character to break file into lines. Only valid with C parser. quotechar : str (length 1), optional The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored. quoting : int or csv.QUOTE_* instance, default 0 Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3). doublequote : bool, default ``True`` When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a single ``quotechar`` element. escapechar : str (length 1), optional One-character string used to escape other characters. comment : str, optional Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as ``skip_blank_lines=True``), fully commented lines are ignored by the parameter `header` but not by `skiprows`. For example, if ``comment='#'``, parsing ``#empty\\na,b,c\\n1,2,3`` with ``header=0`` will result in 'a,b,c' being treated as the header. encoding : str, optional Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python standard encodings <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ . .. versionchanged:: 1.2 When ``encoding`` is ``None``, ``errors="replace"`` is passed to ``open()``. Otherwise, ``errors="strict"`` is passed to ``open()``. This behavior was previously only the case for ``engine="python"``. .. versionchanged:: 1.3.0 ``encoding_errors`` is a new argument. ``encoding`` has no longer an influence on how encoding errors are handled. encoding_errors : str, optional, default "strict" How encoding errors are treated. `List of possible values <https://docs.python.org/3/library/codecs.html#error-handlers>`_ . .. versionadded:: 1.3.0 dialect : str or csv.Dialect, optional If provided, this parameter will override values (default or not) for the following parameters: `delimiter`, `doublequote`, `escapechar`, `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details. error_bad_lines : bool, default ``None`` Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these "bad lines" will be dropped from the DataFrame that is returned. .. deprecated:: 1.3.0 The ``on_bad_lines`` parameter should be used instead to specify behavior upon encountering a bad line instead. warn_bad_lines : bool, default ``None`` If error_bad_lines is False, and warn_bad_lines is True, a warning for each "bad line" will be output. .. deprecated:: 1.3.0 The ``on_bad_lines`` parameter should be used instead to specify behavior upon encountering a bad line instead. on_bad_lines : {{'error', 'warn', 'skip'}}, default 'error' Specifies what to do upon encountering a bad line (a line with too many fields). Allowed values are : - 'error', raise an Exception when a bad line is encountered. - 'warn', raise a warning when a bad line is encountered and skip that line. - 'skip', skip bad lines without raising or warning when they are encountered. .. versionadded:: 1.3.0 delim_whitespace : bool, default False Specifies whether or not whitespace (e.g. ``' '`` or ``'\t'``) will be used as the sep. Equivalent to setting ``sep='\\s+'``. If this option is set to True, nothing should be passed in for the ``delimiter`` parameter. low_memory : bool, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the `dtype` parameter. Note that the entire file is read into a single DataFrame regardless, use the `chunksize` or `iterator` parameter to return the data in chunks. (Only valid with C parser). memory_map : bool, default False If a filepath is provided for `filepath_or_buffer`, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead. float_precision : str, optional Specifies which converter the C engine should use for floating-point values. The options are ``None`` or 'high' for the ordinary converter, 'legacy' for the original lower precision pandas converter, and 'round_trip' for the round-trip converter. .. versionchanged:: 1.2 {storage_options} .. versionadded:: 1.2 Returns ------- DataFrame or TextParser A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame. Examples -------- >>> pd.{func_name}('data.csv') # doctest: +SKIP """ ) _c_parser_defaults = { "delim_whitespace": False, "na_filter": True, "low_memory": True, "memory_map": False, "error_bad_lines": None, "warn_bad_lines": None, "float_precision": None, } _fwf_defaults = {"colspecs": "infer", "infer_nrows": 100, "widths": None} _c_unsupported = {"skipfooter"} _python_unsupported = {"low_memory", "float_precision"} _deprecated_defaults: dict[str, Any] = {"error_bad_lines": None, "warn_bad_lines": None} _deprecated_args: set[str] = {"error_bad_lines", "warn_bad_lines"} def validate_integer(name, val, min_val=0): """ Checks whether the 'name' parameter for parsing is either an integer OR float that can SAFELY be cast to an integer without losing accuracy. Raises a ValueError if that is not the case. Parameters ---------- name : str Parameter name (used for error reporting) val : int or float The value to check min_val : int Minimum allowed value (val < min_val will result in a ValueError) """ msg = f"'{name:s}' must be an integer >={min_val:d}" if val is not None: if is_float(val): if int(val) != val: raise ValueError(msg) val = int(val) elif not (is_integer(val) and val >= min_val): raise ValueError(msg) return val def _validate_names(names): """ Raise ValueError if the `names` parameter contains duplicates or has an invalid data type. Parameters ---------- names : array-like or None An array containing a list of the names used for the output DataFrame. Raises ------ ValueError If names are not unique or are not ordered (e.g. set). """ if names is not None: if len(names) != len(set(names)): raise ValueError("Duplicate names are not allowed.") if not ( is_list_like(names, allow_sets=False) or isinstance(names, abc.KeysView) ): raise ValueError("Names should be an ordered collection.") def _read(filepath_or_buffer: FilePathOrBuffer, kwds): """Generic reader of line files.""" if kwds.get("date_parser", None) is not None: if isinstance(kwds["parse_dates"], bool): kwds["parse_dates"] = True # Extract some of the arguments (pass chunksize on). iterator = kwds.get("iterator", False) chunksize = validate_integer("chunksize", kwds.get("chunksize", None), 1) nrows = kwds.get("nrows", None) # Check for duplicates in names. _validate_names(kwds.get("names", None)) # Create the parser. parser = TextFileReader(filepath_or_buffer, **kwds) if chunksize or iterator: return parser with parser: return parser.read(nrows) @deprecate_nonkeyword_arguments( version=None, allowed_args=["filepath_or_buffer"], stacklevel=3 ) @Appender( _doc_read_csv_and_table.format( func_name="read_csv", summary="Read a comma-separated values (csv) file into DataFrame.", _default_sep="','", storage_options=generic._shared_docs["storage_options"], ) ) def read_csv( filepath_or_buffer: FilePathOrBuffer, sep=lib.no_default, delimiter=None, # Column and Index Locations and Names header="infer", names=lib.no_default, index_col=None, usecols=None, squeeze=False, prefix=lib.no_default, mangle_dupe_cols=True, # General Parsing Configuration dtype: DtypeArg | None = None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, # NA and Missing Data Handling na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, # Datetime Handling parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, # Iteration iterator=False, chunksize=None, # Quoting, Compression, and File Format compression="infer", thousands=None, decimal: str = ".", lineterminator=None, quotechar='"', quoting=csv.QUOTE_MINIMAL, doublequote=True, escapechar=None, comment=None, encoding=None, encoding_errors: str | None = "strict", dialect=None, # Error Handling error_bad_lines=None, warn_bad_lines=None, # TODO (2.0): set on_bad_lines to "error". # See _refine_defaults_read comment for why we do this. on_bad_lines=None, # Internal delim_whitespace=False, low_memory=_c_parser_defaults["low_memory"], memory_map=False, float_precision=None, storage_options: StorageOptions = None, ): # locals() should never be modified kwds = locals().copy() del kwds["filepath_or_buffer"] del kwds["sep"] kwds_defaults = _refine_defaults_read( dialect, delimiter, delim_whitespace, engine, sep, error_bad_lines, warn_bad_lines, on_bad_lines, names, prefix, defaults={"delimiter": ","}, ) kwds.update(kwds_defaults) return _read(filepath_or_buffer, kwds) @deprecate_nonkeyword_arguments( version=None, allowed_args=["filepath_or_buffer"], stacklevel=3 ) @Appender( _doc_read_csv_and_table.format( func_name="read_table", summary="Read general delimited file into DataFrame.", _default_sep=r"'\\t' (tab-stop)", storage_options=generic._shared_docs["storage_options"], ) ) def read_table( filepath_or_buffer: FilePathOrBuffer, sep=lib.no_default, delimiter=None, # Column and Index Locations and Names header="infer", names=lib.no_default, index_col=None, usecols=None, squeeze=False, prefix=lib.no_default, mangle_dupe_cols=True, # General Parsing Configuration dtype: DtypeArg | None = None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, # NA and Missing Data Handling na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, # Datetime Handling parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, # Iteration iterator=False, chunksize=None, # Quoting, Compression, and File Format compression="infer", thousands=None, decimal: str = ".", lineterminator=None, quotechar='"', quoting=csv.QUOTE_MINIMAL, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, # Error Handling error_bad_lines=None, warn_bad_lines=None, # TODO (2.0): set on_bad_lines to "error". # See _refine_defaults_read comment for why we do this. on_bad_lines=None, encoding_errors: str | None = "strict", # Internal delim_whitespace=False, low_memory=_c_parser_defaults["low_memory"], memory_map=False, float_precision=None, ): # locals() should never be modified kwds = locals().copy() del kwds["filepath_or_buffer"] del kwds["sep"] kwds_defaults = _refine_defaults_read( dialect, delimiter, delim_whitespace, engine, sep, error_bad_lines, warn_bad_lines, on_bad_lines, names, prefix, defaults={"delimiter": "\t"}, ) kwds.update(kwds_defaults) return _read(filepath_or_buffer, kwds) def read_fwf( filepath_or_buffer: FilePathOrBuffer, colspecs="infer", widths=None, infer_nrows=100, **kwds, ): r""" Read a table of fixed-width formatted lines into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the `online docs for IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_. Parameters ---------- filepath_or_buffer : str, path object or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.csv``. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. colspecs : list of tuple (int, int) or 'infer'. optional A list of tuples giving the extents of the fixed-width fields of each line as half-open intervals (i.e., [from, to[ ). String value 'infer' can be used to instruct the parser to try detecting the column specifications from the first 100 rows of the data which are not being skipped via skiprows (default='infer'). widths : list of int, optional A list of field widths which can be used instead of 'colspecs' if the intervals are contiguous. infer_nrows : int, default 100 The number of rows to consider when letting the parser determine the `colspecs`. **kwds : optional Optional keyword arguments can be passed to ``TextFileReader``. Returns ------- DataFrame or TextParser A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. Examples -------- >>> pd.read_fwf('data.csv') # doctest: +SKIP """ # Check input arguments. if colspecs is None and widths is None: raise ValueError("Must specify either colspecs or widths") elif colspecs not in (None, "infer") and widths is not None: raise ValueError("You must specify only one of 'widths' and 'colspecs'") # Compute 'colspecs' from 'widths', if specified. if widths is not None: colspecs, col = [], 0 for w in widths: colspecs.append((col, col + w)) col += w kwds["colspecs"] = colspecs kwds["infer_nrows"] = infer_nrows kwds["engine"] = "python-fwf" return _read(filepath_or_buffer, kwds) class TextFileReader(abc.Iterator): """ Passed dialect overrides any of the related parser options """ def __init__(self, f, engine=None, **kwds): self.f = f if engine is not None: engine_specified = True else: engine = "python" engine_specified = False self.engine = engine self._engine_specified = kwds.get("engine_specified", engine_specified) _validate_skipfooter(kwds) dialect = _extract_dialect(kwds) if dialect is not None: kwds = _merge_with_dialect_properties(dialect, kwds) if kwds.get("header", "infer") == "infer": kwds["header"] = 0 if kwds.get("names") is None else None self.orig_options = kwds # miscellanea self._currow = 0 options = self._get_options_with_defaults(engine) options["storage_options"] = kwds.get("storage_options", None) self.chunksize = options.pop("chunksize", None) self.nrows = options.pop("nrows", None) self.squeeze = options.pop("squeeze", False) self._check_file_or_buffer(f, engine) self.options, self.engine = self._clean_options(options, engine) if "has_index_names" in kwds: self.options["has_index_names"] = kwds["has_index_names"] self._engine = self._make_engine(self.engine) def close(self): self._engine.close() def _get_options_with_defaults(self, engine): kwds = self.orig_options options = {} default: object | None for argname, default in parser_defaults.items(): value = kwds.get(argname, default) # see gh-12935 if argname == "mangle_dupe_cols" and not value: raise ValueError("Setting mangle_dupe_cols=False is not supported yet") else: options[argname] = value for argname, default in _c_parser_defaults.items(): if argname in kwds: value = kwds[argname] if engine != "c" and value != default: if "python" in engine and argname not in _python_unsupported: pass elif value == _deprecated_defaults.get(argname, default): pass else: raise ValueError( f"The {repr(argname)} option is not supported with the " f"{repr(engine)} engine" ) else: value = _deprecated_defaults.get(argname, default) options[argname] = value if engine == "python-fwf": for argname, default in _fwf_defaults.items(): options[argname] = kwds.get(argname, default) return options def _check_file_or_buffer(self, f, engine): # see gh-16530 if is_file_like(f) and engine != "c" and not hasattr(f, "__next__"): # The C engine doesn't need the file-like to have the "__next__" # attribute. However, the Python engine explicitly calls # "__next__(...)" when iterating through such an object, meaning it # needs to have that attribute raise ValueError( "The 'python' engine cannot iterate through this file buffer." ) def _clean_options(self, options, engine): result = options.copy() fallback_reason = None # C engine not supported yet if engine == "c": if options["skipfooter"] > 0: fallback_reason = "the 'c' engine does not support skipfooter" engine = "python" sep = options["delimiter"] delim_whitespace = options["delim_whitespace"] if sep is None and not delim_whitespace: if engine == "c": fallback_reason = ( "the 'c' engine does not support " "sep=None with delim_whitespace=False" ) engine = "python" elif sep is not None and len(sep) > 1: if engine == "c" and sep == r"\s+": result["delim_whitespace"] = True del result["delimiter"] elif engine not in ("python", "python-fwf"): # wait until regex engine integrated fallback_reason = ( "the 'c' engine does not support " "regex separators (separators > 1 char and " r"different from '\s+' are interpreted as regex)" ) engine = "python" elif delim_whitespace: if "python" in engine: result["delimiter"] = r"\s+" elif sep is not None: encodeable = True encoding = sys.getfilesystemencoding() or "utf-8" try: if len(sep.encode(encoding)) > 1: encodeable = False except UnicodeDecodeError: encodeable = False if not encodeable and engine not in ("python", "python-fwf"): fallback_reason = ( f"the separator encoded in {encoding} " "is > 1 char long, and the 'c' engine " "does not support such separators" ) engine = "python" quotechar = options["quotechar"] if quotechar is not None and isinstance(quotechar, (str, bytes)): if ( len(quotechar) == 1 and ord(quotechar) > 127 and engine not in ("python", "python-fwf") ): fallback_reason = ( "ord(quotechar) > 127, meaning the " "quotechar is larger than one byte, " "and the 'c' engine does not support such quotechars" ) engine = "python" if fallback_reason and self._engine_specified: raise ValueError(fallback_reason) if engine == "c": for arg in _c_unsupported: del result[arg] if "python" in engine: for arg in _python_unsupported: if fallback_reason and result[arg] != _c_parser_defaults[arg]: raise ValueError( "Falling back to the 'python' engine because " f"{fallback_reason}, but this causes {repr(arg)} to be " "ignored as it is not supported by the 'python' engine." ) del result[arg] if fallback_reason: warnings.warn( ( "Falling back to the 'python' engine because " f"{fallback_reason}; you can avoid this warning by specifying " "engine='python'." ), ParserWarning, stacklevel=5, ) index_col = options["index_col"] names = options["names"] converters = options["converters"] na_values = options["na_values"] skiprows = options["skiprows"] validate_header_arg(options["header"]) for arg in _deprecated_args: parser_default = _c_parser_defaults[arg] depr_default = _deprecated_defaults[arg] if result.get(arg, depr_default) != depr_default: msg = ( f"The {arg} argument has been deprecated and will be " "removed in a future version.\n\n" ) warnings.warn(msg, FutureWarning, stacklevel=7) else: result[arg] = parser_default if index_col is True: raise ValueError("The value of index_col couldn't be 'True'") if is_index_col(index_col): if not isinstance(index_col, (list, tuple, np.ndarray)): index_col = [index_col] result["index_col"] = index_col names = list(names) if names is not None else names # type conversion-related if converters is not None: if not isinstance(converters, dict): raise TypeError( "Type converters must be a dict or subclass, " f"input was a {type(converters).__name__}" ) else: converters = {} # Converting values to NA keep_default_na = options["keep_default_na"] na_values, na_fvalues = _clean_na_values(na_values, keep_default_na) # handle skiprows; this is internally handled by the # c-engine, so only need for python parsers if engine != "c": if is_integer(skiprows): skiprows = list(range(skiprows)) if skiprows is None: skiprows = set() elif not callable(skiprows): skiprows = set(skiprows) # put stuff back result["names"] = names result["converters"] = converters result["na_values"] = na_values result["na_fvalues"] = na_fvalues result["skiprows"] = skiprows return result, engine def __next__(self): try: return self.get_chunk() except StopIteration: self.close() raise def _make_engine(self, engine="c"): mapping: dict[str, type[ParserBase]] = { "c": CParserWrapper, "python": PythonParser, "python-fwf": FixedWidthFieldParser, } if engine not in mapping: raise ValueError( f"Unknown engine: {engine} (valid options are {mapping.keys()})" ) # error: Too many arguments for "ParserBase" return mapping[engine](self.f, **self.options) # type: ignore[call-arg] def _failover_to_python(self): raise AbstractMethodError(self) def read(self, nrows=None): nrows = validate_integer("nrows", nrows) index, columns, col_dict = self._engine.read(nrows) if index is None: if col_dict: # Any column is actually fine: new_rows = len(next(iter(col_dict.values()))) index = RangeIndex(self._currow, self._currow + new_rows) else: new_rows = 0 else: new_rows = len(index) df = DataFrame(col_dict, columns=columns, index=index) self._currow += new_rows if self.squeeze and len(df.columns) == 1: return df[df.columns[0]].copy() return df def get_chunk(self, size=None): if size is None: size = self.chunksize if self.nrows is not None: if self._currow >= self.nrows: raise StopIteration size = min(size, self.nrows - self._currow) return self.read(nrows=size) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def TextParser(*args, **kwds): """ Converts lists of lists/tuples into DataFrames with proper type inference and optional (e.g. string to datetime) conversion. Also enables iterating lazily over chunks of large files Parameters ---------- data : file-like object or list delimiter : separator character to use dialect : str or csv.Dialect instance, optional Ignored if delimiter is longer than 1 character names : sequence, default header : int, default 0 Row to use to parse column labels. Defaults to the first row. Prior rows will be discarded index_col : int or list, optional Column or columns to use as the (possibly hierarchical) index has_index_names: bool, default False True if the cols defined in index_col have an index name and are not in the header. na_values : scalar, str, list-like, or dict, optional Additional strings to recognize as NA/NaN. keep_default_na : bool, default True thousands : str, optional Thousands separator comment : str, optional Comment out remainder of line parse_dates : bool, default False keep_date_col : bool, default False date_parser : function, optional skiprows : list of integers Row numbers to skip skipfooter : int Number of line at bottom of file to skip converters : dict, optional Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the cell (not column) content, and return the transformed content. encoding : str, optional Encoding to use for UTF when reading/writing (ex. 'utf-8') squeeze : bool, default False returns Series if only one column. infer_datetime_format: bool, default False If True and `parse_dates` is True for a column, try to infer the datetime format based on the first datetime string. If the format can be inferred, there often will be a large parsing speed-up. float_precision : str, optional Specifies which converter the C engine should use for floating-point values. The options are `None` or `high` for the ordinary converter, `legacy` for the original lower precision pandas converter, and `round_trip` for the round-trip converter. .. versionchanged:: 1.2 """ kwds["engine"] = "python" return TextFileReader(*args, **kwds) def _clean_na_values(na_values, keep_default_na=True): na_fvalues: set | dict if na_values is None: if keep_default_na: na_values = STR_NA_VALUES else: na_values = set() na_fvalues = set() elif isinstance(na_values, dict): old_na_values = na_values.copy() na_values = {} # Prevent aliasing. # Convert the values in the na_values dictionary # into array-likes for further use. This is also # where we append the default NaN values, provided # that `keep_default_na=True`. for k, v in old_na_values.items(): if not is_list_like(v): v = [v] if keep_default_na: v = set(v) | STR_NA_VALUES na_values[k] = v na_fvalues = {k: _floatify_na_values(v) for k, v in na_values.items()} else: if not is_list_like(na_values): na_values = [na_values] na_values = _stringify_na_values(na_values) if keep_default_na: na_values = na_values | STR_NA_VALUES na_fvalues = _floatify_na_values(na_values) return na_values, na_fvalues def _floatify_na_values(na_values): # create float versions of the na_values result = set() for v in na_values: try: v = float(v) if not np.isnan(v): result.add(v) except (TypeError, ValueError, OverflowError): pass return result def _stringify_na_values(na_values): """ return a stringified and numeric for these values """ result: list[int | str | float] = [] for x in na_values: result.append(str(x)) result.append(x) try: v = float(x) # we are like 999 here if v == int(v): v = int(v) result.append(f"{v}.0") result.append(str(v)) result.append(v) except (TypeError, ValueError, OverflowError): pass try: result.append(int(x)) except (TypeError, ValueError, OverflowError): pass return set(result) def _refine_defaults_read( dialect: str | csv.Dialect, delimiter: str | object, delim_whitespace: bool, engine: str, sep: str | object, error_bad_lines: bool | None, warn_bad_lines: bool | None, on_bad_lines: str | None, names: ArrayLike | None | object, prefix: str | None | object, defaults: dict[str, Any], ): """Validate/refine default values of input parameters of read_csv, read_table. Parameters ---------- dialect : str or csv.Dialect If provided, this parameter will override values (default or not) for the following parameters: `delimiter`, `doublequote`, `escapechar`, `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details. delimiter : str or object Alias for sep. delim_whitespace : bool Specifies whether or not whitespace (e.g. ``' '`` or ``'\t'``) will be used as the sep. Equivalent to setting ``sep='\\s+'``. If this option is set to True, nothing should be passed in for the ``delimiter`` parameter. engine : {{'c', 'python'}} Parser engine to use. The C engine is faster while the python engine is currently more feature-complete. sep : str or object A delimiter provided by the user (str) or a sentinel value, i.e. pandas._libs.lib.no_default. error_bad_lines : str or None Whether to error on a bad line or not. warn_bad_lines : str or None Whether to warn on a bad line or not. on_bad_lines : str or None An option for handling bad lines or a sentinel value(None). names : array-like, optional List of column names to use. If the file contains a header row, then you should explicitly pass ``header=0`` to override the column names. Duplicates in this list are not allowed. prefix : str, optional Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ... defaults: dict Default values of input parameters. Returns ------- kwds : dict Input parameters with correct values. Raises ------ ValueError : If a delimiter was specified with ``sep`` (or ``delimiter``) and ``delim_whitespace=True``. If on_bad_lines is specified(not ``None``) and ``error_bad_lines``/ ``warn_bad_lines`` is True. """ # fix types for sep, delimiter to Union(str, Any) delim_default = defaults["delimiter"] kwds: dict[str, Any] = {} # gh-23761 # # When a dialect is passed, it overrides any of the overlapping # parameters passed in directly. We don't want to warn if the # default parameters were passed in (since it probably means # that the user didn't pass them in explicitly in the first place). # # "delimiter" is the annoying corner case because we alias it to # "sep" before doing comparison to the dialect values later on. # Thus, we need a flag to indicate that we need to "override" # the comparison to dialect values by checking if default values # for BOTH "delimiter" and "sep" were provided. if dialect is not None: kwds["sep_override"] = delimiter is None and ( sep is lib.no_default or sep == delim_default ) if delimiter and (sep is not lib.no_default): raise ValueError("Specified a sep and a delimiter; you can only specify one.") if names is not lib.no_default and prefix is not lib.no_default: raise ValueError("Specified named and prefix; you can only specify one.") kwds["names"] = None if names is lib.no_default else names kwds["prefix"] = None if prefix is lib.no_default else prefix # Alias sep -> delimiter. if delimiter is None: delimiter = sep if delim_whitespace and (delimiter is not lib.no_default): raise ValueError( "Specified a delimiter with both sep and " "delim_whitespace=True; you can only specify one." ) if delimiter is lib.no_default: # assign default separator value kwds["delimiter"] = delim_default else: kwds["delimiter"] = delimiter if engine is not None: kwds["engine_specified"] = True else: kwds["engine"] = "c" kwds["engine_specified"] = False # Ensure that on_bad_lines and error_bad_lines/warn_bad_lines # aren't specified at the same time. If so, raise. Otherwise, # alias on_bad_lines to "error" if error/warn_bad_lines not set # and on_bad_lines is not set. on_bad_lines is defaulted to None # so we can tell if it is set (this is why this hack exists). if on_bad_lines is not None: if error_bad_lines is not None or warn_bad_lines is not None: raise ValueError( "Both on_bad_lines and error_bad_lines/warn_bad_lines are set. " "Please only set on_bad_lines." ) if on_bad_lines == "error": kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.ERROR elif on_bad_lines == "warn": kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.WARN elif on_bad_lines == "skip": kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.SKIP else: raise ValueError(f"Argument {on_bad_lines} is invalid for on_bad_lines") else: if error_bad_lines is not None: # Must check is_bool, because other stuff(e.g. non-empty lists) eval to true validate_bool_kwarg(error_bad_lines, "error_bad_lines") if error_bad_lines: kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.ERROR else: if warn_bad_lines is not None: # This is the case where error_bad_lines is False # We can only warn/skip if error_bad_lines is False # None doesn't work because backwards-compatibility reasons validate_bool_kwarg(warn_bad_lines, "warn_bad_lines") if warn_bad_lines: kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.WARN else: kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.SKIP else: # Backwards compat, when only error_bad_lines = false, we warn kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.WARN else: # Everything None -> Error kwds["on_bad_lines"] = ParserBase.BadLineHandleMethod.ERROR return kwds def _extract_dialect(kwds: dict[str, Any]) -> csv.Dialect | None: """ Extract concrete csv dialect instance. Returns ------- csv.Dialect or None """ if kwds.get("dialect") is None: return None dialect = kwds["dialect"] if dialect in csv.list_dialects(): dialect = csv.get_dialect(dialect) _validate_dialect(dialect) return dialect MANDATORY_DIALECT_ATTRS = ( "delimiter", "doublequote", "escapechar", "skipinitialspace", "quotechar", "quoting", ) def _validate_dialect(dialect: csv.Dialect) -> None: """ Validate csv dialect instance. Raises ------ ValueError If incorrect dialect is provided. """ for param in MANDATORY_DIALECT_ATTRS: if not hasattr(dialect, param): raise ValueError(f"Invalid dialect {dialect} provided") def _merge_with_dialect_properties( dialect: csv.Dialect, defaults: dict[str, Any], ) -> dict[str, Any]: """ Merge default kwargs in TextFileReader with dialect parameters. Parameters ---------- dialect : csv.Dialect Concrete csv dialect. See csv.Dialect documentation for more details. defaults : dict Keyword arguments passed to TextFileReader. Returns ------- kwds : dict Updated keyword arguments, merged with dialect parameters. """ kwds = defaults.copy() for param in MANDATORY_DIALECT_ATTRS: dialect_val = getattr(dialect, param) parser_default = parser_defaults[param] provided = kwds.get(param, parser_default) # Messages for conflicting values between the dialect # instance and the actual parameters provided. conflict_msgs = [] # Don't warn if the default parameter was passed in, # even if it conflicts with the dialect (gh-23761). if provided != parser_default and provided != dialect_val: msg = ( f"Conflicting values for '{param}': '{provided}' was " f"provided, but the dialect specifies '{dialect_val}'. " "Using the dialect-specified value." ) # Annoying corner case for not warning about # conflicts between dialect and delimiter parameter. # Refer to the outer "_read_" function for more info. if not (param == "delimiter" and kwds.pop("sep_override", False)): conflict_msgs.append(msg) if conflict_msgs: warnings.warn("\n\n".join(conflict_msgs), ParserWarning, stacklevel=2) kwds[param] = dialect_val return kwds def _validate_skipfooter(kwds: dict[str, Any]) -> None: """ Check whether skipfooter is compatible with other kwargs in TextFileReader. Parameters ---------- kwds : dict Keyword arguments passed to TextFileReader. Raises ------ ValueError If skipfooter is not compatible with other parameters. """ if kwds.get("skipfooter"): if kwds.get("iterator") or kwds.get("chunksize"): raise ValueError("'skipfooter' not supported for iteration") if kwds.get("nrows"): raise ValueError("'skipfooter' not supported with 'nrows'")
[ "csv.get_dialect", "pandas.errors.AbstractMethodError", "pandas.io.common.validate_header_arg", "pandas.core.dtypes.common.is_file_like", "pandas.core.dtypes.common.is_list_like", "sys.getfilesystemencoding", "pandas.io.parsers.base_parser.is_index_col", "pandas.core.dtypes.common.is_float", "csv.list_dialects", "pandas.io.parsers.base_parser.parser_defaults.items", "pandas.util._decorators.deprecate_nonkeyword_arguments", "pandas.core.dtypes.common.is_integer", "pandas.util._validators.validate_bool_kwarg", "numpy.isnan", "warnings.warn", "pandas.core.frame.DataFrame", "pandas.core.indexes.api.RangeIndex" ]
[((20583, 20683), 'pandas.util._decorators.deprecate_nonkeyword_arguments', 'deprecate_nonkeyword_arguments', ([], {'version': 'None', 'allowed_args': "['filepath_or_buffer']", 'stacklevel': '(3)'}), "(version=None, allowed_args=[\n 'filepath_or_buffer'], stacklevel=3)\n", (20613, 20683), False, 'from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments\n'), ((23045, 23145), 'pandas.util._decorators.deprecate_nonkeyword_arguments', 'deprecate_nonkeyword_arguments', ([], {'version': 'None', 'allowed_args': "['filepath_or_buffer']", 'stacklevel': '(3)'}), "(version=None, allowed_args=[\n 'filepath_or_buffer'], stacklevel=3)\n", (23075, 23145), False, 'from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments\n'), ((18938, 18951), 'pandas.core.dtypes.common.is_float', 'is_float', (['val'], {}), '(val)\n', (18946, 18951), False, 'from pandas.core.dtypes.common import is_file_like, is_float, is_integer, is_list_like\n'), ((29966, 29989), 'pandas.io.parsers.base_parser.parser_defaults.items', 'parser_defaults.items', ([], {}), '()\n', (29987, 29989), False, 'from pandas.io.parsers.base_parser import ParserBase, is_index_col, parser_defaults\n'), ((35587, 35625), 'pandas.io.common.validate_header_arg', 'validate_header_arg', (["options['header']"], {}), "(options['header'])\n", (35606, 35625), False, 'from pandas.io.common import validate_header_arg\n'), ((36247, 36270), 'pandas.io.parsers.base_parser.is_index_col', 'is_index_col', (['index_col'], {}), '(index_col)\n', (36259, 36270), False, 'from pandas.io.parsers.base_parser import ParserBase, is_index_col, parser_defaults\n'), ((38322, 38347), 'pandas.errors.AbstractMethodError', 'AbstractMethodError', (['self'], {}), '(self)\n', (38341, 38347), False, 'from pandas.errors import AbstractMethodError, ParserWarning\n'), ((38834, 38883), 'pandas.core.frame.DataFrame', 'DataFrame', (['col_dict'], {'columns': 'columns', 'index': 'index'}), '(col_dict, columns=columns, index=index)\n', (38843, 38883), False, 'from pandas.core.frame import DataFrame\n'), ((51130, 51149), 'csv.list_dialects', 'csv.list_dialects', ([], {}), '()\n', (51147, 51149), False, 'import csv\n'), ((51169, 51193), 'csv.get_dialect', 'csv.get_dialect', (['dialect'], {}), '(dialect)\n', (51184, 51193), False, 'import csv\n'), ((31296, 31311), 'pandas.core.dtypes.common.is_file_like', 'is_file_like', (['f'], {}), '(f)\n', (31308, 31311), False, 'from pandas.core.dtypes.common import is_file_like, is_float, is_integer, is_list_like\n'), ((35063, 35240), 'warnings.warn', 'warnings.warn', (['f"""Falling back to the \'python\' engine because {fallback_reason}; you can avoid this warning by specifying engine=\'python\'."""', 'ParserWarning'], {'stacklevel': '(5)'}), '(\n f"Falling back to the \'python\' engine because {fallback_reason}; you can avoid this warning by specifying engine=\'python\'."\n , ParserWarning, stacklevel=5)\n', (35076, 35240), False, 'import warnings\n'), ((37144, 37164), 'pandas.core.dtypes.common.is_integer', 'is_integer', (['skiprows'], {}), '(skiprows)\n', (37154, 37164), False, 'from pandas.core.dtypes.common import is_file_like, is_float, is_integer, is_list_like\n'), ((49767, 49822), 'pandas.util._validators.validate_bool_kwarg', 'validate_bool_kwarg', (['error_bad_lines', '"""error_bad_lines"""'], {}), "(error_bad_lines, 'error_bad_lines')\n", (49786, 49822), False, 'from pandas.util._validators import validate_bool_kwarg\n'), ((19704, 19741), 'pandas.core.dtypes.common.is_list_like', 'is_list_like', (['names'], {'allow_sets': '(False)'}), '(names, allow_sets=False)\n', (19716, 19741), False, 'from pandas.core.dtypes.common import is_file_like, is_float, is_integer, is_list_like\n'), ((36020, 36067), 'warnings.warn', 'warnings.warn', (['msg', 'FutureWarning'], {'stacklevel': '(7)'}), '(msg, FutureWarning, stacklevel=7)\n', (36033, 36067), False, 'import warnings\n'), ((38675, 38724), 'pandas.core.indexes.api.RangeIndex', 'RangeIndex', (['self._currow', '(self._currow + new_rows)'], {}), '(self._currow, self._currow + new_rows)\n', (38685, 38724), False, 'from pandas.core.indexes.api import RangeIndex\n'), ((42891, 42914), 'pandas.core.dtypes.common.is_list_like', 'is_list_like', (['na_values'], {}), '(na_values)\n', (42903, 42914), False, 'from pandas.core.dtypes.common import is_file_like, is_float, is_integer, is_list_like\n'), ((43352, 43363), 'numpy.isnan', 'np.isnan', (['v'], {}), '(v)\n', (43360, 43363), True, 'import numpy as np\n'), ((19068, 19083), 'pandas.core.dtypes.common.is_integer', 'is_integer', (['val'], {}), '(val)\n', (19078, 19083), False, 'from pandas.core.dtypes.common import is_file_like, is_float, is_integer, is_list_like\n'), ((42640, 42655), 'pandas.core.dtypes.common.is_list_like', 'is_list_like', (['v'], {}), '(v)\n', (42652, 42655), False, 'from pandas.core.dtypes.common import is_file_like, is_float, is_integer, is_list_like\n'), ((50238, 50291), 'pandas.util._validators.validate_bool_kwarg', 'validate_bool_kwarg', (['warn_bad_lines', '"""warn_bad_lines"""'], {}), "(warn_bad_lines, 'warn_bad_lines')\n", (50257, 50291), False, 'from pandas.util._validators import validate_bool_kwarg\n'), ((33225, 33252), 'sys.getfilesystemencoding', 'sys.getfilesystemencoding', ([], {}), '()\n', (33250, 33252), False, 'import sys\n')]
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2019 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import numpy as np import scipy.linalg as spla from pymor.algorithms.arnoldi import arnoldi from pymor.algorithms.gram_schmidt import gram_schmidt, gram_schmidt_biorth from pymor.core.interfaces import BasicInterface from pymor.models.iosys import LTIModel, SecondOrderModel, LinearDelayModel from pymor.operators.constructions import LincombOperator from pymor.reductors.basic import LTIPGReductor, SOLTIPGReductor, DelayLTIPGReductor class GenericBHIReductor(BasicInterface): r"""Generic bitangential Hermite interpolation reductor. This is a generic reductor for reducing any linear :class:`~pymor.models.iosys.InputStateOutputModel` with the transfer function which can be written in the generalized coprime factorization :math:`\mathcal{C}(s) \mathcal{K}(s)^{-1} \mathcal{B}(s)` as in [BG09]_. The interpolation here is limited to only up to the first derivative. Hence, interpolation points are assumed to be pairwise distinct. Parameters ---------- fom Model. """ PGReductor = None def __init__(self, fom): self.fom = fom self._product = None def _B_apply(self, s, V): raise NotImplementedError def _C_apply_adjoint(self, s, V): raise NotImplementedError def _K_apply_inverse(self, s, V): raise NotImplementedError def _K_apply_inverse_adjoint(self, s, V): raise NotImplementedError def reduce(self, sigma, b, c, projection='orth'): """Bitangential Hermite interpolation. Parameters ---------- sigma Interpolation points (closed under conjugation), list of length `r`. b Right tangential directions, |VectorArray| of length `r` from `self.fom.input_space`. c Left tangential directions, |VectorArray| of length `r` from `self.fom.output_space`. projection Projection method: - `'orth'`: projection matrices are orthogonalized with respect to the Euclidean inner product - `'biorth'`: projection matrices are biorthogolized with respect to the E product Returns ------- rom Reduced model. """ r = len(sigma) assert b in self.fom.input_space and len(b) == r assert c in self.fom.output_space and len(c) == r assert projection in ('orth', 'biorth') # rescale tangential directions (to avoid overflow or underflow) if b.dim > 1: b.scal(1 / b.l2_norm()) else: b = self.fom.input_space.ones(r) if c.dim > 1: c.scal(1 / c.l2_norm()) else: c = self.fom.output_space.ones(r) # compute projection matrices self.V = self.fom.state_space.empty(reserve=r) self.W = self.fom.state_space.empty(reserve=r) for i in range(r): if sigma[i].imag == 0: Bb = self._B_apply(sigma[i].real, b.real[i]) self.V.append(self._K_apply_inverse(sigma[i].real, Bb)) CTc = self._C_apply_adjoint(sigma[i].real, c.real[i]) self.W.append(self._K_apply_inverse_adjoint(sigma[i].real, CTc)) elif sigma[i].imag > 0: Bb = self._B_apply(sigma[i], b[i]) v = self._K_apply_inverse(sigma[i], Bb) self.V.append(v.real) self.V.append(v.imag) CTc = self._C_apply_adjoint(sigma[i], c[i].conj()) w = self._K_apply_inverse_adjoint(sigma[i], CTc) self.W.append(w.real) self.W.append(w.imag) if projection == 'orth': self.V = gram_schmidt(self.V, atol=0, rtol=0) self.W = gram_schmidt(self.W, atol=0, rtol=0) elif projection == 'biorth': self.V, self.W = gram_schmidt_biorth(self.V, self.W, product=self._product) self.pg_reductor = self.PGReductor(self.fom, self.W, self.V, projection == 'biorth') rom = self.pg_reductor.reduce() return rom def reconstruct(self, u): """Reconstruct high-dimensional vector from reduced vector `u`.""" return self.RB[:u.dim].lincomb(u.to_numpy()) class LTI_BHIReductor(GenericBHIReductor): """Bitangential Hermite interpolation for |LTIModels|. Parameters ---------- fom |LTIModel|. """ PGReductor = LTIPGReductor def __init__(self, fom): assert isinstance(fom, LTIModel) self.fom = fom self._product = fom.E def _B_apply(self, s, V): return self.fom.B.apply(V) def _C_apply_adjoint(self, s, V): return self.fom.C.apply_adjoint(V) def _K_apply_inverse(self, s, V): sEmA = s * self.fom.E - self.fom.A return sEmA.apply_inverse(V) def _K_apply_inverse_adjoint(self, s, V): sEmA = s * self.fom.E - self.fom.A return sEmA.apply_inverse_adjoint(V) def reduce(self, sigma, b, c, projection='orth', use_arnoldi=False): """Bitangential Hermite interpolation. Parameters ---------- sigma Interpolation points (closed under conjugation), list of length `r`. b Right tangential directions, |VectorArray| of length `r` from `self.fom.input_space`. c Left tangential directions, |VectorArray| of length `r` from `self.fom.output_space`. projection Projection method: - `'orth'`: projection matrices are orthogonalized with respect to the Euclidean inner product - `'biorth'`: projection matrices are biorthogolized with respect to the E product use_arnoldi Should the Arnoldi process be used for rational interpolation. Available only for SISO systems. Otherwise, it is ignored. Returns ------- rom Reduced model. """ if use_arnoldi and self.fom.input_dim == 1 and self.fom.output_dim == 1: return self.reduce_arnoldi(sigma, b, c) else: return super().reduce(sigma, b, c, projection=projection) def reduce_arnoldi(self, sigma, b, c): """Bitangential Hermite interpolation for SISO |LTIModels|. Parameters ---------- sigma Interpolation points (closed under conjugation), list of length `r`. b Right tangential directions, |VectorArray| of length `r` from `self.fom.B.source`. c Left tangential directions, |VectorArray| of length `r` from `self.fom.C.range`. Returns ------- rom Reduced |LTIModel| model. """ fom = self.fom assert fom.input_dim == 1 and fom.output_dim == 1 r = len(sigma) assert b in fom.B.source and len(b) == r assert c in fom.C.range and len(c) == r self.V = arnoldi(fom.A, fom.E, fom.B, sigma) self.W = arnoldi(fom.A, fom.E, fom.C, sigma, trans=True) rom = super(GenericBHIReductor, self).reduce() return rom class SO_BHIReductor(GenericBHIReductor): """Bitangential Hermite interpolation for second-order systems. Parameters ---------- fom :class:`~pymor.models.iosys.SecondOrderModel`. """ PGReductor = SOLTIPGReductor def __init__(self, fom): assert isinstance(fom, SecondOrderModel) self.fom = fom self._product = fom.M def _B_apply(self, s, V): return self.fom.B.apply(V) def _C_apply_adjoint(self, s, V): x = self.fom.Cp.apply_adjoint(V) y = self.fom.Cv.apply_adjoint(V) return x + y * s.conjugate() def _K_apply_inverse(self, s, V): s2MpsEpK = s**2 * self.fom.M + s * self.fom.E + self.fom.K return s2MpsEpK.apply_inverse(V) def _K_apply_inverse_adjoint(self, s, V): s2MpsEpK = s**2 * self.fom.M + s * self.fom.E + self.fom.K return s2MpsEpK.apply_inverse_adjoint(V) class DelayBHIReductor(GenericBHIReductor): """Bitangential Hermite interpolation for delay systems. Parameters ---------- fom :class:`~pymor.models.iosys.LinearDelayModel`. """ PGReductor = DelayLTIPGReductor def __init__(self, fom): assert isinstance(fom, LinearDelayModel) self.fom = fom self._product = fom.E def _B_apply(self, s, V): return self.fom.B.apply(V) def _C_apply_adjoint(self, s, V): return self.fom.C.apply_adjoint(V) def _K_apply_inverse(self, s, V): Ks = LincombOperator((self.fom.E, self.fom.A) + self.fom.Ad, (s, -1) + tuple(-np.exp(-taui * s) for taui in self.fom.tau)) return Ks.apply_inverse(V) def _K_apply_inverse_adjoint(self, s, V): Ks = LincombOperator((self.fom.E, self.fom.A) + self.fom.Ad, (s, -1) + tuple(-np.exp(-taui * s) for taui in self.fom.tau)) return Ks.apply_inverse_adjoint(V) class TFInterpReductor(BasicInterface): """Loewner bitangential Hermite interpolation reductor. See [BG12]_. Parameters ---------- fom Model with `eval_tf` and `eval_dtf` methods. """ def __init__(self, fom): self.fom = fom def reduce(self, sigma, b, c): """Realization-independent tangential Hermite interpolation. Parameters ---------- sigma Interpolation points (closed under conjugation), list of length `r`. b Right tangential directions, |NumPy array| of shape `(fom.input_dim, r)`. c Left tangential directions, |NumPy array| of shape `(fom.output_dim, r)`. Returns ------- lti |LTIModel| interpolating the transfer function of `fom`. """ fom = self.fom r = len(sigma) assert isinstance(b, np.ndarray) and b.shape == (fom.input_dim, r) assert isinstance(c, np.ndarray) and c.shape == (fom.output_dim, r) # rescale tangential directions (to avoid overflow or underflow) if b.shape[0] > 1: for i in range(r): b[:, i] /= spla.norm(b[:, i]) else: b = np.ones((1, r)) if c.shape[0] > 1: for i in range(r): c[:, i] /= spla.norm(c[:, i]) else: c = np.ones((1, r)) # matrices of the interpolatory LTI system Er = np.empty((r, r), dtype=complex) Ar = np.empty((r, r), dtype=complex) Br = np.empty((r, fom.input_dim), dtype=complex) Cr = np.empty((fom.output_dim, r), dtype=complex) Hs = [fom.eval_tf(s) for s in sigma] dHs = [fom.eval_dtf(s) for s in sigma] for i in range(r): for j in range(r): if i != j: Er[i, j] = -c[:, i].dot((Hs[i] - Hs[j]).dot(b[:, j])) / (sigma[i] - sigma[j]) Ar[i, j] = -c[:, i].dot((sigma[i] * Hs[i] - sigma[j] * Hs[j])).dot(b[:, j]) / (sigma[i] - sigma[j]) else: Er[i, i] = -c[:, i].dot(dHs[i].dot(b[:, i])) Ar[i, i] = -c[:, i].dot((Hs[i] + sigma[i] * dHs[i]).dot(b[:, i])) Br[i, :] = Hs[i].T.dot(c[:, i]) Cr[:, i] = Hs[i].dot(b[:, i]) # transform the system to have real matrices T = np.zeros((r, r), dtype=complex) for i in range(r): if sigma[i].imag == 0: T[i, i] = 1 else: indices = np.nonzero(np.isclose(sigma[i + 1:], sigma[i].conjugate()))[0] if len(indices) > 0: j = i + 1 + indices[0] T[i, i] = 1 T[i, j] = 1 T[j, i] = -1j T[j, j] = 1j Er = (T.dot(Er).dot(T.conj().T)).real Ar = (T.dot(Ar).dot(T.conj().T)).real Br = (T.dot(Br)).real Cr = (Cr.dot(T.conj().T)).real return LTIModel.from_matrices(Ar, Br, Cr, D=None, E=Er, cont_time=fom.cont_time)
[ "pymor.algorithms.gram_schmidt.gram_schmidt_biorth", "pymor.algorithms.gram_schmidt.gram_schmidt", "numpy.ones", "numpy.exp", "numpy.zeros", "numpy.empty", "scipy.linalg.norm", "pymor.algorithms.arnoldi.arnoldi", "pymor.models.iosys.LTIModel.from_matrices" ]
[((7315, 7350), 'pymor.algorithms.arnoldi.arnoldi', 'arnoldi', (['fom.A', 'fom.E', 'fom.B', 'sigma'], {}), '(fom.A, fom.E, fom.B, sigma)\n', (7322, 7350), False, 'from pymor.algorithms.arnoldi import arnoldi\n'), ((7368, 7415), 'pymor.algorithms.arnoldi.arnoldi', 'arnoldi', (['fom.A', 'fom.E', 'fom.C', 'sigma'], {'trans': '(True)'}), '(fom.A, fom.E, fom.C, sigma, trans=True)\n', (7375, 7415), False, 'from pymor.algorithms.arnoldi import arnoldi\n'), ((10916, 10947), 'numpy.empty', 'np.empty', (['(r, r)'], {'dtype': 'complex'}), '((r, r), dtype=complex)\n', (10924, 10947), True, 'import numpy as np\n'), ((10961, 10992), 'numpy.empty', 'np.empty', (['(r, r)'], {'dtype': 'complex'}), '((r, r), dtype=complex)\n', (10969, 10992), True, 'import numpy as np\n'), ((11006, 11049), 'numpy.empty', 'np.empty', (['(r, fom.input_dim)'], {'dtype': 'complex'}), '((r, fom.input_dim), dtype=complex)\n', (11014, 11049), True, 'import numpy as np\n'), ((11063, 11107), 'numpy.empty', 'np.empty', (['(fom.output_dim, r)'], {'dtype': 'complex'}), '((fom.output_dim, r), dtype=complex)\n', (11071, 11107), True, 'import numpy as np\n'), ((11830, 11861), 'numpy.zeros', 'np.zeros', (['(r, r)'], {'dtype': 'complex'}), '((r, r), dtype=complex)\n', (11838, 11861), True, 'import numpy as np\n'), ((12447, 12520), 'pymor.models.iosys.LTIModel.from_matrices', 'LTIModel.from_matrices', (['Ar', 'Br', 'Cr'], {'D': 'None', 'E': 'Er', 'cont_time': 'fom.cont_time'}), '(Ar, Br, Cr, D=None, E=Er, cont_time=fom.cont_time)\n', (12469, 12520), False, 'from pymor.models.iosys import LTIModel, SecondOrderModel, LinearDelayModel\n'), ((3982, 4018), 'pymor.algorithms.gram_schmidt.gram_schmidt', 'gram_schmidt', (['self.V'], {'atol': '(0)', 'rtol': '(0)'}), '(self.V, atol=0, rtol=0)\n', (3994, 4018), False, 'from pymor.algorithms.gram_schmidt import gram_schmidt, gram_schmidt_biorth\n'), ((4040, 4076), 'pymor.algorithms.gram_schmidt.gram_schmidt', 'gram_schmidt', (['self.W'], {'atol': '(0)', 'rtol': '(0)'}), '(self.W, atol=0, rtol=0)\n', (4052, 4076), False, 'from pymor.algorithms.gram_schmidt import gram_schmidt, gram_schmidt_biorth\n'), ((10685, 10700), 'numpy.ones', 'np.ones', (['(1, r)'], {}), '((1, r))\n', (10692, 10700), True, 'import numpy as np\n'), ((10835, 10850), 'numpy.ones', 'np.ones', (['(1, r)'], {}), '((1, r))\n', (10842, 10850), True, 'import numpy as np\n'), ((4143, 4201), 'pymor.algorithms.gram_schmidt.gram_schmidt_biorth', 'gram_schmidt_biorth', (['self.V', 'self.W'], {'product': 'self._product'}), '(self.V, self.W, product=self._product)\n', (4162, 4201), False, 'from pymor.algorithms.gram_schmidt import gram_schmidt, gram_schmidt_biorth\n'), ((10636, 10654), 'scipy.linalg.norm', 'spla.norm', (['b[:, i]'], {}), '(b[:, i])\n', (10645, 10654), True, 'import scipy.linalg as spla\n'), ((10786, 10804), 'scipy.linalg.norm', 'spla.norm', (['c[:, i]'], {}), '(c[:, i])\n', (10795, 10804), True, 'import scipy.linalg as spla\n'), ((9085, 9102), 'numpy.exp', 'np.exp', (['(-taui * s)'], {}), '(-taui * s)\n', (9091, 9102), True, 'import numpy as np\n'), ((9327, 9344), 'numpy.exp', 'np.exp', (['(-taui * s)'], {}), '(-taui * s)\n', (9333, 9344), True, 'import numpy as np\n')]
#!/usr/bin/env python import random import numpy as np import tensorflow as tf import cv2 import matplotlib.pyplot as plt seed = 0 random.seed(seed) np.random.seed(seed) tf.random.set_seed(seed) (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train[..., None] x_test = x_test[..., None] datagen = tf.keras.preprocessing.image.ImageDataGenerator( rotation_range=15, width_shift_range=0.1, height_shift_range=0.1, zoom_range=0.1) #validation_split=0.2 #flow = datagen.flow(x_train, y_train, batch_size=16, subset="training") #flow = datagen.flow(x_train, y_train, batch_size=16, subset="validation") flow = datagen.flow(x_train, y_train, batch_size=16) plt.figure(figsize=(19.2, 10.8)) for i in range(16): x, y = flow.next() for j in range(16): plt.subplot(16, 16, i*16+j+1) plt.imshow(x[j, ..., 0]) plt.xticks([]), plt.yticks([]), plt.title(y[j], x=-0.2, y=0.6) plt.show()
[ "matplotlib.pyplot.imshow", "tensorflow.random.set_seed", "matplotlib.pyplot.xticks", "tensorflow.keras.datasets.mnist.load_data", "tensorflow.keras.preprocessing.image.ImageDataGenerator", "random.seed", "matplotlib.pyplot.figure", "matplotlib.pyplot.yticks", "numpy.random.seed", "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show" ]
[((135, 152), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (146, 152), False, 'import random\n'), ((153, 173), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (167, 173), True, 'import numpy as np\n'), ((174, 198), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['seed'], {}), '(seed)\n', (192, 198), True, 'import tensorflow as tf\n'), ((239, 274), 'tensorflow.keras.datasets.mnist.load_data', 'tf.keras.datasets.mnist.load_data', ([], {}), '()\n', (272, 274), True, 'import tensorflow as tf\n'), ((342, 475), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'tf.keras.preprocessing.image.ImageDataGenerator', ([], {'rotation_range': '(15)', 'width_shift_range': '(0.1)', 'height_shift_range': '(0.1)', 'zoom_range': '(0.1)'}), '(rotation_range=15,\n width_shift_range=0.1, height_shift_range=0.1, zoom_range=0.1)\n', (389, 475), True, 'import tensorflow as tf\n'), ((718, 750), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(19.2, 10.8)'}), '(figsize=(19.2, 10.8))\n', (728, 750), True, 'import matplotlib.pyplot as plt\n'), ((960, 970), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (968, 970), True, 'import matplotlib.pyplot as plt\n'), ((826, 861), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(16)', '(16)', '(i * 16 + j + 1)'], {}), '(16, 16, i * 16 + j + 1)\n', (837, 861), True, 'import matplotlib.pyplot as plt\n'), ((864, 888), 'matplotlib.pyplot.imshow', 'plt.imshow', (['x[j, ..., 0]'], {}), '(x[j, ..., 0])\n', (874, 888), True, 'import matplotlib.pyplot as plt\n'), ((897, 911), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (907, 911), True, 'import matplotlib.pyplot as plt\n'), ((913, 927), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (923, 927), True, 'import matplotlib.pyplot as plt\n'), ((929, 959), 'matplotlib.pyplot.title', 'plt.title', (['y[j]'], {'x': '(-0.2)', 'y': '(0.6)'}), '(y[j], x=-0.2, y=0.6)\n', (938, 959), True, 'import matplotlib.pyplot as plt\n')]
import os, sys import numpy as np from sklearn.cluster import KMeans import matplotlib.pyplot as plt percentages = [0.01, 0.1, 0.2, 0.4, 0.5, 0.6] for percentage in percentages: data = [] save_path = '../logs/SOM_weights_MNIST_noise_{}.npy'.format(percentage) wts = np.load(save_path).reshape(-1, 784) print ("============{}============".format(wts.shape)) kmeans = KMeans(n_clusters=10).fit(wts) centers = kmeans.cluster_centers_ for i in range(2): for j in range(5): plt.subplot(2, 5, i*5 + j + 1) plt.imshow(centers[i*5+j].reshape(28, 28).T) if (i == 0) and (j == 0): plt.title("MNIST Noise {}".format(percentage)) plt.show()
[ "sklearn.cluster.KMeans", "numpy.load", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show" ]
[((647, 657), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (655, 657), True, 'import matplotlib.pyplot as plt\n'), ((272, 290), 'numpy.load', 'np.load', (['save_path'], {}), '(save_path)\n', (279, 290), True, 'import numpy as np\n'), ((374, 395), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(10)'}), '(n_clusters=10)\n', (380, 395), False, 'from sklearn.cluster import KMeans\n'), ((489, 521), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(5)', '(i * 5 + j + 1)'], {}), '(2, 5, i * 5 + j + 1)\n', (500, 521), True, 'import matplotlib.pyplot as plt\n')]
import matplotlib matplotlib.use('Agg') from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.pyplot import gcf from flask import Flask, render_template, request, flash, redirect import pandas as pd import librosa import ffmpeg import librosa.display import numpy as np import matplotlib.pyplot as plt import io import os import base64 from tensorflow.keras.models import Model, load_model from tensorflow.keras.layers import Flatten, Dense, Dropout from tensorflow.keras.optimizers import Adam from tensorflow.keras.applications import MobileNetV2 from keras.preprocessing.image import img_to_array from PIL import Image THIS_DIR = os.path.dirname(os.path.realpath(__file__)) BIRD_DATA = os.path.join(THIS_DIR, 'bird_data.xlsx') def fig2img(fig): ''' Transforms matplotlib figure to image ''' fig.canvas.draw() w,h = fig.canvas.get_width_height() buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8) buf.shape = (w,h,4) buf = np.roll(buf,3,axis = 2) w, h, d = buf.shape return Image.frombytes("RGB",(w,h),buf.tostring()) def create_spectrogram(file): ''' loads audio file and creates spectrogram ''' signal, sr = librosa.load(file,duration=10) fig = gcf() DPI = fig.get_dpi() fig = plt.figure() fig.set_size_inches(224/float(DPI),224/float(DPI)) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) S = librosa.feature.melspectrogram(y=signal,sr=sr, n_fft=1024, hop_length=1024, n_mels=128, htk=True, fmin=1400, fmax=sr/2) librosa.display.specshow(librosa.power_to_db(S**2,ref=np.max), fmin=1400,y_axis='linear') image = fig2img(fig) image = img_to_array(image) image = np.array([image]) return image, fig def predict(model, image): ''' makes prediction out of the spectrogram ''' net = MobileNetV2(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224,224,3)) x = net.output x = Flatten()(x) x = Dropout(0.5)(x) output_layer = Dense(5, activation='softmax')(x) loaded_model = Model(inputs=net.input, outputs=output_layer) loaded_model.load_weights(model) loaded_model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy']) pred = loaded_model.predict(image) return pred def get_bird_data(bird): df = pd.read_excel(BIRD_DATA) df = df[df['species']==bird].reset_index(drop=True) name = df['name'][0] en_name = df['en_name'][0] desc = df['desc'][0] return name, en_name, desc def create_bird_path(bird): img_path = '/static/images/' bird = bird.lower() img_file = bird + '.jpg' bird_path = img_path + img_file return bird_path def create_result(pred, classes): ''' creates results (bird class and probability) ''' top = np.argsort(pred[0])[:-2:-1] result = {'bird': '', 'probability': ''} result['bird'] = classes[top[0]] result['probability'] = int(round(pred[0][top[0]],2)*100) return result
[ "keras.preprocessing.image.img_to_array", "numpy.argsort", "numpy.array", "tensorflow.keras.layers.Dense", "pandas.read_excel", "librosa.load", "tensorflow.keras.models.Model", "tensorflow.keras.applications.MobileNetV2", "matplotlib.use", "matplotlib.pyplot.gcf", "tensorflow.keras.layers.Dropout", "librosa.power_to_db", "tensorflow.keras.layers.Flatten", "librosa.feature.melspectrogram", "numpy.roll", "matplotlib.pyplot.Axes", "os.path.join", "os.path.realpath", "tensorflow.keras.optimizers.Adam", "matplotlib.pyplot.figure" ]
[((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((767, 807), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""bird_data.xlsx"""'], {}), "(THIS_DIR, 'bird_data.xlsx')\n", (779, 807), False, 'import os\n'), ((727, 753), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (743, 753), False, 'import os\n'), ((1043, 1066), 'numpy.roll', 'np.roll', (['buf', '(3)'], {'axis': '(2)'}), '(buf, 3, axis=2)\n', (1050, 1066), True, 'import numpy as np\n'), ((1247, 1278), 'librosa.load', 'librosa.load', (['file'], {'duration': '(10)'}), '(file, duration=10)\n', (1259, 1278), False, 'import librosa\n'), ((1291, 1296), 'matplotlib.pyplot.gcf', 'gcf', ([], {}), '()\n', (1294, 1296), False, 'from matplotlib.pyplot import gcf\n'), ((1331, 1343), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1341, 1343), True, 'import matplotlib.pyplot as plt\n'), ((1413, 1448), 'matplotlib.pyplot.Axes', 'plt.Axes', (['fig', '[0.0, 0.0, 1.0, 1.0]'], {}), '(fig, [0.0, 0.0, 1.0, 1.0])\n', (1421, 1448), True, 'import matplotlib.pyplot as plt\n'), ((1497, 1623), 'librosa.feature.melspectrogram', 'librosa.feature.melspectrogram', ([], {'y': 'signal', 'sr': 'sr', 'n_fft': '(1024)', 'hop_length': '(1024)', 'n_mels': '(128)', 'htk': '(True)', 'fmin': '(1400)', 'fmax': '(sr / 2)'}), '(y=signal, sr=sr, n_fft=1024, hop_length=1024,\n n_mels=128, htk=True, fmin=1400, fmax=sr / 2)\n', (1527, 1623), False, 'import librosa\n'), ((2022, 2041), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['image'], {}), '(image)\n', (2034, 2041), False, 'from keras.preprocessing.image import img_to_array\n'), ((2054, 2071), 'numpy.array', 'np.array', (['[image]'], {}), '([image])\n', (2062, 2071), True, 'import numpy as np\n'), ((2185, 2285), 'tensorflow.keras.applications.MobileNetV2', 'MobileNetV2', ([], {'include_top': '(False)', 'weights': '"""imagenet"""', 'input_tensor': 'None', 'input_shape': '(224, 224, 3)'}), "(include_top=False, weights='imagenet', input_tensor=None,\n input_shape=(224, 224, 3))\n", (2196, 2285), False, 'from tensorflow.keras.applications import MobileNetV2\n'), ((2500, 2545), 'tensorflow.keras.models.Model', 'Model', ([], {'inputs': 'net.input', 'outputs': 'output_layer'}), '(inputs=net.input, outputs=output_layer)\n', (2505, 2545), False, 'from tensorflow.keras.models import Model, load_model\n'), ((2793, 2817), 'pandas.read_excel', 'pd.read_excel', (['BIRD_DATA'], {}), '(BIRD_DATA)\n', (2806, 2817), True, 'import pandas as pd\n'), ((1915, 1954), 'librosa.power_to_db', 'librosa.power_to_db', (['(S ** 2)'], {'ref': 'np.max'}), '(S ** 2, ref=np.max)\n', (1934, 1954), False, 'import librosa\n'), ((2391, 2400), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (2398, 2400), False, 'from tensorflow.keras.layers import Flatten, Dense, Dropout\n'), ((2412, 2424), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (2419, 2424), False, 'from tensorflow.keras.layers import Flatten, Dense, Dropout\n'), ((2447, 2477), 'tensorflow.keras.layers.Dense', 'Dense', (['(5)'], {'activation': '"""softmax"""'}), "(5, activation='softmax')\n", (2452, 2477), False, 'from tensorflow.keras.layers import Flatten, Dense, Dropout\n'), ((3263, 3282), 'numpy.argsort', 'np.argsort', (['pred[0]'], {}), '(pred[0])\n', (3273, 3282), True, 'import numpy as np\n'), ((2618, 2624), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {}), '()\n', (2622, 2624), False, 'from tensorflow.keras.optimizers import Adam\n')]
import os from pathlib import Path import cv2 import numpy as np import pandas as pd from pandas import DataFrame from sklearn.model_selection import train_test_split def create_info_csv(mvtec_dir: Path) -> DataFrame: df = pd.DataFrame({}) for data_type in ["train", "test"]: for p in mvtec_dir.glob(f"*/{data_type}/*/*.png"): raw_stem = p.stem defect = p.parents[0].name data_type = p.parents[1].name category = p.parents[2].name df = df.append( { "raw_img_path": str(p), "raw_stem": raw_stem, "defect": defect, "data_type": data_type, "category": category, }, ignore_index=True, ) for category in df["category"].unique(): category_df = df.query("data_type=='train' & category==@category") _, val_index = train_test_split( category_df.index.tolist(), train_size=0.8, test_size=0.2, random_state=5, shuffle=True, ) df.loc[val_index, "data_type"] = "val" df["stem"] = df.apply( lambda x: f"{x.category}_{x.data_type}_{x.defect}_{x.raw_stem}", axis=1, ) df["raw_mask_path"] = df.apply( lambda x: f"{mvtec_dir}/{x.category}/ground_truth/{x.defect}/{x.raw_stem}_mask.png", axis=1, ) return df def move_images_and_masks(df: DataFrame) -> None: os.makedirs("/data/images", exist_ok=True) os.makedirs("/data/masks", exist_ok=True) for i in df.index: raw_img_path, raw_mask_path, stem = df.loc[i, ["raw_img_path", "raw_mask_path", "stem"]] if os.path.exists(raw_mask_path): os.rename(raw_mask_path, f"/data/masks/{stem}.png") else: # create masks for train images img = cv2.imread(raw_img_path) mask = np.zeros(img.shape) cv2.imwrite(f"/data/masks/{stem}.png", mask) os.rename(raw_img_path, f"/data/images/{stem}.png") df.drop(columns=["raw_stem", "raw_img_path", "raw_mask_path"]) df.to_csv("/data/info.csv", index=False) if __name__ == "__main__": mvtec_dir = Path("/data/MVTec") df = create_info_csv(mvtec_dir) move_images_and_masks(df)
[ "os.path.exists", "cv2.imwrite", "os.makedirs", "pathlib.Path", "os.rename", "numpy.zeros", "pandas.DataFrame", "cv2.imread" ]
[((231, 247), 'pandas.DataFrame', 'pd.DataFrame', (['{}'], {}), '({})\n', (243, 247), True, 'import pandas as pd\n'), ((1542, 1584), 'os.makedirs', 'os.makedirs', (['"""/data/images"""'], {'exist_ok': '(True)'}), "('/data/images', exist_ok=True)\n", (1553, 1584), False, 'import os\n'), ((1589, 1630), 'os.makedirs', 'os.makedirs', (['"""/data/masks"""'], {'exist_ok': '(True)'}), "('/data/masks', exist_ok=True)\n", (1600, 1630), False, 'import os\n'), ((2276, 2295), 'pathlib.Path', 'Path', (['"""/data/MVTec"""'], {}), "('/data/MVTec')\n", (2280, 2295), False, 'from pathlib import Path\n'), ((1764, 1793), 'os.path.exists', 'os.path.exists', (['raw_mask_path'], {}), '(raw_mask_path)\n', (1778, 1793), False, 'import os\n'), ((2065, 2116), 'os.rename', 'os.rename', (['raw_img_path', 'f"""/data/images/{stem}.png"""'], {}), "(raw_img_path, f'/data/images/{stem}.png')\n", (2074, 2116), False, 'import os\n'), ((1807, 1858), 'os.rename', 'os.rename', (['raw_mask_path', 'f"""/data/masks/{stem}.png"""'], {}), "(raw_mask_path, f'/data/masks/{stem}.png')\n", (1816, 1858), False, 'import os\n'), ((1935, 1959), 'cv2.imread', 'cv2.imread', (['raw_img_path'], {}), '(raw_img_path)\n', (1945, 1959), False, 'import cv2\n'), ((1979, 1998), 'numpy.zeros', 'np.zeros', (['img.shape'], {}), '(img.shape)\n', (1987, 1998), True, 'import numpy as np\n'), ((2011, 2055), 'cv2.imwrite', 'cv2.imwrite', (['f"""/data/masks/{stem}.png"""', 'mask'], {}), "(f'/data/masks/{stem}.png', mask)\n", (2022, 2055), False, 'import cv2\n')]
import tensorflow as tf # numpy 是个科学计算的工具包,这里通过Numpy生成模拟数据 from numpy.random import RandomState # 训练数据batch的大小 batch_size = 8 # 定义神经网络的参数,这里还是沿用3.4.2 小结中给出的神经网络结构 w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) # 在shape的维度上使用None可以方便使用不打的batch大小,在训练时需要把数据 # 分成比较小的batch,但是在测试时,可以一次性使用全部数据,当数据集比较小时这样比较 # 方便测试,但是数据集比较大时放入一个batch会导致内存溢出 x = tf.placeholder(tf.float32, shape=(None, 2), name="x-input") y_ = tf.placeholder(tf.float32, shape=(None, 1), name='y-input') # 定义神经网络向前传播的过程 x w1 w2 两层神经 a = tf.matmul(x, w1) y = tf.matmul(a, w2) # 定义损失函数和反向传播的算法 # tf.clip_by_value 因为 log 会产生 none (如 log-3 ), 用它来限定不出现none # 替代方法 cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv + 1e-10)) cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0))) train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy) # 通过随机数生成一个模拟数据集 rdm = RandomState(1) X = rdm.rand(128, 2) # Y 为对数据集数据 进行 结果收集分类 和大于1 为1 小于 1为0 # 定义规则来给样本的标签。在这里所有x1 + x2 < 1 的样本都被认为是正样本(比如零件合格) # 而其他为负样本(比如样本不合格)。和TensorFlow 游乐场中的表示法不大一样的地方是, # 这里的0表示负样本,1 表示正样本。大部分解决分类问题的神经网络都采用 # 0 和 1 的表示方法 Y = [[int(x1 + x2) < 1] for (x1, x2) in X] # 创建一个会话运行TensorFlow程序 with tf.Session() as sess: # 初始化变量 init_op = tf.global_variables_initializer() sess.run(init_op) # 在训练之前神经网络参数 print("w1:", sess.run(w1)) print("w2:", sess.run(w2)) print("\n") ''' 训练之前神经网络参数的值 w1: [[-0.81131822 1.48459876 0.06532937] [-2.44270396 0.0992484 0.59122431]] w2: [[-0.81131822] [ 1.48459876] [ 0.06532937]] ''' # 设定训练的轮数 STEPS = 5000 for i in range(STEPS): start = (i * batch_size) % 128 end = (i * batch_size) % 128 + batch_size # 通过选取样本训练神经网络并更新参数 sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]}) if i % 1000 == 0: # 每隔一段时间计算在所有数据上的交叉熵并输出 total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_: Y}) print("After %d training steps(s), cross entropy on all data is %g" % (i, total_cross_entropy)) ''' 输出结果 After 0 training steps(s), cross entropy on all data is 0.0674925 After 1000 training steps(s), cross entropy on all data is 0.0163385 After 2000 training steps(s), cross entropy on all data is 0.00907547 After 3000 training steps(s), cross entropy on all data is 0.00714436 After 4000 training steps(s), cross entropy on all data is 0.00578471 通过这个结果可以发现随着训练的进行,交叉熵是逐渐减小的。交叉熵越小说明预测的结果和真实的结果差距越小 ''' print("\n") print("w1:", sess.run(w1)) print("w2:", sess.run(w2)) ''' w1: [[-1.9618274 2.58235407 1.68203783] [-3.4681716 1.06982327 2.11788988]] w2: [[-1.8247149 ] [ 2.68546653] [ 1.41819501]] 可以发现这两个参数的取值已经发生了编发,这个变化是训练的结果 它使得这个神经网络能根号的拟合提供的训练数据 ''' ''' 1、定义神经网络的结构和前向传播的输出结果 2、定义损失函数以及选择反向传播的优化算法 3、生成会话(tf.Session)并且在训练数据上反复运行反向传播优化算法 '''
[ "tensorflow.random_normal", "tensorflow.Session", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.matmul", "tensorflow.clip_by_value", "tensorflow.train.AdamOptimizer", "numpy.random.RandomState" ]
[((416, 475), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, 2)', 'name': '"""x-input"""'}), "(tf.float32, shape=(None, 2), name='x-input')\n", (430, 475), True, 'import tensorflow as tf\n'), ((481, 540), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, 1)', 'name': '"""y-input"""'}), "(tf.float32, shape=(None, 1), name='y-input')\n", (495, 540), True, 'import tensorflow as tf\n'), ((577, 593), 'tensorflow.matmul', 'tf.matmul', (['x', 'w1'], {}), '(x, w1)\n', (586, 593), True, 'import tensorflow as tf\n'), ((598, 614), 'tensorflow.matmul', 'tf.matmul', (['a', 'w2'], {}), '(a, w2)\n', (607, 614), True, 'import tensorflow as tf\n'), ((927, 941), 'numpy.random.RandomState', 'RandomState', (['(1)'], {}), '(1)\n', (938, 941), False, 'from numpy.random import RandomState\n'), ((182, 224), 'tensorflow.random_normal', 'tf.random_normal', (['[2, 3]'], {'stddev': '(1)', 'seed': '(1)'}), '([2, 3], stddev=1, seed=1)\n', (198, 224), True, 'import tensorflow as tf\n'), ((243, 285), 'tensorflow.random_normal', 'tf.random_normal', (['[3, 1]'], {'stddev': '(1)', 'seed': '(1)'}), '([3, 1], stddev=1, seed=1)\n', (259, 285), True, 'import tensorflow as tf\n'), ((1225, 1237), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1235, 1237), True, 'import tensorflow as tf\n'), ((1273, 1306), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1304, 1306), True, 'import tensorflow as tf\n'), ((849, 878), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['(0.001)'], {}), '(0.001)\n', (871, 878), True, 'import tensorflow as tf\n'), ((802, 833), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['y', '(1e-10)', '(1.0)'], {}), '(y, 1e-10, 1.0)\n', (818, 833), True, 'import tensorflow as tf\n')]
"""Retokenization helpers This module provides helpers for projecting span annotations from one tokenization to another. Notes: * Code is ported from https://github.com/nyu-mll/jiant/blob/master/jiant/utils/retokenize.py * Please keep this code as a standalone utility; don't make this module depend on jiant modules. """ from typing import Iterable, Sequence, Tuple, Union from Levenshtein.StringMatcher import StringMatcher from nltk.tokenize.util import string_span_tokenize import numpy as np _DTYPE = np.int32 def _mat_from_blocks_dense(mb, n_chars_src, n_chars_tgt): M = np.zeros((n_chars_src, n_chars_tgt), dtype=_DTYPE) for i in range(len(mb)): b = mb[i] # current block # Fill in-between this block and last block if i > 0: lb = mb[i - 1] # last block s0 = lb[0] + lb[2] # top e0 = b[0] # bottom s1 = lb[1] + lb[2] # left e1 = b[1] # right M[s0:e0, s1:e1] = 1 # Fill matching region on diagonal M[b[0]: b[0] + b[2], b[1]: b[1] + b[2]] = 2 * \ np.identity(b[2], dtype=_DTYPE) return M def _mat_from_spans_dense(spans: Sequence[Tuple[int, int]], n_chars: int) -> np.ndarray: """Construct a token-to-char matrix from a list of char spans.""" M = np.zeros((len(spans), n_chars), dtype=_DTYPE) for i, s in enumerate(spans): M[i, s[0]: s[1]] = 1 return M def token_to_char(text: str, sep=" ") -> np.ndarray: """Takes a string, space tokenizes the string, and returns a mapping from tokens to chars. Examples: >>> token_to_char("testing 1, 2, 3") # produces a (m) token by (M) char matrix: t e s t i n g 1 , 2 , 3 testing [[1 1 1 1 1 1 1 0 0 0 0 0 0 0 0] 1, [0 0 0 0 0 0 0 0 1 1 0 0 0 0 0] 2, [0 0 0 0 0 0 0 0 0 0 0 1 1 0 0] 3 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]] Args: text (str): string to tokenize and build the token to char mapping. Returns: np.ndarray mapping from (m) tokens to (M) chars. """ spans = string_span_tokenize(text, sep=sep) return _mat_from_spans_dense(tuple(spans), len(text)) def _mat_from_blocks( mb: Sequence[Tuple[int, int, int]], n_chars_src: int, n_chars_tgt: int ) -> np.ndarray: """Construct a char-to-char matrix from a list of matching blocks. mb is a sequence of (s1, s2, n_char) tuples, where s1 and s2 are the start indices in the first and second sequence, and n_char is the length of the block. Args: mb: list of triples of non-overlapping matching subsequences in source str and target. n_chars_src (int): number of chars in the source string. n_chars_tgt (int): number of chars in the target string. Returns: np.ndarray adjacency matrix mapping chars in the source str to chars in the target str. """ return _mat_from_blocks_dense(mb, n_chars_src, n_chars_tgt) def char_to_char(source: str, target: str) -> np.ndarray: """Find the character adjacency matrix mapping source string chars to target string chars. Uses StringMatcher from Levenshtein package to find non-overlapping matching subsequences in input strings. Uses the result to create a character adjacency matrix from source to target. (https://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher.get_matching_blocks) Args: source (str): string of source chars. target (str): string of target chars. Returns: np.ndarray adjacency matrix mapping chars in the source str to chars in the target str. """ sm = StringMatcher(seq1=source, seq2=target) mb = sm.get_matching_blocks() return _mat_from_blocks(mb, len(source), len(target)) class TokenAligner(object): """Align two similiar tokenizations. Args: source (Union[Iterable[str], str]): Source text tokens or string. target (Union[Iterable[str], str]): Target text tokens or string. Usage: ta = TokenAligner(source_tokens, target_tokens) target_span = ta.project_span(*source_span) Uses Levenshtein distance to align two similar tokenizations, and provide facilities to project indices and spans from the source tokenization to the target. Let source contain m tokens and M chars, and target contain n tokens and N chars. The token alignment is treated as a (sparse) m x n adjacency matrix T representing the bipartite graph between the source and target tokens. This is constructed by performing a character-level alignment using Levenshtein distance to obtain a (M x N) character adjacency matrix C. We then construct token-to-character matricies U (m x M) and V (n x N) and construct T as: T = (U C V') where V' denotes the transpose. Spans of non-aligned bytes are assumed to contain a many-to-many alignment of all chars in that range. This can lead to unwanted alignments if, for example, two consecutive tokens are mapped to escape sequences: source: ["'s", "["] target: ["&apos;", "s", "&#91;"] In the above case, "'s'" may be spuriously aligned to "&apos;" while "[" has no character match with "s" or "&#91;", and so is aligned to both. To make a correct alignment more likely, ensure that the characters in target correspond as closely as possible to those in source. For example, the following will align correctly: source: ["'s", "["] target: ["'", "s", "["] """ def __init__(self, source: Union[Iterable[str], str], target: Union[Iterable[str], str]): # Coerce source and target to space-delimited string. if not isinstance(source, str): source = " ".join(source) if not isinstance(target, str): target = " ".join(target) # (m X M) source token idx to source char idx self.U = token_to_char(source) # (n x N) target token idx to target char idx self.V = token_to_char(target) # (M x N) source char idx to target char idx self.C = char_to_char(source, target) # Token transfer matrix from (m) tokens in source to (n) tokens in the target. Mat value at # index i, j measures the character overlap btwn the ith source token and jth target token. self.source_token_idx_to_target_token_idx = self.U.dot( self.C).dot(self.V.T) self.source_token_idx_to_target_char_idx = self.U.dot(self.C) self.source_char_idx_to_target_token_idx = self.C.dot(self.V.T) def project_token_idxs(self, idxs: Union[int, Sequence[int]]) -> Sequence[int]: """Project source token index(s) to target token indices. Takes a list of token indices in the source token sequence, and returns the corresponding tokens in the target sequence. Args: idxs (Union[int, Sequence[int]]): source token index(s) to get related target indices. Examples: >>> source_tokens = ['abc', 'def', 'ghi', 'jkl'] >>> target_tokens = ['abc', 'd', 'ef', 'ghi', 'jkl'] >>> ta = TokenAligner(source_tokens, target_tokens) >>> print(ta.project_token_idxs([1, 2])) [1 2 3] Returns: List[int] representing the target indices associated with the provided source indices. """ if isinstance(idxs, int): idxs = [idxs] # column indices return self.source_token_idx_to_target_token_idx[idxs].nonzero()[1] @staticmethod def _project_span(mat, start, end, inclusive): if inclusive: end = end + 1 target_matches = mat[start:end].nonzero()[1].tolist() if len(target_matches) == 0: raise ValueError( f"Project {(start, end)} into empty span in target sequence") output_start, output_end = min(target_matches), max(target_matches) if not inclusive: output_end = output_end + 1 return (output_start, output_end) def project_token_span(self, start, end, inclusive=False) -> Tuple[int, int]: """Project a span from source to target token sequence. Notes: When param inclusive=False, the end index is interpreted as exclusive, and the end of the span returned by the function will also be exclusive. When param inclusive=True, both start and end indexes are interpreted as inclusive, and the span returned by the function will also be inclusive. Examples: >>> source_tokens = ['abc', 'def', 'ghi', 'jkl'] >>> target_tokens = ['abc', 'd', 'ef', 'ghi', 'jkl'] >>> ta = TokenAligner(source_tokens, target_tokens) >>> start, end = 0, 2 >>> print(ta.project_token_span(start, end)) (0, 3) Raise: When target span is empty Returns: Tuple[int, int] representing the target span corresponding to the source span. """ return self._project_span( mat=self.source_token_idx_to_target_token_idx, start=start, end=end, inclusive=inclusive ) def project_token_to_char_span(self, start, end, inclusive=False) -> Tuple[int, int]: """Project a span from source to target token sequence. Notes: When param inclusive=False, the end index is interpreted as exclusive, and the end of the span returned by the function will also be exclusive. When param inclusive=True, both start and end indexes are interpreted as inclusive, and the span returned by the function will also be inclusive. Examples: >>> source_tokens = ['abc', 'def', 'ghi', 'jkl'] >>> target_str = 'abc d ef ghi jkl' >>> ta = TokenAligner(source_tokens, target_str) >>> start, end = 0, 2 >>> print(ta.project_token_to_char_span(start, end)) (0, 8) Raise: When target span is empty Returns: Tuple[int, int] representing the target span corresponding to the source span. """ return self._project_span( mat=self.source_token_idx_to_target_char_idx, start=start, end=end, inclusive=inclusive ) def project_char_to_token_span(self, start, end, inclusive=False) -> Tuple[int, int]: """Project a span from source to target token sequence. Notes: When param inclusive=False, the end index is interpreted as exclusive, and the end of the span returned by the function will also be exclusive. When param inclusive=True, both start and end indexes are interpreted as inclusive, and the span returned by the function will also be inclusive. Examples: >>> source_str = 'abc def ghi jkl' >>> target_tokens = ['abc', 'd', 'ef', 'ghi', 'jkl'] >>> ta = TokenAligner(source_str, target_tokens) >>> start, end = 0, 4 >>> print(ta.project_char_to_token_span(start, end)) (0, 1) Raise: When target span is empty Returns: Tuple[int, int] representing the target span corresponding to the source span. """ return self._project_span( mat=self.source_char_idx_to_target_token_idx, start=start, end=end, inclusive=inclusive )
[ "numpy.identity", "numpy.zeros", "Levenshtein.StringMatcher.StringMatcher", "nltk.tokenize.util.string_span_tokenize" ]
[((597, 647), 'numpy.zeros', 'np.zeros', (['(n_chars_src, n_chars_tgt)'], {'dtype': '_DTYPE'}), '((n_chars_src, n_chars_tgt), dtype=_DTYPE)\n', (605, 647), True, 'import numpy as np\n'), ((2133, 2168), 'nltk.tokenize.util.string_span_tokenize', 'string_span_tokenize', (['text'], {'sep': 'sep'}), '(text, sep=sep)\n', (2153, 2168), False, 'from nltk.tokenize.util import string_span_tokenize\n'), ((3676, 3715), 'Levenshtein.StringMatcher.StringMatcher', 'StringMatcher', ([], {'seq1': 'source', 'seq2': 'target'}), '(seq1=source, seq2=target)\n', (3689, 3715), False, 'from Levenshtein.StringMatcher import StringMatcher\n'), ((1106, 1137), 'numpy.identity', 'np.identity', (['b[2]'], {'dtype': '_DTYPE'}), '(b[2], dtype=_DTYPE)\n', (1117, 1137), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ :math:`IC_TC_P` Colour Encoding =============================== Defines the :math:`IC_TC_P` colour encoding related transformations: - :func:`colour.RGB_to_ICtCp` - :func:`colour.ICtCp_to_RGB` - :func:`colour.XYZ_to_ICtCp` - :func:`colour.ICtCp_to_XYZ` References ---------- - :cite:`Dolby2016a` : Dolby. (2016). WHAT IS ICtCp? - INTRODUCTION. https://www.dolby.com/us/en/technologies/dolby-vision/ICtCp-white-paper.pdf - :cite:`InternationalTelecommunicationUnion2018` : International Telecommunication Union. (2018). Recommendation ITU-R BT.2100-2 - Image parameter values for high dynamic range television for use in production and international programme exchange. https://www.itu.int/dms_pubrec/itu-r/rec/bt/\ R-REC-BT.2100-2-201807-I!!PDF-E.pdf - :cite:`Lu2016c` : <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., Pytlarz, J., <NAME>., <NAME>., & <NAME>. (2016). ITP Colour Space and Its Compression Performance for High Dynamic Range and Wide Colour Gamut Video Distribution. ZTE Communications, 14(1), 32-38. """ import numpy as np from colour.algebra import vector_dot from colour.colorimetry import CCS_ILLUMINANTS from colour.models.rgb import RGB_COLOURSPACES, RGB_to_XYZ, XYZ_to_RGB from colour.models.rgb.transfer_functions import ( eotf_ST2084, eotf_inverse_ST2084, oetf_HLG_BT2100, oetf_inverse_HLG_BT2100) from colour.utilities import (domain_range_scale, from_range_1, to_domain_1, validate_method) __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2013-2021 - Colour Developers' __license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = '<EMAIL>' __status__ = 'Production' __all__ = [ 'MATRIX_ICTCP_RGB_TO_LMS', 'MATRIX_ICTCP_LMS_TO_RGB', 'MATRIX_ICTCP_LMS_P_TO_ICTCP', 'MATRIX_ICTCP_ICTCP_TO_LMS_P', 'MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2', 'MATRIX_ICTCP_ICTCP_TO_LMS_P_HLG_BT2100_2', 'RGB_to_ICtCp', 'ICtCp_to_RGB', 'XYZ_to_ICtCp', 'ICtCp_to_XYZ' ] MATRIX_ICTCP_RGB_TO_LMS = np.array([ [1688, 2146, 262], [683, 2951, 462], [99, 309, 3688], ]) / 4096 """ *ITU-R BT.2020* colourspace to normalised cone responses matrix. MATRIX_ICTCP_RGB_TO_LMS : array_like, (3, 3) """ MATRIX_ICTCP_LMS_TO_RGB = np.linalg.inv(MATRIX_ICTCP_RGB_TO_LMS) """ :math:`IC_TC_P` colourspace normalised cone responses to *ITU-R BT.2020* colourspace matrix. MATRIX_ICTCP_LMS_TO_RGB : array_like, (3, 3) """ MATRIX_ICTCP_LMS_P_TO_ICTCP = np.array([ [2048, 2048, 0], [6610, -13613, 7003], [17933, -17390, -543], ]) / 4096 """ :math:`LMS_p` *SMPTE ST 2084:2014* encoded normalised cone responses to :math:`IC_TC_P` colour encoding matrix. MATRIX_ICTCP_LMS_P_TO_ICTCP : array_like, (3, 3) """ MATRIX_ICTCP_ICTCP_TO_LMS_P = np.linalg.inv(MATRIX_ICTCP_LMS_P_TO_ICTCP) """ :math:`IC_TC_P` colour encoding to :math:`LMS_p` *SMPTE ST 2084:2014* encoded normalised cone responses matrix. MATRIX_ICTCP_ICTCP_TO_LMS_P : array_like, (3, 3) """ MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2 = np.array([ [2048, 2048, 0], [3625, -7465, 3840], [9500, -9212, -288], ]) / 4096 """ :math:`LMS_p` *SMPTE ST 2084:2014* encoded normalised cone responses to :math:`IC_TC_P` colour encoding matrix as given in *ITU-R BT.2100-2*. MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2 : array_like, (3, 3) """ MATRIX_ICTCP_ICTCP_TO_LMS_P_HLG_BT2100_2 = np.linalg.inv( MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2) """ :math:`IC_TC_P` colour encoding to :math:`LMS_p` *SMPTE ST 2084:2014* encoded normalised cone responses matrix as given in *ITU-R BT.2100-2*. MATRIX_ICTCP_ICTCP_TO_LMS_P_HLG_BT2100_2 : array_like, (3, 3) """ def RGB_to_ICtCp(RGB, method='Dolby 2016', L_p=10000): """ Converts from *ITU-R BT.2020* colourspace to :math:`IC_TC_P` colour encoding. Parameters ---------- RGB : array_like *ITU-R BT.2020* colourspace array. method : unicode, optional **{'Dolby 2016', 'ITU-R BT.2100-1 HLG', 'ITU-R BT.2100-1 PQ', 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ'}**, Computation method. *Recommendation ITU-R BT.2100* defines multiple variants of the :math:`IC_TC_P` colour encoding: - *ITU-R BT.2100-1* - *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *Dolby 2016*, *ITU-R BT.2100-1 PQ*, *ITU-R BT.2100-2 PQ* methods. - *Recommendation ITU-R BT.2100* *Reference HLG* opto-electrical transfer function (OETF / OECF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *ITU-R BT.2100-1 HLG* method. - *ITU-R BT.2100-2* - *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *Dolby 2016*, *ITU-R BT.2100-1 PQ*, *ITU-R BT.2100-2 PQ* methods. - *Recommendation ITU-R BT.2100* *Reference HLG* opto-electrical transfer function (OETF / OECF) and a custom :math:`IC_TC_P` matrix from :cite:`InternationalTelecommunicationUnion2018`: *ITU-R BT.2100-2 HLG* method. L_p : numeric, optional Display peak luminance :math:`cd/m^2` for *SMPTE ST 2084:2014* non-linear encoding. This parameter should stay at its default :math:`10000 cd/m^2` value for practical applications. It is exposed so that the definition can be used as a fitting function. Returns ------- ndarray :math:`IC_TC_P` colour encoding array. Warnings -------- The underlying *SMPTE ST 2084:2014* transfer function is an absolute transfer function. Notes ----- - The *ITU-R BT.2100-1 PQ* and *ITU-R BT.2100-2 PQ* methods are aliases for the *Dolby 2016* method. - The underlying *SMPTE ST 2084:2014* transfer function is an absolute transfer function, thus the domain and range values for the *Reference* and *1* scales are only indicative that the data is not affected by scale transformations. The effective domain of *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) is [0.0001, 10000]. +------------+-----------------------+------------------+ | **Domain** | **Scale - Reference** | **Scale - 1** | +============+=======================+==================+ | ``RGB`` | ``UN`` | ``UN`` | +------------+-----------------------+------------------+ +------------+-----------------------+------------------+ | **Range** | **Scale - Reference** | **Scale - 1** | +============+=======================+==================+ | ``ICtCp`` | ``I`` : [0, 1] | ``I`` : [0, 1] | | | | | | | ``CT`` : [-1, 1] | ``CT`` : [-1, 1] | | | | | | | ``CP`` : [-1, 1] | ``CP`` : [-1, 1] | +------------+-----------------------+------------------+ References ---------- :cite:`Dolby2016a`, :cite:`Lu2016c` Examples -------- >>> RGB = np.array([0.45620519, 0.03081071, 0.04091952]) >>> RGB_to_ICtCp(RGB) # doctest: +ELLIPSIS array([ 0.0735136..., 0.0047525..., 0.0935159...]) >>> RGB_to_ICtCp(RGB, method='ITU-R BT.2100-2 HLG') # doctest: +ELLIPSIS array([ 0.6256789..., -0.0198449..., 0.3591125...]) """ RGB = to_domain_1(RGB) method = validate_method(method, [ 'Dolby 2016', 'ITU-R BT.2100-1 HLG', 'ITU-R BT.2100-1 PQ', 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ' ]) is_hlg_method = 'hlg' in method is_BT2100_2_method = '2100-2' in method LMS = vector_dot(MATRIX_ICTCP_RGB_TO_LMS, RGB) with domain_range_scale('ignore'): LMS_p = (oetf_HLG_BT2100(LMS) if is_hlg_method else eotf_inverse_ST2084(LMS, L_p)) ICtCp = (vector_dot(MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2, LMS_p) if (is_hlg_method and is_BT2100_2_method) else vector_dot( MATRIX_ICTCP_LMS_P_TO_ICTCP, LMS_p)) return from_range_1(ICtCp) def ICtCp_to_RGB(ICtCp, method='Dolby 2016', L_p=10000): """ Converts from :math:`IC_TC_P` colour encoding to *ITU-R BT.2020* colourspace. Parameters ---------- ICtCp : array_like :math:`IC_TC_P` colour encoding array. method : unicode, optional **{'Dolby 2016', 'ITU-R BT.2100-1 HLG', 'ITU-R BT.2100-1 PQ', 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ'}**, Computation method. *Recommendation ITU-R BT.2100* defines multiple variants of the :math:`IC_TC_P` colour encoding: - *ITU-R BT.2100-1* - *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *Dolby 2016*, *ITU-R BT.2100-1 PQ*, *ITU-R BT.2100-2 PQ* methods. - *Recommendation ITU-R BT.2100* *Reference HLG* opto-electrical transfer function (OETF / OECF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *ITU-R BT.2100-1 HLG* method. - *ITU-R BT.2100-2* - *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *Dolby 2016*, *ITU-R BT.2100-1 PQ*, *ITU-R BT.2100-2 PQ* methods. - *Recommendation ITU-R BT.2100* *Reference HLG* opto-electrical transfer function (OETF / OECF) and a custom :math:`IC_TC_P` matrix from :cite:`InternationalTelecommunicationUnion2018`: *ITU-R BT.2100-2 HLG* method. L_p : numeric, optional Display peak luminance :math:`cd/m^2` for *SMPTE ST 2084:2014* non-linear encoding. This parameter should stay at its default :math:`10000 cd/m^2` value for practical applications. It is exposed so that the definition can be used as a fitting function. Returns ------- ndarray *ITU-R BT.2020* colourspace array. Warnings -------- The underlying *SMPTE ST 2084:2014* transfer function is an absolute transfer function. Notes ----- - The *ITU-R BT.2100-1 PQ* and *ITU-R BT.2100-2 PQ* methods are aliases for the *Dolby 2016* method. - The underlying *SMPTE ST 2084:2014* transfer function is an absolute transfer function, thus the domain and range values for the *Reference* and *1* scales are only indicative that the data is not affected by scale transformations. +------------+-----------------------+------------------+ | **Domain** | **Scale - Reference** | **Scale - 1** | +============+=======================+==================+ | ``ICtCp`` | ``I`` : [0, 1] | ``I`` : [0, 1] | | | | | | | ``CT`` : [-1, 1] | ``CT`` : [-1, 1] | | | | | | | ``CP`` : [-1, 1] | ``CP`` : [-1, 1] | +------------+-----------------------+------------------+ +------------+-----------------------+------------------+ | **Range** | **Scale - Reference** | **Scale - 1** | +============+=======================+==================+ | ``RGB`` | ``UN`` | ``UN`` | +------------+-----------------------+------------------+ References ---------- :cite:`Dolby2016a`, :cite:`Lu2016c` Examples -------- >>> ICtCp = np.array([0.07351364, 0.00475253, 0.09351596]) >>> ICtCp_to_RGB(ICtCp) # doctest: +ELLIPSIS array([ 0.4562052..., 0.0308107..., 0.0409195...]) >>> ICtCp = np.array([0.62567899, -0.01984490, 0.35911259]) >>> ICtCp_to_RGB(ICtCp, method='ITU-R BT.2100-2 HLG') # doctest: +ELLIPSIS array([ 0.4562052..., 0.0308107..., 0.0409195...]) """ ICtCp = to_domain_1(ICtCp) method = validate_method(method, [ 'Dolby 2016', 'ITU-R BT.2100-1 HLG', 'ITU-R BT.2100-1 PQ', 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ' ]) is_hlg_method = 'hlg' in method is_BT2100_2_method = '2100-2' in method LMS_p = (vector_dot(MATRIX_ICTCP_ICTCP_TO_LMS_P_HLG_BT2100_2, ICtCp) if (is_hlg_method and is_BT2100_2_method) else vector_dot( MATRIX_ICTCP_ICTCP_TO_LMS_P, ICtCp)) with domain_range_scale('ignore'): LMS = (oetf_inverse_HLG_BT2100(LMS_p) if is_hlg_method else eotf_ST2084(LMS_p, L_p)) RGB = vector_dot(MATRIX_ICTCP_LMS_TO_RGB, LMS) return from_range_1(RGB) def XYZ_to_ICtCp(XYZ, illuminant=CCS_ILLUMINANTS[ 'CIE 1931 2 Degree Standard Observer']['D65'], chromatic_adaptation_transform='CAT02', method='Dolby 2016', L_p=10000): """ Converts from *CIE XYZ* tristimulus values to :math:`IC_TC_P` colour encoding. Parameters ---------- XYZ : array_like *CIE XYZ* tristimulus values. illuminant : array_like, optional Source illuminant chromaticity coordinates. chromatic_adaptation_transform : unicode, optional **{'CAT02', 'XYZ Scaling', '<NAME>', 'Bradford', 'Sharp', 'Fairchild', 'CMCCAT97', 'CMCCAT2000', 'CAT02 Brill 2008', 'CAT16', 'Bianco 2010', 'Bianco PC 2010'}**, *Chromatic adaptation* transform. method : unicode, optional **{'Dolby 2016', 'ITU-R BT.2100-1 HLG', 'ITU-R BT.2100-1 PQ', 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ'}**, Computation method. *Recommendation ITU-R BT.2100* defines multiple variants of the :math:`IC_TC_P` colour encoding: - *ITU-R BT.2100-1* - *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *Dolby 2016*, *ITU-R BT.2100-1 PQ*, *ITU-R BT.2100-2 PQ* methods. - *Recommendation ITU-R BT.2100* *Reference HLG* opto-electrical transfer function (OETF / OECF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *ITU-R BT.2100-1 HLG* method. - *ITU-R BT.2100-2* - *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *Dolby 2016*, *ITU-R BT.2100-1 PQ*, *ITU-R BT.2100-2 PQ* methods. - *Recommendation ITU-R BT.2100* *Reference HLG* opto-electrical transfer function (OETF / OECF) and a custom :math:`IC_TC_P` matrix from :cite:`InternationalTelecommunicationUnion2018`: *ITU-R BT.2100-2 HLG* method. L_p : numeric, optional Display peak luminance :math:`cd/m^2` for *SMPTE ST 2084:2014* non-linear encoding. This parameter should stay at its default :math:`10000 cd/m^2` value for practical applications. It is exposed so that the definition can be used as a fitting function. Returns ------- ndarray :math:`IC_TC_P` colour encoding array. Warnings -------- The underlying *SMPTE ST 2084:2014* transfer function is an absolute transfer function. Notes ----- - The underlying *SMPTE ST 2084:2014* transfer function is an absolute transfer function, thus the domain and range values for the *Reference* - The *ITU-R BT.2100-1 PQ* and *ITU-R BT.2100-2 PQ* methods are aliases for the *Dolby 2016* method. and *1* scales are only indicative that the data is not affected by scale transformations. The effective domain of *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) is [0.0001, 10000]. +------------+-----------------------+------------------+ | **Domain** | **Scale - Reference** | **Scale - 1** | +============+=======================+==================+ | ``XYZ`` | ``UN`` | ``UN`` | +------------+-----------------------+------------------+ +------------+-----------------------+------------------+ | **Range** | **Scale - Reference** | **Scale - 1** | +============+=======================+==================+ | ``ICtCp`` | ``I`` : [0, 1] | ``I`` : [0, 1] | | | | | | | ``CT`` : [-1, 1] | ``CT`` : [-1, 1] | | | | | | | ``CP`` : [-1, 1] | ``CP`` : [-1, 1] | +------------+-----------------------+------------------+ References ---------- :cite:`Dolby2016a`, :cite:`Lu2016c` Examples -------- >>> XYZ = np.array([0.20654008, 0.12197225, 0.05136952]) >>> XYZ_to_ICtCp(XYZ) # doctest: +ELLIPSIS array([ 0.0685809..., -0.0028384..., 0.0602098...]) >>> XYZ_to_ICtCp(XYZ, method='ITU-R BT.2100-2 HLG') # doctest: +ELLIPSIS array([ 0.5924279..., -0.0374073..., 0.2512267...]) """ BT2020 = RGB_COLOURSPACES['ITU-R BT.2020'] RGB = XYZ_to_RGB( XYZ, illuminant, BT2020.whitepoint, BT2020.matrix_XYZ_to_RGB, chromatic_adaptation_transform, ) return RGB_to_ICtCp(RGB, method, L_p) def ICtCp_to_XYZ(ICtCp, illuminant=CCS_ILLUMINANTS[ 'CIE 1931 2 Degree Standard Observer']['D65'], chromatic_adaptation_transform='CAT02', method='Dolby 2016', L_p=10000): """ Converts from :math:`IC_TC_P` colour encoding to *CIE XYZ* tristimulus values. Parameters ---------- ICtCp : array_like :math:`IC_TC_P` colour encoding array. illuminant : array_like, optional Source illuminant chromaticity coordinates. chromatic_adaptation_transform : unicode, optional **{'CAT02', 'XYZ Scaling', '<NAME>', 'Bradford', 'Sharp', 'Fairchild', 'CMCCAT97', 'CMCCAT2000', 'CAT02 Brill 2008', 'CAT16', 'Bianco 2010', 'Bianco PC 2010'}**, *Chromatic adaptation* transform. method : unicode, optional **{'Dolby 2016', 'ITU-R BT.2100-1 HLG', 'ITU-R BT.2100-1 PQ', 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ'}**, Computation method. *Recommendation ITU-R BT.2100* defines multiple variants of the :math:`IC_TC_P` colour encoding: - *ITU-R BT.2100-1* - *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *Dolby 2016*, *ITU-R BT.2100-1 PQ*, *ITU-R BT.2100-2 PQ* methods. - *Recommendation ITU-R BT.2100* *Reference HLG* opto-electrical transfer function (OETF / OECF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *ITU-R BT.2100-1 HLG* method. - *ITU-R BT.2100-2* - *SMPTE ST 2084:2014* inverse electro-optical transfer function (EOTF / EOCF) and the :math:`IC_TC_P` matrix from :cite:`Dolby2016a`: *Dolby 2016*, *ITU-R BT.2100-1 PQ*, *ITU-R BT.2100-2 PQ* methods. - *Recommendation ITU-R BT.2100* *Reference HLG* opto-electrical transfer function (OETF / OECF) and a custom :math:`IC_TC_P` matrix from :cite:`InternationalTelecommunicationUnion2018`: *ITU-R BT.2100-2 HLG* method. L_p : numeric, optional Display peak luminance :math:`cd/m^2` for *SMPTE ST 2084:2014* non-linear encoding. This parameter should stay at its default :math:`10000 cd/m^2` value for practical applications. It is exposed so that the definition can be used as a fitting function. Returns ------- ndarray *CIE XYZ* tristimulus values. Warnings -------- The underlying *SMPTE ST 2084:2014* transfer function is an absolute transfer function. Notes ----- - The *ITU-R BT.2100-1 PQ* and *ITU-R BT.2100-2 PQ* methods are aliases for the *Dolby 2016* method. - The underlying *SMPTE ST 2084:2014* transfer function is an absolute transfer function, thus the domain and range values for the *Reference* and *1* scales are only indicative that the data is not affected by scale transformations. +------------+-----------------------+------------------+ | **Domain** | **Scale - Reference** | **Scale - 1** | +============+=======================+==================+ | ``ICtCp`` | ``I`` : [0, 1] | ``I`` : [0, 1] | | | | | | | ``CT`` : [-1, 1] | ``CT`` : [-1, 1] | | | | | | | ``CP`` : [-1, 1] | ``CP`` : [-1, 1] | +------------+-----------------------+------------------+ +------------+-----------------------+------------------+ | **Range** | **Scale - Reference** | **Scale - 1** | +============+=======================+==================+ | ``XYZ`` | ``UN`` | ``UN`` | +------------+-----------------------+------------------+ References ---------- :cite:`Dolby2016a`, :cite:`Lu2016c` Examples -------- >>> ICtCp = np.array([0.06858097, -0.00283842, 0.06020983]) >>> ICtCp_to_XYZ(ICtCp) # doctest: +ELLIPSIS array([ 0.2065400..., 0.1219722..., 0.0513695...]) >>> ICtCp = np.array([0.59242792, -0.03740730, 0.25122675]) >>> ICtCp_to_XYZ(ICtCp, method='ITU-R BT.2100-2 HLG') # doctest: +ELLIPSIS array([ 0.2065400..., 0.1219722..., 0.0513695...]) """ RGB = ICtCp_to_RGB(ICtCp, method, L_p) BT2020 = RGB_COLOURSPACES['ITU-R BT.2020'] XYZ = RGB_to_XYZ( RGB, BT2020.whitepoint, illuminant, BT2020.matrix_RGB_to_XYZ, chromatic_adaptation_transform, ) return XYZ
[ "colour.algebra.vector_dot", "colour.utilities.to_domain_1", "colour.utilities.from_range_1", "colour.models.rgb.RGB_to_XYZ", "colour.models.rgb.transfer_functions.oetf_HLG_BT2100", "colour.models.rgb.XYZ_to_RGB", "colour.utilities.domain_range_scale", "colour.models.rgb.transfer_functions.eotf_inverse_ST2084", "colour.utilities.validate_method", "numpy.array", "numpy.linalg.inv", "colour.models.rgb.transfer_functions.eotf_ST2084", "colour.models.rgb.transfer_functions.oetf_inverse_HLG_BT2100" ]
[((2348, 2386), 'numpy.linalg.inv', 'np.linalg.inv', (['MATRIX_ICTCP_RGB_TO_LMS'], {}), '(MATRIX_ICTCP_RGB_TO_LMS)\n', (2361, 2386), True, 'import numpy as np\n'), ((2861, 2903), 'numpy.linalg.inv', 'np.linalg.inv', (['MATRIX_ICTCP_LMS_P_TO_ICTCP'], {}), '(MATRIX_ICTCP_LMS_P_TO_ICTCP)\n', (2874, 2903), True, 'import numpy as np\n'), ((3467, 3522), 'numpy.linalg.inv', 'np.linalg.inv', (['MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2'], {}), '(MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2)\n', (3480, 3522), True, 'import numpy as np\n'), ((2115, 2179), 'numpy.array', 'np.array', (['[[1688, 2146, 262], [683, 2951, 462], [99, 309, 3688]]'], {}), '([[1688, 2146, 262], [683, 2951, 462], [99, 309, 3688]])\n', (2123, 2179), True, 'import numpy as np\n'), ((2565, 2637), 'numpy.array', 'np.array', (['[[2048, 2048, 0], [6610, -13613, 7003], [17933, -17390, -543]]'], {}), '([[2048, 2048, 0], [6610, -13613, 7003], [17933, -17390, -543]])\n', (2573, 2637), True, 'import numpy as np\n'), ((3118, 3187), 'numpy.array', 'np.array', (['[[2048, 2048, 0], [3625, -7465, 3840], [9500, -9212, -288]]'], {}), '([[2048, 2048, 0], [3625, -7465, 3840], [9500, -9212, -288]])\n', (3126, 3187), True, 'import numpy as np\n'), ((7721, 7737), 'colour.utilities.to_domain_1', 'to_domain_1', (['RGB'], {}), '(RGB)\n', (7732, 7737), False, 'from colour.utilities import domain_range_scale, from_range_1, to_domain_1, validate_method\n'), ((7751, 7884), 'colour.utilities.validate_method', 'validate_method', (['method', "['Dolby 2016', 'ITU-R BT.2100-1 HLG', 'ITU-R BT.2100-1 PQ',\n 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ']"], {}), "(method, ['Dolby 2016', 'ITU-R BT.2100-1 HLG',\n 'ITU-R BT.2100-1 PQ', 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ'])\n", (7766, 7884), False, 'from colour.utilities import domain_range_scale, from_range_1, to_domain_1, validate_method\n'), ((7995, 8035), 'colour.algebra.vector_dot', 'vector_dot', (['MATRIX_ICTCP_RGB_TO_LMS', 'RGB'], {}), '(MATRIX_ICTCP_RGB_TO_LMS, RGB)\n', (8005, 8035), False, 'from colour.algebra import vector_dot\n'), ((8396, 8415), 'colour.utilities.from_range_1', 'from_range_1', (['ICtCp'], {}), '(ICtCp)\n', (8408, 8415), False, 'from colour.utilities import domain_range_scale, from_range_1, to_domain_1, validate_method\n'), ((12336, 12354), 'colour.utilities.to_domain_1', 'to_domain_1', (['ICtCp'], {}), '(ICtCp)\n', (12347, 12354), False, 'from colour.utilities import domain_range_scale, from_range_1, to_domain_1, validate_method\n'), ((12368, 12501), 'colour.utilities.validate_method', 'validate_method', (['method', "['Dolby 2016', 'ITU-R BT.2100-1 HLG', 'ITU-R BT.2100-1 PQ',\n 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ']"], {}), "(method, ['Dolby 2016', 'ITU-R BT.2100-1 HLG',\n 'ITU-R BT.2100-1 PQ', 'ITU-R BT.2100-2 HLG', 'ITU-R BT.2100-2 PQ'])\n", (12383, 12501), False, 'from colour.utilities import domain_range_scale, from_range_1, to_domain_1, validate_method\n'), ((12960, 13000), 'colour.algebra.vector_dot', 'vector_dot', (['MATRIX_ICTCP_LMS_TO_RGB', 'LMS'], {}), '(MATRIX_ICTCP_LMS_TO_RGB, LMS)\n', (12970, 13000), False, 'from colour.algebra import vector_dot\n'), ((13013, 13030), 'colour.utilities.from_range_1', 'from_range_1', (['RGB'], {}), '(RGB)\n', (13025, 13030), False, 'from colour.utilities import domain_range_scale, from_range_1, to_domain_1, validate_method\n'), ((17633, 17741), 'colour.models.rgb.XYZ_to_RGB', 'XYZ_to_RGB', (['XYZ', 'illuminant', 'BT2020.whitepoint', 'BT2020.matrix_XYZ_to_RGB', 'chromatic_adaptation_transform'], {}), '(XYZ, illuminant, BT2020.whitepoint, BT2020.matrix_XYZ_to_RGB,\n chromatic_adaptation_transform)\n', (17643, 17741), False, 'from colour.models.rgb import RGB_COLOURSPACES, RGB_to_XYZ, XYZ_to_RGB\n'), ((22412, 22520), 'colour.models.rgb.RGB_to_XYZ', 'RGB_to_XYZ', (['RGB', 'BT2020.whitepoint', 'illuminant', 'BT2020.matrix_RGB_to_XYZ', 'chromatic_adaptation_transform'], {}), '(RGB, BT2020.whitepoint, illuminant, BT2020.matrix_RGB_to_XYZ,\n chromatic_adaptation_transform)\n', (22422, 22520), False, 'from colour.models.rgb import RGB_COLOURSPACES, RGB_to_XYZ, XYZ_to_RGB\n'), ((8046, 8074), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['"""ignore"""'], {}), "('ignore')\n", (8064, 8074), False, 'from colour.utilities import domain_range_scale, from_range_1, to_domain_1, validate_method\n'), ((8198, 8257), 'colour.algebra.vector_dot', 'vector_dot', (['MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2', 'LMS_p'], {}), '(MATRIX_ICTCP_LMS_P_TO_ICTCP_HLG_BT2100_2, LMS_p)\n', (8208, 8257), False, 'from colour.algebra import vector_dot\n'), ((8318, 8364), 'colour.algebra.vector_dot', 'vector_dot', (['MATRIX_ICTCP_LMS_P_TO_ICTCP', 'LMS_p'], {}), '(MATRIX_ICTCP_LMS_P_TO_ICTCP, LMS_p)\n', (8328, 8364), False, 'from colour.algebra import vector_dot\n'), ((12615, 12674), 'colour.algebra.vector_dot', 'vector_dot', (['MATRIX_ICTCP_ICTCP_TO_LMS_P_HLG_BT2100_2', 'ICtCp'], {}), '(MATRIX_ICTCP_ICTCP_TO_LMS_P_HLG_BT2100_2, ICtCp)\n', (12625, 12674), False, 'from colour.algebra import vector_dot\n'), ((12735, 12781), 'colour.algebra.vector_dot', 'vector_dot', (['MATRIX_ICTCP_ICTCP_TO_LMS_P', 'ICtCp'], {}), '(MATRIX_ICTCP_ICTCP_TO_LMS_P, ICtCp)\n', (12745, 12781), False, 'from colour.algebra import vector_dot\n'), ((12811, 12839), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['"""ignore"""'], {}), "('ignore')\n", (12829, 12839), False, 'from colour.utilities import domain_range_scale, from_range_1, to_domain_1, validate_method\n'), ((8093, 8113), 'colour.models.rgb.transfer_functions.oetf_HLG_BT2100', 'oetf_HLG_BT2100', (['LMS'], {}), '(LMS)\n', (8108, 8113), False, 'from colour.models.rgb.transfer_functions import eotf_ST2084, eotf_inverse_ST2084, oetf_HLG_BT2100, oetf_inverse_HLG_BT2100\n'), ((8153, 8182), 'colour.models.rgb.transfer_functions.eotf_inverse_ST2084', 'eotf_inverse_ST2084', (['LMS', 'L_p'], {}), '(LMS, L_p)\n', (8172, 8182), False, 'from colour.models.rgb.transfer_functions import eotf_ST2084, eotf_inverse_ST2084, oetf_HLG_BT2100, oetf_inverse_HLG_BT2100\n'), ((12856, 12886), 'colour.models.rgb.transfer_functions.oetf_inverse_HLG_BT2100', 'oetf_inverse_HLG_BT2100', (['LMS_p'], {}), '(LMS_p)\n', (12879, 12886), False, 'from colour.models.rgb.transfer_functions import eotf_ST2084, eotf_inverse_ST2084, oetf_HLG_BT2100, oetf_inverse_HLG_BT2100\n'), ((12924, 12947), 'colour.models.rgb.transfer_functions.eotf_ST2084', 'eotf_ST2084', (['LMS_p', 'L_p'], {}), '(LMS_p, L_p)\n', (12935, 12947), False, 'from colour.models.rgb.transfer_functions import eotf_ST2084, eotf_inverse_ST2084, oetf_HLG_BT2100, oetf_inverse_HLG_BT2100\n')]
#!/usr/bin/env python3 import csv import numpy thr_sig=5.0 def sigmoid(x): return 1.0/(1.0+numpy.exp(-(x-thr_sig))) if __name__=="__main__": #parameters time_pitch=1.0 #ms save_pitch=10 save_pitch_weight=1000 simlen_sec=900.0 simlen=int(simlen_sec*1000.0/time_pitch) tauL=10.0 #ms phi=80.0/1000.0 phi_input=80.0/1000.0 alpha_som=0.5 alpha_dnd=0.5 beta_som=0.0 beta_dnd=0.0 gamma=1.0 c0=70.0 eta_som=0.2 eta_dnd=0.2 taudeltaW=1.0*1000.0 #ms tau_mean=60.0*1000.0 eta_Wdecay=1e-7 Wnoise_amp=5e-3/numpy.sqrt(time_pitch) som_input_num=50 dnd_input_num=som_input_num+0 group1_num=10 input_src_num=4 tau_input=10.0 #ms input_amp=0.1/numpy.sqrt(time_pitch) noise_amp=0.1/numpy.sqrt(time_pitch) Winit=5.0 Wmin=0.0 E0=0.05 #variables x=0.0 y=0.0 Ex=E0 Ey=E0 input_src=numpy.zeros(input_src_num) som_input_current=numpy.zeros(som_input_num) dnd_input_current=numpy.zeros(dnd_input_num) som_inputPSC=numpy.zeros(som_input_num) dnd_inputPSC=numpy.zeros(dnd_input_num) deltaWsom=numpy.zeros(som_input_num) deltaWdnd=numpy.zeros(dnd_input_num) Wsom=Winit*(numpy.random.rand(som_input_num)) Wdnd=Winit*(numpy.random.rand(dnd_input_num)) #save f_activity=open("activity.csv", "w") csv_activity=csv.writer(f_activity, delimiter=",") f_Wsom=open("Wsom.csv", "w") csv_Wsom=csv.writer(f_Wsom, delimiter=",") f_Wdnd=open("Wdnd.csv", "w") csv_Wdnd=csv.writer(f_Wdnd, delimiter=",") f_som_input=open("som_input.csv", "w") csv_som_input=csv.writer(f_som_input, delimiter=",") f_dnd_input=open("dnd_input.csv", "w") csv_dnd_input=csv.writer(f_dnd_input, delimiter=",") som_src=numpy.zeros([som_input_num, input_src_num]) som_src[:group1_num, 0]=1.0 som_src[group1_num:, 2]=1.0 dnd_src=numpy.zeros([dnd_input_num, input_src_num]) dnd_src[:group1_num,1]=1.0 dnd_src[group1_num:,3]=1.0 #simulation for t in range(simlen): time_sec=float(t)*time_pitch/1000.0 if time_sec==int(time_sec): print(time_sec,"sec") #source signal input_src=input_src+time_pitch*(-input_src/tau_input+input_amp*numpy.random.randn(input_src_num)) #inputs som_input_current+=time_pitch*(-som_input_current/tauL+som_src@input_src+noise_amp*numpy.random.randn(som_input_num)) dnd_input_current+=time_pitch*(-dnd_input_current/tauL+dnd_src@input_src+noise_amp*numpy.random.randn(dnd_input_num)) som_input=phi_input*sigmoid(som_input_current) dnd_input=phi_input*sigmoid(dnd_input_current) som_inputPSC+=time_pitch*(-som_inputPSC/tauL+som_input) dnd_inputPSC+=time_pitch*(-dnd_inputPSC/tauL+dnd_input) #dynamics xprev=x+0.0 yprev=y+0.0 Isom=Wsom@som_inputPSC Idnd=Wdnd@dnd_inputPSC x=sigmoid(Isom+beta_som*yprev) y=sigmoid(Idnd+beta_dnd*xprev) z=(1.0+gamma*y)*phi*x #plasticity #som Wsom+=time_pitch*(eta_som*deltaWsom+Wnoise_amp*numpy.random.randn(som_input_num)-eta_Wdecay*Wsom) Wsom[Wsom<Wmin]=Wmin theta_som=c0*Ex*Ex deltaWsom+=time_pitch*(-deltaWsom+((1.0-alpha_som)*x*(x-theta_som)+alpha_som*x*y)*(1.0-x)*som_inputPSC)/taudeltaW #dnd Wdnd+=time_pitch*(eta_dnd*deltaWdnd+Wnoise_amp*numpy.random.randn(dnd_input_num)-eta_Wdecay*Wdnd) Wdnd[Wdnd<Wmin]=Wmin theta_dnd=c0*Ey*Ey deltaWdnd+=time_pitch*(-deltaWdnd+((1.0-alpha_dnd)*y*(y-theta_dnd)+alpha_dnd*x*y)*(1.0-y)*dnd_inputPSC)/taudeltaW Ex+=time_pitch*(-Ex+x)/tau_mean Ey+=time_pitch*(-Ey+y)/tau_mean if t%save_pitch==0: csv_activity.writerow([time_sec, x, y, z]); f_activity.flush(); csv_som_input.writerow(numpy.hstack([time_sec, som_input])); f_som_input.flush(); csv_dnd_input.writerow(numpy.hstack([time_sec, dnd_input])); f_dnd_input.flush(); if t%save_pitch_weight==0: csv_Wsom.writerow(numpy.hstack([time_sec, Wsom])); f_Wsom.flush(); csv_Wdnd.writerow(numpy.hstack([time_sec, Wdnd])); f_Wdnd.flush();
[ "numpy.sqrt", "numpy.random.rand", "numpy.hstack", "csv.writer", "numpy.exp", "numpy.zeros", "numpy.random.randn" ]
[((917, 943), 'numpy.zeros', 'numpy.zeros', (['input_src_num'], {}), '(input_src_num)\n', (928, 943), False, 'import numpy\n'), ((966, 992), 'numpy.zeros', 'numpy.zeros', (['som_input_num'], {}), '(som_input_num)\n', (977, 992), False, 'import numpy\n'), ((1015, 1041), 'numpy.zeros', 'numpy.zeros', (['dnd_input_num'], {}), '(dnd_input_num)\n', (1026, 1041), False, 'import numpy\n'), ((1059, 1085), 'numpy.zeros', 'numpy.zeros', (['som_input_num'], {}), '(som_input_num)\n', (1070, 1085), False, 'import numpy\n'), ((1103, 1129), 'numpy.zeros', 'numpy.zeros', (['dnd_input_num'], {}), '(dnd_input_num)\n', (1114, 1129), False, 'import numpy\n'), ((1144, 1170), 'numpy.zeros', 'numpy.zeros', (['som_input_num'], {}), '(som_input_num)\n', (1155, 1170), False, 'import numpy\n'), ((1185, 1211), 'numpy.zeros', 'numpy.zeros', (['dnd_input_num'], {}), '(dnd_input_num)\n', (1196, 1211), False, 'import numpy\n'), ((1381, 1418), 'csv.writer', 'csv.writer', (['f_activity'], {'delimiter': '""","""'}), "(f_activity, delimiter=',')\n", (1391, 1418), False, 'import csv\n'), ((1466, 1499), 'csv.writer', 'csv.writer', (['f_Wsom'], {'delimiter': '""","""'}), "(f_Wsom, delimiter=',')\n", (1476, 1499), False, 'import csv\n'), ((1546, 1579), 'csv.writer', 'csv.writer', (['f_Wdnd'], {'delimiter': '""","""'}), "(f_Wdnd, delimiter=',')\n", (1556, 1579), False, 'import csv\n'), ((1642, 1680), 'csv.writer', 'csv.writer', (['f_som_input'], {'delimiter': '""","""'}), "(f_som_input, delimiter=',')\n", (1652, 1680), False, 'import csv\n'), ((1742, 1780), 'csv.writer', 'csv.writer', (['f_dnd_input'], {'delimiter': '""","""'}), "(f_dnd_input, delimiter=',')\n", (1752, 1780), False, 'import csv\n'), ((1794, 1837), 'numpy.zeros', 'numpy.zeros', (['[som_input_num, input_src_num]'], {}), '([som_input_num, input_src_num])\n', (1805, 1837), False, 'import numpy\n'), ((1915, 1958), 'numpy.zeros', 'numpy.zeros', (['[dnd_input_num, input_src_num]'], {}), '([dnd_input_num, input_src_num])\n', (1926, 1958), False, 'import numpy\n'), ((585, 607), 'numpy.sqrt', 'numpy.sqrt', (['time_pitch'], {}), '(time_pitch)\n', (595, 607), False, 'import numpy\n'), ((743, 765), 'numpy.sqrt', 'numpy.sqrt', (['time_pitch'], {}), '(time_pitch)\n', (753, 765), False, 'import numpy\n'), ((784, 806), 'numpy.sqrt', 'numpy.sqrt', (['time_pitch'], {}), '(time_pitch)\n', (794, 806), False, 'import numpy\n'), ((1228, 1260), 'numpy.random.rand', 'numpy.random.rand', (['som_input_num'], {}), '(som_input_num)\n', (1245, 1260), False, 'import numpy\n'), ((1278, 1310), 'numpy.random.rand', 'numpy.random.rand', (['dnd_input_num'], {}), '(dnd_input_num)\n', (1295, 1310), False, 'import numpy\n'), ((97, 122), 'numpy.exp', 'numpy.exp', (['(-(x - thr_sig))'], {}), '(-(x - thr_sig))\n', (106, 122), False, 'import numpy\n'), ((3919, 3954), 'numpy.hstack', 'numpy.hstack', (['[time_sec, som_input]'], {}), '([time_sec, som_input])\n', (3931, 3954), False, 'import numpy\n'), ((4013, 4048), 'numpy.hstack', 'numpy.hstack', (['[time_sec, dnd_input]'], {}), '([time_sec, dnd_input])\n', (4025, 4048), False, 'import numpy\n'), ((4137, 4167), 'numpy.hstack', 'numpy.hstack', (['[time_sec, Wsom]'], {}), '([time_sec, Wsom])\n', (4149, 4167), False, 'import numpy\n'), ((4216, 4246), 'numpy.hstack', 'numpy.hstack', (['[time_sec, Wdnd]'], {}), '([time_sec, Wdnd])\n', (4228, 4246), False, 'import numpy\n'), ((2426, 2459), 'numpy.random.randn', 'numpy.random.randn', (['som_input_num'], {}), '(som_input_num)\n', (2444, 2459), False, 'import numpy\n'), ((2552, 2585), 'numpy.random.randn', 'numpy.random.randn', (['dnd_input_num'], {}), '(dnd_input_num)\n', (2570, 2585), False, 'import numpy\n'), ((2275, 2308), 'numpy.random.randn', 'numpy.random.randn', (['input_src_num'], {}), '(input_src_num)\n', (2293, 2308), False, 'import numpy\n'), ((3169, 3202), 'numpy.random.randn', 'numpy.random.randn', (['som_input_num'], {}), '(som_input_num)\n', (3187, 3202), False, 'import numpy\n'), ((3468, 3501), 'numpy.random.randn', 'numpy.random.randn', (['dnd_input_num'], {}), '(dnd_input_num)\n', (3486, 3501), False, 'import numpy\n')]
# Copyright 2020 Makani Technologies LLC # # 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. """View functions to interact with web clients.""" import atexit import json import logging import os import re import string import time from django import http from django import shortcuts from django import template from django.core import urlresolvers from makani.analysis.checks import log_util from makani.avionics.network import message_type as aio_message_type from makani.avionics.network import network_config from makani.gs.monitor2.apps.layout import autogen from makani.gs.monitor2.apps.layout import base as layout_base from makani.gs.monitor2.apps.layout import layout_util from makani.gs.monitor2.apps.layout import loader from makani.gs.monitor2.apps.layout import memory as layout_memory from makani.gs.monitor2.apps.layout import stoplights from makani.gs.monitor2.apps.layout import widgets from makani.gs.monitor2.apps.receiver import receiver_manager from makani.gs.monitor2.apps.receiver import views as receiver_views from makani.gs.monitor2.project import settings from makani.lib.bazel import bazel_util from makani.lib.python import c_helpers from makani.lib.python import debug_util from makani.lib.python import struct_tree from makani.lib.python.h5_utils import h5_io import numpy MESSAGE_TYPE_HELPER = c_helpers.EnumHelper('MessageType', aio_message_type) CONFIG_FILES = { 'plot_defs': os.path.join(settings.MONITOR_PATH, 'configs/plot_defs.json'), } def Home(request): """Get the response for the home page.""" layout_names = loader.LayoutLoader().Names() layout_names.sort() all_layouts = [ {'name': layout, 'url': urlresolvers.reverse( 'view_aio_layout', args=[loader.LayoutLoader().ModuleName(layout)])} for layout in layout_names] context = { 'layouts': all_layouts, 'canvas_cols': settings.CSS_GRID_COLUMNS, } _CreateAndAddClientIdToContext(context) template_name = 'home.html' return shortcuts.render(request, template_name, context, context_instance=template.RequestContext(request)) def _ListFiles(path_arg): """List files under a local path.""" path_template = string.Template(path_arg) prefix_path = path_template.substitute(os.environ) sub_paths = os.listdir(prefix_path) return prefix_path, sub_paths def _GetFullFilePath(prefix_path, sub_path): return os.path.join(prefix_path, sub_path) def SelectAllLogs(request): """Select all logs in the last visited directory.""" current_path = request.session['current_path'] try: prefix_path, sub_paths = _ListFiles(current_path) except OSError: return http.HttpResponse('Cannot list directory "%s"!' % current_path) file_list = [] for sub_path in sorted(sub_paths): # Construct the full path. if sub_path.endswith('.h5') and not sub_path.startswith('format'): full_path = _GetFullFilePath(prefix_path, sub_path) if not os.path.isdir(full_path): file_list.append(full_path) return http.HttpResponse(';\n'.join(file_list)) def Console(request, command, args): """Take commandlines from the client and respond with console outputs. Args: request: The HTML resquest object. command: The command to be run. Only 'ls' is permitted for now. args: The string of arguments to the command. Returns: The HttpResponse telling the output of the command. """ if command != 'ls': message = 'Command "%s" is not allowed.' % command return http.HttpResponse(message) arg_template = string.Template(args) arg_path = arg_template.safe_substitute( {'MAKANI_HOME': bazel_util.GetWorkspaceRoot()}) try: prefix_path, sub_paths = _ListFiles(arg_path) request.session['current_path'] = arg_path except OSError: return http.HttpResponse('Cannot list directory "%s"!' % arg_path) file_list = [] for sub_path in sorted(sub_paths): # Construct the full path. full_path = _GetFullFilePath(prefix_path, sub_path) if os.path.isdir(full_path): # If this is a directory, add the javascript to allow users to click # into it. file_list.append( '<a href="javascript:void(0)" onclick="onListFiles(\'%s\')">%s</a>' % (full_path, sub_path)) elif sub_path.endswith('.h5') and not sub_path.startswith('format'): # If this is an HDF5 file, add the javascript to allow users to # visualize it. file_list.append( '<a href="javascript:void(0)" onclick="onAddLog(\'%s\')">%s</a>' % (full_path, sub_path)) else: file_list.append(sub_path) text = '<br>'.join(file_list) return http.HttpResponse(text) def _GetMinMessageFrequency(): """Get the minimum frequency across all message types.""" config = network_config.NetworkConfig(settings.NETWORK_YAML) return min(m.frequency_hz for m in config.all_messages if m.frequency_hz > 0) def _TryToEnforceAioReceiver(client_id): """Ensure that the client is subscribed to the AioReceiver.""" # TODO: Investigate always running the AioReceiver. message_receiver = receiver_manager.ReceiverManager.GetReceiver(client_id) if not message_receiver: if receiver_manager.ReceiverManager.CheckAndStartAioReceiver( client_id, receiver_views.CreateAioReceiver): # A new AioReceiver is started. # Get the longest period for all messages, and multiply it by two to # make sure we do not miss any message. time.sleep(2.0 / _GetMinMessageFrequency()) return receiver_manager.ReceiverManager.GetReceiver(client_id) else: return message_receiver def ViewMessageType(request, client_id, message_type, template_name='monitor.html'): """View information within a message by automatically generating a layout. Args: request: An HttpRequest from the client. client_id: The ID of the client's browser tab. message_type: The Enum name of a message type. template_name: The HTML template used to render the layout. Returns: An HttpResponse in the format of a serialized JSON object. """ configs = _LoadConfigs() _TryToEnforceAioReceiver(client_id) resp = _GetMessage(request, client_id, message_type) resp = resp.Data(convert_to_basic_types=True) if resp else {} configs['scenarios'] = autogen.GenerateScenario(resp, message_type) context = _PrepareContext(configs) new_client_id = _CreateAndAddClientIdToContext(context) context['periodic_url'] = '/dashboard/periodic/msg_enum/%s/%s' % ( new_client_id, message_type) context['content_width'] = settings.CSS_GRID_COLUMNS context['order_horizontally'] = True return shortcuts.render(request, template_name, context, context_instance=template.RequestContext(request)) def UpdateMessageOptions(unused_request, client_id): """Detect what messages have been received and update the client. Args: unused_request: An HttpRequest from the client. client_id: The ID of the client's browser tab. Returns: An HttpResponse about a dictionary of {message_enum: message_short_name} """ message_receiver = _TryToEnforceAioReceiver(client_id) info = message_receiver.GetReceivedMessageTypes() if message_receiver else [] return http.HttpResponse(json.dumps(info)) def ViewAioLayout(request, layout_name): """Open a monitor layout that get data from AIO. Args: request: An HttpRequest from the client. layout_name: Name of the layout associated with the client. Returns: An HttpResponse in the format of a serialized JSON object. """ context = {'receiver_type': 'aio'} return _ViewLayout(request, layout_name, context) def BrowseLog(request, path): """Browse the log by expanding the field at `path`. Args: request: An HttpRequest from the client. path: A path pointing to one field in the log. Returns: An HttpResponse serializing a list of names for child fields. """ # The log structure may differ across logs, we always use the first log to # construct the log structure. log_path = request.session['log_paths'][0] log_data = struct_tree.StructTree(log_path, fail_silently=True, readonly=True) try: skeleton = log_data.Skeleton(path, depth=1) except h5_io.H5IndexError: return http.HttpResponse('{}') parent_path = path d3_data = struct_tree.DictToD3Tree(skeleton, '.', parent_path) if 'children' in d3_data: # The first layer is a placeholder. Starts from the second layer. return http.HttpResponse(json.dumps(d3_data['children'])) else: return http.HttpResponse('{}') def ViewLogStructure(request, paths, template_name='log_structure.html'): """View structure of an HDF5 log at given log path. Args: request: An HttpRequest from the client. paths: Paths to the local log files. template_name: The HTML template used to render the layout. Returns: An HttpResponse that renders the log structure. """ # `context` includes variables used to render the HTML. context = { 'graph_width': 6000, 'graph_height': 6000, 'frame_width': 200, 'frame_height': 540, 'canvas_cols': 12, } log_paths = [] for path in paths.split(';'): path = path.strip() if not path: continue path_template = string.Template(path) log_path = path_template.substitute(os.environ) basename = os.path.basename(log_path) if basename.startswith('(') and basename.endswith(')'): dirname = os.path.dirname(log_path) regex_pattern = re.compile(basename[1:-1]+'$') filenames = os.listdir(dirname) matched_files = [f for f in filenames if regex_pattern.match(f)] log_paths += [os.path.join(dirname, f) for f in matched_files] else: log_paths.append(log_path) if not log_paths: context['errors'] = 'Cannot find log data' else: # Use the first log to index fields. log_data = struct_tree.StructTree( log_paths[0], fail_silently=True, readonly=True) log_skeleton = log_data.Skeleton(depth=1) d3_data = struct_tree.DictToD3Tree(log_skeleton, '/') d3_data['expand_url'] = urlresolvers.reverse('browse_log', args=['']) request.session['log_paths'] = log_paths context['skeleton'] = json.dumps(d3_data) order_horizontally = True configs = _LoadConfigs() scenarios = layout_base.AssembleLayout([ ('Signals', [ widgets.DictLinesWidget('series', None, interactive=True, use_markers=True), ]), ], desired_view_cols=1, order_horizontally=order_horizontally) layout_names = loader.LayoutLoader().ModuleNames() layout_names.sort() configs['scenarios'] = scenarios context.update(_PrepareContext(configs)) context['layout_names'] = layout_names context['content_width'] = settings.CSS_GRID_COLUMNS - 2 context['order_horizontally'] = order_horizontally _CreateAndAddClientIdToContext(context) return shortcuts.render(request, template_name, context, context_instance=template.RequestContext(request)) def PeriodicDataPoll(request, client_id, layout_name): """Compute realtime data and respond to periodic polling from a client layout. Args: request: An HttpRequest from the client. client_id: The ID of the client's browser tab. layout_name: Name of the layout associated with the client. Returns: An HttpResponse in the format of a serialized JSON object. """ aggregated_message = _GetMessage(request, client_id) if not aggregated_message: aggregated_message = struct_tree.StructTree( {}, fail_silently=True, readonly=True) layout = loader.LayoutLoader().GetLayoutByModuleName(layout_name) tab_memory = layout_memory.GetMemory(client_id, False) if tab_memory is not None: # Load the persistent memory. layout.Import(tab_memory) else: layout.Initialize() tab_memory = layout_memory.GetMemory(client_id, True) # Start the AIO receiver in case the server has restarted. _TryToEnforceAioReceiver(client_id) try: data = layout.Filter(aggregated_message) except Exception: # pylint: disable=broad-except # layout.Filter may introduce any kind of exception. logging.error('PeriodicDataPoll encountered an error:\n%s', debug_util.FormatTraceback()) layout.Export(tab_memory) return http.HttpResponse('{}') # Save the persistent memory. layout.Export(tab_memory) resp = data.Json() if settings.DEBUG: resp['__message__'] = '\n-----------------------------\n'.join( 'Error in indicator "%s":\n%s' % (k, v) for k, v in layout.ErrorReport()) resp_str = json.dumps(resp) layout.ClearErrors() return http.HttpResponse(resp_str) def _DownSample(data, length): window_size = max(1, len(data)/length) if window_size > 1: data = data[:len(data) / window_size * window_size] return numpy.mean(data.reshape(-1, window_size), 1), window_size else: return data, 1 def GetLogData(request, mode, fields): """Get values of data fields within a log file.""" log_paths = request.session['log_paths'] fields = [f.strip() for f in fields.split('\n') if f.strip()] field_labels = layout_util.GetDistinguishableNames( fields, '.', ['kAioNode', 'kMessageType']) if mode == 'merge': series = ConcatenateLogData(log_paths, field_labels) else: # By default, mode = 'compare' series = CompareLogData(log_paths, field_labels) resp = {'series': series} return http.HttpResponse(json.dumps(resp)) def _StringReplace(subject, translate): for s, t in translate: subject = subject.replace(s, t) return subject def GetMessageSnapshot(request, client_id, title): aggregated_message = _GetMessage(request, client_id) result = aggregated_message.Data(True) response = http.HttpResponse(content_type='text/plain') response['Content-Disposition'] = ( 'attachment; filename=snapshot_%s.json' % title) response.write(json.dumps(result, indent=2)) return response def GetRawLogData(request, fields): """Get values of data fields within a log file.""" log_paths = request.session['log_paths'] fields = [f.strip() for f in fields.split('\n') if f.strip()] field_labels = layout_util.GetDistinguishableNames( fields, '.', ['kAioNode', 'kMessageType']) result = {} # Remove special characters so variables can be parsed and loaded into Matlab. bad_chars = ['.', ',', '-', '+', '(', ')', '[', ']', '{', '}', ':', 'kMessageType', 'kAioNode', 'messages', 'message'] replacement = list(zip(bad_chars, ['_'] * len(bad_chars))) replacement = [('[:]', ''), (':,', ''), (' ', '')] + replacement for log_path in log_paths: base_name = os.path.basename(log_path) log_name = 'log_' + _StringReplace(base_name[:base_name.find('.')], replacement) log_data = struct_tree.StructTree( log_path, fail_silently=True, readonly=True) result[log_name] = {} for field, legend_label in field_labels.iteritems(): data, timestamps = log_util.GetOrderedDedupDataAndTimeByField( log_data, field, rebase=False) result[log_name][_StringReplace(legend_label, replacement)] = { 'values': data.tolist() if data is not None else None, 'timestamps': timestamps.tolist() if timestamps is not None else None, 'status': 'success' if data is not None else 'missing', } response = http.HttpResponse(content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=makani_log_data.json' response.write(json.dumps(result, indent=2)) return response def ConcatenateLogData(log_paths, field_labels): """Get series of data, each corresponding to field values in all logs.""" series = {} base_timeline = float('inf') for log_path in log_paths: log_data = struct_tree.StructTree( log_path, fail_silently=True, readonly=True) for field, legend_label in field_labels.iteritems(): data, timestamps = log_util.GetOrderedDedupDataAndTimeByField( log_data, field, rebase=False) if data is None or timestamps is None: continue base_timeline = min(base_timeline, float(timestamps[0])) if legend_label not in series: series[legend_label] = {'x': timestamps, 'y': data} else: series[legend_label]['x'] = numpy.concatenate( (series[legend_label]['x'], timestamps)) series[legend_label]['y'] = numpy.concatenate( (series[legend_label]['y'], data)) result = {} for field, legend_label in field_labels.iteritems(): timestamps, _ = _DownSample( series[legend_label]['x'], settings.MAX_DATA_POINTS_PER_LOG_FIELD) data, downsample_rate = _DownSample( series[legend_label]['y'], settings.MAX_DATA_POINTS_PER_LOG_FIELD) if downsample_rate > 1: legend_label += '(/%d)' % downsample_rate result[legend_label] = {'x': (timestamps - base_timeline).tolist(), 'y': data.tolist()} return result def CompareLogData(log_paths, field_labels): """Get series of data, each corresponding to field values within a log.""" series = {} base_timeline = float('inf') for log_path in log_paths: log_data = struct_tree.StructTree( log_path, fail_silently=True, readonly=True) log_name = os.path.basename(log_path) if '.' in log_name: log_name = log_name[:log_name.rfind('.')] for field, legend_label in field_labels.iteritems(): data, timestamps = log_util.GetOrderedDedupDataAndTimeByField( log_data, field, rebase=True) if data is None or timestamps is None: continue data, _ = _DownSample(data, settings.MAX_DATA_POINTS_PER_LOG_FIELD) timestamps, downsample_rate = _DownSample( timestamps, settings.MAX_DATA_POINTS_PER_LOG_FIELD) base_timeline = min(base_timeline, float(timestamps[0])) short_name = '%s.%s' % (log_name, legend_label) if downsample_rate > 1: short_name += '(/%d)' % downsample_rate series[short_name] = {'x': timestamps, 'y': data.tolist()} for short_name in series: series[short_name]['x'] = (series[short_name]['x'] - base_timeline).tolist() return series def PeriodicMessagePoll(request, client_id, message_type=None): """Retrieve realtime data and respond to periodic polling from a message view. Args: request: An HttpRequest from the client. client_id: The ID of the client's browser tab. message_type: The Enum name of a message type. Returns: An HttpResponse in the format of a serialized JSON object. """ resp = _GetMessage(request, client_id, message_type) if not resp: resp = {} else: resp = resp.Data(convert_to_basic_types=True) resp_str = json.dumps(resp) return http.HttpResponse(resp_str) def _LoadConfigs(): """Load default layout configuration parameters.""" configs = {} for cf, filename in CONFIG_FILES.iteritems(): with open(filename, 'r') as fp: configs[cf] = json.load(fp) if 'plot_defs' not in configs: logging.Error('Missing definitions for plotting javascripts.') return configs def _PrepareContext(configs): """Prepare the context to render the layout.""" context = {} fig_templates = set() canvas_cols = configs['scenarios']['canvas']['grid_width'] context['canvas_cols'] = canvas_cols row_height_px = configs['scenarios']['canvas']['row_height_px'] ui_objs = [] max_cols = canvas_cols for stripe in configs['scenarios']['views']: for view in stripe['stripe']: view['canvas_cols'] = int( float(view['grid_width']) / stripe['grid_width'] * canvas_cols + 0.5) for indicator in view['indicators']: ui_obj = indicator if 'rows' not in ui_obj: ui_obj['height'] = 'auto' else: rows = ui_obj['rows'] ui_obj['height'] = str(rows * row_height_px) + 'px' if 'cols' not in ui_obj: ui_obj['cols'] = max_cols # TODO: Change `id` to 'indicator_id', and 'selector' # to 'dom_selector'. ui_obj['id'] = 'ui_obj_%s' % len(ui_objs) ui_obj['selector'] = '#%s' % (ui_obj['id']) ui_objs.append(ui_obj) fig_templates.add(ui_obj['template']) context['fig_templates'] = fig_templates context['plot_defs'] = configs['plot_defs'] context['views'] = configs['scenarios']['views'] context['ui_objs_str'] = json.dumps(ui_objs) context['stoplight_error'] = stoplights.STOPLIGHT_ERROR context['stoplight_warning'] = stoplights.STOPLIGHT_WARNING context['stoplight_normal'] = stoplights.STOPLIGHT_NORMAL context['stoplight_unavailable'] = stoplights.STOPLIGHT_UNAVAILABLE context['stoplight_any'] = stoplights.STOPLIGHT_ANY return context def _GetMessage(unused_request, client_id, message_type=None): """Get a message from the receiver.""" message_receiver = receiver_manager.ReceiverManager.GetReceiver(client_id) resp = struct_tree.StructTree({}, fail_silently=True, readonly=True) if message_receiver: if message_type is not None: message_enum = MESSAGE_TYPE_HELPER.Value(message_type) else: message_enum = None resp = message_receiver.GetLatest(message_enum) return resp def _CreateAndAddClientIdToContext(context): client_id = receiver_manager.ReceiverManager.GetNewClientId() context['client_id'] = client_id return client_id def _ViewLayout(request, layout_name, extra_context=None): """Get a monitor layout according to `layout_name`.""" layout = loader.LayoutLoader().GetLayoutByModuleName(layout_name) if layout is None: return http.HttpResponseRedirect(urlresolvers.reverse('home')) layout.Initialize() configs = _LoadConfigs() configs['scenarios'] = layout.Scenario() context = _PrepareContext(configs) client_id = _CreateAndAddClientIdToContext(context) # Initialize the layout. layout.Export(layout_memory.GetMemory(client_id, True)) # Add polling URL. context['periodic_url'] = '/dashboard/periodic/layout/%s/%s' % (client_id, layout_name) context['layout_name'] = layout_name context['content_width'] = settings.CSS_GRID_COLUMNS context['order_horizontally'] = layout.OrderHorizontally() context['default_font_size'] = layout.DefaultFontSize() context['sim_mode'] = settings.POPULATE_MESSAGES_FROM_SIM if extra_context: context.update(extra_context) template_name = 'monitor.html' return shortcuts.render(request, template_name, context, context_instance=template.RequestContext(request))
[ "logging.Error", "re.compile", "makani.lib.python.debug_util.FormatTraceback", "makani.gs.monitor2.apps.layout.autogen.GenerateScenario", "django.core.urlresolvers.reverse", "makani.analysis.checks.log_util.GetOrderedDedupDataAndTimeByField", "makani.lib.python.c_helpers.EnumHelper", "os.listdir", "makani.gs.monitor2.apps.receiver.receiver_manager.ReceiverManager.GetReceiver", "django.http.HttpResponse", "json.dumps", "makani.gs.monitor2.apps.layout.widgets.DictLinesWidget", "makani.gs.monitor2.apps.receiver.receiver_manager.ReceiverManager.CheckAndStartAioReceiver", "os.path.isdir", "numpy.concatenate", "makani.lib.python.struct_tree.DictToD3Tree", "makani.gs.monitor2.apps.layout.memory.GetMemory", "os.path.dirname", "makani.avionics.network.network_config.NetworkConfig", "makani.lib.python.struct_tree.StructTree", "string.Template", "makani.gs.monitor2.apps.receiver.receiver_manager.ReceiverManager.GetNewClientId", "makani.gs.monitor2.apps.layout.layout_util.GetDistinguishableNames", "makani.lib.bazel.bazel_util.GetWorkspaceRoot", "os.path.join", "django.template.RequestContext", "os.path.basename", "json.load", "makani.gs.monitor2.apps.layout.loader.LayoutLoader" ]
[((1826, 1879), 'makani.lib.python.c_helpers.EnumHelper', 'c_helpers.EnumHelper', (['"""MessageType"""', 'aio_message_type'], {}), "('MessageType', aio_message_type)\n", (1846, 1879), False, 'from makani.lib.python import c_helpers\n'), ((1915, 1976), 'os.path.join', 'os.path.join', (['settings.MONITOR_PATH', '"""configs/plot_defs.json"""'], {}), "(settings.MONITOR_PATH, 'configs/plot_defs.json')\n", (1927, 1976), False, 'import os\n'), ((2696, 2721), 'string.Template', 'string.Template', (['path_arg'], {}), '(path_arg)\n', (2711, 2721), False, 'import string\n'), ((2789, 2812), 'os.listdir', 'os.listdir', (['prefix_path'], {}), '(prefix_path)\n', (2799, 2812), False, 'import os\n'), ((2901, 2936), 'os.path.join', 'os.path.join', (['prefix_path', 'sub_path'], {}), '(prefix_path, sub_path)\n', (2913, 2936), False, 'import os\n'), ((4051, 4072), 'string.Template', 'string.Template', (['args'], {}), '(args)\n', (4066, 4072), False, 'import string\n'), ((5151, 5174), 'django.http.HttpResponse', 'http.HttpResponse', (['text'], {}), '(text)\n', (5168, 5174), False, 'from django import http\n'), ((5279, 5330), 'makani.avionics.network.network_config.NetworkConfig', 'network_config.NetworkConfig', (['settings.NETWORK_YAML'], {}), '(settings.NETWORK_YAML)\n', (5307, 5330), False, 'from makani.avionics.network import network_config\n'), ((5594, 5649), 'makani.gs.monitor2.apps.receiver.receiver_manager.ReceiverManager.GetReceiver', 'receiver_manager.ReceiverManager.GetReceiver', (['client_id'], {}), '(client_id)\n', (5638, 5649), False, 'from makani.gs.monitor2.apps.receiver import receiver_manager\n'), ((6804, 6848), 'makani.gs.monitor2.apps.layout.autogen.GenerateScenario', 'autogen.GenerateScenario', (['resp', 'message_type'], {}), '(resp, message_type)\n', (6828, 6848), False, 'from makani.gs.monitor2.apps.layout import autogen\n'), ((8616, 8683), 'makani.lib.python.struct_tree.StructTree', 'struct_tree.StructTree', (['log_path'], {'fail_silently': '(True)', 'readonly': '(True)'}), '(log_path, fail_silently=True, readonly=True)\n', (8638, 8683), False, 'from makani.lib.python import struct_tree\n'), ((8836, 8888), 'makani.lib.python.struct_tree.DictToD3Tree', 'struct_tree.DictToD3Tree', (['skeleton', '"""."""', 'parent_path'], {}), "(skeleton, '.', parent_path)\n", (8860, 8888), False, 'from makani.lib.python import struct_tree\n'), ((12211, 12252), 'makani.gs.monitor2.apps.layout.memory.GetMemory', 'layout_memory.GetMemory', (['client_id', '(False)'], {}), '(client_id, False)\n', (12234, 12252), True, 'from makani.gs.monitor2.apps.layout import memory as layout_memory\n'), ((13150, 13166), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (13160, 13166), False, 'import json\n'), ((13199, 13226), 'django.http.HttpResponse', 'http.HttpResponse', (['resp_str'], {}), '(resp_str)\n', (13216, 13226), False, 'from django import http\n'), ((13694, 13772), 'makani.gs.monitor2.apps.layout.layout_util.GetDistinguishableNames', 'layout_util.GetDistinguishableNames', (['fields', '"""."""', "['kAioNode', 'kMessageType']"], {}), "(fields, '.', ['kAioNode', 'kMessageType'])\n", (13729, 13772), False, 'from makani.gs.monitor2.apps.layout import layout_util\n'), ((14308, 14352), 'django.http.HttpResponse', 'http.HttpResponse', ([], {'content_type': '"""text/plain"""'}), "(content_type='text/plain')\n", (14325, 14352), False, 'from django import http\n'), ((14726, 14804), 'makani.gs.monitor2.apps.layout.layout_util.GetDistinguishableNames', 'layout_util.GetDistinguishableNames', (['fields', '"""."""', "['kAioNode', 'kMessageType']"], {}), "(fields, '.', ['kAioNode', 'kMessageType'])\n", (14761, 14804), False, 'from makani.gs.monitor2.apps.layout import layout_util\n'), ((15957, 16001), 'django.http.HttpResponse', 'http.HttpResponse', ([], {'content_type': '"""text/plain"""'}), "(content_type='text/plain')\n", (15974, 16001), False, 'from django import http\n'), ((19326, 19342), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (19336, 19342), False, 'import json\n'), ((19352, 19379), 'django.http.HttpResponse', 'http.HttpResponse', (['resp_str'], {}), '(resp_str)\n', (19369, 19379), False, 'from django import http\n'), ((20984, 21003), 'json.dumps', 'json.dumps', (['ui_objs'], {}), '(ui_objs)\n', (20994, 21003), False, 'import json\n'), ((21452, 21507), 'makani.gs.monitor2.apps.receiver.receiver_manager.ReceiverManager.GetReceiver', 'receiver_manager.ReceiverManager.GetReceiver', (['client_id'], {}), '(client_id)\n', (21496, 21507), False, 'from makani.gs.monitor2.apps.receiver import receiver_manager\n'), ((21517, 21578), 'makani.lib.python.struct_tree.StructTree', 'struct_tree.StructTree', (['{}'], {'fail_silently': '(True)', 'readonly': '(True)'}), '({}, fail_silently=True, readonly=True)\n', (21539, 21578), False, 'from makani.lib.python import struct_tree\n'), ((21859, 21908), 'makani.gs.monitor2.apps.receiver.receiver_manager.ReceiverManager.GetNewClientId', 'receiver_manager.ReceiverManager.GetNewClientId', ([], {}), '()\n', (21906, 21908), False, 'from makani.gs.monitor2.apps.receiver import receiver_manager\n'), ((4006, 4032), 'django.http.HttpResponse', 'http.HttpResponse', (['message'], {}), '(message)\n', (4023, 4032), False, 'from django import http\n'), ((4513, 4537), 'os.path.isdir', 'os.path.isdir', (['full_path'], {}), '(full_path)\n', (4526, 4537), False, 'import os\n'), ((5684, 5790), 'makani.gs.monitor2.apps.receiver.receiver_manager.ReceiverManager.CheckAndStartAioReceiver', 'receiver_manager.ReceiverManager.CheckAndStartAioReceiver', (['client_id', 'receiver_views.CreateAioReceiver'], {}), '(client_id,\n receiver_views.CreateAioReceiver)\n', (5741, 5790), False, 'from makani.gs.monitor2.apps.receiver import receiver_manager\n'), ((6017, 6072), 'makani.gs.monitor2.apps.receiver.receiver_manager.ReceiverManager.GetReceiver', 'receiver_manager.ReceiverManager.GetReceiver', (['client_id'], {}), '(client_id)\n', (6061, 6072), False, 'from makani.gs.monitor2.apps.receiver import receiver_manager\n'), ((7772, 7788), 'json.dumps', 'json.dumps', (['info'], {}), '(info)\n', (7782, 7788), False, 'import json\n'), ((9068, 9091), 'django.http.HttpResponse', 'http.HttpResponse', (['"""{}"""'], {}), "('{}')\n", (9085, 9091), False, 'from django import http\n'), ((9787, 9808), 'string.Template', 'string.Template', (['path'], {}), '(path)\n', (9802, 9808), False, 'import string\n'), ((9876, 9902), 'os.path.basename', 'os.path.basename', (['log_path'], {}), '(log_path)\n', (9892, 9902), False, 'import os\n'), ((10411, 10482), 'makani.lib.python.struct_tree.StructTree', 'struct_tree.StructTree', (['log_paths[0]'], {'fail_silently': '(True)', 'readonly': '(True)'}), '(log_paths[0], fail_silently=True, readonly=True)\n', (10433, 10482), False, 'from makani.lib.python import struct_tree\n'), ((10552, 10595), 'makani.lib.python.struct_tree.DictToD3Tree', 'struct_tree.DictToD3Tree', (['log_skeleton', '"""/"""'], {}), "(log_skeleton, '/')\n", (10576, 10595), False, 'from makani.lib.python import struct_tree\n'), ((10624, 10669), 'django.core.urlresolvers.reverse', 'urlresolvers.reverse', (['"""browse_log"""'], {'args': "['']"}), "('browse_log', args=[''])\n", (10644, 10669), False, 'from django.core import urlresolvers\n'), ((10741, 10760), 'json.dumps', 'json.dumps', (['d3_data'], {}), '(d3_data)\n', (10751, 10760), False, 'import json\n'), ((12057, 12118), 'makani.lib.python.struct_tree.StructTree', 'struct_tree.StructTree', (['{}'], {'fail_silently': '(True)', 'readonly': '(True)'}), '({}, fail_silently=True, readonly=True)\n', (12079, 12118), False, 'from makani.lib.python import struct_tree\n'), ((12395, 12435), 'makani.gs.monitor2.apps.layout.memory.GetMemory', 'layout_memory.GetMemory', (['client_id', '(True)'], {}), '(client_id, True)\n', (12418, 12435), True, 'from makani.gs.monitor2.apps.layout import memory as layout_memory\n'), ((14008, 14024), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (14018, 14024), False, 'import json\n'), ((14463, 14491), 'json.dumps', 'json.dumps', (['result'], {'indent': '(2)'}), '(result, indent=2)\n', (14473, 14491), False, 'import json\n'), ((15217, 15243), 'os.path.basename', 'os.path.basename', (['log_path'], {}), '(log_path)\n', (15233, 15243), False, 'import os\n'), ((15383, 15450), 'makani.lib.python.struct_tree.StructTree', 'struct_tree.StructTree', (['log_path'], {'fail_silently': '(True)', 'readonly': '(True)'}), '(log_path, fail_silently=True, readonly=True)\n', (15405, 15450), False, 'from makani.lib.python import struct_tree\n'), ((16099, 16127), 'json.dumps', 'json.dumps', (['result'], {'indent': '(2)'}), '(result, indent=2)\n', (16109, 16127), False, 'import json\n'), ((16363, 16430), 'makani.lib.python.struct_tree.StructTree', 'struct_tree.StructTree', (['log_path'], {'fail_silently': '(True)', 'readonly': '(True)'}), '(log_path, fail_silently=True, readonly=True)\n', (16385, 16430), False, 'from makani.lib.python import struct_tree\n'), ((17770, 17837), 'makani.lib.python.struct_tree.StructTree', 'struct_tree.StructTree', (['log_path'], {'fail_silently': '(True)', 'readonly': '(True)'}), '(log_path, fail_silently=True, readonly=True)\n', (17792, 17837), False, 'from makani.lib.python import struct_tree\n'), ((17862, 17888), 'os.path.basename', 'os.path.basename', (['log_path'], {}), '(log_path)\n', (17878, 17888), False, 'import os\n'), ((19626, 19688), 'logging.Error', 'logging.Error', (['"""Missing definitions for plotting javascripts."""'], {}), "('Missing definitions for plotting javascripts.')\n", (19639, 19688), False, 'import logging\n'), ((22463, 22503), 'makani.gs.monitor2.apps.layout.memory.GetMemory', 'layout_memory.GetMemory', (['client_id', '(True)'], {}), '(client_id, True)\n', (22486, 22503), True, 'from makani.gs.monitor2.apps.layout import memory as layout_memory\n'), ((2063, 2084), 'makani.gs.monitor2.apps.layout.loader.LayoutLoader', 'loader.LayoutLoader', ([], {}), '()\n', (2082, 2084), False, 'from makani.gs.monitor2.apps.layout import loader\n'), ((2577, 2609), 'django.template.RequestContext', 'template.RequestContext', (['request'], {}), '(request)\n', (2600, 2609), False, 'from django import template\n'), ((3161, 3224), 'django.http.HttpResponse', 'http.HttpResponse', (['(\'Cannot list directory "%s"!\' % current_path)'], {}), '(\'Cannot list directory "%s"!\' % current_path)\n', (3178, 3224), False, 'from django import http\n'), ((4138, 4167), 'makani.lib.bazel.bazel_util.GetWorkspaceRoot', 'bazel_util.GetWorkspaceRoot', ([], {}), '()\n', (4165, 4167), False, 'from makani.lib.bazel import bazel_util\n'), ((4304, 4363), 'django.http.HttpResponse', 'http.HttpResponse', (['(\'Cannot list directory "%s"!\' % arg_path)'], {}), '(\'Cannot list directory "%s"!\' % arg_path)\n', (4321, 4363), False, 'from django import http\n'), ((7244, 7276), 'django.template.RequestContext', 'template.RequestContext', (['request'], {}), '(request)\n', (7267, 7276), False, 'from django import template\n'), ((8779, 8802), 'django.http.HttpResponse', 'http.HttpResponse', (['"""{}"""'], {}), "('{}')\n", (8796, 8802), False, 'from django import http\n'), ((9016, 9047), 'json.dumps', 'json.dumps', (["d3_data['children']"], {}), "(d3_data['children'])\n", (9026, 9047), False, 'import json\n'), ((9979, 10004), 'os.path.dirname', 'os.path.dirname', (['log_path'], {}), '(log_path)\n', (9994, 10004), False, 'import os\n'), ((10027, 10059), 're.compile', 're.compile', (["(basename[1:-1] + '$')"], {}), "(basename[1:-1] + '$')\n", (10037, 10059), False, 'import re\n'), ((10076, 10095), 'os.listdir', 'os.listdir', (['dirname'], {}), '(dirname)\n', (10086, 10095), False, 'import os\n'), ((11093, 11114), 'makani.gs.monitor2.apps.layout.loader.LayoutLoader', 'loader.LayoutLoader', ([], {}), '()\n', (11112, 11114), False, 'from makani.gs.monitor2.apps.layout import loader\n'), ((11526, 11558), 'django.template.RequestContext', 'template.RequestContext', (['request'], {}), '(request)\n', (11549, 11558), False, 'from django import template\n'), ((12139, 12160), 'makani.gs.monitor2.apps.layout.loader.LayoutLoader', 'loader.LayoutLoader', ([], {}), '()\n', (12158, 12160), False, 'from makani.gs.monitor2.apps.layout import loader\n'), ((12852, 12875), 'django.http.HttpResponse', 'http.HttpResponse', (['"""{}"""'], {}), "('{}')\n", (12869, 12875), False, 'from django import http\n'), ((15568, 15641), 'makani.analysis.checks.log_util.GetOrderedDedupDataAndTimeByField', 'log_util.GetOrderedDedupDataAndTimeByField', (['log_data', 'field'], {'rebase': '(False)'}), '(log_data, field, rebase=False)\n', (15610, 15641), False, 'from makani.analysis.checks import log_util\n'), ((16522, 16595), 'makani.analysis.checks.log_util.GetOrderedDedupDataAndTimeByField', 'log_util.GetOrderedDedupDataAndTimeByField', (['log_data', 'field'], {'rebase': '(False)'}), '(log_data, field, rebase=False)\n', (16564, 16595), False, 'from makani.analysis.checks import log_util\n'), ((18043, 18115), 'makani.analysis.checks.log_util.GetOrderedDedupDataAndTimeByField', 'log_util.GetOrderedDedupDataAndTimeByField', (['log_data', 'field'], {'rebase': '(True)'}), '(log_data, field, rebase=True)\n', (18085, 18115), False, 'from makani.analysis.checks import log_util\n'), ((19575, 19588), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (19584, 19588), False, 'import json\n'), ((22092, 22113), 'makani.gs.monitor2.apps.layout.loader.LayoutLoader', 'loader.LayoutLoader', ([], {}), '()\n', (22111, 22113), False, 'from makani.gs.monitor2.apps.layout import loader\n'), ((22207, 22235), 'django.core.urlresolvers.reverse', 'urlresolvers.reverse', (['"""home"""'], {}), "('home')\n", (22227, 22235), False, 'from django.core import urlresolvers\n'), ((23146, 23178), 'django.template.RequestContext', 'template.RequestContext', (['request'], {}), '(request)\n', (23169, 23178), False, 'from django import template\n'), ((3453, 3477), 'os.path.isdir', 'os.path.isdir', (['full_path'], {}), '(full_path)\n', (3466, 3477), False, 'import os\n'), ((10187, 10211), 'os.path.join', 'os.path.join', (['dirname', 'f'], {}), '(dirname, f)\n', (10199, 10211), False, 'import os\n'), ((12780, 12808), 'makani.lib.python.debug_util.FormatTraceback', 'debug_util.FormatTraceback', ([], {}), '()\n', (12806, 12808), False, 'from makani.lib.python import debug_util\n'), ((16877, 16935), 'numpy.concatenate', 'numpy.concatenate', (["(series[legend_label]['x'], timestamps)"], {}), "((series[legend_label]['x'], timestamps))\n", (16894, 16935), False, 'import numpy\n'), ((16985, 17037), 'numpy.concatenate', 'numpy.concatenate', (["(series[legend_label]['y'], data)"], {}), "((series[legend_label]['y'], data))\n", (17002, 17037), False, 'import numpy\n'), ((10890, 10965), 'makani.gs.monitor2.apps.layout.widgets.DictLinesWidget', 'widgets.DictLinesWidget', (['"""series"""', 'None'], {'interactive': '(True)', 'use_markers': '(True)'}), "('series', None, interactive=True, use_markers=True)\n", (10913, 10965), False, 'from makani.gs.monitor2.apps.layout import widgets\n'), ((2228, 2249), 'makani.gs.monitor2.apps.layout.loader.LayoutLoader', 'loader.LayoutLoader', ([], {}), '()\n', (2247, 2249), False, 'from makani.gs.monitor2.apps.layout import loader\n')]
# coding=utf-8 # Copyright 2018 The TF-Agents 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 tf_agents.bandits.agents.neural_linucb_agent.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl.testing import parameterized import numpy as np import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import import tensorflow_probability as tfp from tf_agents.bandits.agents import neural_linucb_agent from tf_agents.bandits.agents import utils as bandit_utils from tf_agents.bandits.drivers import driver_utils from tf_agents.bandits.networks import global_and_arm_feature_network from tf_agents.bandits.policies import policy_utilities from tf_agents.bandits.specs import utils as bandit_spec_utils from tf_agents.networks import network from tf_agents.specs import tensor_spec from tf_agents.trajectories import policy_step from tf_agents.trajectories import time_step from tf_agents.utils import common from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import # TF internal tfd = tfp.distributions class DummyNet(network.Network): def __init__(self, observation_spec, encoding_dim=10): super(DummyNet, self).__init__( observation_spec, state_spec=(), name='DummyNet') context_dim = observation_spec.shape[0] # Store custom layers that can be serialized through the Checkpointable API. self._dummy_layers = [ tf.keras.layers.Dense( encoding_dim, kernel_initializer=tf.compat.v1.initializers.constant( np.ones([context_dim, encoding_dim])), bias_initializer=tf.compat.v1.initializers.constant( np.zeros([encoding_dim]))) ] def call(self, inputs, step_type=None, network_state=()): del step_type inputs = tf.cast(inputs, tf.float32) for layer in self._dummy_layers: inputs = layer(inputs) return inputs, network_state def test_cases(): return parameterized.named_parameters( { 'testcase_name': '_batch1_contextdim10', 'batch_size': 1, 'context_dim': 10, }, { 'testcase_name': '_batch4_contextdim5', 'batch_size': 4, 'context_dim': 5, }) def _get_initial_and_final_steps(batch_size, context_dim): observation = np.array(range(batch_size * context_dim)).reshape( [batch_size, context_dim]) reward = np.random.uniform(0.0, 1.0, [batch_size]) initial_step = time_step.TimeStep( tf.constant( time_step.StepType.FIRST, dtype=tf.int32, shape=[batch_size], name='step_type'), tf.constant(0.0, dtype=tf.float32, shape=[batch_size], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[batch_size], name='discount'), tf.constant(observation, dtype=tf.float32, shape=[batch_size, context_dim], name='observation')) final_step = time_step.TimeStep( tf.constant( time_step.StepType.LAST, dtype=tf.int32, shape=[batch_size], name='step_type'), tf.constant(reward, dtype=tf.float32, shape=[batch_size], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[batch_size], name='discount'), tf.constant(observation + 100.0, dtype=tf.float32, shape=[batch_size, context_dim], name='observation')) return initial_step, final_step def _get_initial_and_final_steps_with_action_mask(batch_size, context_dim, num_actions=None): observation = np.array(range(batch_size * context_dim)).reshape( [batch_size, context_dim]) observation = tf.constant(observation, dtype=tf.float32) mask = 1 - tf.eye(batch_size, num_columns=num_actions, dtype=tf.int32) reward = np.random.uniform(0.0, 1.0, [batch_size]) initial_step = time_step.TimeStep( tf.constant( time_step.StepType.FIRST, dtype=tf.int32, shape=[batch_size], name='step_type'), tf.constant(0.0, dtype=tf.float32, shape=[batch_size], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[batch_size], name='discount'), (observation, mask)) final_step = time_step.TimeStep( tf.constant( time_step.StepType.LAST, dtype=tf.int32, shape=[batch_size], name='step_type'), tf.constant(reward, dtype=tf.float32, shape=[batch_size], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[batch_size], name='discount'), (observation + 100.0, mask)) return initial_step, final_step def _get_action_step(action): return policy_step.PolicyStep( action=tf.convert_to_tensor(action), info=policy_utilities.PolicyInfo()) def _get_experience(initial_step, action_step, final_step): single_experience = driver_utils.trajectory_for_bandit( initial_step, action_step, final_step) # Adds a 'time' dimension. return tf.nest.map_structure( lambda x: tf.expand_dims(tf.convert_to_tensor(x), 1), single_experience) @test_util.run_all_in_graph_and_eager_modes class NeuralLinUCBAgentTest(tf.test.TestCase, parameterized.TestCase): def setUp(self): super(NeuralLinUCBAgentTest, self).setUp() tf.compat.v1.enable_resource_variables() @test_cases() def testInitializeAgentNumTrainSteps0(self, batch_size, context_dim): num_actions = 5 observation_spec = tensor_spec.TensorSpec([context_dim], tf.float32) time_step_spec = time_step.time_step_spec(observation_spec) action_spec = tensor_spec.BoundedTensorSpec( dtype=tf.int32, shape=(), minimum=0, maximum=num_actions - 1) encoder = DummyNet(observation_spec) agent = neural_linucb_agent.NeuralLinUCBAgent( time_step_spec=time_step_spec, action_spec=action_spec, encoding_network=encoder, encoding_network_num_train_steps=0, encoding_dim=10, optimizer=None) self.evaluate(agent.initialize()) @test_cases() def testInitializeAgentNumTrainSteps10(self, batch_size, context_dim): num_actions = 5 observation_spec = tensor_spec.TensorSpec([context_dim], tf.float32) time_step_spec = time_step.time_step_spec(observation_spec) action_spec = tensor_spec.BoundedTensorSpec( dtype=tf.int32, shape=(), minimum=0, maximum=num_actions - 1) encoder = DummyNet(observation_spec) agent = neural_linucb_agent.NeuralLinUCBAgent( time_step_spec=time_step_spec, action_spec=action_spec, encoding_network=encoder, encoding_network_num_train_steps=10, encoding_dim=10, optimizer=None) self.evaluate(agent.initialize()) @test_cases() def testNeuralLinUCBUpdateNumTrainSteps0(self, batch_size=1, context_dim=10): """Check NeuralLinUCBAgent updates when behaving like LinUCB.""" # Construct a `Trajectory` for the given action, observation, reward. num_actions = 5 initial_step, final_step = _get_initial_and_final_steps( batch_size, context_dim) action = np.random.randint(num_actions, size=batch_size, dtype=np.int32) action_step = _get_action_step(action) experience = _get_experience(initial_step, action_step, final_step) # Construct an agent and perform the update. observation_spec = tensor_spec.TensorSpec([context_dim], tf.float32) time_step_spec = time_step.time_step_spec(observation_spec) action_spec = tensor_spec.BoundedTensorSpec( dtype=tf.int32, shape=(), minimum=0, maximum=num_actions - 1) encoder = DummyNet(observation_spec) encoding_dim = 10 agent = neural_linucb_agent.NeuralLinUCBAgent( time_step_spec=time_step_spec, action_spec=action_spec, encoding_network=encoder, encoding_network_num_train_steps=0, encoding_dim=encoding_dim, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=1e-2)) loss_info = agent.train(experience) self.evaluate(agent.initialize()) self.evaluate(tf.compat.v1.global_variables_initializer()) self.evaluate(loss_info) final_a = self.evaluate(agent.cov_matrix) final_b = self.evaluate(agent.data_vector) # Compute the expected updated estimates. observations_list = tf.dynamic_partition( data=tf.reshape(tf.cast(experience.observation, tf.float64), [batch_size, context_dim]), partitions=tf.convert_to_tensor(action), num_partitions=num_actions) rewards_list = tf.dynamic_partition( data=tf.reshape(tf.cast(experience.reward, tf.float64), [batch_size]), partitions=tf.convert_to_tensor(action), num_partitions=num_actions) expected_a_updated_list = [] expected_b_updated_list = [] for _, (observations_for_arm, rewards_for_arm) in enumerate(zip( observations_list, rewards_list)): encoded_observations_for_arm, _ = encoder(observations_for_arm) encoded_observations_for_arm = tf.cast( encoded_observations_for_arm, dtype=tf.float64) num_samples_for_arm_current = tf.cast( tf.shape(rewards_for_arm)[0], tf.float64) num_samples_for_arm_total = num_samples_for_arm_current # pylint: disable=cell-var-from-loop def true_fn(): a_new = tf.matmul( encoded_observations_for_arm, encoded_observations_for_arm, transpose_a=True) b_new = bandit_utils.sum_reward_weighted_observations( rewards_for_arm, encoded_observations_for_arm) return a_new, b_new def false_fn(): return (tf.zeros([encoding_dim, encoding_dim], dtype=tf.float64), tf.zeros([encoding_dim], dtype=tf.float64)) a_new, b_new = tf.cond( tf.squeeze(num_samples_for_arm_total) > 0, true_fn, false_fn) expected_a_updated_list.append(self.evaluate(a_new)) expected_b_updated_list.append(self.evaluate(b_new)) # Check that the actual updated estimates match the expectations. self.assertAllClose(expected_a_updated_list, final_a) self.assertAllClose(expected_b_updated_list, final_b) @test_cases() def testNeuralLinUCBUpdateDistributed(self, batch_size=1, context_dim=10): """Same as above but with distributed LinUCB updates.""" # Construct a `Trajectory` for the given action, observation, reward. num_actions = 5 initial_step, final_step = _get_initial_and_final_steps( batch_size, context_dim) action = np.random.randint(num_actions, size=batch_size, dtype=np.int32) action_step = _get_action_step(action) experience = _get_experience(initial_step, action_step, final_step) # Construct an agent and perform the update. observation_spec = tensor_spec.TensorSpec([context_dim], tf.float32) time_step_spec = time_step.time_step_spec(observation_spec) action_spec = tensor_spec.BoundedTensorSpec( dtype=tf.int32, shape=(), minimum=0, maximum=num_actions - 1) encoder = DummyNet(observation_spec) encoding_dim = 10 agent = neural_linucb_agent.NeuralLinUCBAgent( time_step_spec=time_step_spec, action_spec=action_spec, encoding_network=encoder, encoding_network_num_train_steps=0, encoding_dim=encoding_dim, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=1e-2)) self.evaluate(agent.initialize()) self.evaluate(tf.compat.v1.global_variables_initializer()) # Call the distributed LinUCB training instead of agent.train(). train_fn = common.function_in_tf1()( agent.compute_loss_using_linucb_distributed) reward = tf.cast(experience.reward, agent._dtype) loss_info = train_fn( experience.observation, action, reward, weights=None) self.evaluate(loss_info) final_a = self.evaluate(agent.cov_matrix) final_b = self.evaluate(agent.data_vector) # Compute the expected updated estimates. observations_list = tf.dynamic_partition( data=tf.reshape(tf.cast(experience.observation, tf.float64), [batch_size, context_dim]), partitions=tf.convert_to_tensor(action), num_partitions=num_actions) rewards_list = tf.dynamic_partition( data=tf.reshape(tf.cast(experience.reward, tf.float64), [batch_size]), partitions=tf.convert_to_tensor(action), num_partitions=num_actions) expected_a_updated_list = [] expected_b_updated_list = [] for _, (observations_for_arm, rewards_for_arm) in enumerate(zip( observations_list, rewards_list)): encoded_observations_for_arm, _ = encoder(observations_for_arm) encoded_observations_for_arm = tf.cast( encoded_observations_for_arm, dtype=tf.float64) num_samples_for_arm_current = tf.cast( tf.shape(rewards_for_arm)[0], tf.float64) num_samples_for_arm_total = num_samples_for_arm_current # pylint: disable=cell-var-from-loop def true_fn(): a_new = tf.matmul( encoded_observations_for_arm, encoded_observations_for_arm, transpose_a=True) b_new = bandit_utils.sum_reward_weighted_observations( rewards_for_arm, encoded_observations_for_arm) return a_new, b_new def false_fn(): return (tf.zeros([encoding_dim, encoding_dim], dtype=tf.float64), tf.zeros([encoding_dim], dtype=tf.float64)) a_new, b_new = tf.cond( tf.squeeze(num_samples_for_arm_total) > 0, true_fn, false_fn) expected_a_updated_list.append(self.evaluate(a_new)) expected_b_updated_list.append(self.evaluate(b_new)) # Check that the actual updated estimates match the expectations. self.assertAllClose(expected_a_updated_list, final_a) self.assertAllClose(expected_b_updated_list, final_b) @test_cases() def testNeuralLinUCBUpdateNumTrainSteps10(self, batch_size=1, context_dim=10): """Check NeuralLinUCBAgent updates when behaving like eps-greedy.""" # Construct a `Trajectory` for the given action, observation, reward. num_actions = 5 initial_step, final_step = _get_initial_and_final_steps( batch_size, context_dim) action = np.random.randint(num_actions, size=batch_size, dtype=np.int32) action_step = _get_action_step(action) experience = _get_experience(initial_step, action_step, final_step) # Construct an agent and perform the update. observation_spec = tensor_spec.TensorSpec([context_dim], tf.float32) time_step_spec = time_step.time_step_spec(observation_spec) action_spec = tensor_spec.BoundedTensorSpec( dtype=tf.int32, shape=(), minimum=0, maximum=num_actions - 1) encoder = DummyNet(observation_spec) encoding_dim = 10 variable_collection = neural_linucb_agent.NeuralLinUCBVariableCollection( num_actions, encoding_dim) agent = neural_linucb_agent.NeuralLinUCBAgent( time_step_spec=time_step_spec, action_spec=action_spec, encoding_network=encoder, encoding_network_num_train_steps=10, encoding_dim=encoding_dim, variable_collection=variable_collection, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=0.001)) loss_info, _ = agent.train(experience) self.evaluate(agent.initialize()) self.evaluate(tf.compat.v1.global_variables_initializer()) loss_value = self.evaluate(loss_info) self.assertGreater(loss_value, 0.0) @test_cases() def testNeuralLinUCBUpdateNumTrainSteps10MaskedActions( self, batch_size=1, context_dim=10): """Check updates when behaving like eps-greedy and using masked actions.""" # Construct a `Trajectory` for the given action, observation, reward. num_actions = 5 initial_step, final_step = _get_initial_and_final_steps_with_action_mask( batch_size, context_dim, num_actions) action = np.random.randint(num_actions, size=batch_size, dtype=np.int32) action_step = _get_action_step(action) experience = _get_experience(initial_step, action_step, final_step) # Construct an agent and perform the update. observation_spec = (tensor_spec.TensorSpec([context_dim], tf.float32), tensor_spec.TensorSpec([num_actions], tf.int32)) time_step_spec = time_step.time_step_spec(observation_spec) action_spec = tensor_spec.BoundedTensorSpec( dtype=tf.int32, shape=(), minimum=0, maximum=num_actions - 1) encoder = DummyNet(observation_spec[0]) encoding_dim = 10 agent = neural_linucb_agent.NeuralLinUCBAgent( time_step_spec=time_step_spec, action_spec=action_spec, encoding_network=encoder, encoding_network_num_train_steps=10, encoding_dim=encoding_dim, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=0.001), observation_and_action_constraint_splitter=lambda x: (x[0], x[1])) loss_info, _ = agent.train(experience) self.evaluate(agent.initialize()) self.evaluate(tf.compat.v1.global_variables_initializer()) loss_value = self.evaluate(loss_info) self.assertGreater(loss_value, 0.0) def testInitializeRestoreVariableCollection(self): if not tf.executing_eagerly(): self.skipTest('Test only works in eager mode.') num_actions = 5 encoding_dim = 7 variable_collection = neural_linucb_agent.NeuralLinUCBVariableCollection( num_actions=num_actions, encoding_dim=encoding_dim) self.evaluate(tf.compat.v1.global_variables_initializer()) self.evaluate(variable_collection.num_samples_list) checkpoint = tf.train.Checkpoint(variable_collection=variable_collection) checkpoint_dir = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_dir, 'checkpoint') checkpoint.save(file_prefix=checkpoint_prefix) variable_collection.actions_from_reward_layer.assign(False) latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir) checkpoint_load_status = checkpoint.restore(latest_checkpoint) self.evaluate(checkpoint_load_status.initialize_or_restore()) self.assertEqual( self.evaluate(variable_collection.actions_from_reward_layer), True) def testTrainPerArmAgentWithMask(self): num_actions = 5 obs_spec = bandit_spec_utils.create_per_arm_observation_spec( 2, 3, num_actions, add_action_mask=True) time_step_spec = time_step.time_step_spec(obs_spec) action_spec = tensor_spec.BoundedTensorSpec( dtype=tf.int32, shape=(), minimum=0, maximum=num_actions - 1) encoding_dim = 10 encoder = ( global_and_arm_feature_network.create_feed_forward_common_tower_network( obs_spec[0], (4, 3), (3, 4), (4, 2), encoding_dim)) agent = neural_linucb_agent.NeuralLinUCBAgent( time_step_spec=time_step_spec, action_spec=action_spec, encoding_network=encoder, encoding_network_num_train_steps=10, encoding_dim=encoding_dim, observation_and_action_constraint_splitter=lambda x: (x[0], x[1]), accepts_per_arm_features=True, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=0.001)) observations = ({ bandit_spec_utils.GLOBAL_FEATURE_KEY: tf.constant([[1, 2], [3, 4]], dtype=tf.float32), bandit_spec_utils.PER_ARM_FEATURE_KEY: tf.cast( tf.reshape(tf.range(30), shape=[2, 5, 3]), dtype=tf.float32) }, tf.ones(shape=(2, num_actions), dtype=tf.int32)) actions = np.array([0, 3], dtype=np.int32) rewards = np.array([0.5, 3.0], dtype=np.float32) initial_step = time_step.TimeStep( tf.constant( time_step.StepType.FIRST, dtype=tf.int32, shape=[2], name='step_type'), tf.constant(0.0, dtype=tf.float32, shape=[2], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[2], name='discount'), observations) final_step = time_step.TimeStep( tf.constant( time_step.StepType.LAST, dtype=tf.int32, shape=[2], name='step_type'), tf.constant(rewards, dtype=tf.float32, name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[2], name='discount'), observations) action_step = policy_step.PolicyStep( action=tf.convert_to_tensor(actions), info=policy_utilities.PerArmPolicyInfo( chosen_arm_features=np.array([[1, 2, 3], [3, 2, 1]], dtype=np.float32))) experience = _get_experience(initial_step, action_step, final_step) loss_info, _ = agent.train(experience, None) self.evaluate(tf.compat.v1.initialize_all_variables()) loss_value = self.evaluate(loss_info) self.assertGreater(loss_value, 0.0) def testTrainPerArmAgentVariableActions(self): num_actions = 5 obs_spec = bandit_spec_utils.create_per_arm_observation_spec( 2, 3, num_actions, add_num_actions_feature=True) time_step_spec = time_step.time_step_spec(obs_spec) action_spec = tensor_spec.BoundedTensorSpec( dtype=tf.int32, shape=(), minimum=0, maximum=num_actions - 1) encoding_dim = 10 encoder = ( global_and_arm_feature_network.create_feed_forward_common_tower_network( obs_spec, (4, 3), (3, 4), (4, 2), encoding_dim)) agent = neural_linucb_agent.NeuralLinUCBAgent( time_step_spec=time_step_spec, action_spec=action_spec, encoding_network=encoder, encoding_network_num_train_steps=10, encoding_dim=encoding_dim, accepts_per_arm_features=True, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=0.001)) observations = { bandit_spec_utils.GLOBAL_FEATURE_KEY: tf.constant([[1, 2], [3, 4]], dtype=tf.float32), bandit_spec_utils.PER_ARM_FEATURE_KEY: tf.cast( tf.reshape(tf.range(30), shape=[2, 5, 3]), dtype=tf.float32), bandit_spec_utils.NUM_ACTIONS_FEATURE_KEY: tf.constant([3, 4], dtype=tf.int32) } actions = np.array([0, 3], dtype=np.int32) rewards = np.array([0.5, 3.0], dtype=np.float32) initial_step = time_step.TimeStep( tf.constant( time_step.StepType.FIRST, dtype=tf.int32, shape=[2], name='step_type'), tf.constant(0.0, dtype=tf.float32, shape=[2], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[2], name='discount'), observations) final_step = time_step.TimeStep( tf.constant( time_step.StepType.LAST, dtype=tf.int32, shape=[2], name='step_type'), tf.constant(rewards, dtype=tf.float32, name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[2], name='discount'), observations) action_step = policy_step.PolicyStep( action=tf.convert_to_tensor(actions), info=policy_utilities.PerArmPolicyInfo( chosen_arm_features=np.array([[1, 2, 3], [3, 2, 1]], dtype=np.float32))) experience = _get_experience(initial_step, action_step, final_step) loss_info, _ = agent.train(experience, None) self.evaluate(tf.compat.v1.initialize_all_variables()) loss_value = self.evaluate(loss_info) self.assertGreater(loss_value, 0.0) if __name__ == '__main__': tf.test.main()
[ "tensorflow.train.Checkpoint", "tensorflow.shape", "tensorflow.compat.v1.train.AdamOptimizer", "tf_agents.specs.tensor_spec.BoundedTensorSpec", "numpy.array", "tf_agents.trajectories.time_step.time_step_spec", "tensorflow.cast", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.eye", "tf_agents.bandits.agents.neural_linucb_agent.NeuralLinUCBAgent", "tensorflow.executing_eagerly", "tf_agents.bandits.specs.utils.create_per_arm_observation_spec", "tf_agents.bandits.drivers.driver_utils.trajectory_for_bandit", "tf_agents.bandits.policies.policy_utilities.PolicyInfo", "tensorflow.matmul", "tf_agents.bandits.networks.global_and_arm_feature_network.create_feed_forward_common_tower_network", "tensorflow.convert_to_tensor", "tensorflow.zeros", "tf_agents.specs.tensor_spec.TensorSpec", "numpy.ones", "tf_agents.bandits.agents.utils.sum_reward_weighted_observations", "tensorflow.compat.v1.enable_resource_variables", "tensorflow.range", "tensorflow.squeeze", "tensorflow.train.latest_checkpoint", "tf_agents.bandits.agents.neural_linucb_agent.NeuralLinUCBVariableCollection", "tensorflow.ones", "os.path.join", "absl.testing.parameterized.named_parameters", "tensorflow.test.main", "numpy.random.randint", "numpy.zeros", "tensorflow.constant", "numpy.random.uniform", "tensorflow.compat.v1.initialize_all_variables", "tf_agents.utils.common.function_in_tf1" ]
[((2541, 2735), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': '_batch1_contextdim10', 'batch_size': 1, 'context_dim': 10}", "{'testcase_name': '_batch4_contextdim5', 'batch_size': 4, 'context_dim': 5}"], {}), "({'testcase_name': '_batch1_contextdim10',\n 'batch_size': 1, 'context_dim': 10}, {'testcase_name':\n '_batch4_contextdim5', 'batch_size': 4, 'context_dim': 5})\n", (2571, 2735), False, 'from absl.testing import parameterized\n'), ((2985, 3026), 'numpy.random.uniform', 'np.random.uniform', (['(0.0)', '(1.0)', '[batch_size]'], {}), '(0.0, 1.0, [batch_size])\n', (3002, 3026), True, 'import numpy as np\n'), ((4249, 4291), 'tensorflow.constant', 'tf.constant', (['observation'], {'dtype': 'tf.float32'}), '(observation, dtype=tf.float32)\n', (4260, 4291), True, 'import tensorflow as tf\n'), ((4376, 4417), 'numpy.random.uniform', 'np.random.uniform', (['(0.0)', '(1.0)', '[batch_size]'], {}), '(0.0, 1.0, [batch_size])\n', (4393, 4417), True, 'import numpy as np\n'), ((5414, 5487), 'tf_agents.bandits.drivers.driver_utils.trajectory_for_bandit', 'driver_utils.trajectory_for_bandit', (['initial_step', 'action_step', 'final_step'], {}), '(initial_step, action_step, final_step)\n', (5448, 5487), False, 'from tf_agents.bandits.drivers import driver_utils\n'), ((23937, 23951), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (23949, 23951), True, 'import tensorflow as tf\n'), ((2385, 2412), 'tensorflow.cast', 'tf.cast', (['inputs', 'tf.float32'], {}), '(inputs, tf.float32)\n', (2392, 2412), True, 'import tensorflow as tf\n'), ((3070, 3165), 'tensorflow.constant', 'tf.constant', (['time_step.StepType.FIRST'], {'dtype': 'tf.int32', 'shape': '[batch_size]', 'name': '"""step_type"""'}), "(time_step.StepType.FIRST, dtype=tf.int32, shape=[batch_size],\n name='step_type')\n", (3081, 3165), True, 'import tensorflow as tf\n'), ((3190, 3259), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {'dtype': 'tf.float32', 'shape': '[batch_size]', 'name': '"""reward"""'}), "(0.0, dtype=tf.float32, shape=[batch_size], name='reward')\n", (3201, 3259), True, 'import tensorflow as tf\n'), ((3267, 3338), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32', 'shape': '[batch_size]', 'name': '"""discount"""'}), "(1.0, dtype=tf.float32, shape=[batch_size], name='discount')\n", (3278, 3338), True, 'import tensorflow as tf\n'), ((3346, 3445), 'tensorflow.constant', 'tf.constant', (['observation'], {'dtype': 'tf.float32', 'shape': '[batch_size, context_dim]', 'name': '"""observation"""'}), "(observation, dtype=tf.float32, shape=[batch_size, context_dim],\n name='observation')\n", (3357, 3445), True, 'import tensorflow as tf\n'), ((3502, 3596), 'tensorflow.constant', 'tf.constant', (['time_step.StepType.LAST'], {'dtype': 'tf.int32', 'shape': '[batch_size]', 'name': '"""step_type"""'}), "(time_step.StepType.LAST, dtype=tf.int32, shape=[batch_size],\n name='step_type')\n", (3513, 3596), True, 'import tensorflow as tf\n'), ((3621, 3693), 'tensorflow.constant', 'tf.constant', (['reward'], {'dtype': 'tf.float32', 'shape': '[batch_size]', 'name': '"""reward"""'}), "(reward, dtype=tf.float32, shape=[batch_size], name='reward')\n", (3632, 3693), True, 'import tensorflow as tf\n'), ((3701, 3772), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32', 'shape': '[batch_size]', 'name': '"""discount"""'}), "(1.0, dtype=tf.float32, shape=[batch_size], name='discount')\n", (3712, 3772), True, 'import tensorflow as tf\n'), ((3780, 3887), 'tensorflow.constant', 'tf.constant', (['(observation + 100.0)'], {'dtype': 'tf.float32', 'shape': '[batch_size, context_dim]', 'name': '"""observation"""'}), "(observation + 100.0, dtype=tf.float32, shape=[batch_size,\n context_dim], name='observation')\n", (3791, 3887), True, 'import tensorflow as tf\n'), ((4305, 4364), 'tensorflow.eye', 'tf.eye', (['batch_size'], {'num_columns': 'num_actions', 'dtype': 'tf.int32'}), '(batch_size, num_columns=num_actions, dtype=tf.int32)\n', (4311, 4364), True, 'import tensorflow as tf\n'), ((4461, 4556), 'tensorflow.constant', 'tf.constant', (['time_step.StepType.FIRST'], {'dtype': 'tf.int32', 'shape': '[batch_size]', 'name': '"""step_type"""'}), "(time_step.StepType.FIRST, dtype=tf.int32, shape=[batch_size],\n name='step_type')\n", (4472, 4556), True, 'import tensorflow as tf\n'), ((4601, 4670), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {'dtype': 'tf.float32', 'shape': '[batch_size]', 'name': '"""reward"""'}), "(0.0, dtype=tf.float32, shape=[batch_size], name='reward')\n", (4612, 4670), True, 'import tensorflow as tf\n'), ((4678, 4749), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32', 'shape': '[batch_size]', 'name': '"""discount"""'}), "(1.0, dtype=tf.float32, shape=[batch_size], name='discount')\n", (4689, 4749), True, 'import tensorflow as tf\n'), ((4819, 4913), 'tensorflow.constant', 'tf.constant', (['time_step.StepType.LAST'], {'dtype': 'tf.int32', 'shape': '[batch_size]', 'name': '"""step_type"""'}), "(time_step.StepType.LAST, dtype=tf.int32, shape=[batch_size],\n name='step_type')\n", (4830, 4913), True, 'import tensorflow as tf\n'), ((4958, 5030), 'tensorflow.constant', 'tf.constant', (['reward'], {'dtype': 'tf.float32', 'shape': '[batch_size]', 'name': '"""reward"""'}), "(reward, dtype=tf.float32, shape=[batch_size], name='reward')\n", (4969, 5030), True, 'import tensorflow as tf\n'), ((5038, 5109), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32', 'shape': '[batch_size]', 'name': '"""discount"""'}), "(1.0, dtype=tf.float32, shape=[batch_size], name='discount')\n", (5049, 5109), True, 'import tensorflow as tf\n'), ((5829, 5869), 'tensorflow.compat.v1.enable_resource_variables', 'tf.compat.v1.enable_resource_variables', ([], {}), '()\n', (5867, 5869), True, 'import tensorflow as tf\n'), ((6002, 6051), 'tf_agents.specs.tensor_spec.TensorSpec', 'tensor_spec.TensorSpec', (['[context_dim]', 'tf.float32'], {}), '([context_dim], tf.float32)\n', (6024, 6051), False, 'from tf_agents.specs import tensor_spec\n'), ((6073, 6115), 'tf_agents.trajectories.time_step.time_step_spec', 'time_step.time_step_spec', (['observation_spec'], {}), '(observation_spec)\n', (6097, 6115), False, 'from tf_agents.trajectories import time_step\n'), ((6134, 6230), 'tf_agents.specs.tensor_spec.BoundedTensorSpec', 'tensor_spec.BoundedTensorSpec', ([], {'dtype': 'tf.int32', 'shape': '()', 'minimum': '(0)', 'maximum': '(num_actions - 1)'}), '(dtype=tf.int32, shape=(), minimum=0, maximum=\n num_actions - 1)\n', (6163, 6230), False, 'from tf_agents.specs import tensor_spec\n'), ((6289, 6485), 'tf_agents.bandits.agents.neural_linucb_agent.NeuralLinUCBAgent', 'neural_linucb_agent.NeuralLinUCBAgent', ([], {'time_step_spec': 'time_step_spec', 'action_spec': 'action_spec', 'encoding_network': 'encoder', 'encoding_network_num_train_steps': '(0)', 'encoding_dim': '(10)', 'optimizer': 'None'}), '(time_step_spec=time_step_spec,\n action_spec=action_spec, encoding_network=encoder,\n encoding_network_num_train_steps=0, encoding_dim=10, optimizer=None)\n', (6326, 6485), False, 'from tf_agents.bandits.agents import neural_linucb_agent\n'), ((6698, 6747), 'tf_agents.specs.tensor_spec.TensorSpec', 'tensor_spec.TensorSpec', (['[context_dim]', 'tf.float32'], {}), '([context_dim], tf.float32)\n', (6720, 6747), False, 'from tf_agents.specs import tensor_spec\n'), ((6769, 6811), 'tf_agents.trajectories.time_step.time_step_spec', 'time_step.time_step_spec', (['observation_spec'], {}), '(observation_spec)\n', (6793, 6811), False, 'from tf_agents.trajectories import time_step\n'), ((6830, 6926), 'tf_agents.specs.tensor_spec.BoundedTensorSpec', 'tensor_spec.BoundedTensorSpec', ([], {'dtype': 'tf.int32', 'shape': '()', 'minimum': '(0)', 'maximum': '(num_actions - 1)'}), '(dtype=tf.int32, shape=(), minimum=0, maximum=\n num_actions - 1)\n', (6859, 6926), False, 'from tf_agents.specs import tensor_spec\n'), ((6985, 7182), 'tf_agents.bandits.agents.neural_linucb_agent.NeuralLinUCBAgent', 'neural_linucb_agent.NeuralLinUCBAgent', ([], {'time_step_spec': 'time_step_spec', 'action_spec': 'action_spec', 'encoding_network': 'encoder', 'encoding_network_num_train_steps': '(10)', 'encoding_dim': '(10)', 'optimizer': 'None'}), '(time_step_spec=time_step_spec,\n action_spec=action_spec, encoding_network=encoder,\n encoding_network_num_train_steps=10, encoding_dim=10, optimizer=None)\n', (7022, 7182), False, 'from tf_agents.bandits.agents import neural_linucb_agent\n'), ((7630, 7693), 'numpy.random.randint', 'np.random.randint', (['num_actions'], {'size': 'batch_size', 'dtype': 'np.int32'}), '(num_actions, size=batch_size, dtype=np.int32)\n', (7647, 7693), True, 'import numpy as np\n'), ((7882, 7931), 'tf_agents.specs.tensor_spec.TensorSpec', 'tensor_spec.TensorSpec', (['[context_dim]', 'tf.float32'], {}), '([context_dim], tf.float32)\n', (7904, 7931), False, 'from tf_agents.specs import tensor_spec\n'), ((7953, 7995), 'tf_agents.trajectories.time_step.time_step_spec', 'time_step.time_step_spec', (['observation_spec'], {}), '(observation_spec)\n', (7977, 7995), False, 'from tf_agents.trajectories import time_step\n'), ((8014, 8110), 'tf_agents.specs.tensor_spec.BoundedTensorSpec', 'tensor_spec.BoundedTensorSpec', ([], {'dtype': 'tf.int32', 'shape': '()', 'minimum': '(0)', 'maximum': '(num_actions - 1)'}), '(dtype=tf.int32, shape=(), minimum=0, maximum=\n num_actions - 1)\n', (8043, 8110), False, 'from tf_agents.specs import tensor_spec\n'), ((11064, 11127), 'numpy.random.randint', 'np.random.randint', (['num_actions'], {'size': 'batch_size', 'dtype': 'np.int32'}), '(num_actions, size=batch_size, dtype=np.int32)\n', (11081, 11127), True, 'import numpy as np\n'), ((11316, 11365), 'tf_agents.specs.tensor_spec.TensorSpec', 'tensor_spec.TensorSpec', (['[context_dim]', 'tf.float32'], {}), '([context_dim], tf.float32)\n', (11338, 11365), False, 'from tf_agents.specs import tensor_spec\n'), ((11387, 11429), 'tf_agents.trajectories.time_step.time_step_spec', 'time_step.time_step_spec', (['observation_spec'], {}), '(observation_spec)\n', (11411, 11429), False, 'from tf_agents.trajectories import time_step\n'), ((11448, 11544), 'tf_agents.specs.tensor_spec.BoundedTensorSpec', 'tensor_spec.BoundedTensorSpec', ([], {'dtype': 'tf.int32', 'shape': '()', 'minimum': '(0)', 'maximum': '(num_actions - 1)'}), '(dtype=tf.int32, shape=(), minimum=0, maximum=\n num_actions - 1)\n', (11477, 11544), False, 'from tf_agents.specs import tensor_spec\n'), ((12198, 12238), 'tensorflow.cast', 'tf.cast', (['experience.reward', 'agent._dtype'], {}), '(experience.reward, agent._dtype)\n', (12205, 12238), True, 'import tensorflow as tf\n'), ((14779, 14842), 'numpy.random.randint', 'np.random.randint', (['num_actions'], {'size': 'batch_size', 'dtype': 'np.int32'}), '(num_actions, size=batch_size, dtype=np.int32)\n', (14796, 14842), True, 'import numpy as np\n'), ((15031, 15080), 'tf_agents.specs.tensor_spec.TensorSpec', 'tensor_spec.TensorSpec', (['[context_dim]', 'tf.float32'], {}), '([context_dim], tf.float32)\n', (15053, 15080), False, 'from tf_agents.specs import tensor_spec\n'), ((15102, 15144), 'tf_agents.trajectories.time_step.time_step_spec', 'time_step.time_step_spec', (['observation_spec'], {}), '(observation_spec)\n', (15126, 15144), False, 'from tf_agents.trajectories import time_step\n'), ((15163, 15259), 'tf_agents.specs.tensor_spec.BoundedTensorSpec', 'tensor_spec.BoundedTensorSpec', ([], {'dtype': 'tf.int32', 'shape': '()', 'minimum': '(0)', 'maximum': '(num_actions - 1)'}), '(dtype=tf.int32, shape=(), minimum=0, maximum=\n num_actions - 1)\n', (15192, 15259), False, 'from tf_agents.specs import tensor_spec\n'), ((15353, 15430), 'tf_agents.bandits.agents.neural_linucb_agent.NeuralLinUCBVariableCollection', 'neural_linucb_agent.NeuralLinUCBVariableCollection', (['num_actions', 'encoding_dim'], {}), '(num_actions, encoding_dim)\n', (15403, 15430), False, 'from tf_agents.bandits.agents import neural_linucb_agent\n'), ((16456, 16519), 'numpy.random.randint', 'np.random.randint', (['num_actions'], {'size': 'batch_size', 'dtype': 'np.int32'}), '(num_actions, size=batch_size, dtype=np.int32)\n', (16473, 16519), True, 'import numpy as np\n'), ((16854, 16896), 'tf_agents.trajectories.time_step.time_step_spec', 'time_step.time_step_spec', (['observation_spec'], {}), '(observation_spec)\n', (16878, 16896), False, 'from tf_agents.trajectories import time_step\n'), ((16915, 17011), 'tf_agents.specs.tensor_spec.BoundedTensorSpec', 'tensor_spec.BoundedTensorSpec', ([], {'dtype': 'tf.int32', 'shape': '()', 'minimum': '(0)', 'maximum': '(num_actions - 1)'}), '(dtype=tf.int32, shape=(), minimum=0, maximum=\n num_actions - 1)\n', (16944, 17011), False, 'from tf_agents.specs import tensor_spec\n'), ((17904, 18010), 'tf_agents.bandits.agents.neural_linucb_agent.NeuralLinUCBVariableCollection', 'neural_linucb_agent.NeuralLinUCBVariableCollection', ([], {'num_actions': 'num_actions', 'encoding_dim': 'encoding_dim'}), '(num_actions=num_actions,\n encoding_dim=encoding_dim)\n', (17954, 18010), False, 'from tf_agents.bandits.agents import neural_linucb_agent\n'), ((18152, 18212), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {'variable_collection': 'variable_collection'}), '(variable_collection=variable_collection)\n', (18171, 18212), True, 'import tensorflow as tf\n'), ((18278, 18320), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""checkpoint"""'], {}), "(checkpoint_dir, 'checkpoint')\n", (18290, 18320), False, 'import os\n'), ((18462, 18504), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (18488, 18504), True, 'import tensorflow as tf\n'), ((18814, 18908), 'tf_agents.bandits.specs.utils.create_per_arm_observation_spec', 'bandit_spec_utils.create_per_arm_observation_spec', (['(2)', '(3)', 'num_actions'], {'add_action_mask': '(True)'}), '(2, 3, num_actions,\n add_action_mask=True)\n', (18863, 18908), True, 'from tf_agents.bandits.specs import utils as bandit_spec_utils\n'), ((18935, 18969), 'tf_agents.trajectories.time_step.time_step_spec', 'time_step.time_step_spec', (['obs_spec'], {}), '(obs_spec)\n', (18959, 18969), False, 'from tf_agents.trajectories import time_step\n'), ((18988, 19084), 'tf_agents.specs.tensor_spec.BoundedTensorSpec', 'tensor_spec.BoundedTensorSpec', ([], {'dtype': 'tf.int32', 'shape': '()', 'minimum': '(0)', 'maximum': '(num_actions - 1)'}), '(dtype=tf.int32, shape=(), minimum=0, maximum=\n num_actions - 1)\n', (19017, 19084), False, 'from tf_agents.specs import tensor_spec\n'), ((19135, 19262), 'tf_agents.bandits.networks.global_and_arm_feature_network.create_feed_forward_common_tower_network', 'global_and_arm_feature_network.create_feed_forward_common_tower_network', (['obs_spec[0]', '(4, 3)', '(3, 4)', '(4, 2)', 'encoding_dim'], {}), '(\n obs_spec[0], (4, 3), (3, 4), (4, 2), encoding_dim)\n', (19206, 19262), False, 'from tf_agents.bandits.networks import global_and_arm_feature_network\n'), ((20040, 20072), 'numpy.array', 'np.array', (['[0, 3]'], {'dtype': 'np.int32'}), '([0, 3], dtype=np.int32)\n', (20048, 20072), True, 'import numpy as np\n'), ((20087, 20125), 'numpy.array', 'np.array', (['[0.5, 3.0]'], {'dtype': 'np.float32'}), '([0.5, 3.0], dtype=np.float32)\n', (20095, 20125), True, 'import numpy as np\n'), ((21413, 21515), 'tf_agents.bandits.specs.utils.create_per_arm_observation_spec', 'bandit_spec_utils.create_per_arm_observation_spec', (['(2)', '(3)', 'num_actions'], {'add_num_actions_feature': '(True)'}), '(2, 3, num_actions,\n add_num_actions_feature=True)\n', (21462, 21515), True, 'from tf_agents.bandits.specs import utils as bandit_spec_utils\n'), ((21542, 21576), 'tf_agents.trajectories.time_step.time_step_spec', 'time_step.time_step_spec', (['obs_spec'], {}), '(obs_spec)\n', (21566, 21576), False, 'from tf_agents.trajectories import time_step\n'), ((21595, 21691), 'tf_agents.specs.tensor_spec.BoundedTensorSpec', 'tensor_spec.BoundedTensorSpec', ([], {'dtype': 'tf.int32', 'shape': '()', 'minimum': '(0)', 'maximum': '(num_actions - 1)'}), '(dtype=tf.int32, shape=(), minimum=0, maximum=\n num_actions - 1)\n', (21624, 21691), False, 'from tf_agents.specs import tensor_spec\n'), ((21742, 21866), 'tf_agents.bandits.networks.global_and_arm_feature_network.create_feed_forward_common_tower_network', 'global_and_arm_feature_network.create_feed_forward_common_tower_network', (['obs_spec', '(4, 3)', '(3, 4)', '(4, 2)', 'encoding_dim'], {}), '(\n obs_spec, (4, 3), (3, 4), (4, 2), encoding_dim)\n', (21813, 21866), False, 'from tf_agents.bandits.networks import global_and_arm_feature_network\n'), ((22618, 22650), 'numpy.array', 'np.array', (['[0, 3]'], {'dtype': 'np.int32'}), '([0, 3], dtype=np.int32)\n', (22626, 22650), True, 'import numpy as np\n'), ((22665, 22703), 'numpy.array', 'np.array', (['[0.5, 3.0]'], {'dtype': 'np.float32'}), '([0.5, 3.0], dtype=np.float32)\n', (22673, 22703), True, 'import numpy as np\n'), ((5258, 5286), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['action'], {}), '(action)\n', (5278, 5286), True, 'import tensorflow as tf\n'), ((5299, 5328), 'tf_agents.bandits.policies.policy_utilities.PolicyInfo', 'policy_utilities.PolicyInfo', ([], {}), '()\n', (5326, 5328), False, 'from tf_agents.bandits.policies import policy_utilities\n'), ((8583, 8626), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (8624, 8626), True, 'import tensorflow as tf\n'), ((9540, 9595), 'tensorflow.cast', 'tf.cast', (['encoded_observations_for_arm'], {'dtype': 'tf.float64'}), '(encoded_observations_for_arm, dtype=tf.float64)\n', (9547, 9595), True, 'import tensorflow as tf\n'), ((11977, 12020), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (12018, 12020), True, 'import tensorflow as tf\n'), ((12106, 12130), 'tf_agents.utils.common.function_in_tf1', 'common.function_in_tf1', ([], {}), '()\n', (12128, 12130), False, 'from tf_agents.utils import common\n'), ((13239, 13294), 'tensorflow.cast', 'tf.cast', (['encoded_observations_for_arm'], {'dtype': 'tf.float64'}), '(encoded_observations_for_arm, dtype=tf.float64)\n', (13246, 13294), True, 'import tensorflow as tf\n'), ((15899, 15942), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (15940, 15942), True, 'import tensorflow as tf\n'), ((16709, 16758), 'tf_agents.specs.tensor_spec.TensorSpec', 'tensor_spec.TensorSpec', (['[context_dim]', 'tf.float32'], {}), '([context_dim], tf.float32)\n', (16731, 16758), False, 'from tf_agents.specs import tensor_spec\n'), ((16784, 16831), 'tf_agents.specs.tensor_spec.TensorSpec', 'tensor_spec.TensorSpec', (['[num_actions]', 'tf.int32'], {}), '([num_actions], tf.int32)\n', (16806, 16831), False, 'from tf_agents.specs import tensor_spec\n'), ((17567, 17610), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (17608, 17610), True, 'import tensorflow as tf\n'), ((17759, 17781), 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), '()\n', (17779, 17781), True, 'import tensorflow as tf\n'), ((18034, 18077), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (18075, 18077), True, 'import tensorflow as tf\n'), ((19977, 20024), 'tensorflow.ones', 'tf.ones', ([], {'shape': '(2, num_actions)', 'dtype': 'tf.int32'}), '(shape=(2, num_actions), dtype=tf.int32)\n', (19984, 20024), True, 'import tensorflow as tf\n'), ((20173, 20260), 'tensorflow.constant', 'tf.constant', (['time_step.StepType.FIRST'], {'dtype': 'tf.int32', 'shape': '[2]', 'name': '"""step_type"""'}), "(time_step.StepType.FIRST, dtype=tf.int32, shape=[2], name=\n 'step_type')\n", (20184, 20260), True, 'import tensorflow as tf\n'), ((20314, 20374), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {'dtype': 'tf.float32', 'shape': '[2]', 'name': '"""reward"""'}), "(0.0, dtype=tf.float32, shape=[2], name='reward')\n", (20325, 20374), True, 'import tensorflow as tf\n'), ((20384, 20446), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32', 'shape': '[2]', 'name': '"""discount"""'}), "(1.0, dtype=tf.float32, shape=[2], name='discount')\n", (20395, 20446), True, 'import tensorflow as tf\n'), ((20515, 20601), 'tensorflow.constant', 'tf.constant', (['time_step.StepType.LAST'], {'dtype': 'tf.int32', 'shape': '[2]', 'name': '"""step_type"""'}), "(time_step.StepType.LAST, dtype=tf.int32, shape=[2], name=\n 'step_type')\n", (20526, 20601), True, 'import tensorflow as tf\n'), ((20655, 20708), 'tensorflow.constant', 'tf.constant', (['rewards'], {'dtype': 'tf.float32', 'name': '"""reward"""'}), "(rewards, dtype=tf.float32, name='reward')\n", (20666, 20708), True, 'import tensorflow as tf\n'), ((20718, 20780), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32', 'shape': '[2]', 'name': '"""discount"""'}), "(1.0, dtype=tf.float32, shape=[2], name='discount')\n", (20729, 20780), True, 'import tensorflow as tf\n'), ((21205, 21244), 'tensorflow.compat.v1.initialize_all_variables', 'tf.compat.v1.initialize_all_variables', ([], {}), '()\n', (21242, 21244), True, 'import tensorflow as tf\n'), ((22304, 22351), 'tensorflow.constant', 'tf.constant', (['[[1, 2], [3, 4]]'], {'dtype': 'tf.float32'}), '([[1, 2], [3, 4]], dtype=tf.float32)\n', (22315, 22351), True, 'import tensorflow as tf\n'), ((22562, 22597), 'tensorflow.constant', 'tf.constant', (['[3, 4]'], {'dtype': 'tf.int32'}), '([3, 4], dtype=tf.int32)\n', (22573, 22597), True, 'import tensorflow as tf\n'), ((22751, 22838), 'tensorflow.constant', 'tf.constant', (['time_step.StepType.FIRST'], {'dtype': 'tf.int32', 'shape': '[2]', 'name': '"""step_type"""'}), "(time_step.StepType.FIRST, dtype=tf.int32, shape=[2], name=\n 'step_type')\n", (22762, 22838), True, 'import tensorflow as tf\n'), ((22892, 22952), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {'dtype': 'tf.float32', 'shape': '[2]', 'name': '"""reward"""'}), "(0.0, dtype=tf.float32, shape=[2], name='reward')\n", (22903, 22952), True, 'import tensorflow as tf\n'), ((22962, 23024), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32', 'shape': '[2]', 'name': '"""discount"""'}), "(1.0, dtype=tf.float32, shape=[2], name='discount')\n", (22973, 23024), True, 'import tensorflow as tf\n'), ((23093, 23179), 'tensorflow.constant', 'tf.constant', (['time_step.StepType.LAST'], {'dtype': 'tf.int32', 'shape': '[2]', 'name': '"""step_type"""'}), "(time_step.StepType.LAST, dtype=tf.int32, shape=[2], name=\n 'step_type')\n", (23104, 23179), True, 'import tensorflow as tf\n'), ((23233, 23286), 'tensorflow.constant', 'tf.constant', (['rewards'], {'dtype': 'tf.float32', 'name': '"""reward"""'}), "(rewards, dtype=tf.float32, name='reward')\n", (23244, 23286), True, 'import tensorflow as tf\n'), ((23296, 23358), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32', 'shape': '[2]', 'name': '"""discount"""'}), "(1.0, dtype=tf.float32, shape=[2], name='discount')\n", (23307, 23358), True, 'import tensorflow as tf\n'), ((23783, 23822), 'tensorflow.compat.v1.initialize_all_variables', 'tf.compat.v1.initialize_all_variables', ([], {}), '()\n', (23820, 23822), True, 'import tensorflow as tf\n'), ((5587, 5610), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x'], {}), '(x)\n', (5607, 5610), True, 'import tensorflow as tf\n'), ((8432, 8484), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {'learning_rate': '(0.01)'}), '(learning_rate=0.01)\n', (8464, 8484), True, 'import tensorflow as tf\n'), ((8983, 9011), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['action'], {}), '(action)\n', (9003, 9011), True, 'import tensorflow as tf\n'), ((9188, 9216), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['action'], {}), '(action)\n', (9208, 9216), True, 'import tensorflow as tf\n'), ((9848, 9939), 'tensorflow.matmul', 'tf.matmul', (['encoded_observations_for_arm', 'encoded_observations_for_arm'], {'transpose_a': '(True)'}), '(encoded_observations_for_arm, encoded_observations_for_arm,\n transpose_a=True)\n', (9857, 9939), True, 'import tensorflow as tf\n'), ((9989, 10085), 'tf_agents.bandits.agents.utils.sum_reward_weighted_observations', 'bandit_utils.sum_reward_weighted_observations', (['rewards_for_arm', 'encoded_observations_for_arm'], {}), '(rewards_for_arm,\n encoded_observations_for_arm)\n', (10034, 10085), True, 'from tf_agents.bandits.agents import utils as bandit_utils\n'), ((11866, 11918), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {'learning_rate': '(0.01)'}), '(learning_rate=0.01)\n', (11898, 11918), True, 'import tensorflow as tf\n'), ((12682, 12710), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['action'], {}), '(action)\n', (12702, 12710), True, 'import tensorflow as tf\n'), ((12887, 12915), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['action'], {}), '(action)\n', (12907, 12915), True, 'import tensorflow as tf\n'), ((13547, 13638), 'tensorflow.matmul', 'tf.matmul', (['encoded_observations_for_arm', 'encoded_observations_for_arm'], {'transpose_a': '(True)'}), '(encoded_observations_for_arm, encoded_observations_for_arm,\n transpose_a=True)\n', (13556, 13638), True, 'import tensorflow as tf\n'), ((13688, 13784), 'tf_agents.bandits.agents.utils.sum_reward_weighted_observations', 'bandit_utils.sum_reward_weighted_observations', (['rewards_for_arm', 'encoded_observations_for_arm'], {}), '(rewards_for_arm,\n encoded_observations_for_arm)\n', (13733, 13784), True, 'from tf_agents.bandits.agents import utils as bandit_utils\n'), ((15744, 15797), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {'learning_rate': '(0.001)'}), '(learning_rate=0.001)\n', (15776, 15797), True, 'import tensorflow as tf\n'), ((17337, 17390), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {'learning_rate': '(0.001)'}), '(learning_rate=0.001)\n', (17369, 17390), True, 'import tensorflow as tf\n'), ((19641, 19694), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {'learning_rate': '(0.001)'}), '(learning_rate=0.001)\n', (19673, 19694), True, 'import tensorflow as tf\n'), ((19776, 19823), 'tensorflow.constant', 'tf.constant', (['[[1, 2], [3, 4]]'], {'dtype': 'tf.float32'}), '([[1, 2], [3, 4]], dtype=tf.float32)\n', (19787, 19823), True, 'import tensorflow as tf\n'), ((20861, 20890), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['actions'], {}), '(actions)\n', (20881, 20890), True, 'import tensorflow as tf\n'), ((22170, 22223), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {'learning_rate': '(0.001)'}), '(learning_rate=0.001)\n', (22202, 22223), True, 'import tensorflow as tf\n'), ((23439, 23468), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['actions'], {}), '(actions)\n', (23459, 23468), True, 'import tensorflow as tf\n'), ((8867, 8910), 'tensorflow.cast', 'tf.cast', (['experience.observation', 'tf.float64'], {}), '(experience.observation, tf.float64)\n', (8874, 8910), True, 'import tensorflow as tf\n'), ((9114, 9152), 'tensorflow.cast', 'tf.cast', (['experience.reward', 'tf.float64'], {}), '(experience.reward, tf.float64)\n', (9121, 9152), True, 'import tensorflow as tf\n'), ((9663, 9688), 'tensorflow.shape', 'tf.shape', (['rewards_for_arm'], {}), '(rewards_for_arm)\n', (9671, 9688), True, 'import tensorflow as tf\n'), ((10161, 10217), 'tensorflow.zeros', 'tf.zeros', (['[encoding_dim, encoding_dim]'], {'dtype': 'tf.float64'}), '([encoding_dim, encoding_dim], dtype=tf.float64)\n', (10169, 10217), True, 'import tensorflow as tf\n'), ((10235, 10277), 'tensorflow.zeros', 'tf.zeros', (['[encoding_dim]'], {'dtype': 'tf.float64'}), '([encoding_dim], dtype=tf.float64)\n', (10243, 10277), True, 'import tensorflow as tf\n'), ((10319, 10356), 'tensorflow.squeeze', 'tf.squeeze', (['num_samples_for_arm_total'], {}), '(num_samples_for_arm_total)\n', (10329, 10356), True, 'import tensorflow as tf\n'), ((12566, 12609), 'tensorflow.cast', 'tf.cast', (['experience.observation', 'tf.float64'], {}), '(experience.observation, tf.float64)\n', (12573, 12609), True, 'import tensorflow as tf\n'), ((12813, 12851), 'tensorflow.cast', 'tf.cast', (['experience.reward', 'tf.float64'], {}), '(experience.reward, tf.float64)\n', (12820, 12851), True, 'import tensorflow as tf\n'), ((13362, 13387), 'tensorflow.shape', 'tf.shape', (['rewards_for_arm'], {}), '(rewards_for_arm)\n', (13370, 13387), True, 'import tensorflow as tf\n'), ((13860, 13916), 'tensorflow.zeros', 'tf.zeros', (['[encoding_dim, encoding_dim]'], {'dtype': 'tf.float64'}), '([encoding_dim, encoding_dim], dtype=tf.float64)\n', (13868, 13916), True, 'import tensorflow as tf\n'), ((13934, 13976), 'tensorflow.zeros', 'tf.zeros', (['[encoding_dim]'], {'dtype': 'tf.float64'}), '([encoding_dim], dtype=tf.float64)\n', (13942, 13976), True, 'import tensorflow as tf\n'), ((14018, 14055), 'tensorflow.squeeze', 'tf.squeeze', (['num_samples_for_arm_total'], {}), '(num_samples_for_arm_total)\n', (14028, 14055), True, 'import tensorflow as tf\n'), ((22448, 22460), 'tensorflow.range', 'tf.range', (['(30)'], {}), '(30)\n', (22456, 22460), True, 'import tensorflow as tf\n'), ((2140, 2176), 'numpy.ones', 'np.ones', (['[context_dim, encoding_dim]'], {}), '([context_dim, encoding_dim])\n', (2147, 2176), True, 'import numpy as np\n'), ((2260, 2284), 'numpy.zeros', 'np.zeros', (['[encoding_dim]'], {}), '([encoding_dim])\n', (2268, 2284), True, 'import numpy as np\n'), ((19920, 19932), 'tensorflow.range', 'tf.range', (['(30)'], {}), '(30)\n', (19928, 19932), True, 'import tensorflow as tf\n'), ((20972, 21022), 'numpy.array', 'np.array', (['[[1, 2, 3], [3, 2, 1]]'], {'dtype': 'np.float32'}), '([[1, 2, 3], [3, 2, 1]], dtype=np.float32)\n', (20980, 21022), True, 'import numpy as np\n'), ((23550, 23600), 'numpy.array', 'np.array', (['[[1, 2, 3], [3, 2, 1]]'], {'dtype': 'np.float32'}), '([[1, 2, 3], [3, 2, 1]], dtype=np.float32)\n', (23558, 23600), True, 'import numpy as np\n')]
from __future__ import print_function, absolute_import from distutils import sysconfig from distutils import version from distutils.core import Extension import glob import io import multiprocessing import os import re import subprocess import sys import warnings from textwrap import fill PY3 = (sys.version_info[0] >= 3) try: from subprocess import check_output except ImportError: # check_output is not available in Python 2.6 def check_output(*popenargs, **kwargs): """ Run command with arguments and return its output as a byte string. Backported from Python 2.7 as it's implemented as pure python on stdlib. """ process = subprocess.Popen( stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] error = subprocess.CalledProcessError(retcode, cmd) error.output = output raise error return output if sys.platform != 'win32': if sys.version_info[0] < 3: from commands import getstatusoutput else: from subprocess import getstatusoutput if PY3: import configparser else: import ConfigParser as configparser # matplotlib build options, which can be altered using setup.cfg options = { 'display_status': True, 'verbose': False, 'backend': None, 'basedirlist': None } setup_cfg = os.environ.get('MPLSETUPCFG', 'setup.cfg') if os.path.exists(setup_cfg): config = configparser.SafeConfigParser() config.read(setup_cfg) try: options['display_status'] = not config.getboolean("status", "suppress") except: pass try: options['backend'] = config.get("rc_options", "backend") except: pass try: options['basedirlist'] = [ x.strip() for x in config.get("directories", "basedirlist").split(',')] except: pass else: config = None def get_win32_compiler(): """ Determine the compiler being used on win32. """ # Used to determine mingw32 or msvc # This is pretty bad logic, someone know a better way? for v in sys.argv: if 'mingw32' in v: return 'mingw32' return 'msvc' win32_compiler = get_win32_compiler() def extract_versions(): """ Extracts version values from the main matplotlib __init__.py and returns them as a dictionary. """ with open('lib/matplotlib/__init__.py') as fd: for line in fd.readlines(): if (line.startswith('__version__')): exec(line.strip()) return locals() def has_include_file(include_dirs, filename): """ Returns `True` if `filename` can be found in one of the directories in `include_dirs`. """ for dir in include_dirs: if os.path.exists(os.path.join(dir, filename)): return True return False def check_include_file(include_dirs, filename, package): """ Raises an exception if the given include file can not be found. """ if sys.platform == 'win32': include_dirs.extend(os.getenv('INCLUDE', '.').split(';')) if not has_include_file(include_dirs, filename): raise CheckFailed( "The C/C++ header for %s (%s) could not be found. You " "may need to install the development package." % (package, filename)) def get_base_dirs(): """ Returns a list of standard base directories on this platform. """ if options['basedirlist']: return options['basedirlist'] basedir_map = { 'win32': ['win32_static',], 'darwin': ['/usr/local/', '/usr', '/usr/X11', '/opt/local'], 'sunos5': [os.getenv('MPLIB_BASE') or '/usr/local',], 'gnu0': ['/usr'], 'aix5': ['/usr/local'], } return basedir_map.get(sys.platform, ['/usr/local', '/usr']) def is_min_version(found, minversion): """ Returns `True` if `found` is at least as high a version as `minversion`. """ expected_version = version.LooseVersion(minversion) found_version = version.LooseVersion(found) return found_version >= expected_version # Define the display functions only if display_status is True. if options['display_status']: def print_line(char='='): print(char * 76) def print_status(package, status): initial_indent = "%22s: " % package indent = ' ' * 24 print(fill(str(status), width=76, initial_indent=initial_indent, subsequent_indent=indent)) def print_message(message): indent = ' ' * 24 + "* " print(fill(str(message), width=76, initial_indent=indent, subsequent_indent=indent)) def print_raw(section): print(section) else: def print_line(*args, **kwargs): pass print_status = print_message = print_raw = print_line # Remove the -Wstrict-prototypesoption, is it's not valid for C++ customize_compiler = sysconfig.customize_compiler def my_customize_compiler(compiler): retval = customize_compiler(compiler) try: compiler.compiler_so.remove('-Wstrict-prototypes') except (ValueError, AttributeError): pass return retval sysconfig.customize_compiler = my_customize_compiler def make_extension(name, files, *args, **kwargs): """ Make a new extension. Automatically sets include_dirs and library_dirs to the base directories appropriate for this platform. `name` is the name of the extension. `files` is a list of source files. Any additional arguments are passed to the `distutils.core.Extension` constructor. """ ext = DelayedExtension(name, files, *args, **kwargs) for dir in get_base_dirs(): include_dir = os.path.join(dir, 'include') if os.path.exists(include_dir): ext.include_dirs.append(include_dir) for lib in ('lib', 'lib64'): lib_dir = os.path.join(dir, lib) if os.path.exists(lib_dir): ext.library_dirs.append(lib_dir) ext.include_dirs.append('.') return ext class PkgConfig(object): """ This is a class for communicating with pkg-config. """ def __init__(self): """ Determines whether pkg-config exists on this machine. """ if sys.platform == 'win32': self.has_pkgconfig = False else: self.set_pkgconfig_path() status, output = getstatusoutput("pkg-config --help") self.has_pkgconfig = (status == 0) def set_pkgconfig_path(self): pkgconfig_path = sysconfig.get_config_var('LIBDIR') if pkgconfig_path is None: return pkgconfig_path = os.path.join(pkgconfig_path, 'pkgconfig') if not os.path.isdir(pkgconfig_path): return try: os.environ['PKG_CONFIG_PATH'] += ':' + pkgconfig_path except KeyError: os.environ['PKG_CONFIG_PATH'] = pkgconfig_path def setup_extension(self, ext, package, default_include_dirs=[], default_library_dirs=[], default_libraries=[], alt_exec=None): """ Add parameters to the given `ext` for the given `package`. """ flag_map = { '-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} executable = alt_exec if self.has_pkgconfig: executable = 'pkg-config {0}'.format(package) use_defaults = True if executable is not None: command = "{0} --libs --cflags ".format(executable) try: output = check_output(command, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: pass else: output = output.decode(sys.getfilesystemencoding()) use_defaults = False for token in output.split(): attr = flag_map.get(token[:2]) if attr is not None: getattr(ext, attr).insert(0, token[2:]) if use_defaults: basedirs = get_base_dirs() for base in basedirs: for include in default_include_dirs: dir = os.path.join(base, include) if os.path.exists(dir): ext.include_dirs.append(dir) for lib in default_library_dirs: dir = os.path.join(base, lib) if os.path.exists(dir): ext.library_dirs.append(dir) ext.libraries.extend(default_libraries) return True return False def get_version(self, package): """ Get the version of the package from pkg-config. """ if not self.has_pkgconfig: return None status, output = getstatusoutput( "pkg-config %s --modversion" % (package)) if status == 0: return output return None # The PkgConfig class should be used through this singleton pkg_config = PkgConfig() class CheckFailed(Exception): """ Exception thrown when a `SetupPackage.check` method fails. """ pass class SetupPackage(object): optional = False def check(self): """ Checks whether the dependencies are met. Should raise a `CheckFailed` exception if the dependency could not be met, otherwise return a string indicating a version number or some other message indicating what was found. """ pass def get_packages(self): """ Get a list of package names to add to the configuration. These are added to the `packages` list passed to `distutils.setup`. """ return [] def get_namespace_packages(self): """ Get a list of namespace package names to add to the configuration. These are added to the `namespace_packages` list passed to `distutils.setup`. """ return [] def get_py_modules(self): """ Get a list of top-level modules to add to the configuration. These are added to the `py_modules` list passed to `distutils.setup`. """ return [] def get_package_data(self): """ Get a package data dictionary to add to the configuration. These are merged into to the `package_data` list passed to `distutils.setup`. """ return {} def get_extension(self): """ Get a list of C extensions (`distutils.core.Extension` objects) to add to the configuration. These are added to the `extensions` list passed to `distutils.setup`. """ return None def get_install_requires(self): """ Get a list of Python packages that we require. pip/easy_install will attempt to download and install this package if it is not installed. """ return [] def get_setup_requires(self): """ Get a list of Python packages that we require at build time. pip/easy_install will attempt to download and install this package if it is not installed. """ return [] def _check_for_pkg_config(self, package, include_file, min_version=None, version=None): """ A convenience function for writing checks for a pkg_config-defined dependency. `package` is the pkg_config package name. `include_file` is a top-level include file we expect to find. `min_version` is the minimum version required. `version` will override the found version if this package requires an alternate method for that. """ if version is None: version = pkg_config.get_version(package) if version is None: raise CheckFailed( "pkg-config information for '%s' could not be found." % package) if min_version == 'PATCH': raise CheckFailed( "Requires patches that have not been merged upstream.") if min_version: if (not is_min_version(version, min_version)): raise CheckFailed( "Requires %s %s or later. Found %s." % (package, min_version, version)) ext = self.get_extension() if ext is None: ext = make_extension('test', []) pkg_config.setup_extension(ext, package) check_include_file(ext.include_dirs, include_file, package) return 'version %s' % version class OptionalPackage(SetupPackage): optional = True force = False config_category = "packages" def get_config(self): """ Look at `setup.cfg` and return one of ["auto", True, False] indicating if the package is at default state ("auto"), forced by the user (True) or opted-out (False). """ try: return config.getboolean(self.config_category, self.name) except: return "auto" def check(self): """ Do not override this method! For custom dependency checks override self.check_requirements(). Two things are checked: Configuration file and requirements. """ # Check configuration file conf = self.get_config() # Default "auto" state or install forced by user if conf in [True, 'auto']: message = "installing" # Set non-optional if user sets `True` in config if conf is True: self.optional = False # Configuration opt-out by user else: # Some backend extensions (e.g. Agg) need to be built for certain # other GUI backends (e.g. TkAgg) even when manually disabled if self.force is True: message = "installing forced (config override)" else: raise CheckFailed("skipping due to configuration") # Check requirements and add extra information (if any) to message. # If requirements are not met a CheckFailed should be raised in there. additional_info = self.check_requirements() if additional_info: message += ", " + additional_info # No CheckFailed raised until now, return install message. return message def check_requirements(self): """ Override this method to do custom dependency checks. - Raise CheckFailed() if requirements are not met. - Return message with additional information, or an empty string (or None) for no additional information. """ return "" class OptionalBackendPackage(OptionalPackage): config_category = "gui_support" class Platform(SetupPackage): name = "platform" def check(self): return sys.platform class Python(SetupPackage): name = "python" def check(self): major, minor1, minor2, s, tmp = sys.version_info if major < 2: raise CheckFailed( "Requires Python 2.6 or later") elif major == 2 and minor1 < 6: raise CheckFailed( "Requires Python 2.6 or later (in the 2.x series)") elif major == 3 and minor1 < 1: raise CheckFailed( "Requires Python 3.1 or later (in the 3.x series)") return sys.version class Matplotlib(SetupPackage): name = "matplotlib" def check(self): return extract_versions()['__version__'] def get_packages(self): return [ 'matplotlib', 'matplotlib.backends', 'matplotlib.backends.qt_editor', 'matplotlib.compat', 'matplotlib.projections', 'matplotlib.axes', 'matplotlib.sphinxext', 'matplotlib.style', 'matplotlib.testing', 'matplotlib.testing.jpl_units', 'matplotlib.tri', ] def get_py_modules(self): return ['pylab'] def get_package_data(self): return { 'matplotlib': [ 'mpl-data/fonts/afm/*.afm', 'mpl-data/fonts/pdfcorefonts/*.afm', 'mpl-data/fonts/pdfcorefonts/*.txt', 'mpl-data/fonts/ttf/*.ttf', 'mpl-data/fonts/ttf/LICENSE_STIX', 'mpl-data/fonts/ttf/COPYRIGHT.TXT', 'mpl-data/fonts/ttf/README.TXT', 'mpl-data/fonts/ttf/RELEASENOTES.TXT', 'mpl-data/images/*.xpm', 'mpl-data/images/*.svg', 'mpl-data/images/*.gif', 'mpl-data/images/*.png', 'mpl-data/images/*.ppm', 'mpl-data/example/*.npy', 'mpl-data/matplotlibrc', 'backends/web_backend/*.*', 'backends/web_backend/jquery/js/*', 'backends/web_backend/jquery/css/themes/base/*.*', 'backends/web_backend/jquery/css/themes/base/images/*', 'backends/web_backend/css/*.*', 'backends/Matplotlib.nib/*', 'style/stylelib/*.mplstyle', ]} class SampleData(OptionalPackage): """ This handles the sample data that ships with matplotlib. It is technically optional, though most often will be desired. """ name = "sample_data" def get_package_data(self): return { 'matplotlib': [ 'mpl-data/sample_data/*.*', 'mpl-data/sample_data/axes_grid/*.*', ]} class Toolkits(OptionalPackage): name = "toolkits" def get_packages(self): return [ 'mpl_toolkits', 'mpl_toolkits.mplot3d', 'mpl_toolkits.axes_grid', 'mpl_toolkits.axes_grid1', 'mpl_toolkits.axisartist', ] def get_namespace_packages(self): return ['mpl_toolkits'] class Tests(OptionalPackage): name = "tests" nose_min_version = '0.11.1' def check(self): super(Tests, self).check() msgs = [] msg_template = ('{package} is required to run the matplotlib test ' 'suite. pip/easy_install may attempt to install it ' 'after matplotlib.') bad_nose = msg_template.format( package='nose %s or later' % self.nose_min_version ) try: import nose if is_min_version(nose.__version__, self.nose_min_version): msgs += ['using nose version %s' % nose.__version__] else: msgs += [bad_nose] except ImportError: msgs += [bad_nose] if sys.version_info >= (3, 3): msgs += ['using unittest.mock'] else: try: import mock msgs += ['using mock %s' % mock.__version__] except ImportError: msgs += [msg_template.format(package='mock')] return ' / '.join(msgs) def get_packages(self): return [ 'matplotlib.tests', ] def get_package_data(self): baseline_images = [ 'tests/baseline_images/%s/*' % x for x in os.listdir('lib/matplotlib/tests/baseline_images')] return { 'matplotlib': baseline_images + [ 'tests/mpltest.ttf', 'tests/test_rcparams.rc' ]} def get_install_requires(self): requires = ['nose>=%s' % self.nose_min_version] if not sys.version_info >= (3, 3): requires += ['mock'] return requires class DelayedExtension(Extension, object): """ A distutils Extension subclass where some of its members may have delayed computation until reaching the build phase. This is so we can, for example, get the Numpy include dirs after pip has installed Numpy for us if it wasn't already on the system. """ def __init__(self, *args, **kwargs): super(DelayedExtension, self).__init__(*args, **kwargs) self._finalized = False self._hooks = {} def add_hook(self, member, func): """ Add a hook to dynamically compute a member. Parameters ---------- member : string The name of the member func : callable The function to call to get dynamically-computed values for the member. """ self._hooks[member] = func def finalize(self): self._finalized = True class DelayedMember(property): def __init__(self, name): self._name = name def __get__(self, obj, objtype=None): result = getattr(obj, '_' + self._name, []) if obj._finalized: if self._name in obj._hooks: result = obj._hooks[self._name]() + result return result def __set__(self, obj, value): setattr(obj, '_' + self._name, value) include_dirs = DelayedMember('include_dirs') class Numpy(SetupPackage): name = "numpy" @staticmethod def include_dirs_hook(): if sys.version_info[0] >= 3: import builtins if hasattr(builtins, '__NUMPY_SETUP__'): del builtins.__NUMPY_SETUP__ import imp import numpy imp.reload(numpy) else: import __builtin__ if hasattr(__builtin__, '__NUMPY_SETUP__'): del __builtin__.__NUMPY_SETUP__ import numpy reload(numpy) ext = Extension('test', []) ext.include_dirs.append(numpy.get_include()) if not has_include_file( ext.include_dirs, os.path.join("numpy", "arrayobject.h")): warnings.warn( "The C headers for numpy could not be found. " "You may need to install the development package") return [numpy.get_include()] def check(self): min_version = extract_versions()['__version__numpy__'] try: import numpy except ImportError: return 'not found. pip may install it below.' if not is_min_version(numpy.__version__, min_version): raise SystemExit( "Requires numpy %s or later to build. (Found %s)" % (min_version, numpy.__version__)) return 'version %s' % numpy.__version__ def add_flags(self, ext): # Ensure that PY_ARRAY_UNIQUE_SYMBOL is uniquely defined for # each extension array_api_name = 'MPL_' + ext.name.replace('.', '_') + '_ARRAY_API' ext.define_macros.append(('PY_ARRAY_UNIQUE_SYMBOL', array_api_name)) ext.add_hook('include_dirs', self.include_dirs_hook) def get_setup_requires(self): return ['numpy>=1.5'] def get_install_requires(self): return ['numpy>=1.5'] class CXX(SetupPackage): name = 'pycxx' def check(self): if PY3: # There is no version of PyCXX in the wild that will work # with Python 3.x self.__class__.found_external = False return ("Official versions of PyCXX are not compatible with " "Python 3.x. Using local copy") self.__class__.found_external = True old_stdout = sys.stdout if PY3: sys.stdout = io.StringIO() else: sys.stdout = io.BytesIO() try: import CXX except ImportError: self.__class__.found_external = False return "Couldn't import. Using local copy." finally: sys.stdout = old_stdout try: return self._check_for_pkg_config( 'PyCXX', 'CXX/Extensions.hxx', min_version='6.2.4') except CheckFailed as e: # It's ok to just proceed here, since the `import CXX` # worked above, and PyCXX (at least upstream) ensures that # its header files are on the default distutils include # path (either in a standard C place such as /usr/include, # or in /usr/include/pythonX.Y. return 'Using system CXX (version unknown, no pkg-config info)' def add_flags(self, ext): if self.found_external and not 'sdist' in sys.argv: support_dir = os.path.normpath( os.path.join( sys.prefix, 'share', 'python%d.%d' % ( sys.version_info[0], sys.version_info[1]), 'CXX')) if not os.path.exists(support_dir): # On Fedora 17, these files are installed in /usr/share/CXX support_dir = '/usr/src/CXX' ext.sources.extend([ os.path.join(support_dir, x) for x in ['cxxsupport.cxx', 'cxx_extensions.cxx', 'IndirectPythonInterface.cxx', 'cxxextensions.c']]) pkg_config.setup_extension(ext, 'PyCXX') else: ext.include_dirs.append('extern') ext.sources.extend(glob.glob('extern/CXX/*.cxx')) ext.sources.extend(glob.glob('extern/CXX/*.c')) ext.define_macros.append(('PYCXX_ISO_CPP_LIB', '1')) if PY3: ext.define_macros.append(('PYCXX_PYTHON_2TO3', '1')) if not (sys.platform == 'win32' and win32_compiler == 'msvc'): ext.libraries.append('stdc++') ext.libraries.append('m') class LibAgg(SetupPackage): name = 'libagg' def check(self): self.__class__.found_external = True try: return self._check_for_pkg_config( 'libagg', 'agg2/agg_basics.h', min_version='PATCH') except CheckFailed as e: self.__class__.found_external = False return str(e) + ' Using local copy.' def add_flags(self, ext): if self.found_external: pkg_config.setup_extension(ext, 'libagg') else: ext.include_dirs.append('extern/agg24/include') agg_sources = [ 'agg_bezier_arc.cpp', 'agg_curves.cpp', 'agg_image_filters.cpp', 'agg_trans_affine.cpp', 'agg_vcgen_contour.cpp', 'agg_vcgen_dash.cpp', 'agg_vcgen_stroke.cpp', 'agg_vpgen_segmentator.cpp' ] ext.sources.extend( os.path.join('extern', 'agg24', 'src', x) for x in agg_sources) class FreeType(SetupPackage): name = "freetype" def check(self): if sys.platform == 'win32': return "Unknown version" status, output = getstatusoutput("freetype-config --version") if status == 0: version = output else: version = None return self._check_for_pkg_config( 'freetype2', 'ft2build.h', min_version='2.4', version=version) def add_flags(self, ext): pkg_config.setup_extension( ext, 'freetype2', default_include_dirs=[ 'freetype2', 'lib/freetype2/include', 'lib/freetype2/include/freetype2'], default_library_dirs=[ 'freetype2/lib'], default_libraries=['freetype', 'z'], alt_exec='freetype-config') def get_extension(self): ext = make_extension('freetype2', []) self.add_flags(ext) return ext class FT2Font(SetupPackage): name = 'ft2font' def get_extension(self): sources = [ 'src/ft2font.cpp', 'src/mplutils.cpp' ] ext = make_extension('matplotlib.ft2font', sources) FreeType().add_flags(ext) Numpy().add_flags(ext) CXX().add_flags(ext) return ext class Png(SetupPackage): name = "png" def check(self): try: return self._check_for_pkg_config( 'libpng', 'png.h', min_version='1.2') except CheckFailed as e: self.__class__.found_external = False return str(e) + ' Using unknown version.' def get_extension(self): sources = [ 'src/_png.cpp', 'src/mplutils.cpp' ] ext = make_extension('matplotlib._png', sources) pkg_config.setup_extension( ext, 'libpng', default_libraries=['png', 'z']) Numpy().add_flags(ext) CXX().add_flags(ext) return ext class Qhull(SetupPackage): name = "qhull" def check(self): self.__class__.found_external = True try: return self._check_for_pkg_config( 'qhull', 'qhull/qhull_a.h', min_version='2003.1') except CheckFailed as e: self.__class__.found_pkgconfig = False # Qhull may not be in the pkg-config system but may still be # present on this system, so check if the header files can be # found. include_dirs = [ os.path.join(x, 'include', 'qhull') for x in get_base_dirs()] if has_include_file(include_dirs, 'qhull_a.h'): return 'Using system Qhull (version unknown, no pkg-config info)' else: self.__class__.found_external = False return str(e) + ' Using local copy.' def add_flags(self, ext): if self.found_external: pkg_config.setup_extension(ext, 'qhull', default_libraries=['qhull']) else: ext.include_dirs.append('extern') ext.sources.extend(glob.glob('extern/qhull/*.c')) class TTConv(SetupPackage): name = "ttconv" def get_extension(self): sources = [ 'src/_ttconv.cpp', 'extern/ttconv/pprdrv_tt.cpp', 'extern/ttconv/pprdrv_tt2.cpp', 'extern/ttconv/ttutil.cpp' ] ext = make_extension('matplotlib.ttconv', sources) Numpy().add_flags(ext) CXX().add_flags(ext) ext.include_dirs.append('extern') return ext class Path(SetupPackage): name = "path" def get_extension(self): sources = [ 'src/_path.cpp', 'src/path_cleanup.cpp', 'src/agg_py_transforms.cpp' ] ext = make_extension('matplotlib._path', sources) Numpy().add_flags(ext) LibAgg().add_flags(ext) CXX().add_flags(ext) return ext class Image(SetupPackage): name = "image" def get_extension(self): sources = [ 'src/_image.cpp', 'src/mplutils.cpp' ] ext = make_extension('matplotlib._image', sources) Numpy().add_flags(ext) LibAgg().add_flags(ext) CXX().add_flags(ext) return ext class Contour(SetupPackage): name = "contour" def get_extension(self): sources = [ "src/cntr.c" ] ext = make_extension('matplotlib._cntr', sources) Numpy().add_flags(ext) return ext class Delaunay(SetupPackage): name = "delaunay" def get_packages(self): return ['matplotlib.delaunay'] def get_extension(self): sources = ["_delaunay.cpp", "VoronoiDiagramGenerator.cpp", "delaunay_utils.cpp", "natneighbors.cpp"] sources = [os.path.join('lib/matplotlib/delaunay', s) for s in sources] ext = make_extension('matplotlib._delaunay', sources) Numpy().add_flags(ext) return ext class QhullWrap(SetupPackage): name = "qhull_wrap" def get_extension(self): sources = ['src/qhull_wrap.c'] ext = make_extension('matplotlib._qhull', sources, define_macros=[('MPL_DEVNULL', os.devnull)]) Numpy().add_flags(ext) Qhull().add_flags(ext) return ext class Tri(SetupPackage): name = "tri" def get_extension(self): sources = [ "lib/matplotlib/tri/_tri.cpp", "src/mplutils.cpp" ] ext = make_extension('matplotlib._tri', sources) Numpy().add_flags(ext) CXX().add_flags(ext) return ext class Six(SetupPackage): name = "six" min_version = "1.3" def check(self): try: import six except ImportError: return ( "six was not found.") if not is_min_version(six.__version__, self.min_version): raise CheckFailed( "Requires six %s or later. Found %s." % (self.min_version, six.__version__)) return "using six version %s" % six.__version__ def get_install_requires(self): return ['six>={0}'.format(self.min_version)] class Dateutil(SetupPackage): name = "dateutil" def __init__(self, version=None): self.version = version def check(self): try: import dateutil except ImportError: # dateutil 2.1 has a file encoding bug that breaks installation on # python 3.3 # https://github.com/matplotlib/matplotlib/issues/2373 # hack around the problem by installing the the (working) v2.0 major, minor1, _, _, _ = sys.version_info if self.version is None and (major, minor1) == (3, 3): self.version = '!=2.1' return ( "dateutil was not found. It is required for date axis " "support. pip/easy_install may attempt to install it " "after matplotlib.") return "using dateutil version %s" % dateutil.__version__ def get_install_requires(self): dateutil = 'python-dateutil' if self.version is not None: dateutil += self.version return [dateutil] class Tornado(OptionalPackage): name = "tornado" def check(self): try: import tornado except ImportError: return ( "tornado was not found. It is required for the WebAgg " "backend. pip/easy_install may attempt to install it " "after matplotlib.") return "using tornado version %s" % tornado.version class Pyparsing(SetupPackage): name = "pyparsing" def is_ok(self): # pyparsing 2.0.0 bug, but it may be patched in distributions try: import pyparsing f = pyparsing.Forward() f <<= pyparsing.Literal('a') return f is not None except (ImportError, TypeError): return False def check(self): try: import pyparsing except ImportError: return ( "pyparsing was not found. It is required for mathtext " "support. pip/easy_install may attempt to install it " "after matplotlib.") required = [1, 5, 6] if [int(x) for x in pyparsing.__version__.split('.')] < required: return ( "matplotlib requires pyparsing >= {0}".format( '.'.join(str(x) for x in required))) if not self.is_ok(): return ( "Your pyparsing contains a bug that will be monkey-patched by " "matplotlib. For best results, upgrade to pyparsing 2.0.1 or " "later.") return "using pyparsing version %s" % pyparsing.__version__ def get_install_requires(self): if self.is_ok(): return ['pyparsing>=1.5.6'] else: return ['pyparsing>=1.5.6,!=2.0.0'] class BackendAgg(OptionalBackendPackage): name = "agg" def get_extension(self): sources = [ "src/mplutils.cpp", "src/agg_py_transforms.cpp", "src/_backend_agg.cpp" ] ext = make_extension('matplotlib.backends._backend_agg', sources) Numpy().add_flags(ext) LibAgg().add_flags(ext) FreeType().add_flags(ext) CXX().add_flags(ext) return ext class BackendTkAgg(OptionalBackendPackage): name = "tkagg" def __init__(self): self.tcl_tk_cache = None def check_requirements(self): try: if PY3: import tkinter as Tkinter else: import Tkinter except ImportError: raise CheckFailed('TKAgg requires Tkinter.') except RuntimeError: raise CheckFailed('Tkinter present but import failed.') else: if Tkinter.TkVersion < 8.3: raise CheckFailed("Tcl/Tk v8.3 or later required.") ext = self.get_extension() check_include_file(ext.include_dirs, "tk.h", "Tk") try: tk_v = Tkinter.__version__.split()[-2] except (AttributeError, IndexError): # Tkinter.__version__ has been removed in python 3 tk_v = 'version not identified' BackendAgg.force = True return "version %s" % tk_v def get_extension(self): sources = [ 'src/agg_py_transforms.cpp', 'src/_tkagg.cpp' ] ext = make_extension('matplotlib.backends._tkagg', sources) self.add_flags(ext) Numpy().add_flags(ext) LibAgg().add_flags(ext) CXX().add_flags(ext) return ext def query_tcltk(self): """ Tries to open a Tk window in order to query the Tk object about its library paths. This should never be called more than once by the same process, as Tk intricacies may cause the Python interpreter to hang. The function also has a workaround if no X server is running (useful for autobuild systems). """ # Use cached values if they exist, which ensures this function # only executes once if self.tcl_tk_cache is not None: return self.tcl_tk_cache # By this point, we already know that Tkinter imports correctly if PY3: import tkinter as Tkinter else: import Tkinter tcl_lib_dir = '' tk_lib_dir = '' # First try to open a Tk window (requires a running X server) try: tk = Tkinter.Tk() except Tkinter.TclError: # Next, start Tcl interpreter without opening a Tk window # (no need for X server) This feature is available in # python version 2.4 and up try: tcl = Tkinter.Tcl() except AttributeError: # Python version not high enough pass except Tkinter.TclError: # Something went wrong while opening Tcl pass else: tcl_lib_dir = str(tcl.getvar('tcl_library')) # Guess Tk location based on Tcl location (head, tail) = os.path.split(tcl_lib_dir) tail = tail.replace('Tcl', 'Tk').replace('tcl', 'tk') tk_lib_dir = os.path.join(head, tail) if not os.path.exists(tk_lib_dir): tk_lib_dir = tcl_lib_dir.replace( 'Tcl', 'Tk').replace('tcl', 'tk') else: # Obtain Tcl and Tk locations from Tk widget tk.withdraw() tcl_lib_dir = str(tk.getvar('tcl_library')) tk_lib_dir = str(tk.getvar('tk_library')) tk.destroy() # Save directories and version string to cache self.tcl_tk_cache = tcl_lib_dir, tk_lib_dir, str(Tkinter.TkVersion)[:3] return self.tcl_tk_cache def parse_tcl_config(self, tcl_lib_dir, tk_lib_dir): try: if PY3: import tkinter as Tkinter else: import Tkinter except ImportError: return None tcl_poss = [tcl_lib_dir, os.path.normpath(os.path.join(tcl_lib_dir, '..')), "/usr/lib/tcl" + str(Tkinter.TclVersion), "/usr/lib"] tk_poss = [tk_lib_dir, os.path.normpath(os.path.join(tk_lib_dir, '..')), "/usr/lib/tk" + str(Tkinter.TkVersion), "/usr/lib"] for ptcl, ptk in zip(tcl_poss, tk_poss): tcl_config = os.path.join(ptcl, "tclConfig.sh") tk_config = os.path.join(ptk, "tkConfig.sh") if (os.path.exists(tcl_config) and os.path.exists(tk_config)): break if not (os.path.exists(tcl_config) and os.path.exists(tk_config)): return None def get_var(file, varname): p = subprocess.Popen( '. %s ; eval echo ${%s}' % (file, varname), shell=True, executable="/bin/sh", stdout=subprocess.PIPE) result = p.communicate()[0] return result.decode('ascii') tcl_lib_dir = get_var( tcl_config, 'TCL_LIB_SPEC').split()[0][2:].strip() tcl_inc_dir = get_var( tcl_config, 'TCL_INCLUDE_SPEC')[2:].strip() tcl_lib = get_var(tcl_config, 'TCL_LIB_FLAG')[2:].strip() tk_lib_dir = get_var(tk_config, 'TK_LIB_SPEC').split()[0][2:].strip() tk_inc_dir = get_var(tk_config, 'TK_INCLUDE_SPEC').strip() if tk_inc_dir == '': tk_inc_dir = tcl_inc_dir else: tk_inc_dir = tk_inc_dir[2:] tk_lib = get_var(tk_config, 'TK_LIB_FLAG')[2:].strip() if not os.path.exists(os.path.join(tk_inc_dir, 'tk.h')): return None return (tcl_lib_dir, tcl_inc_dir, tcl_lib, tk_lib_dir, tk_inc_dir, tk_lib) def guess_tcl_config(self, tcl_lib_dir, tk_lib_dir, tk_ver): if not (os.path.exists(tcl_lib_dir) and os.path.exists(tk_lib_dir)): return None tcl_lib = os.path.normpath(os.path.join(tcl_lib_dir, '../')) tk_lib = os.path.normpath(os.path.join(tk_lib_dir, '../')) tcl_inc = os.path.normpath( os.path.join(tcl_lib_dir, '../../include/tcl' + tk_ver)) if not os.path.exists(tcl_inc): tcl_inc = os.path.normpath( os.path.join(tcl_lib_dir, '../../include')) tk_inc = os.path.normpath(os.path.join( tk_lib_dir, '../../include/tk' + tk_ver)) if not os.path.exists(tk_inc): tk_inc = os.path.normpath(os.path.join( tk_lib_dir, '../../include')) if not os.path.exists(os.path.join(tk_inc, 'tk.h')): tk_inc = tcl_inc if not os.path.exists(tcl_inc): # this is a hack for suse linux, which is broken if (sys.platform.startswith('linux') and os.path.exists('/usr/include/tcl.h') and os.path.exists('/usr/include/tk.h')): tcl_inc = '/usr/include' tk_inc = '/usr/include' if not os.path.exists(os.path.join(tk_inc, 'tk.h')): return None return tcl_lib, tcl_inc, 'tcl' + tk_ver, tk_lib, tk_inc, 'tk' + tk_ver def hardcoded_tcl_config(self): tcl_inc = "/usr/local/include" tk_inc = "/usr/local/include" tcl_lib = "/usr/local/lib" tk_lib = "/usr/local/lib" return tcl_lib, tcl_inc, 'tcl', tk_lib, tk_inc, 'tk' def add_flags(self, ext): if sys.platform == 'win32': major, minor1, minor2, s, tmp = sys.version_info if sys.version_info[0:2] < (3, 4): ext.include_dirs.extend(['win32_static/include/tcl85']) ext.libraries.extend(['tk85', 'tcl85']) else: ext.include_dirs.extend(['win32_static/include/tcl86']) ext.libraries.extend(['tk86t', 'tcl86t']) ext.library_dirs.extend([os.path.join(sys.prefix, 'dlls')]) elif sys.platform == 'darwin': # this config section lifted directly from Imaging - thanks to # the effbot! # First test for a MacOSX/darwin framework install from os.path import join, exists framework_dirs = [ join(os.getenv('HOME'), '/Library/Frameworks'), '/Library/Frameworks', '/System/Library/Frameworks/', ] # Find the directory that contains the Tcl.framework and # Tk.framework bundles. tk_framework_found = 0 for F in framework_dirs: # both Tcl.framework and Tk.framework should be present for fw in 'Tcl', 'Tk': if not exists(join(F, fw + '.framework')): break else: # ok, F is now directory with both frameworks. Continure # building tk_framework_found = 1 break if tk_framework_found: # For 8.4a2, we must add -I options that point inside # the Tcl and Tk frameworks. In later release we # should hopefully be able to pass the -F option to # gcc, which specifies a framework lookup path. tk_include_dirs = [ join(F, fw + '.framework', H) for fw in ('Tcl', 'Tk') for H in ('Headers', 'Versions/Current/PrivateHeaders') ] # For 8.4a2, the X11 headers are not included. Rather # than include a complicated search, this is a # hard-coded path. It could bail out if X11 libs are # not found... # tk_include_dirs.append('/usr/X11R6/include') frameworks = ['-framework', 'Tcl', '-framework', 'Tk'] ext.include_dirs.extend(tk_include_dirs) ext.extra_link_args.extend(frameworks) ext.extra_compile_args.extend(frameworks) # you're still here? ok we'll try it this way... else: # There are 3 methods to try, in decreasing order of "smartness" # # 1. Parse the tclConfig.sh and tkConfig.sh files that have # all the information we need # # 2. Guess the include and lib dirs based on the location of # Tkinter's 'tcl_library' and 'tk_library' variables. # # 3. Use some hardcoded locations that seem to work on a lot # of distros. # Query Tcl/Tk system for library paths and version string try: tcl_lib_dir, tk_lib_dir, tk_ver = self.query_tcltk() except: tk_ver = '' result = self.hardcoded_tcl_config() else: result = self.parse_tcl_config(tcl_lib_dir, tk_lib_dir) if result is None: result = self.guess_tcl_config( tcl_lib_dir, tk_lib_dir, tk_ver) if result is None: result = self.hardcoded_tcl_config() # Add final versions of directories and libraries to ext lists (tcl_lib_dir, tcl_inc_dir, tcl_lib, tk_lib_dir, tk_inc_dir, tk_lib) = result ext.include_dirs.extend([tcl_inc_dir, tk_inc_dir]) ext.library_dirs.extend([tcl_lib_dir, tk_lib_dir]) ext.libraries.extend([tcl_lib, tk_lib]) class BackendGtk(OptionalBackendPackage): name = "gtk" def check_requirements(self): try: import gtk except ImportError: raise CheckFailed("Requires pygtk") except RuntimeError: raise CheckFailed('pygtk present, but import failed.') else: version = (2, 2, 0) if gtk.pygtk_version < version: raise CheckFailed( "Requires pygtk %d.%d.%d or later. " "Found %d.%d.%d" % (version + gtk.pygtk_version)) ext = self.get_extension() self.add_flags(ext) check_include_file(ext.include_dirs, os.path.join("gtk", "gtk.h"), 'gtk') check_include_file(ext.include_dirs, os.path.join("pygtk", "pygtk.h"), 'pygtk') return 'Gtk: %s pygtk: %s' % ( ".".join(str(x) for x in gtk.gtk_version), ".".join(str(x) for x in gtk.pygtk_version)) def get_package_data(self): return {'matplotlib': ['mpl-data/*.glade']} def get_extension(self): sources = [ 'src/_backend_gdk.c' ] ext = make_extension('matplotlib.backends._backend_gdk', sources) self.add_flags(ext) Numpy().add_flags(ext) return ext def add_flags(self, ext): if sys.platform == 'win32': def getoutput(s): ret = os.popen(s).read().strip() return ret if 'PKG_CONFIG_PATH' not in os.environ: # If Gtk+ is installed, pkg-config is required to be installed os.environ['PKG_CONFIG_PATH'] = 'C:\\GTK\\lib\\pkgconfig' # popen broken on my win32 plaform so I can't use pkgconfig ext.library_dirs.extend( ['C:/GTK/bin', 'C:/GTK/lib']) ext.include_dirs.extend( ['win32_static/include/pygtk-2.0', 'C:/GTK/include', 'C:/GTK/include/gobject', 'C:/GTK/include/gext', 'C:/GTK/include/glib', 'C:/GTK/include/pango', 'C:/GTK/include/atk', 'C:/GTK/include/X11', 'C:/GTK/include/cairo', 'C:/GTK/include/gdk', 'C:/GTK/include/gdk-pixbuf', 'C:/GTK/include/gtk', ]) pygtkIncludes = getoutput( 'pkg-config --cflags-only-I pygtk-2.0').split() gtkIncludes = getoutput( 'pkg-config --cflags-only-I gtk+-2.0').split() includes = pygtkIncludes + gtkIncludes ext.include_dirs.extend([include[2:] for include in includes]) pygtkLinker = getoutput('pkg-config --libs pygtk-2.0').split() gtkLinker = getoutput('pkg-config --libs gtk+-2.0').split() linkerFlags = pygtkLinker + gtkLinker ext.libraries.extend( [flag[2:] for flag in linkerFlags if flag.startswith('-l')]) ext.library_dirs.extend( [flag[2:] for flag in linkerFlags if flag.startswith('-L')]) ext.extra_link_args.extend( [flag for flag in linkerFlags if not (flag.startswith('-l') or flag.startswith('-L'))]) # visual studio doesn't need the math library if (sys.platform == 'win32' and win32_compiler == 'msvc' and 'm' in ext.libraries): ext.libraries.remove('m') elif sys.platform != 'win32': pkg_config.setup_extension(ext, 'pygtk-2.0') pkg_config.setup_extension(ext, 'gtk+-2.0') class BackendGtkAgg(BackendGtk): name = "gtkagg" def check(self): try: return super(BackendGtkAgg, self).check() except: raise else: BackendAgg.force = True def get_package_data(self): return {'matplotlib': ['mpl-data/*.glade']} def get_extension(self): sources = [ 'src/agg_py_transforms.cpp', 'src/_gtkagg.cpp', 'src/mplutils.cpp' ] ext = make_extension('matplotlib.backends._gtkagg', sources) self.add_flags(ext) LibAgg().add_flags(ext) CXX().add_flags(ext) Numpy().add_flags(ext) return ext def backend_gtk3agg_internal_check(x): try: import gi except ImportError: return (False, "Requires pygobject to be installed.") try: gi.require_version("Gtk", "3.0") except ValueError: return (False, "Requires gtk3 development files to be installed.") except AttributeError: return (False, "pygobject version too old.") try: from gi.repository import Gtk, Gdk, GObject except (ImportError, RuntimeError): return (False, "Requires pygobject to be installed.") return (True, "version %s.%s.%s" % ( Gtk.get_major_version(), Gtk.get_micro_version(), Gtk.get_minor_version())) class BackendGtk3Agg(OptionalBackendPackage): name = "gtk3agg" def check_requirements(self): if 'TRAVIS' in os.environ: raise CheckFailed("Can't build with Travis") if PY3: raise CheckFailed("gtk3agg backend does not work on Python 3") # This check needs to be performed out-of-process, because # importing gi and then importing regular old pygtk afterward # segfaults the interpreter. try: p = multiprocessing.Pool() except: return "unknown (can not use multiprocessing to determine)" try: success, msg = p.map(backend_gtk3agg_internal_check, [0])[0] except: success = False msg = "Could not determine" finally: p.close() p.join() if success: BackendAgg.force = True return msg else: raise CheckFailed(msg) def get_package_data(self): return {'matplotlib': ['mpl-data/*.glade']} def backend_gtk3cairo_internal_check(x): try: import cairocffi except ImportError: try: import cairo except ImportError: return (False, "Requires cairocffi or pycairo to be installed.") try: import gi except ImportError: return (False, "Requires pygobject to be installed.") try: gi.require_version("Gtk", "3.0") except ValueError: return (False, "Requires gtk3 development files to be installed.") except AttributeError: return (False, "pygobject version too old.") try: from gi.repository import Gtk, Gdk, GObject except (RuntimeError, ImportError): return (False, "Requires pygobject to be installed.") return (True, "version %s.%s.%s" % ( Gtk.get_major_version(), Gtk.get_micro_version(), Gtk.get_minor_version())) class BackendGtk3Cairo(OptionalBackendPackage): name = "gtk3cairo" def check_requirements(self): if 'TRAVIS' in os.environ: raise CheckFailed("Can't build with Travis") # This check needs to be performed out-of-process, because # importing gi and then importing regular old pygtk afterward # segfaults the interpreter. try: p = multiprocessing.Pool() except: return "unknown (can not use multiprocessing to determine)" success, msg = p.map(backend_gtk3cairo_internal_check, [0])[0] p.close() p.join() if success: BackendAgg.force = True return msg else: raise CheckFailed(msg) def get_package_data(self): return {'matplotlib': ['mpl-data/*.glade']} class BackendWxAgg(OptionalBackendPackage): name = "wxagg" def check_requirements(self): try: import wxversion except ImportError: raise CheckFailed("requires wxPython") try: _wx_ensure_failed = wxversion.AlreadyImportedError except AttributeError: _wx_ensure_failed = wxversion.VersionError try: wxversion.ensureMinimal('2.8') except _wx_ensure_failed: pass try: import wx backend_version = wx.VERSION_STRING except ImportError: raise CheckFailed("requires wxPython") # Extra version check in case wxversion lacks AlreadyImportedError; # then VersionError might have been raised and ignored when # there really *is* a problem with the version. major, minor = [int(n) for n in backend_version.split('.')[:2]] if major < 2 or (major < 3 and minor < 8): raise CheckFailed( "Requires wxPython 2.8, found %s" % backend_version) BackendAgg.force = True return "version %s" % backend_version class BackendMacOSX(OptionalBackendPackage): name = 'macosx' def check_requirements(self): if sys.platform != 'darwin': raise CheckFailed("Mac OS-X only") return 'darwin' def get_extension(self): sources = [ 'src/_macosx.m', 'src/agg_py_transforms.cpp', 'src/path_cleanup.cpp' ] ext = make_extension('matplotlib.backends._macosx', sources) Numpy().add_flags(ext) LibAgg().add_flags(ext) CXX().add_flags(ext) ext.extra_link_args.extend(['-framework', 'Cocoa']) return ext class Windowing(OptionalBackendPackage): """ Builds the windowing extension. """ name = "windowing" def check_requirements(self): if sys.platform != 'win32': raise CheckFailed("Microsoft Windows only") config = self.get_config() if config is False: raise CheckFailed("skipping due to configuration") return "installing" def get_extension(self): sources = [ "src/_windowing.cpp" ] ext = make_extension('matplotlib._windowing', sources) ext.include_dirs.extend(['C:/include']) ext.libraries.extend(['user32']) ext.library_dirs.extend(['C:/lib']) ext.extra_link_args.append("-mwindows") return ext class BackendQtBase(OptionalBackendPackage): def convert_qt_version(self, version): version = '%x' % version temp = [] while len(version) > 0: version, chunk = version[:-2], version[-2:] temp.insert(0, str(int(chunk, 16))) return '.'.join(temp) def check_requirements(self): ''' If PyQt4/PyQt5 is already imported, importing PyQt5/PyQt4 will fail so we need to test in a subprocess (as for Gtk3). ''' try: p = multiprocessing.Pool() except: # Can't do multiprocessing, fall back to normal approach ( this will fail if importing both PyQt4 and PyQt5 ) try: # Try in-process msg = self.callback(self) except RuntimeError: raise CheckFailed("Could not import: are PyQt4 & PyQt5 both installed?") except: # Raise any other exceptions raise else: # Multiprocessing OK try: msg = p.map(self.callback, [self])[0] except: # If we hit an error on multiprocessing raise it raise finally: # Tidy up multiprocessing p.close() p.join() return msg def backend_qt4_internal_check(self): try: from PyQt4 import QtCore except ImportError: raise CheckFailed("PyQt4 not found") try: qt_version = QtCore.QT_VERSION pyqt_version_str = QtCore.QT_VERSION_STR except AttributeError: raise CheckFailed('PyQt4 not correctly imported') else: BackendAgg.force = True return ("Qt: %s, PyQt: %s" % (self.convert_qt_version(qt_version), pyqt_version_str)) class BackendQt4(BackendQtBase): name = "qt4agg" def __init__(self, *args, **kwargs): BackendQtBase.__init__(self, *args, **kwargs) self.callback = backend_qt4_internal_check def backend_qt5_internal_check(self): try: from PyQt5 import QtCore except ImportError: raise CheckFailed("PyQt5 not found") try: qt_version = QtCore.QT_VERSION pyqt_version_str = QtCore.QT_VERSION_STR except AttributeError: raise CheckFailed('PyQt5 not correctly imported') else: BackendAgg.force = True return ("Qt: %s, PyQt: %s" % (self.convert_qt_version(qt_version), pyqt_version_str)) class BackendQt5(BackendQtBase): name = "qt5agg" def __init__(self, *args, **kwargs): BackendQtBase.__init__(self, *args, **kwargs) self.callback = backend_qt5_internal_check def backend_pyside_internal_check(self): try: from PySide import __version__ from PySide import QtCore except ImportError: raise CheckFailed("PySide not found") else: BackendAgg.force = True return ("Qt: %s, PySide: %s" % (QtCore.__version__, __version__)) class BackendPySide(BackendQtBase): name = "pyside" def __init__(self, *args, **kwargs): BackendQtBase.__init__(self, *args, **kwargs) self.callback = backend_pyside_internal_check class BackendCairo(OptionalBackendPackage): name = "cairo" def check_requirements(self): try: import cairocffi except ImportError: try: import cairo except ImportError: raise CheckFailed("cairocffi or pycairo not found") else: return "pycairo version %s" % cairo.version else: return "cairocffi version %s" % cairocffi.version class DviPng(SetupPackage): name = "dvipng" optional = True def check(self): try: output = check_output('dvipng -version', shell=True, stderr=subprocess.STDOUT) return "version %s" % output.splitlines()[1].decode().split()[-1] except (IndexError, ValueError, subprocess.CalledProcessError): raise CheckFailed() class Ghostscript(SetupPackage): name = "ghostscript" optional = True def check(self): try: if sys.platform == 'win32': command = 'gswin32c --version' try: output = check_output(command, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: command = 'gswin64c --version' output = check_output(command, shell=True, stderr=subprocess.STDOUT) else: command = 'gs --version' output = check_output(command, shell=True, stderr=subprocess.STDOUT) return "version %s" % output.decode()[:-1] except (IndexError, ValueError, subprocess.CalledProcessError): raise CheckFailed() class LaTeX(SetupPackage): name = "latex" optional = True def check(self): try: output = check_output('latex -version', shell=True, stderr=subprocess.STDOUT) line = output.splitlines()[0].decode() pattern = '(3\.1\d+)|(MiKTeX \d+.\d+)' match = re.search(pattern, line) return "version %s" % match.group(0) except (IndexError, ValueError, AttributeError, subprocess.CalledProcessError): raise CheckFailed() class PdfToPs(SetupPackage): name = "pdftops" optional = True def check(self): try: output = check_output('pdftops -v', shell=True, stderr=subprocess.STDOUT) for line in output.splitlines(): line = line.decode() if 'version' in line: return "version %s" % line.split()[2] except (IndexError, ValueError, subprocess.CalledProcessError): pass raise CheckFailed()
[ "io.BytesIO", "sys.platform.startswith", "gi.repository.Gtk.get_micro_version", "re.search", "os.path.exists", "os.listdir", "sys.getfilesystemencoding", "pyparsing.Forward", "CXX", "subprocess.Popen", "subprocess.CalledProcessError", "os.path.split", "os.path.isdir", "os.popen", "numpy.get_include", "warnings.warn", "io.StringIO", "pyparsing.__version__.split", "pyparsing.Literal", "distutils.sysconfig.get_config_var", "subprocess.getstatusoutput", "subprocess.check_output", "glob.glob", "Tkinter.__version__.split", "ConfigParser.SafeConfigParser", "Tkinter.Tk", "imp.reload", "gi.require_version", "wxversion.ensureMinimal", "gi.repository.Gtk.get_minor_version", "distutils.core.Extension", "gi.repository.Gtk.get_major_version", "os.getenv", "Tkinter.Tcl", "os.environ.get", "os.path.join", "multiprocessing.Pool", "distutils.version.LooseVersion" ]
[((1564, 1606), 'os.environ.get', 'os.environ.get', (['"""MPLSETUPCFG"""', '"""setup.cfg"""'], {}), "('MPLSETUPCFG', 'setup.cfg')\n", (1578, 1606), False, 'import os\n'), ((1610, 1635), 'os.path.exists', 'os.path.exists', (['setup_cfg'], {}), '(setup_cfg)\n', (1624, 1635), False, 'import os\n'), ((1650, 1681), 'ConfigParser.SafeConfigParser', 'configparser.SafeConfigParser', ([], {}), '()\n', (1679, 1681), True, 'import ConfigParser as configparser\n'), ((4201, 4233), 'distutils.version.LooseVersion', 'version.LooseVersion', (['minversion'], {}), '(minversion)\n', (4221, 4233), False, 'from distutils import version\n'), ((4254, 4281), 'distutils.version.LooseVersion', 'version.LooseVersion', (['found'], {}), '(found)\n', (4274, 4281), False, 'from distutils import version\n'), ((5971, 5999), 'os.path.join', 'os.path.join', (['dir', '"""include"""'], {}), "(dir, 'include')\n", (5983, 5999), False, 'import os\n'), ((6011, 6038), 'os.path.exists', 'os.path.exists', (['include_dir'], {}), '(include_dir)\n', (6025, 6038), False, 'import os\n'), ((6817, 6851), 'distutils.sysconfig.get_config_var', 'sysconfig.get_config_var', (['"""LIBDIR"""'], {}), "('LIBDIR')\n", (6841, 6851), False, 'from distutils import sysconfig\n'), ((6932, 6973), 'os.path.join', 'os.path.join', (['pkgconfig_path', '"""pkgconfig"""'], {}), "(pkgconfig_path, 'pkgconfig')\n", (6944, 6973), False, 'import os\n'), ((9155, 9210), 'subprocess.getstatusoutput', 'getstatusoutput', (["('pkg-config %s --modversion' % package)"], {}), "('pkg-config %s --modversion' % package)\n", (9170, 9210), False, 'from subprocess import getstatusoutput\n'), ((22115, 22136), 'distutils.core.Extension', 'Extension', (['"""test"""', '[]'], {}), "('test', [])\n", (22124, 22136), False, 'from distutils.core import Extension\n'), ((27288, 27332), 'subprocess.getstatusoutput', 'getstatusoutput', (['"""freetype-config --version"""'], {}), "('freetype-config --version')\n", (27303, 27332), False, 'from subprocess import getstatusoutput\n'), ((52850, 52882), 'gi.require_version', 'gi.require_version', (['"""Gtk"""', '"""3.0"""'], {}), "('Gtk', '3.0')\n", (52868, 52882), False, 'import gi\n'), ((54790, 54822), 'gi.require_version', 'gi.require_version', (['"""Gtk"""', '"""3.0"""'], {}), "('Gtk', '3.0')\n", (54808, 54822), False, 'import gi\n'), ((702, 764), 'subprocess.Popen', 'subprocess.Popen', (['*popenargs'], {'stdout': 'subprocess.PIPE'}), '(*popenargs, stdout=subprocess.PIPE, **kwargs)\n', (718, 764), False, 'import subprocess\n'), ((2990, 3017), 'os.path.join', 'os.path.join', (['dir', 'filename'], {}), '(dir, filename)\n', (3002, 3017), False, 'import os\n'), ((6148, 6170), 'os.path.join', 'os.path.join', (['dir', 'lib'], {}), '(dir, lib)\n', (6160, 6170), False, 'import os\n'), ((6186, 6209), 'os.path.exists', 'os.path.exists', (['lib_dir'], {}), '(lib_dir)\n', (6200, 6209), False, 'import os\n'), ((6673, 6709), 'subprocess.getstatusoutput', 'getstatusoutput', (['"""pkg-config --help"""'], {}), "('pkg-config --help')\n", (6688, 6709), False, 'from subprocess import getstatusoutput\n'), ((6989, 7018), 'os.path.isdir', 'os.path.isdir', (['pkgconfig_path'], {}), '(pkgconfig_path)\n', (7002, 7018), False, 'import os\n'), ((21882, 21899), 'imp.reload', 'imp.reload', (['numpy'], {}), '(numpy)\n', (21892, 21899), False, 'import imp\n'), ((22169, 22188), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (22186, 22188), False, 'import numpy\n'), ((22310, 22428), 'warnings.warn', 'warnings.warn', (['"""The C headers for numpy could not be found. You may need to install the development package"""'], {}), "(\n 'The C headers for numpy could not be found. You may need to install the development package'\n )\n", (22323, 22428), False, 'import warnings\n'), ((22472, 22491), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (22489, 22491), False, 'import numpy\n'), ((23916, 23929), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (23927, 23929), False, 'import io\n'), ((23969, 23981), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (23979, 23981), False, 'import io\n'), ((31990, 32032), 'os.path.join', 'os.path.join', (['"""lib/matplotlib/delaunay"""', 's'], {}), "('lib/matplotlib/delaunay', s)\n", (32002, 32032), False, 'import os\n'), ((35066, 35085), 'pyparsing.Forward', 'pyparsing.Forward', ([], {}), '()\n', (35083, 35085), False, 'import pyparsing\n'), ((35104, 35126), 'pyparsing.Literal', 'pyparsing.Literal', (['"""a"""'], {}), "('a')\n", (35121, 35126), False, 'import pyparsing\n'), ((38884, 38896), 'Tkinter.Tk', 'Tkinter.Tk', ([], {}), '()\n', (38894, 38896), False, 'import Tkinter\n'), ((40932, 40966), 'os.path.join', 'os.path.join', (['ptcl', '"""tclConfig.sh"""'], {}), "(ptcl, 'tclConfig.sh')\n", (40944, 40966), False, 'import os\n'), ((40991, 41023), 'os.path.join', 'os.path.join', (['ptk', '"""tkConfig.sh"""'], {}), "(ptk, 'tkConfig.sh')\n", (41003, 41023), False, 'import os\n'), ((41273, 41395), 'subprocess.Popen', 'subprocess.Popen', (["('. %s ; eval echo ${%s}' % (file, varname))"], {'shell': '(True)', 'executable': '"""/bin/sh"""', 'stdout': 'subprocess.PIPE'}), "('. %s ; eval echo ${%s}' % (file, varname), shell=True,\n executable='/bin/sh', stdout=subprocess.PIPE)\n", (41289, 41395), False, 'import subprocess\n'), ((42509, 42541), 'os.path.join', 'os.path.join', (['tcl_lib_dir', '"""../"""'], {}), "(tcl_lib_dir, '../')\n", (42521, 42541), False, 'import os\n'), ((42577, 42608), 'os.path.join', 'os.path.join', (['tk_lib_dir', '"""../"""'], {}), "(tk_lib_dir, '../')\n", (42589, 42608), False, 'import os\n'), ((42659, 42714), 'os.path.join', 'os.path.join', (['tcl_lib_dir', "('../../include/tcl' + tk_ver)"], {}), "(tcl_lib_dir, '../../include/tcl' + tk_ver)\n", (42671, 42714), False, 'import os\n'), ((42756, 42779), 'os.path.exists', 'os.path.exists', (['tcl_inc'], {}), '(tcl_inc)\n', (42770, 42779), False, 'import os\n'), ((42945, 42998), 'os.path.join', 'os.path.join', (['tk_lib_dir', "('../../include/tk' + tk_ver)"], {}), "(tk_lib_dir, '../../include/tk' + tk_ver)\n", (42957, 42998), False, 'import os\n'), ((43040, 43062), 'os.path.exists', 'os.path.exists', (['tk_inc'], {}), '(tk_inc)\n', (43054, 43062), False, 'import os\n'), ((43285, 43308), 'os.path.exists', 'os.path.exists', (['tcl_inc'], {}), '(tcl_inc)\n', (43299, 43308), False, 'import os\n'), ((48846, 48874), 'os.path.join', 'os.path.join', (['"""gtk"""', '"""gtk.h"""'], {}), "('gtk', 'gtk.h')\n", (48858, 48874), False, 'import os\n'), ((48982, 49014), 'os.path.join', 'os.path.join', (['"""pygtk"""', '"""pygtk.h"""'], {}), "('pygtk', 'pygtk.h')\n", (48994, 49014), False, 'import os\n'), ((53859, 53881), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {}), '()\n', (53879, 53881), False, 'import multiprocessing\n'), ((55711, 55733), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {}), '()\n', (55731, 55733), False, 'import multiprocessing\n'), ((56552, 56582), 'wxversion.ensureMinimal', 'wxversion.ensureMinimal', (['"""2.8"""'], {}), "('2.8')\n", (56575, 56582), False, 'import wxversion\n'), ((59211, 59233), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {}), '()\n', (59231, 59233), False, 'import multiprocessing\n'), ((62512, 62581), 'subprocess.check_output', 'check_output', (['"""dvipng -version"""'], {'shell': '(True)', 'stderr': 'subprocess.STDOUT'}), "('dvipng -version', shell=True, stderr=subprocess.STDOUT)\n", (62524, 62581), False, 'from subprocess import check_output\n'), ((63853, 63921), 'subprocess.check_output', 'check_output', (['"""latex -version"""'], {'shell': '(True)', 'stderr': 'subprocess.STDOUT'}), "('latex -version', shell=True, stderr=subprocess.STDOUT)\n", (63865, 63921), False, 'from subprocess import check_output\n'), ((64078, 64102), 're.search', 're.search', (['pattern', 'line'], {}), '(pattern, line)\n', (64087, 64102), False, 'import re\n'), ((64400, 64464), 'subprocess.check_output', 'check_output', (['"""pdftops -v"""'], {'shell': '(True)', 'stderr': 'subprocess.STDOUT'}), "('pdftops -v', shell=True, stderr=subprocess.STDOUT)\n", (64412, 64464), False, 'from subprocess import check_output\n'), ((1002, 1045), 'subprocess.CalledProcessError', 'subprocess.CalledProcessError', (['retcode', 'cmd'], {}), '(retcode, cmd)\n', (1031, 1045), False, 'import subprocess\n'), ((3864, 3887), 'os.getenv', 'os.getenv', (['"""MPLIB_BASE"""'], {}), "('MPLIB_BASE')\n", (3873, 3887), False, 'import os\n'), ((7863, 7922), 'subprocess.check_output', 'check_output', (['command'], {'shell': '(True)', 'stderr': 'subprocess.STDOUT'}), '(command, shell=True, stderr=subprocess.STDOUT)\n', (7875, 7922), False, 'from subprocess import check_output\n'), ((19708, 19758), 'os.listdir', 'os.listdir', (['"""lib/matplotlib/tests/baseline_images"""'], {}), "('lib/matplotlib/tests/baseline_images')\n", (19718, 19758), False, 'import os\n'), ((22257, 22295), 'os.path.join', 'os.path.join', (['"""numpy"""', '"""arrayobject.h"""'], {}), "('numpy', 'arrayobject.h')\n", (22269, 22295), False, 'import os\n'), ((24920, 25025), 'os.path.join', 'os.path.join', (['sys.prefix', '"""share"""', "('python%d.%d' % (sys.version_info[0], sys.version_info[1]))", '"""CXX"""'], {}), "(sys.prefix, 'share', 'python%d.%d' % (sys.version_info[0], sys\n .version_info[1]), 'CXX')\n", (24932, 25025), False, 'import os\n'), ((25162, 25189), 'os.path.exists', 'os.path.exists', (['support_dir'], {}), '(support_dir)\n', (25176, 25189), False, 'import os\n'), ((25686, 25715), 'glob.glob', 'glob.glob', (['"""extern/CXX/*.cxx"""'], {}), "('extern/CXX/*.cxx')\n", (25695, 25715), False, 'import glob\n'), ((25748, 25775), 'glob.glob', 'glob.glob', (['"""extern/CXX/*.c"""'], {}), "('extern/CXX/*.c')\n", (25757, 25775), False, 'import glob\n'), ((28387, 28392), 'CXX', 'CXX', ([], {}), '()\n', (28390, 28392), False, 'import CXX\n'), ((29062, 29067), 'CXX', 'CXX', ([], {}), '()\n', (29065, 29067), False, 'import CXX\n'), ((30244, 30273), 'glob.glob', 'glob.glob', (['"""extern/qhull/*.c"""'], {}), "('extern/qhull/*.c')\n", (30253, 30273), False, 'import glob\n'), ((30644, 30649), 'CXX', 'CXX', ([], {}), '()\n', (30647, 30649), False, 'import CXX\n'), ((31071, 31076), 'CXX', 'CXX', ([], {}), '()\n', (31074, 31076), False, 'import CXX\n'), ((31402, 31407), 'CXX', 'CXX', ([], {}), '()\n', (31405, 31407), False, 'import CXX\n'), ((32781, 32786), 'CXX', 'CXX', ([], {}), '()\n', (32784, 32786), False, 'import CXX\n'), ((36646, 36651), 'CXX', 'CXX', ([], {}), '()\n', (36649, 36651), False, 'import CXX\n'), ((37400, 37427), 'Tkinter.__version__.split', 'Tkinter.__version__.split', ([], {}), '()\n', (37425, 37427), False, 'import Tkinter\n'), ((37955, 37960), 'CXX', 'CXX', ([], {}), '()\n', (37958, 37960), False, 'import CXX\n'), ((40539, 40570), 'os.path.join', 'os.path.join', (['tcl_lib_dir', '""".."""'], {}), "(tcl_lib_dir, '..')\n", (40551, 40570), False, 'import os\n'), ((40735, 40765), 'os.path.join', 'os.path.join', (['tk_lib_dir', '""".."""'], {}), "(tk_lib_dir, '..')\n", (40747, 40765), False, 'import os\n'), ((41040, 41066), 'os.path.exists', 'os.path.exists', (['tcl_config'], {}), '(tcl_config)\n', (41054, 41066), False, 'import os\n'), ((41071, 41096), 'os.path.exists', 'os.path.exists', (['tk_config'], {}), '(tk_config)\n', (41085, 41096), False, 'import os\n'), ((41137, 41163), 'os.path.exists', 'os.path.exists', (['tcl_config'], {}), '(tcl_config)\n', (41151, 41163), False, 'import os\n'), ((41168, 41193), 'os.path.exists', 'os.path.exists', (['tk_config'], {}), '(tk_config)\n', (41182, 41193), False, 'import os\n'), ((42147, 42179), 'os.path.join', 'os.path.join', (['tk_inc_dir', '"""tk.h"""'], {}), "(tk_inc_dir, 'tk.h')\n", (42159, 42179), False, 'import os\n'), ((42388, 42415), 'os.path.exists', 'os.path.exists', (['tcl_lib_dir'], {}), '(tcl_lib_dir)\n', (42402, 42415), False, 'import os\n'), ((42420, 42446), 'os.path.exists', 'os.path.exists', (['tk_lib_dir'], {}), '(tk_lib_dir)\n', (42434, 42446), False, 'import os\n'), ((42837, 42879), 'os.path.join', 'os.path.join', (['tcl_lib_dir', '"""../../include"""'], {}), "(tcl_lib_dir, '../../include')\n", (42849, 42879), False, 'import os\n'), ((43102, 43143), 'os.path.join', 'os.path.join', (['tk_lib_dir', '"""../../include"""'], {}), "(tk_lib_dir, '../../include')\n", (43114, 43143), False, 'import os\n'), ((43209, 43237), 'os.path.join', 'os.path.join', (['tk_inc', '"""tk.h"""'], {}), "(tk_inc, 'tk.h')\n", (43221, 43237), False, 'import os\n'), ((43387, 43419), 'sys.platform.startswith', 'sys.platform.startswith', (['"""linux"""'], {}), "('linux')\n", (43410, 43419), False, 'import sys\n'), ((43440, 43476), 'os.path.exists', 'os.path.exists', (['"""/usr/include/tcl.h"""'], {}), "('/usr/include/tcl.h')\n", (43454, 43476), False, 'import os\n'), ((43497, 43532), 'os.path.exists', 'os.path.exists', (['"""/usr/include/tk.h"""'], {}), "('/usr/include/tk.h')\n", (43511, 43532), False, 'import os\n'), ((43647, 43675), 'os.path.join', 'os.path.join', (['tk_inc', '"""tk.h"""'], {}), "(tk_inc, 'tk.h')\n", (43659, 43675), False, 'import os\n'), ((52607, 52612), 'CXX', 'CXX', ([], {}), '()\n', (52610, 52612), False, 'import CXX\n'), ((53275, 53298), 'gi.repository.Gtk.get_major_version', 'Gtk.get_major_version', ([], {}), '()\n', (53296, 53298), False, 'from gi.repository import Gtk, Gdk, GObject\n'), ((53308, 53331), 'gi.repository.Gtk.get_micro_version', 'Gtk.get_micro_version', ([], {}), '()\n', (53329, 53331), False, 'from gi.repository import Gtk, Gdk, GObject\n'), ((53341, 53364), 'gi.repository.Gtk.get_minor_version', 'Gtk.get_minor_version', ([], {}), '()\n', (53362, 53364), False, 'from gi.repository import Gtk, Gdk, GObject\n'), ((55215, 55238), 'gi.repository.Gtk.get_major_version', 'Gtk.get_major_version', ([], {}), '()\n', (55236, 55238), False, 'from gi.repository import Gtk, Gdk, GObject\n'), ((55248, 55271), 'gi.repository.Gtk.get_micro_version', 'Gtk.get_micro_version', ([], {}), '()\n', (55269, 55271), False, 'from gi.repository import Gtk, Gdk, GObject\n'), ((55281, 55304), 'gi.repository.Gtk.get_minor_version', 'Gtk.get_minor_version', ([], {}), '()\n', (55302, 55304), False, 'from gi.repository import Gtk, Gdk, GObject\n'), ((57822, 57827), 'CXX', 'CXX', ([], {}), '()\n', (57825, 57827), False, 'import CXX\n'), ((63472, 63531), 'subprocess.check_output', 'check_output', (['command'], {'shell': '(True)', 'stderr': 'subprocess.STDOUT'}), '(command, shell=True, stderr=subprocess.STDOUT)\n', (63484, 63531), False, 'from subprocess import check_output\n'), ((3264, 3289), 'os.getenv', 'os.getenv', (['"""INCLUDE"""', '"""."""'], {}), "('INCLUDE', '.')\n", (3273, 3289), False, 'import os\n'), ((8089, 8116), 'sys.getfilesystemencoding', 'sys.getfilesystemencoding', ([], {}), '()\n', (8114, 8116), False, 'import sys\n'), ((8534, 8561), 'os.path.join', 'os.path.join', (['base', 'include'], {}), '(base, include)\n', (8546, 8561), False, 'import os\n'), ((8585, 8604), 'os.path.exists', 'os.path.exists', (['dir'], {}), '(dir)\n', (8599, 8604), False, 'import os\n'), ((8734, 8757), 'os.path.join', 'os.path.join', (['base', 'lib'], {}), '(base, lib)\n', (8746, 8757), False, 'import os\n'), ((8781, 8800), 'os.path.exists', 'os.path.exists', (['dir'], {}), '(dir)\n', (8795, 8800), False, 'import os\n'), ((25361, 25389), 'os.path.join', 'os.path.join', (['support_dir', 'x'], {}), '(support_dir, x)\n', (25373, 25389), False, 'import os\n'), ((27049, 27090), 'os.path.join', 'os.path.join', (['"""extern"""', '"""agg24"""', '"""src"""', 'x'], {}), "('extern', 'agg24', 'src', x)\n", (27061, 27090), False, 'import os\n'), ((29640, 29675), 'os.path.join', 'os.path.join', (['x', '"""include"""', '"""qhull"""'], {}), "(x, 'include', 'qhull')\n", (29652, 29675), False, 'import os\n'), ((35577, 35609), 'pyparsing.__version__.split', 'pyparsing.__version__.split', (['"""."""'], {}), "('.')\n", (35604, 35609), False, 'import pyparsing\n'), ((39145, 39158), 'Tkinter.Tcl', 'Tkinter.Tcl', ([], {}), '()\n', (39156, 39158), False, 'import Tkinter\n'), ((39519, 39545), 'os.path.split', 'os.path.split', (['tcl_lib_dir'], {}), '(tcl_lib_dir)\n', (39532, 39545), False, 'import os\n'), ((39645, 39669), 'os.path.join', 'os.path.join', (['head', 'tail'], {}), '(head, tail)\n', (39657, 39669), False, 'import os\n'), ((44514, 44546), 'os.path.join', 'os.path.join', (['sys.prefix', '"""dlls"""'], {}), "(sys.prefix, 'dlls')\n", (44526, 44546), False, 'import os\n'), ((63050, 63109), 'subprocess.check_output', 'check_output', (['command'], {'shell': '(True)', 'stderr': 'subprocess.STDOUT'}), '(command, shell=True, stderr=subprocess.STDOUT)\n', (63062, 63109), False, 'from subprocess import check_output\n'), ((39693, 39719), 'os.path.exists', 'os.path.exists', (['tk_lib_dir'], {}), '(tk_lib_dir)\n', (39707, 39719), False, 'import os\n'), ((44851, 44868), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (44860, 44868), False, 'import os\n'), ((45934, 45963), 'os.path.join', 'join', (['F', "(fw + '.framework')", 'H'], {}), "(F, fw + '.framework', H)\n", (45938, 45963), False, 'from os.path import join, exists\n'), ((63286, 63345), 'subprocess.check_output', 'check_output', (['command'], {'shell': '(True)', 'stderr': 'subprocess.STDOUT'}), '(command, shell=True, stderr=subprocess.STDOUT)\n', (63298, 63345), False, 'from subprocess import check_output\n'), ((45317, 45343), 'os.path.join', 'join', (['F', "(fw + '.framework')"], {}), "(F, fw + '.framework')\n", (45321, 45343), False, 'from os.path import join, exists\n'), ((49657, 49668), 'os.popen', 'os.popen', (['s'], {}), '(s)\n', (49665, 49668), False, 'import os\n')]
# Copyright 2021 Sony Group 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. ''' MUSDB18 data-iterator code for MSS. ''' import random import numpy as np import musdb from nnabla.utils.data_source import DataSource class Compose(): """Composes several augmentation transforms. Args: augmentations: list of augmentations to compose. """ def __init__(self, transforms): self.transforms = transforms def __call__(self, audio): for t in self.transforms: audio = t(audio) return audio def _augment_gain(audio, low=0.75, high=1.25): """Applies a random gain between `low` and `high`""" g = random.uniform(low, high) return audio * g def _augment_channelswap(audio): """Swap channels of stereo signals with a probability of p=0.5""" if audio.shape[0] == 2 and random.random() < 0.5: return np.flip(audio, 0) else: return audio def load_datasources(parser, args): """Loads the specified dataset from commandline arguments Returns: train_dataset, validation_dataset """ parser.add_argument('--is-wav', action='store_true', default=True, help='loads wav instead of STEMS') parser.add_argument('--samples-per-track', type=int, default=64) parser.add_argument( '--source-augmentations', type=str, nargs='+', default=['gain', 'channelswap'] ) args = parser.parse_args() source_augmentations = Compose( [globals()['_augment_' + aug] for aug in args.source_augmentations] ) train_dataset = MUSDBDataSource( source_augmentations=source_augmentations, random_track_mix=True, args=args) return train_dataset, args class MUSDBDataSource(DataSource): def __init__( self, args, download=False, samples_per_track=64, source_augmentations=lambda audio: audio, random_track_mix=False, dtype=np.float32, seed=42, rng=None ): """ MUSDB18 nnabla.utils.data_source that samples from the MUSDB tracks using track and excerpts with replacement. Parameters ---------- args : additional arguments used to add further control for the musdb dataset initialization function. download : boolean automatically download 7s preview version of MUS samples_per_track : int sets the number of samples, yielded from each track per epoch. Defaults to 64 source_augmentations : list[callables] provide list of augmentation function that take a multi-channel audio file of shape (src, samples) as input and output. Defaults to no-augmentations (input = output) random_track_mix : boolean randomly mixes sources from different tracks to assemble a custom mix. This augmenation is only applied for the train subset. seed : int control randomness of dataset iterations dtype : numeric type data type of torch output tuple x and y """ super(MUSDBDataSource, self).__init__(shuffle=True) if rng is None: rng = np.random.RandomState(seed) self.rng = rng random.seed(seed) self.args = args self.download = args.root is None self.samples_per_track = samples_per_track self.source_augmentations = source_augmentations self.random_track_mix = random_track_mix self.mus = musdb.DB( root=args.root, is_wav=args.is_wav, split=None, subsets='train', download=download ) print(f"Finished loading dataset with {len(self.mus.tracks)} tracks.") self.sample_rate = 44100 # musdb has fixed sample rate self.dtype = dtype self._size = len(self.mus.tracks) * self.samples_per_track self._variables = ('mixture', 'target') self.reset() def _get_data(self, position): index = self._indexes[position] audio_sources = [] target_ind = None # select track track = self.mus.tracks[index // self.samples_per_track] # at training time we assemble a custom mix if self.args.seq_dur: for k, source in enumerate(self.mus.setup['sources']): # memorize index of target source if source == self.args.target: target_ind = k # select a random track if self.random_track_mix: track = random.choice(self.mus.tracks) # set the excerpt duration track.chunk_duration = self.args.seq_dur # set random start index track.chunk_start = random.uniform( 0, track.duration - self.args.seq_dur ) # load source audio and apply time domain source_augmentations audio = track.sources[source].audio.T audio = self.source_augmentations(audio) audio_sources.append(audio) # create stem tensor of shape (source, channel, samples) stems = np.stack(audio_sources, axis=0) # # apply linear mix over source index=0 x = np.sum(stems, axis=0) # get the target stem if target_ind is not None: y = stems[target_ind] # assuming vocal/accompaniment scenario if target!=source else: vocind = list(self.mus.setup['sources'].keys()).index('vocals') # apply time domain subtraction y = x - stems[vocind] # for validation and test, we deterministically yield the full musdb track else: # get the non-linear source mix straight from musdb x = track.audio.T y = track.targets[self.args.target].audio.T return x, y def reset(self): if self._shuffle: self._indexes = self.rng.permutation(self._size) else: self._indexes = np.arange(self._size) super(MUSDBDataSource, self).reset()
[ "numpy.flip", "random.uniform", "random.choice", "numpy.arange", "random.seed", "numpy.stack", "musdb.DB", "numpy.sum", "random.random", "numpy.random.RandomState" ]
[((1174, 1199), 'random.uniform', 'random.uniform', (['low', 'high'], {}), '(low, high)\n', (1188, 1199), False, 'import random\n'), ((1395, 1412), 'numpy.flip', 'np.flip', (['audio', '(0)'], {}), '(audio, 0)\n', (1402, 1412), True, 'import numpy as np\n'), ((3811, 3828), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (3822, 3828), False, 'import random\n'), ((4072, 4168), 'musdb.DB', 'musdb.DB', ([], {'root': 'args.root', 'is_wav': 'args.is_wav', 'split': 'None', 'subsets': '"""train"""', 'download': 'download'}), "(root=args.root, is_wav=args.is_wav, split=None, subsets='train',\n download=download)\n", (4080, 4168), False, 'import musdb\n'), ((1357, 1372), 'random.random', 'random.random', ([], {}), '()\n', (1370, 1372), False, 'import random\n'), ((3751, 3778), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (3772, 3778), True, 'import numpy as np\n'), ((5783, 5814), 'numpy.stack', 'np.stack', (['audio_sources'], {'axis': '(0)'}), '(audio_sources, axis=0)\n', (5791, 5814), True, 'import numpy as np\n'), ((5884, 5905), 'numpy.sum', 'np.sum', (['stems'], {'axis': '(0)'}), '(stems, axis=0)\n', (5890, 5905), True, 'import numpy as np\n'), ((6691, 6712), 'numpy.arange', 'np.arange', (['self._size'], {}), '(self._size)\n', (6700, 6712), True, 'import numpy as np\n'), ((5366, 5419), 'random.uniform', 'random.uniform', (['(0)', '(track.duration - self.args.seq_dur)'], {}), '(0, track.duration - self.args.seq_dur)\n', (5380, 5419), False, 'import random\n'), ((5156, 5186), 'random.choice', 'random.choice', (['self.mus.tracks'], {}), '(self.mus.tracks)\n', (5169, 5186), False, 'import random\n')]
import unittest import numpy as np from revpy import fare_transformation class FareTransformationTest(unittest.TestCase): def setUp(self): # example data from page 13 of research paper # "Optimization of Mixed Fare Structures: Theory and Applications" # by <NAME> al. (2010) self.fares = np.array([1200, 1000, 800, 600, 400, 200]) self.demands = np.array([31.2, 10.9, 14.8, 19.9, 26.9, 36.3]) def test_faretrafo_zero_demand(self): demands = np.zeros(self.fares.shape) adjusted_fares, adjusted_demand = \ fare_transformation.calc_fare_transformation(self.fares, demands) np.testing.assert_equal([1200, np.nan, np.nan, np.nan, np.nan, np.nan], adjusted_fares) np.testing.assert_equal([0, np.nan, np.nan, np.nan, np.nan, np.nan], adjusted_demand) def test_example1(self): # test example from above mentioned paper adjusted_fares, adjusted_demand = \ fare_transformation.calc_fare_transformation(self.fares, self.demands) np.testing.assert_almost_equal(adjusted_fares, [1200, 427, 231, 28, np.nan, np.nan], 0) def test_example2(self): # example containing some zero demands demands = np.array([0, 15, 0, 30, 2, 60]) adjusted_fares, adjusted_demand = \ fare_transformation.calc_fare_transformation(self.fares, demands) np.testing.assert_almost_equal(adjusted_fares, [1200, 1000, np.nan, 400, np.nan, np.nan, ]) def test_efficient_strategies(self): fares = np.array([69.5, 59.5, 48.5, 37.5, 29.]) demands = np.array([3, 1, 0, 0, 10]) Q = demands.cumsum() TR = Q*fares __, __, __, __, eff_indices = \ fare_transformation.efficient_strategies(Q, TR, fares[0]) self.assertEqual(eff_indices.tolist(), [0, 1, 4])
[ "revpy.fare_transformation.calc_fare_transformation", "revpy.fare_transformation.efficient_strategies", "numpy.testing.assert_equal", "numpy.array", "numpy.zeros", "numpy.testing.assert_almost_equal" ]
[((329, 371), 'numpy.array', 'np.array', (['[1200, 1000, 800, 600, 400, 200]'], {}), '([1200, 1000, 800, 600, 400, 200])\n', (337, 371), True, 'import numpy as np\n'), ((395, 441), 'numpy.array', 'np.array', (['[31.2, 10.9, 14.8, 19.9, 26.9, 36.3]'], {}), '([31.2, 10.9, 14.8, 19.9, 26.9, 36.3])\n', (403, 441), True, 'import numpy as np\n'), ((503, 529), 'numpy.zeros', 'np.zeros', (['self.fares.shape'], {}), '(self.fares.shape)\n', (511, 529), True, 'import numpy as np\n'), ((587, 652), 'revpy.fare_transformation.calc_fare_transformation', 'fare_transformation.calc_fare_transformation', (['self.fares', 'demands'], {}), '(self.fares, demands)\n', (631, 652), False, 'from revpy import fare_transformation\n'), ((662, 753), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['[1200, np.nan, np.nan, np.nan, np.nan, np.nan]', 'adjusted_fares'], {}), '([1200, np.nan, np.nan, np.nan, np.nan, np.nan],\n adjusted_fares)\n', (685, 753), True, 'import numpy as np\n'), ((790, 879), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['[0, np.nan, np.nan, np.nan, np.nan, np.nan]', 'adjusted_demand'], {}), '([0, np.nan, np.nan, np.nan, np.nan, np.nan],\n adjusted_demand)\n', (813, 879), True, 'import numpy as np\n'), ((1045, 1115), 'revpy.fare_transformation.calc_fare_transformation', 'fare_transformation.calc_fare_transformation', (['self.fares', 'self.demands'], {}), '(self.fares, self.demands)\n', (1089, 1115), False, 'from revpy import fare_transformation\n'), ((1182, 1273), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['adjusted_fares', '[1200, 427, 231, 28, np.nan, np.nan]', '(0)'], {}), '(adjusted_fares, [1200, 427, 231, 28, np.nan,\n np.nan], 0)\n', (1212, 1273), True, 'import numpy as np\n'), ((1421, 1452), 'numpy.array', 'np.array', (['[0, 15, 0, 30, 2, 60]'], {}), '([0, 15, 0, 30, 2, 60])\n', (1429, 1452), True, 'import numpy as np\n'), ((1510, 1575), 'revpy.fare_transformation.calc_fare_transformation', 'fare_transformation.calc_fare_transformation', (['self.fares', 'demands'], {}), '(self.fares, demands)\n', (1554, 1575), False, 'from revpy import fare_transformation\n'), ((1585, 1679), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['adjusted_fares', '[1200, 1000, np.nan, 400, np.nan, np.nan]'], {}), '(adjusted_fares, [1200, 1000, np.nan, 400, np\n .nan, np.nan])\n', (1615, 1679), True, 'import numpy as np\n'), ((1791, 1831), 'numpy.array', 'np.array', (['[69.5, 59.5, 48.5, 37.5, 29.0]'], {}), '([69.5, 59.5, 48.5, 37.5, 29.0])\n', (1799, 1831), True, 'import numpy as np\n'), ((1853, 1879), 'numpy.array', 'np.array', (['[3, 1, 0, 0, 10]'], {}), '([3, 1, 0, 0, 10])\n', (1861, 1879), True, 'import numpy as np\n'), ((1983, 2040), 'revpy.fare_transformation.efficient_strategies', 'fare_transformation.efficient_strategies', (['Q', 'TR', 'fares[0]'], {}), '(Q, TR, fares[0])\n', (2023, 2040), False, 'from revpy import fare_transformation\n')]
from __future__ import (absolute_import, division, print_function, unicode_literals) from matplotlib.externals import six from matplotlib.tri import Triangulation import _tri as _tri import numpy as np class TriFinder(object): """ Abstract base class for classes used to find the triangles of a Triangulation in which (x,y) points lie. Rather than instantiate an object of a class derived from TriFinder, it is usually better to use the function :func:`matplotlib.tri.Triangulation.get_trifinder`. Derived classes implement __call__(x,y) where x,y are array_like point coordinates of the same shape. """ def __init__(self, triangulation): if not isinstance(triangulation, Triangulation): raise ValueError('Expected a Triangulation object') self._triangulation = triangulation class TrapezoidMapTriFinder(TriFinder): """ :class:`~matplotlib.tri.TriFinder` class implemented using the trapezoid map algorithm from the book "Computational Geometry, Algorithms and Applications", second edition, by <NAME>, <NAME>, <NAME> and <NAME>. The triangulation must be valid, i.e. it must not have duplicate points, triangles formed from colinear points, or overlapping triangles. The algorithm has some tolerance to triangles formed from colinear points, but this should not be relied upon. """ def __init__(self, triangulation): TriFinder.__init__(self, triangulation) self._cpp_trifinder = _tri.TrapezoidMapTriFinder( triangulation.get_cpp_triangulation()) self._initialize() def __call__(self, x, y): """ Return an array containing the indices of the triangles in which the specified x,y points lie, or -1 for points that do not lie within a triangle. *x*, *y* are array_like x and y coordinates of the same shape and any number of dimensions. Returns integer array with the same shape and *x* and *y*. """ x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) if x.shape != y.shape: raise ValueError("x and y must be array-like with the same shape") # C++ does the heavy lifting, and expects 1D arrays. indices = self._cpp_trifinder.find_many(x.ravel(), y.ravel()) indices.shape = x.shape return indices def _get_tree_stats(self): """ Return a python list containing the statistics about the node tree: 0: number of nodes (tree size) 1: number of unique nodes 2: number of trapezoids (tree leaf nodes) 3: number of unique trapezoids 4: maximum parent count (max number of times a node is repeated in tree) 5: maximum depth of tree (one more than the maximum number of comparisons needed to search through the tree) 6: mean of all trapezoid depths (one more than the average number of comparisons needed to search through the tree) """ return self._cpp_trifinder.get_tree_stats() def _initialize(self): """ Initialize the underlying C++ object. Can be called multiple times if, for example, the triangulation is modified. """ self._cpp_trifinder.initialize() def _print_tree(self): """ Print a text representation of the node tree, which is useful for debugging purposes. """ self._cpp_trifinder.print_tree()
[ "numpy.asarray" ]
[((2063, 2094), 'numpy.asarray', 'np.asarray', (['x'], {'dtype': 'np.float64'}), '(x, dtype=np.float64)\n', (2073, 2094), True, 'import numpy as np\n'), ((2107, 2138), 'numpy.asarray', 'np.asarray', (['y'], {'dtype': 'np.float64'}), '(y, dtype=np.float64)\n', (2117, 2138), True, 'import numpy as np\n')]
""" Generate BpForms for all of the proteins in PRO, verify them, and calculate their properties :Author: <NAME> <<EMAIL>> :Date: 2019-06-24 :Copyright: 2019, Karr Lab :License: MIT """ from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from matplotlib import pyplot from xml.etree import ElementTree import bpforms import copy import csv import matplotlib import numpy import os import pickle import re import requests import requests_cache IN_URL = 'https://proconsortium.org/download/current/pro_nonreasoned.obo' IN_OBO_FILENAME = os.path.join('examples', 'pro_nonreasoned.obo') IN_PKL_FILENAME = os.path.join('examples', 'pro_nonreasoned.pkl') IN_TSV_FILELANE = os.path.join('examples', 'pro_input.in.tsv') # from <NAME> IN_MONOMERS_FILENAME = os.path.join('examples', 'pro.monomers.csv') UNIPROT_SEQ_ENDPOINT = 'https://www.uniprot.org/uniprot/{}.fasta' UNIPROT_XML_ENDPOINT = 'https://www.uniprot.org/uniprot/{}.xml' OUT_PICKLE_FILENAME = os.path.join('examples', 'pro_input.out.pkl') OUT_PICKLE_FILENAME_2 = os.path.join('examples', 'pro_input.out.2.pkl') OUT_TSV_FILENAME = os.path.join('examples', 'pro_input.out.tsv') OUT_FASTA_FILENAME = os.path.join('examples', 'pro_input.fasta') OUT_FIG_FILENAME = os.path.join('examples', 'pro_input.svg') OUT_STRUCTURE_DIRNAME = os.path.join('examples', 'pro_input_structure') OUT_VIZ_DIRNAME = os.path.join('examples', 'pro_input_viz') cache_name = os.path.join('examples', 'pro') session = requests_cache.core.CachedSession(cache_name, backend='sqlite', expire_after=None) session.mount('https://www.uniprot.org/', requests.adapters.HTTPAdapter(max_retries=5)) AA_CHARS_TO_CODES = { 'Ala': 'A', 'Arg': 'R', 'Asn': 'N', 'Asp': 'D', 'Cys': 'C', 'Glu': 'E', 'Gln': 'Q', 'Gly': 'G', 'His': 'H', 'Ile': 'I', 'Leu': 'L', 'Lys': 'K', 'Met': 'M', 'Phe': 'F', 'Pro': 'P', 'Ser': 'S', 'Thr': 'T', 'Trp': 'W', 'Tyr': 'Y', 'Val': 'V', } def run(in_obo_filename=IN_OBO_FILENAME, in_pkl_filename=IN_PKL_FILENAME, in_tsv_filename=IN_TSV_FILELANE, in_monomers_filename=IN_MONOMERS_FILENAME, max_num_proteins=None, out_pickle_filename=OUT_PICKLE_FILENAME, out_pickle_filename_2=OUT_PICKLE_FILENAME_2, out_tsv_filename=OUT_TSV_FILENAME, out_fasta_filename=OUT_FASTA_FILENAME, out_fig_filename=OUT_FIG_FILENAME, out_structure_dirname=OUT_STRUCTURE_DIRNAME, out_viz_dirname=OUT_VIZ_DIRNAME): """ Download PRO ontology, generate proteoforms, and encode with BpForms Args: in_obo_filename (:obj:`str`, optional): path to save/read PRO ontology in OBO format in_pkl_filename (:obj:`str`, optional): path to save/read parsed content of PRO ontology in_tsv_filename (:obj:`str`, optional): path to read PRO entries in TSV format in_monomers_filename (:obj:`str`, optional): path to list of ids of monomeric forms used by PRO and their alphabet code in tab-separated format max_num_proteins (:obj:`int`, optional): maximum number of proteins to analyze out_pickle_filename (:obj:`str`, optional): path to save results in pickle format out_pickle_filename_2 (:obj:`str`, optional): path to save results in pickle format out_tsv_filename (:obj:`str`, optional): path to save results in tab-separated format out_fasta_filename (:obj:`str`, optional): path to save results in FASTA format out_fig_filename (:obj:`str`, optional): path to save plot of results out_structure_dirname (:obj:`str`, optional): path to save preoteoforms in CML format out_viz_dirname (:obj:`str`, optional): path to save preoteoforms im SVG format Returns: :obj:`list` of :obj:`dict`: proteoforms encoded with BpForms """ # get the PRO ontology and extract the modified proteins from the ontology # proteins = get_pro_from_obo(obo_filename=in_obo_filename, pkl_filename=in_pkl_filename, max_num_proteins=max_num_proteins) proteins = get_pro_from_tsv(in_tsv_filename, max_num_proteins=max_num_proteins) # parse the modified proteins and retrieve their sequences if not os.path.isfile(out_pickle_filename): # parse the modified proteins and retrieve their sequences parsed_proteins = [] for i_protein, protein in enumerate(proteins): if i_protein % 100 == 0: print('Parsing protein {} of {}'.format(i_protein + 1, len(proteins))) parsed_proteins.append(parse_protein(protein)) # save the parsed proteins in pickle format with open(out_pickle_filename, 'wb') as file: pickle.dump(parsed_proteins, file) else: # load saved parsed proteins in pickle format with open(out_pickle_filename, 'rb') as file: parsed_proteins = pickle.load(file) # read list of monomers monomers = {} with open(in_monomers_filename, 'r') as file: reader = csv.DictReader(file, dialect='excel') for row in reader: monomers[row['PRO id']] = { 'mod': bpforms.protein_alphabet.monomers.get(row['BpForms code'], None), 'origin': [], } if row['Base monomer']: monomers[row['PRO id']]['origin'] = row['Base monomer'].split(', ') # generate list of modified monomeric forms for protein in parsed_proteins: for modification in protein['modifications']: if modification['monomer'] not in monomers: monomers[modification['monomer']] = { 'mod': None, 'origin': [], } # print list of unmapped monomers unmapped_monomers = [] for monomer, code in monomers.items(): if not code['mod']: unmapped_monomers.append(monomer) unmapped_monomers.sort() if unmapped_monomers: print('Several PRO monomeric forms have not been mapped to BpForms monomeric forms:\n {}'.format( '\n '.join(unmapped_monomers))) # check for inconsistencies between residue and modified monomeric form monomer_codes = {} for code, monomer in bpforms.protein_alphabet.monomers.items(): monomer_codes[monomer] = code for protein in parsed_proteins: for modification in protein.get('modifications', []): if modification['residue'] and modification['monomer']: monomer = monomers.get(modification['monomer'], None) if (monomer['mod'] and monomer['mod'].get_canonical_code(monomer_codes) != modification['residue']) \ or (monomer['origin'] and modification['residue'] not in monomer['origin']): codes = set(monomer['origin']) if monomer['mod']: codes.add(monomer['mod'].get_canonical_code(monomer_codes)) msg = 'Modified monomeric form {} potentially inconsistent with residue {} != {}'.format( modification['monomer'], modification['residue'], ', '.join(codes)) print(protein['id'] + ': ' + msg) # generate BpForms for each protein if not os.path.isdir(out_structure_dirname): os.mkdir(out_structure_dirname) if not os.path.isdir(out_viz_dirname): os.mkdir(out_viz_dirname) if not os.path.isfile(out_pickle_filename_2): for i_protein, protein in enumerate(parsed_proteins): if i_protein % 100 == 0: print('Generating BpForms {} of {}'.format(i_protein + 1, len(parsed_proteins))) protein['modified_seq'] = None if not protein['uniprot_id']: continue if not protein['seq']: continue if protein['pro_errors']: continue processed_form = gen_bpform(protein, monomers, monomer_codes, apply_modifications=False) protein['processed_seq'] = str(processed_form) if not processed_form.validate(): processed_formula = processed_form.get_formula() protein['processed_formula'] = str(processed_formula) protein['processed_mol_wt'] = processed_form.get_mol_wt() protein['processed_charge'] = processed_form.get_charge() if not protein['modifications']: continue modified_form = gen_bpform(protein, monomers, monomer_codes, include_annotations=False) protein['modified_seq'] = str(modified_form) modified_form = gen_bpform(protein, monomers, monomer_codes) if not modified_form.validate(): modified_formula = modified_form.get_formula() protein['modified_full_seq'] = str(modified_form) protein['modified_formula'] = str(modified_formula) protein['modified_mol_wt'] = modified_form.get_mol_wt() protein['modified_charge'] = modified_form.get_charge() protein['modifications_formula'] = str(modified_formula - processed_formula) protein['modifications_mol_wt'] = protein['modified_mol_wt'] - protein['processed_mol_wt'] protein['modifications_charge'] = protein['modified_charge'] - protein['processed_charge'] # with open(os.path.join(out_structure_dirname, protein['id'] + '.cml'), 'w') as file: # file.write(modified_form.export('cml')) form = gen_bpform(protein, monomers, monomer_codes, apply_processing=False, include_annotations=True) seq_features = [] if protein['processing']: seq_features.append({ 'label': 'Processed', 'color': '#cccccc', 'positions': [], }) last = 0 for p in protein['processing']: seq_features[0]['positions'].append([last + 1, p['start'] - 1]) last = p['end'] seq_features[0]['positions'].append([ protein['processing'][-1]['end'] + 1, len(form.seq), ]) if protein['processing'][0]['start'] == 1: seq_features[0]['positions'].pop(0) if protein['processing'][-1]['end'] == len(form.seq): seq_features[0]['positions'].pop(len(seq_features[0]['positions']) - 1) with open(os.path.join(out_viz_dirname, protein['id'] + '.svg'), 'w') as file: file.write(form.get_genomic_image(seq_features, width=910)) if modified_form.get_canonical_seq(monomer_codes) != protein['processed_seq']: protein['pro_errors'].append('Modified sequence for {} not compatible with the processed sequence'.format( protein['id'])) # save the parsed proteins in pickle format with open(out_pickle_filename_2, 'wb') as file: pickle.dump(parsed_proteins, file) else: with open(out_pickle_filename_2, 'rb') as file: parsed_proteins = pickle.load(file) # save the proteoforms in TSV format with open(out_tsv_filename, 'w') as file: writer = csv.writer(file, dialect='excel-tab') writer.writerow(['PRO id', 'UniProt id', 'Organism', 'Unmodified sequence (IUBMB)', 'Processing', 'Deletions', 'Processsed sequence (IUBMB)', 'Processsed formula', 'Processsed molecular weight', 'Processsed charge', 'Modifications', 'Crosslinks', 'Modified sequence (abbreviated BpForms)', 'Modified sequence (BpForms)', 'Is modified sequence concrete', 'Modified formula', 'Modified molecular weight', 'Modified charge', 'Modifications formula', 'Modifications molecular weight', 'Modifications charge', 'PRO issues', 'Monomeric form issues']) for parsed_protein in parsed_proteins: if parsed_protein.get('pro_errors', None): pro_errors = '. '.join(parsed_protein['pro_errors']) + '.' else: pro_errors = None if parsed_protein.get('modified_errors', None): modified_errors = '. '.join(parsed_protein['modified_errors']) + '.' else: modified_errors = None writer.writerow([ parsed_protein['id'], parsed_protein.get('uniprot_id', None), parsed_protein.get('organism', None), parsed_protein.get('seq', None), ', '.join('{}-{}'.format(p['start'], p['end']) for p in parsed_protein['processing']), ', '.join('{}-{}'.format(deletion[0], deletion[1]) for deletion in parsed_protein.get('deletions', [])), parsed_protein.get('processed_seq', None), parsed_protein.get('processed_formula', None), parsed_protein.get('processed_mol_wt', None), parsed_protein.get('processed_charge', None), ', '.join('{} --> {} ({})'.format(m['residue'] or '?', m['monomer'], ', '.join(str(p) for p in m['positions'])) for m in parsed_protein['modifications']), ', '.join('{}{}-{}{}'.format(xlink[0][1], xlink[0][0], xlink[1][1], xlink[1][0]) for xlink in parsed_protein.get('crosslinks', [])), parsed_protein.get('modified_seq', None), parsed_protein.get('modified_full_seq', None), parsed_protein.get('modified_concrete', False), parsed_protein.get('modified_formula', None), parsed_protein.get('modified_mol_wt', None), parsed_protein.get('modified_charge', None), parsed_protein.get('modifications_formula', None), parsed_protein.get('modifications_mol_wt', None), parsed_protein.get('modifications_charge', None), pro_errors, modified_errors, ]) # save the proteoforms in FASTA format seqs = (SeqRecord(id='{} | {}'.format(protein['id'], protein['uniprot_id']), seq=Seq(protein['modified_seq']), description='') for protein in parsed_proteins if protein['modified_seq']) SeqIO.write(seqs, out_fasta_filename, "fasta") # analyze frequency of modifications plot_modifications(parsed_proteins, fig_filename=out_fig_filename) # return proteins return proteins, parsed_proteins def get_pro_from_obo(obo_filename=IN_OBO_FILENAME, pkl_filename=IN_PKL_FILENAME, max_num_proteins=None): """ Get the PRO ontology and extract the modified proteins from the ontology Args: obo_filename (:obj:`str`, optional): filename to save PRO in OBO format pkl_filename (:obj:`str`, optional): filename to save/read PRO from pickled file max_num_proteins (:obj:`int`, optional): maximum number of proteins to analyze Returns: :obj:`list` of :obj:`dict`: list of PRO ontology terms for modified proteins """ # download PRO if not os.path.isfile(obo_filename): response = requests.get(IN_URL) response.raise_for_status() with open(obo_filename, 'wb') as file: file.write(response.content) # parse PRO or read from cache if not os.path.isfile(pkl_filename): # parse PRO proteins = [] protein = None with open(obo_filename, 'r') as file: for line in file: line = line.rstrip('\n') if line.startswith('['): if line.startswith('[Term]'): if max_num_proteins is not None and len(proteins) >= max_num_proteins: break protein = {} else: protein = None elif line and protein is not None: key, _, value = line.partition(': ') if key not in protein: protein[key] = [] protein[key].append(value) if key == 'comment' and value.startswith('Category=organism-modification.'): proteins.append(protein) # save PRO in pickle format with open(pkl_filename, 'wb') as file: pickle.dump(proteins, file) else: # load PRO from pickle format with open(pkl_filename, 'rb') as file: proteins = pickle.load(file) if max_num_proteins is not None and max_num_proteins < len(proteins): proteins = proteins[0:max_num_proteins] # return PRO return proteins def get_pro_from_tsv(filename, max_num_proteins=None): """ Extract PRO entries from TSV file Args: obo_filename (:obj:`str`, optional): filename to save PRO in OBO format max_num_proteins (:obj:`int`, optional): maximum number of proteins to analyze Returns: :obj:`list` of :obj:`dict`: list of PRO ontology terms for modified proteins """ proteins = [] with open(filename, 'r') as file: reader = csv.DictReader(file, fieldnames=('id', 'category', 'synonym_type', 'seq'), dialect='excel-tab') for row in reader: proteins.append({ 'id': [row['id']], 'category': [row['category']], 'synonym': ['"{}" {} PRO-proteoform-std'.format(row['seq'], row['synonym_type'])], }) if max_num_proteins is not None and len(proteins) >= max_num_proteins: break return proteins def parse_protein(protein): """ Parse the modification information from a term for a modified protein Args: protein (:obj:`dict`): term for a modified protein Returns: :obj:`dict` with PRO id, UniProt id, processing start position, processing end position, unmodified sequence, and modifications """ assert len(protein['id']) == 1 id = protein['id'][0] errors = [] seq_synonyms = [] for synonym in protein.get('synonym', []): if synonym.startswith('"UniProtKB:') and ' PRO-proteoform-std' in synonym: seq_synonyms.append(synonym) if not seq_synonyms: errors.append('No synonym which defines a modified sequence') return { 'id': id, 'uniprot_id': None, 'processing': [], 'modifications': [], 'seq': None, 'pro_errors': errors, } elif len(seq_synonyms) > 1: errors.append('Multiple synonyms which define modified sequences') synonym = seq_synonyms[0] uniprot_id, _, processing_modifications_type = synonym.partition(', ') uniprot_id = uniprot_id.partition(':')[2] organism_name = None response = session.get(UNIPROT_XML_ENDPOINT.format(uniprot_id)) response.raise_for_status() if response.content: xml_root = ElementTree.fromstring(response.content) entry = xml_root.find('{http://uniprot.org/uniprot}entry') organism = entry.find('{http://uniprot.org/uniprot}organism') names = organism.findall('{http://uniprot.org/uniprot}name') for name in names: if name.get('type') == 'scientific': organism_name = name.text break response = session.get(UNIPROT_SEQ_ENDPOINT.format(uniprot_id)) response.raise_for_status() seq = response.content.decode('utf-8').partition('\n')[2].replace('\n', '') if not seq: errors.append('No sequence for UniProt entry; entry may be deprecated') processing_modifications = processing_modifications_type.partition('"')[0] processing = [] while True: match = re.match(r'^(\?|\d+)\-(\?|\d+)(, |$)', processing_modifications) if match: if match.group(1) == '?': start = None errors.append('Unknown processing start position') else: start = int(float(match.group(1))) if start <= 0 or start > len(seq): errors.append('Start position must be within sequence') if match.group(2) == '?': end = None errors.append('Unknown processing end position') else: end = int(float(match.group(2))) if end <= 0 or end > len(seq): errors.append('End position must be within sequence') if start and end and start > end: errors.append('End position must be after start position') processing.append({ 'start': start, 'end': end, }) processing_modifications = processing_modifications[len(match.group(0)):] else: break if processing_modifications.startswith('which') \ or processing_modifications.startswith('with') \ or 'MOD:00046 OR Thr-163, MOD:00047' in processing_modifications: modifications_str = [] errors.append('Unable to parse sequence') elif processing_modifications: modifications_str = processing_modifications.split('|') else: modifications_str = [] modifications = [] for modification in modifications_str: if modification and modification[0] == '(' and modification[-1] == ')': modification = modification[1:-1] if ' or ' in modification or ' and/or ' in modification: errors.append('Boolean logic not supported') continue if ', ' in modification: residue_positions, _, monomer = modification.partition(', ') residue_codes = set() positions = [] for residue_position in residue_positions.split('/'): residue_chars, _, position = residue_position.partition('-') residue_code = AA_CHARS_TO_CODES[residue_chars] position = int(float(position)) if position > len(seq): errors.append('Position {} is greater than the sequence length {}'.format(position, len(seq))) elif seq[position - 1] != residue_code: errors.append('Position {} != {}'.format(position, residue_code)) residue_codes.add(residue_code) positions.append(position) if len(residue_codes) != 1 and monomer != 'PR:000026291': residue_code = None errors.append('Residues {{{}}} annotated with the same modification {}'.format( ', '.join(residue_codes), monomer)) else: residue_code = None positions = [] monomer = modification if monomer == 'PR:000026291': for residue_code in residue_codes: modifications.append({ 'residue': residue_code, 'positions': [p for p in positions if seq[p - 1] == residue_code], 'monomer': monomer, }) else: modifications.append({ 'residue': residue_code, 'positions': positions, 'monomer': monomer, }) return { 'id': id, 'uniprot_id': uniprot_id, 'organism': organism_name, 'processing': processing, 'modifications': modifications, 'seq': seq, 'pro_errors': errors, } def gen_bpform(protein, pro_ids_to_bpform_monomers, monomer_codes, apply_processing=True, apply_modifications=True, include_annotations=True): """ Generate BpForm for a modified protein in PRO Args: protein (:obj:`dict`): term for modified protein pro_ids_to_bpform_monomers (:obj:`dict`): dictionary which maps ids of monomeric forms used by PRO to monomeric forms in the BpForms protein alphabet monomer_codes (:obj:`dict`): dictionary that maps monomers to their codes in the alphabet apply_processing (:obj:`bool`, optional): if :obj:`True`, include processing in proteoform apply_modifications (:obj:`bool`, optional): if :obj:`True`, include modifications in proteoform include_annotations (:obj:`bool`, optional): if :obj:`True`, include metadata about modified monomers Returns: :obj:`bpforms.ProteinForm`: BpForm for a term in PRO """ form = bpforms.ProteinForm() monomers = bpforms.protein_alphabet.monomers # generate BpForm for unmodified sequence for base in protein['seq']: form.seq.append(monomers[base]) # apply processing modifications = copy.deepcopy(protein['modifications']) seq = protein['seq'] if apply_processing and protein['processing']: procesed_seq = [] seq = '' for processing in protein['processing']: procesed_seq.extend(form.seq[processing['start']-1:processing['end']]) seq += protein['seq'][processing['start']-1:processing['end']] form.seq = procesed_seq for modification in modifications: modification['processed_positions'] = [] for position in modification['positions']: seq_len = 0 processed_position = None for processing in protein['processing']: if position >= processing['start'] and position <= processing['end']: processed_position = seq_len + position - processing['start'] + 1 break seq_len += processing['end'] - processing['start'] + 1 if processed_position is not None: modification['processed_positions'].append(processed_position) else: for modification in modifications: modification['processed_positions'] = modification['positions'] # apply modifications if apply_modifications: concrete = True protein['modified_errors'] = [] for modification in modifications: monomer = pro_ids_to_bpform_monomers[modification['monomer']]['mod'] origin = pro_ids_to_bpform_monomers[modification['monomer']]['origin'] if modification['monomer'].startswith('CHEBI:'): mod_ns = 'chebi' elif modification['monomer'].startswith('MOD:'): mod_ns = 'mod' elif modification['monomer'].startswith('PR:'): mod_ns = 'pr' elif modification['monomer'].startswith('UniCarbKB:'): mod_ns = 'unicarbkb' else: raise ValueError('Unsupported identifier {}'.format(modification['monomer'])) if modification['monomer'] == 'PR:000026291': if include_annotations: monomer = bpforms.Monomer().from_dict( monomers[modification['residue']].to_dict( alphabet=bpforms.protein_alphabet), alphabet=bpforms.protein_alphabet) else: monomer = bpforms.Monomer() monomer.id = None monomer.name = None monomer.synonyms = [] monomer.identifiers = [bpforms.Identifier('pr', modification['monomer'])] monomer.comments = None elif modification['monomer'].startswith('CHEBI:'): if include_annotations: monomer = bpforms.Monomer().from_dict( monomers[modification['residue']].to_dict( alphabet=bpforms.protein_alphabet), alphabet=bpforms.protein_alphabet) else: monomer = bpforms.Monomer() monomer.id = None monomer.name = None monomer.synonyms = [] monomer.identifiers = [bpforms.Identifier('chebi', modification['monomer'])] monomer.comments = None elif monomer is None: concrete = False monomer = bpforms.Monomer( identifiers=[bpforms.Identifier(mod_ns, modification['monomer'])]) if modification['positions']: for position in modification['processed_positions']: if form.seq[position - 1] == monomers[seq[position - 1]]: if monomer not in bpforms.protein_alphabet.monomers.values(): monomer.base_monomers = [form.seq[position - 1]] form.seq[position - 1] = monomer else: protein['modified_errors'].append('Unable to set monomeric form at position {}'.format( position)) elif modification['residue']: concrete = False if include_annotations: monomer2 = bpforms.Monomer().from_dict( monomer.to_dict( alphabet=bpforms.protein_alphabet), alphabet=bpforms.protein_alphabet) else: monomer2 = bpforms.Monomer() monomer2.id = None monomer2.name = None monomer2.synonyms = [] monomer2.identifiers = [bpforms.Identifier(mod_ns, modification['monomer'])] monomer2.base_monomers = [bpforms.protein_alphabet.monomers.get(modification['positions'])] monomer2.start_position = seq.find(modification['residue']) + 1 monomer2.end_position = seq.rfind(modification['residue']) + 1 set_monomer = False for i_monomer in range(monomer2.start_position, monomer2.end_position + 1): if form.seq[i_monomer - 1] == monomers[seq[i_monomer - 1]]: set_monomer = True form.seq[i_monomer - 1] = monomer2 break if not set_monomer: protein['modified_errors'].append('Unable to set monomeric form') else: concrete = False canonical_code = monomer.get_canonical_code(monomer_codes) if include_annotations: monomer2 = bpforms.Monomer().from_dict( monomer.to_dict( alphabet=bpforms.protein_alphabet), alphabet=bpforms.protein_alphabet) else: monomer2 = bpforms.Monomer() monomer2.id = None monomer2.name = None monomer2.synonyms = [] monomer2.identifiers = [bpforms.Identifier(mod_ns, modification['monomer'])] monomer2.monomers_position = [ bpforms.protein_alphabet.monomers.get(code) for code in origin] if canonical_code and canonical_code != '?': start_position = seq.find(canonical_code) + 1 end_position = seq.rfind(canonical_code) + 1 if start_position == 0: protein['modified_errors'].append('Sequence does not contain residue {} for modification {}'.format( canonical_code, modification['monomer'])) else: monomer2.start_position = start_position monomer2.end_position = end_position elif origin: start_position = float('inf') end_position = -float('inf') for base in origin: start_pos = seq.find(base) + 1 if start_pos > 0: start_position = min(start_position, start_pos) end_pos = seq.rfind(base) + 1 if end_pos > 0: end_position = max(end_position, end_pos) if numpy.isinf(start_position): protein['modified_errors'].append('Sequence does not contain residues {} for modification {}'.format( ', '.join(origin), modification['monomer'])) else: monomer2.start_position = start_position monomer2.end_position = end_position else: monomer2.start_position = 1 monomer2.end_position = len(seq) if monomer2.start_position: set_monomer = False for i_monomer in range(monomer2.start_position, monomer2.end_position + 1): if form.seq[i_monomer - 1] == monomers[seq[i_monomer - 1]]: monomer2.base_monomers = [bpforms.protein_alphabet.monomers.get(seq[i_monomer - 1])] form.seq[i_monomer - 1] = monomer2 set_monomer = True break if not set_monomer: protein['modified_errors'].append('Unable to set monomeric form') # crosslinks if protein['processing']: xlinks = [] seq_len = 0 protein['crosslinks'] = [] protein['deletions'] = [] for left, right in zip(protein['processing'][0:-1], protein['processing'][1:]): seq_len += left['end'] - left['start'] + 1 i_left = seq_len i_right = i_left + 1 if left['end'] + 1 == right['start']: protein['crosslinks'].append(((left['end'], protein['seq'][left['end']-1]), (right['start'], protein['seq'][right['start'] - 1]))) else: protein['deletions'].append((left['end'] + 1, right['start'] - 1)) if left['end'] + 1 != right['start']: continue #err = False # if protein['seq'][left['end'] - 1] != 'C' or form.seq[i_left - 1] != bpforms.protein_alphabet.monomers.C: # err = True # protein['modified_errors'].append('Disulfide bond site {}{} != C'.format( # protein['seq'][left['end'] - 1], left['end'])) # if protein['seq'][right['start'] - 1] != 'C' or form.seq[i_right - 1] != bpforms.protein_alphabet.monomers.C: # err = True # protein['modified_errors'].append('Disulfide bond site {}{} != C'.format( # protein['seq'][right['start'] - 1], right['start'])) # # if err: # continue concrete = False i_left = '{}-{}'.format(seq_len - (left['end'] - left['start'] + 1) + 1, seq_len) i_right = '{}-{}'.format(seq_len + 1, seq_len + (right['end'] - right['start'] + 1)) if apply_modifications: form.crosslinks.add(bpforms.Bond( #l_bond_atoms=[bpforms.Atom(bpforms.Monomer, 'S', position=11, monomer=i_left)], #r_bond_atoms=[bpforms.Atom(bpforms.Monomer, 'S', position=11, monomer=i_right)], #l_displaced_atoms=[bpforms.Atom(bpforms.Monomer, 'H', position=11, monomer=i_left)], #r_displaced_atoms=[bpforms.Atom(bpforms.Monomer, 'H', position=11, monomer=i_right)], comments='The polymer contains a disulfide bond between the ranges {} and {}'.format(i_left, i_right), )) # validate if apply_modifications: protein['modified_concrete'] = concrete protein['modified_errors'].extend(form.validate()) # return proteoform represented with BpForms return form def plot_modifications(proteins, organism='Homo sapiens', fig_filename=OUT_FIG_FILENAME): """ Plot a summary of the modifications in PRO Args: proteins (:obj:`list` of :obj:`dict`): entries in PRO ontology organism (:obj:`str`, optional): organism to analyze fig_filename (:obj:`str`, optional): path to save analysis """ code_freq = {} canonical_code_freq = {} for protein in proteins: if (organism is None or protein.get('organism', None) == organism) and protein.get('modified_seq', None): for modification in protein['modifications']: if modification['residue'] and modification['monomer']: n_mods = max(1, len(modification['positions'])) if modification['residue'] not in canonical_code_freq: canonical_code_freq[modification['residue']] = 0 if modification['monomer'] not in code_freq: code_freq[modification['monomer']] = 0 canonical_code_freq[modification['residue']] += n_mods code_freq[modification['monomer']] += n_mods pyplot.style.use('ggplot') fig, axes = pyplot.subplots(nrows=1, ncols=2, gridspec_kw={'width_ratios': [1, 4]}) fig.set_size_inches(9.3, 1.5) plot_codes(canonical_code_freq, 'Frequency of modifications', axes[0], ignore_canonical=False) plot_codes(code_freq, 'Frequency of modified monomeric forms', axes[1], ignore_canonical=True) fig.savefig(fig_filename, transparent=True, bbox_inches=matplotlib.transforms.Bbox([[0.69, -0.5], [8.35, 1.5]])) pyplot.close(fig) def plot_codes(code_freq, title, axis, ignore_canonical=False): id_freqs = [] for code, count in code_freq.items(): if ignore_canonical and code in ['A', 'C', 'G', 'U']: continue id_freqs.append((code, count)) id_freqs.sort() y_pos = numpy.arange(len(id_freqs)) freq = numpy.array([id_freq[-1] for id_freq in id_freqs]) freq = freq / numpy.sum(freq) * 100. x_tick_labels = {id: y_pos for y_pos, (id, _) in enumerate(id_freqs)} axis.bar(y_pos, freq, align='center', alpha=0.5) axis.set_xticks(y_pos) axis.set_xticklabels(x_tick_labels, rotation=270, fontsize=6, fontfamily='Raleway') axis.set_ylabel('Frequency (%)', fontdict={ 'fontsize': 10, 'fontweight': 'regular', 'fontfamily': 'Raleway', }) axis.set_title(title, fontdict={ 'fontsize': 10, 'fontweight': 'regular', 'fontfamily': 'Raleway', }) axis.set_xlim((-0.75, len(id_freqs) - 0.25))
[ "csv.DictReader", "Bio.Seq.Seq", "numpy.array", "bpforms.protein_alphabet.monomers.values", "copy.deepcopy", "requests_cache.core.CachedSession", "matplotlib.pyplot.style.use", "bpforms.protein_alphabet.monomers.items", "matplotlib.pyplot.close", "os.path.isdir", "os.mkdir", "Bio.SeqIO.write", "xml.etree.ElementTree.fromstring", "numpy.isinf", "bpforms.protein_alphabet.monomers.get", "bpforms.ProteinForm", "requests.adapters.HTTPAdapter", "re.match", "csv.writer", "requests.get", "pickle.load", "os.path.isfile", "matplotlib.transforms.Bbox", "bpforms.Monomer", "bpforms.Identifier", "pickle.dump", "os.path.join", "numpy.sum", "matplotlib.pyplot.subplots" ]
[((568, 615), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_nonreasoned.obo"""'], {}), "('examples', 'pro_nonreasoned.obo')\n", (580, 615), False, 'import os\n'), ((634, 681), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_nonreasoned.pkl"""'], {}), "('examples', 'pro_nonreasoned.pkl')\n", (646, 681), False, 'import os\n'), ((700, 744), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_input.in.tsv"""'], {}), "('examples', 'pro_input.in.tsv')\n", (712, 744), False, 'import os\n'), ((783, 827), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro.monomers.csv"""'], {}), "('examples', 'pro.monomers.csv')\n", (795, 827), False, 'import os\n'), ((981, 1026), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_input.out.pkl"""'], {}), "('examples', 'pro_input.out.pkl')\n", (993, 1026), False, 'import os\n'), ((1051, 1098), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_input.out.2.pkl"""'], {}), "('examples', 'pro_input.out.2.pkl')\n", (1063, 1098), False, 'import os\n'), ((1118, 1163), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_input.out.tsv"""'], {}), "('examples', 'pro_input.out.tsv')\n", (1130, 1163), False, 'import os\n'), ((1185, 1228), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_input.fasta"""'], {}), "('examples', 'pro_input.fasta')\n", (1197, 1228), False, 'import os\n'), ((1248, 1289), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_input.svg"""'], {}), "('examples', 'pro_input.svg')\n", (1260, 1289), False, 'import os\n'), ((1314, 1361), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_input_structure"""'], {}), "('examples', 'pro_input_structure')\n", (1326, 1361), False, 'import os\n'), ((1380, 1421), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro_input_viz"""'], {}), "('examples', 'pro_input_viz')\n", (1392, 1421), False, 'import os\n'), ((1436, 1467), 'os.path.join', 'os.path.join', (['"""examples"""', '"""pro"""'], {}), "('examples', 'pro')\n", (1448, 1467), False, 'import os\n'), ((1478, 1564), 'requests_cache.core.CachedSession', 'requests_cache.core.CachedSession', (['cache_name'], {'backend': '"""sqlite"""', 'expire_after': 'None'}), "(cache_name, backend='sqlite',\n expire_after=None)\n", (1511, 1564), False, 'import requests_cache\n'), ((1603, 1647), 'requests.adapters.HTTPAdapter', 'requests.adapters.HTTPAdapter', ([], {'max_retries': '(5)'}), '(max_retries=5)\n', (1632, 1647), False, 'import requests\n'), ((6201, 6242), 'bpforms.protein_alphabet.monomers.items', 'bpforms.protein_alphabet.monomers.items', ([], {}), '()\n', (6240, 6242), False, 'import bpforms\n'), ((14665, 14711), 'Bio.SeqIO.write', 'SeqIO.write', (['seqs', 'out_fasta_filename', '"""fasta"""'], {}), "(seqs, out_fasta_filename, 'fasta')\n", (14676, 14711), False, 'from Bio import SeqIO\n'), ((24825, 24846), 'bpforms.ProteinForm', 'bpforms.ProteinForm', ([], {}), '()\n', (24844, 24846), False, 'import bpforms\n'), ((25059, 25098), 'copy.deepcopy', 'copy.deepcopy', (["protein['modifications']"], {}), "(protein['modifications'])\n", (25072, 25098), False, 'import copy\n'), ((37373, 37399), 'matplotlib.pyplot.style.use', 'pyplot.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (37389, 37399), False, 'from matplotlib import pyplot\n'), ((37416, 37487), 'matplotlib.pyplot.subplots', 'pyplot.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'gridspec_kw': "{'width_ratios': [1, 4]}"}), "(nrows=1, ncols=2, gridspec_kw={'width_ratios': [1, 4]})\n", (37431, 37487), False, 'from matplotlib import pyplot\n'), ((37917, 37934), 'matplotlib.pyplot.close', 'pyplot.close', (['fig'], {}), '(fig)\n', (37929, 37934), False, 'from matplotlib import pyplot\n'), ((38255, 38305), 'numpy.array', 'numpy.array', (['[id_freq[-1] for id_freq in id_freqs]'], {}), '([id_freq[-1] for id_freq in id_freqs])\n', (38266, 38305), False, 'import numpy\n'), ((4189, 4224), 'os.path.isfile', 'os.path.isfile', (['out_pickle_filename'], {}), '(out_pickle_filename)\n', (4203, 4224), False, 'import os\n'), ((4994, 5031), 'csv.DictReader', 'csv.DictReader', (['file'], {'dialect': '"""excel"""'}), "(file, dialect='excel')\n", (5008, 5031), False, 'import csv\n'), ((7244, 7280), 'os.path.isdir', 'os.path.isdir', (['out_structure_dirname'], {}), '(out_structure_dirname)\n', (7257, 7280), False, 'import os\n'), ((7290, 7321), 'os.mkdir', 'os.mkdir', (['out_structure_dirname'], {}), '(out_structure_dirname)\n', (7298, 7321), False, 'import os\n'), ((7334, 7364), 'os.path.isdir', 'os.path.isdir', (['out_viz_dirname'], {}), '(out_viz_dirname)\n', (7347, 7364), False, 'import os\n'), ((7374, 7399), 'os.mkdir', 'os.mkdir', (['out_viz_dirname'], {}), '(out_viz_dirname)\n', (7382, 7399), False, 'import os\n'), ((7412, 7449), 'os.path.isfile', 'os.path.isfile', (['out_pickle_filename_2'], {}), '(out_pickle_filename_2)\n', (7426, 7449), False, 'import os\n'), ((11446, 11483), 'csv.writer', 'csv.writer', (['file'], {'dialect': '"""excel-tab"""'}), "(file, dialect='excel-tab')\n", (11456, 11483), False, 'import csv\n'), ((15477, 15505), 'os.path.isfile', 'os.path.isfile', (['obo_filename'], {}), '(obo_filename)\n', (15491, 15505), False, 'import os\n'), ((15526, 15546), 'requests.get', 'requests.get', (['IN_URL'], {}), '(IN_URL)\n', (15538, 15546), False, 'import requests\n'), ((15718, 15746), 'os.path.isfile', 'os.path.isfile', (['pkl_filename'], {}), '(pkl_filename)\n', (15732, 15746), False, 'import os\n'), ((17525, 17624), 'csv.DictReader', 'csv.DictReader', (['file'], {'fieldnames': "('id', 'category', 'synonym_type', 'seq')", 'dialect': '"""excel-tab"""'}), "(file, fieldnames=('id', 'category', 'synonym_type', 'seq'),\n dialect='excel-tab')\n", (17539, 17624), False, 'import csv\n'), ((19335, 19375), 'xml.etree.ElementTree.fromstring', 'ElementTree.fromstring', (['response.content'], {}), '(response.content)\n', (19357, 19375), False, 'from xml.etree import ElementTree\n'), ((20131, 20199), 're.match', 're.match', (['"""^(\\\\?|\\\\d+)\\\\-(\\\\?|\\\\d+)(, |$)"""', 'processing_modifications'], {}), "('^(\\\\?|\\\\d+)\\\\-(\\\\?|\\\\d+)(, |$)', processing_modifications)\n", (20139, 20199), False, 'import re\n'), ((4679, 4713), 'pickle.dump', 'pickle.dump', (['parsed_proteins', 'file'], {}), '(parsed_proteins, file)\n', (4690, 4713), False, 'import pickle\n'), ((4862, 4879), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (4873, 4879), False, 'import pickle\n'), ((11192, 11226), 'pickle.dump', 'pickle.dump', (['parsed_proteins', 'file'], {}), '(parsed_proteins, file)\n', (11203, 11226), False, 'import pickle\n'), ((11323, 11340), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (11334, 11340), False, 'import pickle\n'), ((16735, 16762), 'pickle.dump', 'pickle.dump', (['proteins', 'file'], {}), '(proteins, file)\n', (16746, 16762), False, 'import pickle\n'), ((16881, 16898), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (16892, 16898), False, 'import pickle\n'), ((37856, 37911), 'matplotlib.transforms.Bbox', 'matplotlib.transforms.Bbox', (['[[0.69, -0.5], [8.35, 1.5]]'], {}), '([[0.69, -0.5], [8.35, 1.5]])\n', (37882, 37911), False, 'import matplotlib\n'), ((38324, 38339), 'numpy.sum', 'numpy.sum', (['freq'], {}), '(freq)\n', (38333, 38339), False, 'import numpy\n'), ((5122, 5186), 'bpforms.protein_alphabet.monomers.get', 'bpforms.protein_alphabet.monomers.get', (["row['BpForms code']", 'None'], {}), "(row['BpForms code'], None)\n", (5159, 5186), False, 'import bpforms\n'), ((14510, 14538), 'Bio.Seq.Seq', 'Seq', (["protein['modified_seq']"], {}), "(protein['modified_seq'])\n", (14513, 14538), False, 'from Bio.Seq import Seq\n'), ((27504, 27521), 'bpforms.Monomer', 'bpforms.Monomer', ([], {}), '()\n', (27519, 27521), False, 'import bpforms\n'), ((27669, 27718), 'bpforms.Identifier', 'bpforms.Identifier', (['"""pr"""', "modification['monomer']"], {}), "('pr', modification['monomer'])\n", (27687, 27718), False, 'import bpforms\n'), ((10671, 10724), 'os.path.join', 'os.path.join', (['out_viz_dirname', "(protein['id'] + '.svg')"], {}), "(out_viz_dirname, protein['id'] + '.svg')\n", (10683, 10724), False, 'import os\n'), ((28165, 28182), 'bpforms.Monomer', 'bpforms.Monomer', ([], {}), '()\n', (28180, 28182), False, 'import bpforms\n'), ((28330, 28382), 'bpforms.Identifier', 'bpforms.Identifier', (['"""chebi"""', "modification['monomer']"], {}), "('chebi', modification['monomer'])\n", (28348, 28382), False, 'import bpforms\n'), ((29604, 29621), 'bpforms.Monomer', 'bpforms.Monomer', ([], {}), '()\n', (29619, 29621), False, 'import bpforms\n'), ((29773, 29824), 'bpforms.Identifier', 'bpforms.Identifier', (['mod_ns', "modification['monomer']"], {}), "(mod_ns, modification['monomer'])\n", (29791, 29824), False, 'import bpforms\n'), ((29868, 29932), 'bpforms.protein_alphabet.monomers.get', 'bpforms.protein_alphabet.monomers.get', (["modification['positions']"], {}), "(modification['positions'])\n", (29905, 29932), False, 'import bpforms\n'), ((31000, 31017), 'bpforms.Monomer', 'bpforms.Monomer', ([], {}), '()\n', (31015, 31017), False, 'import bpforms\n'), ((31169, 31220), 'bpforms.Identifier', 'bpforms.Identifier', (['mod_ns', "modification['monomer']"], {}), "(mod_ns, modification['monomer'])\n", (31187, 31220), False, 'import bpforms\n'), ((31289, 31332), 'bpforms.protein_alphabet.monomers.get', 'bpforms.protein_alphabet.monomers.get', (['code'], {}), '(code)\n', (31326, 31332), False, 'import bpforms\n'), ((27233, 27250), 'bpforms.Monomer', 'bpforms.Monomer', ([], {}), '()\n', (27248, 27250), False, 'import bpforms\n'), ((28855, 28897), 'bpforms.protein_alphabet.monomers.values', 'bpforms.protein_alphabet.monomers.values', ([], {}), '()\n', (28895, 28897), False, 'import bpforms\n'), ((32468, 32495), 'numpy.isinf', 'numpy.isinf', (['start_position'], {}), '(start_position)\n', (32479, 32495), False, 'import numpy\n'), ((27894, 27911), 'bpforms.Monomer', 'bpforms.Monomer', ([], {}), '()\n', (27909, 27911), False, 'import bpforms\n'), ((29358, 29375), 'bpforms.Monomer', 'bpforms.Monomer', ([], {}), '()\n', (29373, 29375), False, 'import bpforms\n'), ((30754, 30771), 'bpforms.Monomer', 'bpforms.Monomer', ([], {}), '()\n', (30769, 30771), False, 'import bpforms\n'), ((28569, 28620), 'bpforms.Identifier', 'bpforms.Identifier', (['mod_ns', "modification['monomer']"], {}), "(mod_ns, modification['monomer'])\n", (28587, 28620), False, 'import bpforms\n'), ((33291, 33348), 'bpforms.protein_alphabet.monomers.get', 'bpforms.protein_alphabet.monomers.get', (['seq[i_monomer - 1]'], {}), '(seq[i_monomer - 1])\n', (33328, 33348), False, 'import bpforms\n')]
import argparse import contextlib import csv import logging import os import random import subprocess import tempfile from typing import Callable, Dict, Iterable, List import numpy as np import ray from ray.experimental.raysort import constants from ray.experimental.raysort import logging_utils from ray.experimental.raysort import sortlib from ray.experimental.raysort import tracing_utils from ray.experimental.raysort.types import ( BlockInfo, ByteCount, RecordCount, PartId, PartInfo, Path, ) Args = argparse.Namespace # ------------------------------------------------------------ # Parse Arguments # ------------------------------------------------------------ def get_args(*args, **kwargs): parser = argparse.ArgumentParser() parser.add_argument( "--ray_address", default="auto", type=str, help="if set to None, will launch a local Ray cluster", ) parser.add_argument( "--total_data_size", default=1 * 1000 * 1024 * 1024 * 1024, type=ByteCount, help="total data size in bytes", ) parser.add_argument( "--num_mappers", default=256, type=int, help="number of map tasks", ) parser.add_argument( "--num_mappers_per_round", default=16, type=int, help="number of map tasks per first-stage merge tasks", ) parser.add_argument( "--num_reducers", default=16, type=int, help="number of second-stage reduce tasks", ) parser.add_argument( "--num_concurrent_rounds", default=4, type=int, help="max number of rounds of map/merge tasks in flight", ) parser.add_argument( "--reducer_input_chunk", default=100 * 1024 * 1024, type=ByteCount, help="bytes to read from each file in reduce tasks", ) parser.add_argument( "--skip_sorting", default=False, action="store_true", help="if set, no sorting is actually performed", ) parser.add_argument( "--skip_input", default=False, action="store_true", help="if set, mappers will not read data from disk", ) parser.add_argument( "--skip_output", default=False, action="store_true", help="if set, reducers will not write out results to disk", ) # Which tasks to run? tasks_group = parser.add_argument_group( "tasks to run", "if no task is specified, will run all tasks" ) tasks = ["generate_input", "sort", "validate_output"] for task in tasks: tasks_group.add_argument(f"--{task}", action="store_true") args = parser.parse_args(*args, **kwargs) # Derive additional arguments. args.input_part_size = ByteCount(args.total_data_size / args.num_mappers) assert args.num_mappers % args.num_mappers_per_round == 0 args.num_rounds = int(args.num_mappers / args.num_mappers_per_round) args.mount_points = _get_mount_points() # If no tasks are specified, run all tasks. args_dict = vars(args) if not any(args_dict[task] for task in tasks): for task in tasks: args_dict[task] = True return args def _get_mount_points(): default_ret = [tempfile.gettempdir()] mnt = "/mnt" if os.path.exists(mnt): ret = [os.path.join(mnt, d) for d in os.listdir(mnt)] if len(ret) > 0: return ret return default_ret # ------------------------------------------------------------ # Generate Input # ------------------------------------------------------------ def _part_info(args: Args, part_id: PartId, kind="input") -> PartInfo: node = ray.worker.global_worker.node_ip_address mnt = random.choice(args.mount_points) filepath = _get_part_path(mnt, part_id, kind) return PartInfo(part_id, node, filepath) def _get_part_path(mnt: Path, part_id: PartId, kind="input") -> Path: assert kind in {"input", "output", "temp"} dir_fmt = constants.DATA_DIR_FMT[kind] dirpath = dir_fmt.format(mnt=mnt) os.makedirs(dirpath, exist_ok=True) filename_fmt = constants.FILENAME_FMT[kind] filename = filename_fmt.format(part_id=part_id) filepath = os.path.join(dirpath, filename) return filepath @ray.remote def generate_part( args: Args, part_id: PartId, size: RecordCount, offset: RecordCount ) -> PartInfo: logging_utils.init() pinfo = _part_info(args, part_id) subprocess.run( [constants.GENSORT_PATH, f"-b{offset}", f"{size}", pinfo.path], check=True ) logging.info(f"Generated input {pinfo}") return pinfo def generate_input(args: Args): if args.skip_input: return size = constants.bytes_to_records(args.input_part_size) offset = 0 tasks = [] for part_id in range(args.num_mappers): tasks.append(generate_part.remote(args, part_id, size, offset)) offset += size assert offset == constants.bytes_to_records(args.total_data_size), args logging.info(f"Generating {len(tasks)} partitions") parts = ray.get(tasks) with open(constants.INPUT_MANIFEST_FILE, "w") as fout: writer = csv.writer(fout) writer.writerows(parts) # ------------------------------------------------------------ # Sort # ------------------------------------------------------------ def _load_manifest(args: Args, path: Path) -> List[PartInfo]: if args.skip_input: return [PartInfo(i, None, None) for i in range(args.num_mappers)] with open(path) as fin: reader = csv.reader(fin) return [PartInfo(int(part_id), node, path) for part_id, node, path in reader] def _load_partition(args: Args, path: Path) -> np.ndarray: if args.skip_input: return np.frombuffer( np.random.bytes(args.input_part_size), dtype=np.uint8 ).copy() return np.fromfile(path, dtype=np.uint8) def _dummy_sort_and_partition( part: np.ndarray, boundaries: List[int] ) -> List[BlockInfo]: N = len(boundaries) offset = 0 size = int(np.ceil(part.size / N)) blocks = [] for _ in range(N): blocks.append((offset, size)) offset += size return blocks @ray.remote @tracing_utils.timeit("map") def mapper( args: Args, mapper_id: PartId, boundaries: List[int], path: Path ) -> List[np.ndarray]: logging_utils.init() part = _load_partition(args, path) sort_fn = ( _dummy_sort_and_partition if args.skip_sorting else sortlib.sort_and_partition ) blocks = sort_fn(part, boundaries) return [part[offset : offset + size] for offset, size in blocks] def _dummy_merge( num_blocks: int, _n: int, get_block: Callable[[int, int], np.ndarray] ) -> Iterable[np.ndarray]: blocks = [((i, 0), get_block(i, 0)) for i in range(num_blocks)] while len(blocks) > 0: (m, d), block = blocks.pop(random.randrange(len(blocks))) yield block d_ = d + 1 block = get_block(m, d_) if block is None: continue blocks.append(((m, d_), block)) def _merge_impl( args: Args, M: int, pinfo: PartInfo, get_block: Callable[[int, int], np.ndarray], skip_output=False, ): merge_fn = _dummy_merge if args.skip_sorting else sortlib.merge_partitions merger = merge_fn(M, get_block) if skip_output: for datachunk in merger: del datachunk else: with open(pinfo.path, "wb") as fout: for datachunk in merger: fout.write(datachunk) return pinfo # See worker_placement_groups() for why `num_cpus=0`. @ray.remote(num_cpus=0, resources={"worker": 1}) @tracing_utils.timeit("merge") def merge_mapper_blocks( args: Args, reducer_id: PartId, mapper_id: PartId, *blocks: List[np.ndarray] ) -> PartInfo: part_id = constants.merge_part_ids(reducer_id, mapper_id) pinfo = _part_info(args, part_id, kind="temp") M = len(blocks) def get_block(i, d): if i >= M or d > 0: return None return blocks[i] return _merge_impl(args, M, pinfo, get_block) # See worker_placement_groups() for why `num_cpus=0`. @ray.remote(num_cpus=0, resources={"worker": 1}) @tracing_utils.timeit("reduce") def final_merge( args: Args, reducer_id: PartId, *merged_parts: List[PartInfo] ) -> PartInfo: M = len(merged_parts) def _load_block_chunk(pinfo: PartInfo, d: int) -> np.ndarray: return np.fromfile( pinfo.path, dtype=np.uint8, count=args.reducer_input_chunk, offset=d * args.reducer_input_chunk, ) def get_block(i, d): ret = _load_block_chunk(merged_parts[i], d) if ret.size == 0: return None return ret pinfo = _part_info(args, reducer_id, "output") return _merge_impl(args, M, pinfo, get_block, args.skip_output) def _node_res(node: str) -> Dict[str, float]: return {"resources": {f"node:{node}": 1e-3}} @contextlib.contextmanager def worker_placement_groups(args: Args) -> List[ray.PlacementGroupID]: """ Returns one placement group per node with a `worker` resource. To run tasks in the placement group, use `@ray.remote(num_cpus=0, resources={"worker": 1})`. Ray does not automatically reserve CPU resources, so tasks must specify `num_cpus=0` in order to run in a placement group. """ pgs = [ray.util.placement_group([{"worker": 1}]) for _ in range(args.num_reducers)] ray.get([pg.ready() for pg in pgs]) try: yield pgs finally: for pg in pgs: ray.util.remove_placement_group(pg) @tracing_utils.timeit("sort", report_time=True) def sort_main(args: Args): parts = _load_manifest(args, constants.INPUT_MANIFEST_FILE) assert len(parts) == args.num_mappers boundaries = sortlib.get_boundaries(args.num_reducers) mapper_opt = { "num_returns": args.num_reducers, "num_cpus": os.cpu_count() / args.num_concurrent_rounds, } # Load balance across worker nodes by setting `num_cpus`. merge_results = np.empty((args.num_rounds, args.num_reducers), dtype=object) part_id = 0 with worker_placement_groups(args) as pgs: for round in range(args.num_rounds): # Limit the number of in-flight rounds. num_extra_rounds = round - args.num_concurrent_rounds + 1 if num_extra_rounds > 0: ray.wait( [f for f in merge_results.flatten() if f is not None], num_returns=num_extra_rounds * args.num_reducers, ) # Submit map tasks. mapper_results = np.empty( (args.num_mappers_per_round, args.num_reducers), dtype=object ) for _ in range(args.num_mappers_per_round): _, node, path = parts[part_id] m = part_id % args.num_mappers_per_round mapper_results[m, :] = mapper.options(**mapper_opt).remote( args, part_id, boundaries, path ) part_id += 1 # Submit merge tasks. merge_results[round, :] = [ merge_mapper_blocks.options(placement_group=pgs[r]).remote( args, r, round, *mapper_results[:, r].tolist() ) for r in range(args.num_reducers) ] # Delete local references to mapper results. mapper_results = None # Submit second-stage reduce tasks. reducer_results = [ final_merge.options(placement_group=pgs[r]).remote( args, r, *merge_results[:, r].tolist() ) for r in range(args.num_reducers) ] reducer_results = ray.get(reducer_results) if not args.skip_output: with open(constants.OUTPUT_MANIFEST_FILE, "w") as fout: writer = csv.writer(fout) writer.writerows(reducer_results) logging.info(ray.internal.internal_api.memory_summary(stats_only=True)) # ------------------------------------------------------------ # Validate Output # ------------------------------------------------------------ def _run_valsort(args: List[str]): proc = subprocess.run([constants.VALSORT_PATH] + args, capture_output=True) if proc.returncode != 0: logging.critical("\n" + proc.stderr.decode("ascii")) raise RuntimeError(f"Validation failed: {args}") @ray.remote def validate_part(path: Path): logging_utils.init() sum_path = path + ".sum" _run_valsort(["-o", sum_path, path]) logging.info(f"Validated output {path}") with open(sum_path, "rb") as fin: return os.path.getsize(path), fin.read() def validate_output(args: Args): if args.skip_sorting or args.skip_output: return partitions = _load_manifest(args, constants.OUTPUT_MANIFEST_FILE) results = [] for _, node, path in partitions: results.append(validate_part.options(**_node_res(node)).remote(path)) logging.info(f"Validating {len(results)} partitions") results = ray.get(results) total = sum(s for s, _ in results) assert total == args.total_data_size, total - args.total_data_size all_checksum = b"".join(c for _, c in results) with tempfile.NamedTemporaryFile() as fout: fout.write(all_checksum) fout.flush() _run_valsort(["-s", fout.name]) logging.info("All OK!") # ------------------------------------------------------------ # Main # ------------------------------------------------------------ def init(args: Args): if not args.ray_address: ray.init(resources={"worker": os.cpu_count()}) else: ray.init(address=args.ray_address) logging_utils.init() logging.info(args) os.makedirs(constants.WORK_DIR, exist_ok=True) resources = ray.cluster_resources() logging.info(resources) args.num_workers = resources["worker"] progress_tracker = tracing_utils.create_progress_tracker(args) return progress_tracker def main(args: Args): # Keep the actor handle in scope for the duration of the program. _progress_tracker = init(args) # noqa F841 if args.generate_input: generate_input(args) if args.sort: sort_main(args) if args.validate_output: validate_output(args) if __name__ == "__main__": main(get_args())
[ "numpy.fromfile", "numpy.random.bytes", "ray.cluster_resources", "ray.experimental.raysort.types.PartInfo", "os.cpu_count", "ray.init", "logging.info", "os.path.exists", "os.listdir", "argparse.ArgumentParser", "ray.experimental.raysort.logging_utils.init", "subprocess.run", "ray.util.remove_placement_group", "ray.experimental.raysort.tracing_utils.create_progress_tracker", "numpy.empty", "ray.experimental.raysort.constants.bytes_to_records", "tempfile.NamedTemporaryFile", "ray.remote", "csv.reader", "ray.experimental.raysort.types.ByteCount", "numpy.ceil", "random.choice", "os.path.getsize", "ray.get", "csv.writer", "ray.experimental.raysort.tracing_utils.timeit", "ray.internal.internal_api.memory_summary", "ray.experimental.raysort.sortlib.get_boundaries", "ray.util.placement_group", "os.makedirs", "os.path.join", "tempfile.gettempdir", "ray.experimental.raysort.constants.merge_part_ids" ]
[((6260, 6287), 'ray.experimental.raysort.tracing_utils.timeit', 'tracing_utils.timeit', (['"""map"""'], {}), "('map')\n", (6280, 6287), False, 'from ray.experimental.raysort import tracing_utils\n'), ((7656, 7703), 'ray.remote', 'ray.remote', ([], {'num_cpus': '(0)', 'resources': "{'worker': 1}"}), "(num_cpus=0, resources={'worker': 1})\n", (7666, 7703), False, 'import ray\n'), ((7705, 7734), 'ray.experimental.raysort.tracing_utils.timeit', 'tracing_utils.timeit', (['"""merge"""'], {}), "('merge')\n", (7725, 7734), False, 'from ray.experimental.raysort import tracing_utils\n'), ((8200, 8247), 'ray.remote', 'ray.remote', ([], {'num_cpus': '(0)', 'resources': "{'worker': 1}"}), "(num_cpus=0, resources={'worker': 1})\n", (8210, 8247), False, 'import ray\n'), ((8249, 8279), 'ray.experimental.raysort.tracing_utils.timeit', 'tracing_utils.timeit', (['"""reduce"""'], {}), "('reduce')\n", (8269, 8279), False, 'from ray.experimental.raysort import tracing_utils\n'), ((9675, 9721), 'ray.experimental.raysort.tracing_utils.timeit', 'tracing_utils.timeit', (['"""sort"""'], {'report_time': '(True)'}), "('sort', report_time=True)\n", (9695, 9721), False, 'from ray.experimental.raysort import tracing_utils\n'), ((746, 771), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (769, 771), False, 'import argparse\n'), ((2819, 2869), 'ray.experimental.raysort.types.ByteCount', 'ByteCount', (['(args.total_data_size / args.num_mappers)'], {}), '(args.total_data_size / args.num_mappers)\n', (2828, 2869), False, 'from ray.experimental.raysort.types import BlockInfo, ByteCount, RecordCount, PartId, PartInfo, Path\n'), ((3346, 3365), 'os.path.exists', 'os.path.exists', (['mnt'], {}), '(mnt)\n', (3360, 3365), False, 'import os\n'), ((3784, 3816), 'random.choice', 'random.choice', (['args.mount_points'], {}), '(args.mount_points)\n', (3797, 3816), False, 'import random\n'), ((3878, 3911), 'ray.experimental.raysort.types.PartInfo', 'PartInfo', (['part_id', 'node', 'filepath'], {}), '(part_id, node, filepath)\n', (3886, 3911), False, 'from ray.experimental.raysort.types import BlockInfo, ByteCount, RecordCount, PartId, PartInfo, Path\n'), ((4116, 4151), 'os.makedirs', 'os.makedirs', (['dirpath'], {'exist_ok': '(True)'}), '(dirpath, exist_ok=True)\n', (4127, 4151), False, 'import os\n'), ((4267, 4298), 'os.path.join', 'os.path.join', (['dirpath', 'filename'], {}), '(dirpath, filename)\n', (4279, 4298), False, 'import os\n'), ((4443, 4463), 'ray.experimental.raysort.logging_utils.init', 'logging_utils.init', ([], {}), '()\n', (4461, 4463), False, 'from ray.experimental.raysort import logging_utils\n'), ((4506, 4601), 'subprocess.run', 'subprocess.run', (["[constants.GENSORT_PATH, f'-b{offset}', f'{size}', pinfo.path]"], {'check': '(True)'}), "([constants.GENSORT_PATH, f'-b{offset}', f'{size}', pinfo.\n path], check=True)\n", (4520, 4601), False, 'import subprocess\n'), ((4615, 4655), 'logging.info', 'logging.info', (['f"""Generated input {pinfo}"""'], {}), "(f'Generated input {pinfo}')\n", (4627, 4655), False, 'import logging\n'), ((4757, 4805), 'ray.experimental.raysort.constants.bytes_to_records', 'constants.bytes_to_records', (['args.input_part_size'], {}), '(args.input_part_size)\n', (4783, 4805), False, 'from ray.experimental.raysort import constants\n'), ((5119, 5133), 'ray.get', 'ray.get', (['tasks'], {}), '(tasks)\n', (5126, 5133), False, 'import ray\n'), ((5916, 5949), 'numpy.fromfile', 'np.fromfile', (['path'], {'dtype': 'np.uint8'}), '(path, dtype=np.uint8)\n', (5927, 5949), True, 'import numpy as np\n'), ((6396, 6416), 'ray.experimental.raysort.logging_utils.init', 'logging_utils.init', ([], {}), '()\n', (6414, 6416), False, 'from ray.experimental.raysort import logging_utils\n'), ((7870, 7917), 'ray.experimental.raysort.constants.merge_part_ids', 'constants.merge_part_ids', (['reducer_id', 'mapper_id'], {}), '(reducer_id, mapper_id)\n', (7894, 7917), False, 'from ray.experimental.raysort import constants\n'), ((9872, 9913), 'ray.experimental.raysort.sortlib.get_boundaries', 'sortlib.get_boundaries', (['args.num_reducers'], {}), '(args.num_reducers)\n', (9894, 9913), False, 'from ray.experimental.raysort import sortlib\n'), ((10126, 10186), 'numpy.empty', 'np.empty', (['(args.num_rounds, args.num_reducers)'], {'dtype': 'object'}), '((args.num_rounds, args.num_reducers), dtype=object)\n', (10134, 10186), True, 'import numpy as np\n'), ((12301, 12369), 'subprocess.run', 'subprocess.run', (['([constants.VALSORT_PATH] + args)'], {'capture_output': '(True)'}), '([constants.VALSORT_PATH] + args, capture_output=True)\n', (12315, 12369), False, 'import subprocess\n'), ((12566, 12586), 'ray.experimental.raysort.logging_utils.init', 'logging_utils.init', ([], {}), '()\n', (12584, 12586), False, 'from ray.experimental.raysort import logging_utils\n'), ((12661, 12701), 'logging.info', 'logging.info', (['f"""Validated output {path}"""'], {}), "(f'Validated output {path}')\n", (12673, 12701), False, 'import logging\n'), ((13159, 13175), 'ray.get', 'ray.get', (['results'], {}), '(results)\n', (13166, 13175), False, 'import ray\n'), ((13483, 13506), 'logging.info', 'logging.info', (['"""All OK!"""'], {}), "('All OK!')\n", (13495, 13506), False, 'import logging\n'), ((13811, 13831), 'ray.experimental.raysort.logging_utils.init', 'logging_utils.init', ([], {}), '()\n', (13829, 13831), False, 'from ray.experimental.raysort import logging_utils\n'), ((13836, 13854), 'logging.info', 'logging.info', (['args'], {}), '(args)\n', (13848, 13854), False, 'import logging\n'), ((13859, 13905), 'os.makedirs', 'os.makedirs', (['constants.WORK_DIR'], {'exist_ok': '(True)'}), '(constants.WORK_DIR, exist_ok=True)\n', (13870, 13905), False, 'import os\n'), ((13922, 13945), 'ray.cluster_resources', 'ray.cluster_resources', ([], {}), '()\n', (13943, 13945), False, 'import ray\n'), ((13950, 13973), 'logging.info', 'logging.info', (['resources'], {}), '(resources)\n', (13962, 13973), False, 'import logging\n'), ((14040, 14083), 'ray.experimental.raysort.tracing_utils.create_progress_tracker', 'tracing_utils.create_progress_tracker', (['args'], {}), '(args)\n', (14077, 14083), False, 'from ray.experimental.raysort import tracing_utils\n'), ((3299, 3320), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (3318, 3320), False, 'import tempfile\n'), ((4996, 5044), 'ray.experimental.raysort.constants.bytes_to_records', 'constants.bytes_to_records', (['args.total_data_size'], {}), '(args.total_data_size)\n', (5022, 5044), False, 'from ray.experimental.raysort import constants\n'), ((5210, 5226), 'csv.writer', 'csv.writer', (['fout'], {}), '(fout)\n', (5220, 5226), False, 'import csv\n'), ((5605, 5620), 'csv.reader', 'csv.reader', (['fin'], {}), '(fin)\n', (5615, 5620), False, 'import csv\n'), ((6103, 6125), 'numpy.ceil', 'np.ceil', (['(part.size / N)'], {}), '(part.size / N)\n', (6110, 6125), True, 'import numpy as np\n'), ((8486, 8598), 'numpy.fromfile', 'np.fromfile', (['pinfo.path'], {'dtype': 'np.uint8', 'count': 'args.reducer_input_chunk', 'offset': '(d * args.reducer_input_chunk)'}), '(pinfo.path, dtype=np.uint8, count=args.reducer_input_chunk,\n offset=d * args.reducer_input_chunk)\n', (8497, 8598), True, 'import numpy as np\n'), ((9444, 9485), 'ray.util.placement_group', 'ray.util.placement_group', (["[{'worker': 1}]"], {}), "([{'worker': 1}])\n", (9468, 9485), False, 'import ray\n'), ((11823, 11847), 'ray.get', 'ray.get', (['reducer_results'], {}), '(reducer_results)\n', (11830, 11847), False, 'import ray\n'), ((12044, 12101), 'ray.internal.internal_api.memory_summary', 'ray.internal.internal_api.memory_summary', ([], {'stats_only': '(True)'}), '(stats_only=True)\n', (12084, 12101), False, 'import ray\n'), ((13346, 13375), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\n', (13373, 13375), False, 'import tempfile\n'), ((13772, 13806), 'ray.init', 'ray.init', ([], {'address': 'args.ray_address'}), '(address=args.ray_address)\n', (13780, 13806), False, 'import ray\n'), ((3382, 3402), 'os.path.join', 'os.path.join', (['mnt', 'd'], {}), '(mnt, d)\n', (3394, 3402), False, 'import os\n'), ((5502, 5525), 'ray.experimental.raysort.types.PartInfo', 'PartInfo', (['i', 'None', 'None'], {}), '(i, None, None)\n', (5510, 5525), False, 'from ray.experimental.raysort.types import BlockInfo, ByteCount, RecordCount, PartId, PartInfo, Path\n'), ((9636, 9671), 'ray.util.remove_placement_group', 'ray.util.remove_placement_group', (['pg'], {}), '(pg)\n', (9667, 9671), False, 'import ray\n'), ((9996, 10010), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (10008, 10010), False, 'import os\n'), ((10706, 10777), 'numpy.empty', 'np.empty', (['(args.num_mappers_per_round, args.num_reducers)'], {'dtype': 'object'}), '((args.num_mappers_per_round, args.num_reducers), dtype=object)\n', (10714, 10777), True, 'import numpy as np\n'), ((11963, 11979), 'csv.writer', 'csv.writer', (['fout'], {}), '(fout)\n', (11973, 11979), False, 'import csv\n'), ((12755, 12776), 'os.path.getsize', 'os.path.getsize', (['path'], {}), '(path)\n', (12770, 12776), False, 'import os\n'), ((3412, 3427), 'os.listdir', 'os.listdir', (['mnt'], {}), '(mnt)\n', (3422, 3427), False, 'import os\n'), ((5834, 5871), 'numpy.random.bytes', 'np.random.bytes', (['args.input_part_size'], {}), '(args.input_part_size)\n', (5849, 5871), True, 'import numpy as np\n'), ((13737, 13751), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (13749, 13751), False, 'import os\n')]
__author__ = 'sibirrer' from lenstronomy.LensModel.Profiles.flexion import Flexion from lenstronomy.LensModel.lens_model import LensModel import numpy as np import numpy.testing as npt import pytest class TestExternalShear(object): """ tests the Gaussian methods """ def setup(self): self.flex = Flexion() g1, g2, g3, g4 = 0.01, 0.02, 0.03, 0.04 self.kwargs_lens = {'g1': g1, 'g2': g2, 'g3': g3, 'g4': g4} def test_function(self): x = np.array([1]) y = np.array([2]) values = self.flex.function(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0], 0.135, decimal=5) x = np.array([0]) y = np.array([0]) values = self.flex.function(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0], 0, decimal=5) x = np.array([2, 3, 4]) y = np.array([1, 1, 1]) values = self.flex.function(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0], 0.09, decimal=5) npt.assert_almost_equal(values[1], 0.18666666666666668, decimal=5) def test_derivatives(self): x = np.array([1]) y = np.array([2]) f_x, f_y = self.flex.derivatives(x, y, **self.kwargs_lens) npt.assert_almost_equal(f_x[0], 0.105, decimal=5) npt.assert_almost_equal(f_y[0], 0.15, decimal=5) x = np.array([1, 3, 4]) y = np.array([2, 1, 1]) values = self.flex.derivatives(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0][0], 0.105, decimal=5) npt.assert_almost_equal(values[1][0], 0.15, decimal=5) def test_hessian(self): x = np.array(1) y = np.array(2) f_xx, f_xy, f_yx, f_yy = self.flex.hessian(x, y, **self.kwargs_lens) npt.assert_almost_equal(f_xx, 0.05, decimal=5) npt.assert_almost_equal(f_yy, 0.11, decimal=5) npt.assert_almost_equal(f_xy, 0.08, decimal=5) npt.assert_almost_equal(f_xy, f_yx, decimal=8) x = np.array([1,3,4]) y = np.array([2,1,1]) values = self.flex.hessian(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0][0], 0.05, decimal=5) npt.assert_almost_equal(values[3][0], 0.11, decimal=5) npt.assert_almost_equal(values[2][0], 0.08, decimal=5) npt.assert_almost_equal(values[1][0], 0.08, decimal=5) def test_flexion(self): x = np.array(0) y = np.array(2) flex = LensModel(['FLEXION']) f_xxx, f_xxy, f_xyy, f_yyy = flex.flexion(x, y, [self.kwargs_lens]) npt.assert_almost_equal(f_xxx, self.kwargs_lens['g1'], decimal=9) npt.assert_almost_equal(f_xxy, self.kwargs_lens['g2'], decimal=9) npt.assert_almost_equal(f_xyy, self.kwargs_lens['g3'], decimal=9) npt.assert_almost_equal(f_yyy, self.kwargs_lens['g4'], decimal=9) def test_magnification(self): ra_0, dec_0 = 1, -1 flex = LensModel(['FLEXION']) g1, g2, g3, g4 = 0.01, 0.02, 0.03, 0.04 kwargs = {'g1': g1, 'g2': g2, 'g3': g3, 'g4': g4, 'ra_0': ra_0, 'dec_0': dec_0} mag = flex.magnification(ra_0, dec_0, [kwargs]) npt.assert_almost_equal(mag, 1, decimal=8) if __name__ == '__main__': pytest.main()
[ "lenstronomy.LensModel.lens_model.LensModel", "pytest.main", "numpy.testing.assert_almost_equal", "numpy.array", "lenstronomy.LensModel.Profiles.flexion.Flexion" ]
[((3229, 3242), 'pytest.main', 'pytest.main', ([], {}), '()\n', (3240, 3242), False, 'import pytest\n'), ((325, 334), 'lenstronomy.LensModel.Profiles.flexion.Flexion', 'Flexion', ([], {}), '()\n', (332, 334), False, 'from lenstronomy.LensModel.Profiles.flexion import Flexion\n'), ((494, 507), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (502, 507), True, 'import numpy as np\n'), ((520, 533), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (528, 533), True, 'import numpy as np\n'), ((604, 656), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[0]', '(0.135)'], {'decimal': '(5)'}), '(values[0], 0.135, decimal=5)\n', (627, 656), True, 'import numpy.testing as npt\n'), ((669, 682), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (677, 682), True, 'import numpy as np\n'), ((695, 708), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (703, 708), True, 'import numpy as np\n'), ((779, 827), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[0]', '(0)'], {'decimal': '(5)'}), '(values[0], 0, decimal=5)\n', (802, 827), True, 'import numpy.testing as npt\n'), ((841, 860), 'numpy.array', 'np.array', (['[2, 3, 4]'], {}), '([2, 3, 4])\n', (849, 860), True, 'import numpy as np\n'), ((873, 892), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (881, 892), True, 'import numpy as np\n'), ((963, 1014), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[0]', '(0.09)'], {'decimal': '(5)'}), '(values[0], 0.09, decimal=5)\n', (986, 1014), True, 'import numpy.testing as npt\n'), ((1024, 1090), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[1]', '(0.18666666666666668)'], {'decimal': '(5)'}), '(values[1], 0.18666666666666668, decimal=5)\n', (1047, 1090), True, 'import numpy.testing as npt\n'), ((1136, 1149), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (1144, 1149), True, 'import numpy as np\n'), ((1162, 1175), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (1170, 1175), True, 'import numpy as np\n'), ((1251, 1300), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_x[0]', '(0.105)'], {'decimal': '(5)'}), '(f_x[0], 0.105, decimal=5)\n', (1274, 1300), True, 'import numpy.testing as npt\n'), ((1309, 1357), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_y[0]', '(0.15)'], {'decimal': '(5)'}), '(f_y[0], 0.15, decimal=5)\n', (1332, 1357), True, 'import numpy.testing as npt\n'), ((1371, 1390), 'numpy.array', 'np.array', (['[1, 3, 4]'], {}), '([1, 3, 4])\n', (1379, 1390), True, 'import numpy as np\n'), ((1403, 1422), 'numpy.array', 'np.array', (['[2, 1, 1]'], {}), '([2, 1, 1])\n', (1411, 1422), True, 'import numpy as np\n'), ((1496, 1551), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[0][0]', '(0.105)'], {'decimal': '(5)'}), '(values[0][0], 0.105, decimal=5)\n', (1519, 1551), True, 'import numpy.testing as npt\n'), ((1560, 1614), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[1][0]', '(0.15)'], {'decimal': '(5)'}), '(values[1][0], 0.15, decimal=5)\n', (1583, 1614), True, 'import numpy.testing as npt\n'), ((1656, 1667), 'numpy.array', 'np.array', (['(1)'], {}), '(1)\n', (1664, 1667), True, 'import numpy as np\n'), ((1680, 1691), 'numpy.array', 'np.array', (['(2)'], {}), '(2)\n', (1688, 1691), True, 'import numpy as np\n'), ((1777, 1823), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_xx', '(0.05)'], {'decimal': '(5)'}), '(f_xx, 0.05, decimal=5)\n', (1800, 1823), True, 'import numpy.testing as npt\n'), ((1832, 1878), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_yy', '(0.11)'], {'decimal': '(5)'}), '(f_yy, 0.11, decimal=5)\n', (1855, 1878), True, 'import numpy.testing as npt\n'), ((1887, 1933), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_xy', '(0.08)'], {'decimal': '(5)'}), '(f_xy, 0.08, decimal=5)\n', (1910, 1933), True, 'import numpy.testing as npt\n'), ((1942, 1988), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_xy', 'f_yx'], {'decimal': '(8)'}), '(f_xy, f_yx, decimal=8)\n', (1965, 1988), True, 'import numpy.testing as npt\n'), ((2002, 2021), 'numpy.array', 'np.array', (['[1, 3, 4]'], {}), '([1, 3, 4])\n', (2010, 2021), True, 'import numpy as np\n'), ((2032, 2051), 'numpy.array', 'np.array', (['[2, 1, 1]'], {}), '([2, 1, 1])\n', (2040, 2051), True, 'import numpy as np\n'), ((2119, 2173), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[0][0]', '(0.05)'], {'decimal': '(5)'}), '(values[0][0], 0.05, decimal=5)\n', (2142, 2173), True, 'import numpy.testing as npt\n'), ((2182, 2236), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[3][0]', '(0.11)'], {'decimal': '(5)'}), '(values[3][0], 0.11, decimal=5)\n', (2205, 2236), True, 'import numpy.testing as npt\n'), ((2245, 2299), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[2][0]', '(0.08)'], {'decimal': '(5)'}), '(values[2][0], 0.08, decimal=5)\n', (2268, 2299), True, 'import numpy.testing as npt\n'), ((2308, 2362), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['values[1][0]', '(0.08)'], {'decimal': '(5)'}), '(values[1][0], 0.08, decimal=5)\n', (2331, 2362), True, 'import numpy.testing as npt\n'), ((2404, 2415), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (2412, 2415), True, 'import numpy as np\n'), ((2428, 2439), 'numpy.array', 'np.array', (['(2)'], {}), '(2)\n', (2436, 2439), True, 'import numpy as np\n'), ((2455, 2477), 'lenstronomy.LensModel.lens_model.LensModel', 'LensModel', (["['FLEXION']"], {}), "(['FLEXION'])\n", (2464, 2477), False, 'from lenstronomy.LensModel.lens_model import LensModel\n'), ((2562, 2627), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_xxx', "self.kwargs_lens['g1']"], {'decimal': '(9)'}), "(f_xxx, self.kwargs_lens['g1'], decimal=9)\n", (2585, 2627), True, 'import numpy.testing as npt\n'), ((2636, 2701), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_xxy', "self.kwargs_lens['g2']"], {'decimal': '(9)'}), "(f_xxy, self.kwargs_lens['g2'], decimal=9)\n", (2659, 2701), True, 'import numpy.testing as npt\n'), ((2710, 2775), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_xyy', "self.kwargs_lens['g3']"], {'decimal': '(9)'}), "(f_xyy, self.kwargs_lens['g3'], decimal=9)\n", (2733, 2775), True, 'import numpy.testing as npt\n'), ((2784, 2849), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['f_yyy', "self.kwargs_lens['g4']"], {'decimal': '(9)'}), "(f_yyy, self.kwargs_lens['g4'], decimal=9)\n", (2807, 2849), True, 'import numpy.testing as npt\n'), ((2929, 2951), 'lenstronomy.LensModel.lens_model.LensModel', 'LensModel', (["['FLEXION']"], {}), "(['FLEXION'])\n", (2938, 2951), False, 'from lenstronomy.LensModel.lens_model import LensModel\n'), ((3153, 3195), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['mag', '(1)'], {'decimal': '(8)'}), '(mag, 1, decimal=8)\n', (3176, 3195), True, 'import numpy.testing as npt\n')]
from unittest.mock import Mock, PropertyMock, MagicMock, patch import numpy as np import gym_connect4 from test_fixtures import Connect4Task import regym from regym.environments import EnvType from regym.rl_algorithms import build_MCTS_Agent from regym.rl_algorithms.agents import Agent, build_Deterministic_Agent, DeterministicAgent from regym.rl_loops import Trajectory from regym.rl_algorithms import build_Deterministic_Agent, build_MCTS_Agent from regym.rl_loops.multiagent_loops.vectorenv_sequential_action_rl_loop import async_run_episode from regym.rl_loops.multiagent_loops.sequential_action_rl_loop import propagate_experience, propagate_last_experience def test_sequential_trajectories_feature_agent_predictions_single_env(Connect4Task): agent_1 = build_Deterministic_Agent( Connect4Task, {'action': 0}, 'Col-0-DeterministicAgent') agent_1.requires_opponents_prediction = True # Required! agent_2 = build_Deterministic_Agent( Connect4Task, {'action': 1}, 'Col-0-DeterministicAgent') trajectory = Connect4Task.run_episode([agent_1, agent_2], training=False) expected_prediction_1 = {'a': 0, 'probs': [[1., 0., 0., 0., 0., 0., 0.]]} expected_prediction_2 = {'a': 1, 'probs': [[0., 1., 0., 0., 0., 0., 0.]]} expected_predictions = [expected_prediction_1, expected_prediction_2] compare_trajectory_extra_info_against_expected(trajectory, expected_predictions) def test_sequential_trajectories_feature_agent_predictions_multienv(Connect4Task): agent_1 = build_Deterministic_Agent( Connect4Task, {'action': 0}, 'Col-0-DeterministicAgent') agent_1.requires_opponents_prediction = True # Required! agent_2 = build_Deterministic_Agent( Connect4Task, {'action': 1}, 'Col-0-DeterministicAgent') trajectories = Connect4Task.run_episodes([agent_1, agent_2], training=False, num_envs=2, num_episodes=2) # on single agents there's a batch dimension in 'probs', but not # on multiagent_loops. Does this matter? expected_prediction_1 = {'a': 0, 'probs': [1., 0., 0., 0., 0., 0., 0.]} expected_prediction_2 = {'a': 1, 'probs': [0., 1., 0., 0., 0., 0., 0.]} expected_predictions = [expected_prediction_1, expected_prediction_2] for trajectory in trajectories: compare_trajectory_extra_info_against_expected(trajectory, expected_predictions) def test_agents_in_sequential_environments_handle_experiences_with_extra_info_single_env(Connect4Task): ''' In this test we want to ensure that when agents process experiences via `Agent.handle_experience(...)` calls, they obtain the are able to observe the `predicions` of other agents. There are 2 cases to consider: - Handling an experience in the middle of a trajectory - Handling an experience when the episode just finshed and some agents need to process the last (terminal) timestep ''' mock_agent_1 = Mock(spec=DeterministicAgent) mock_agent_2 = Mock(spec=DeterministicAgent) agent_vector = [mock_agent_1, mock_agent_2] mock_agent_1.requires_opponents_prediction = True mock_agent_1.training = True mock_agent_2.requires_opponents_prediction = False mock_agent_2.training = True prediction_1 = {'a': 0, 'probs': [1., 0., 0., 0., 0., 0., 0.]} prediction_2 = {'a': 1, 'probs': [0., 1., 0., 0., 0., 0., 0.]} predictions = [prediction_1, prediction_2] ''' Creates a trajectory for the game of Connect4 looks like this Total timesteps 7. P1 (x) actions: 4. P2 (o) actions: 3. Board: | | | | |x | |x o | |x o | |x o . . . . . | |--------------| ''' sample_trajectory = Trajectory( env_type=EnvType.MULTIAGENT_SEQUENTIAL_ACTION, num_agents=2) o, a, r, succ_o, done = [None, None], None, [0, 0], [None, None], False sample_trajectory.add_timestep( o, a, r, succ_o, done, acting_agents=[0], extra_info={0: predictions[0]}) sample_trajectory.add_timestep( o, a, r, succ_o, done, acting_agents=[1], extra_info={1: predictions[1]}) # Update agent 0 propagate_experience(agent_vector, sample_trajectory) sample_trajectory.add_timestep( o, a, r, succ_o, done, acting_agents=[0], extra_info={0: predictions[0]}) # Update agent 1 propagate_experience(agent_vector, sample_trajectory) sample_trajectory.add_timestep( o, a, r, succ_o, done, acting_agents=[1], extra_info={1: predictions[1]}) # Update agent 0 propagate_experience(agent_vector, sample_trajectory) sample_trajectory.add_timestep( o, a, r, succ_o, done, acting_agents=[0], extra_info={0: predictions[0]}) # Update agent 1 propagate_experience(agent_vector, sample_trajectory) sample_trajectory.add_timestep( o, a, r, succ_o, done, acting_agents=[1], extra_info={1: predictions[1]}) # Update agent 0 propagate_experience(agent_vector, sample_trajectory) done = True sample_trajectory.add_timestep( o, a, [1, -1], succ_o, done, acting_agents=[0], extra_info={0: predictions[0]}) # Update player 1 propagate_experience(agent_vector, sample_trajectory) # Episode termination # Update player 0 (After done flag) propagate_last_experience(agent_vector, sample_trajectory) def compare_trajectory_extra_info_against_expected(trajectory, expected_predictions): for timestep in trajectory: # Only one agent acts at a time in Connect4 a_i = timestep.acting_agents[0] actual_prediction = timestep.extra_info[a_i] assert 'a' in actual_prediction assert 'probs' in actual_prediction assert actual_prediction['a'] == expected_predictions[a_i]['a'] np.testing.assert_array_equal( actual_prediction['probs'], expected_predictions[a_i]['probs'])
[ "unittest.mock.Mock", "regym.rl_algorithms.build_Deterministic_Agent", "regym.rl_loops.Trajectory", "test_fixtures.Connect4Task.run_episodes", "regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_last_experience", "regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_experience", "numpy.testing.assert_array_equal", "test_fixtures.Connect4Task.run_episode" ]
[((771, 857), 'regym.rl_algorithms.build_Deterministic_Agent', 'build_Deterministic_Agent', (['Connect4Task', "{'action': 0}", '"""Col-0-DeterministicAgent"""'], {}), "(Connect4Task, {'action': 0},\n 'Col-0-DeterministicAgent')\n", (796, 857), False, 'from regym.rl_algorithms import build_Deterministic_Agent, build_MCTS_Agent\n'), ((939, 1025), 'regym.rl_algorithms.build_Deterministic_Agent', 'build_Deterministic_Agent', (['Connect4Task', "{'action': 1}", '"""Col-0-DeterministicAgent"""'], {}), "(Connect4Task, {'action': 1},\n 'Col-0-DeterministicAgent')\n", (964, 1025), False, 'from regym.rl_algorithms import build_Deterministic_Agent, build_MCTS_Agent\n'), ((1049, 1109), 'test_fixtures.Connect4Task.run_episode', 'Connect4Task.run_episode', (['[agent_1, agent_2]'], {'training': '(False)'}), '([agent_1, agent_2], training=False)\n', (1073, 1109), False, 'from test_fixtures import Connect4Task\n'), ((1554, 1640), 'regym.rl_algorithms.build_Deterministic_Agent', 'build_Deterministic_Agent', (['Connect4Task', "{'action': 0}", '"""Col-0-DeterministicAgent"""'], {}), "(Connect4Task, {'action': 0},\n 'Col-0-DeterministicAgent')\n", (1579, 1640), False, 'from regym.rl_algorithms import build_Deterministic_Agent, build_MCTS_Agent\n'), ((1722, 1808), 'regym.rl_algorithms.build_Deterministic_Agent', 'build_Deterministic_Agent', (['Connect4Task', "{'action': 1}", '"""Col-0-DeterministicAgent"""'], {}), "(Connect4Task, {'action': 1},\n 'Col-0-DeterministicAgent')\n", (1747, 1808), False, 'from regym.rl_algorithms import build_Deterministic_Agent, build_MCTS_Agent\n'), ((1834, 1927), 'test_fixtures.Connect4Task.run_episodes', 'Connect4Task.run_episodes', (['[agent_1, agent_2]'], {'training': '(False)', 'num_envs': '(2)', 'num_episodes': '(2)'}), '([agent_1, agent_2], training=False, num_envs=2,\n num_episodes=2)\n', (1859, 1927), False, 'from test_fixtures import Connect4Task\n'), ((3002, 3031), 'unittest.mock.Mock', 'Mock', ([], {'spec': 'DeterministicAgent'}), '(spec=DeterministicAgent)\n', (3006, 3031), False, 'from unittest.mock import Mock, PropertyMock, MagicMock, patch\n'), ((3051, 3080), 'unittest.mock.Mock', 'Mock', ([], {'spec': 'DeterministicAgent'}), '(spec=DeterministicAgent)\n', (3055, 3080), False, 'from unittest.mock import Mock, PropertyMock, MagicMock, patch\n'), ((3885, 3956), 'regym.rl_loops.Trajectory', 'Trajectory', ([], {'env_type': 'EnvType.MULTIAGENT_SEQUENTIAL_ACTION', 'num_agents': '(2)'}), '(env_type=EnvType.MULTIAGENT_SEQUENTIAL_ACTION, num_agents=2)\n', (3895, 3956), False, 'from regym.rl_loops import Trajectory\n'), ((4323, 4376), 'regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_experience', 'propagate_experience', (['agent_vector', 'sample_trajectory'], {}), '(agent_vector, sample_trajectory)\n', (4343, 4376), False, 'from regym.rl_loops.multiagent_loops.sequential_action_rl_loop import propagate_experience, propagate_last_experience\n'), ((4530, 4583), 'regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_experience', 'propagate_experience', (['agent_vector', 'sample_trajectory'], {}), '(agent_vector, sample_trajectory)\n', (4550, 4583), False, 'from regym.rl_loops.multiagent_loops.sequential_action_rl_loop import propagate_experience, propagate_last_experience\n'), ((4737, 4790), 'regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_experience', 'propagate_experience', (['agent_vector', 'sample_trajectory'], {}), '(agent_vector, sample_trajectory)\n', (4757, 4790), False, 'from regym.rl_loops.multiagent_loops.sequential_action_rl_loop import propagate_experience, propagate_last_experience\n'), ((4944, 4997), 'regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_experience', 'propagate_experience', (['agent_vector', 'sample_trajectory'], {}), '(agent_vector, sample_trajectory)\n', (4964, 4997), False, 'from regym.rl_loops.multiagent_loops.sequential_action_rl_loop import propagate_experience, propagate_last_experience\n'), ((5151, 5204), 'regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_experience', 'propagate_experience', (['agent_vector', 'sample_trajectory'], {}), '(agent_vector, sample_trajectory)\n', (5171, 5204), False, 'from regym.rl_loops.multiagent_loops.sequential_action_rl_loop import propagate_experience, propagate_last_experience\n'), ((5381, 5434), 'regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_experience', 'propagate_experience', (['agent_vector', 'sample_trajectory'], {}), '(agent_vector, sample_trajectory)\n', (5401, 5434), False, 'from regym.rl_loops.multiagent_loops.sequential_action_rl_loop import propagate_experience, propagate_last_experience\n'), ((5506, 5564), 'regym.rl_loops.multiagent_loops.sequential_action_rl_loop.propagate_last_experience', 'propagate_last_experience', (['agent_vector', 'sample_trajectory'], {}), '(agent_vector, sample_trajectory)\n', (5531, 5564), False, 'from regym.rl_loops.multiagent_loops.sequential_action_rl_loop import propagate_experience, propagate_last_experience\n'), ((5995, 6092), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (["actual_prediction['probs']", "expected_predictions[a_i]['probs']"], {}), "(actual_prediction['probs'],\n expected_predictions[a_i]['probs'])\n", (6024, 6092), True, 'import numpy as np\n')]
import numpy as np # import os # current_directory = os.path.dirname(os.path.abspath(__file__)).replace('\\','/') # from ctypes import * # bro = cdll.LoadLibrary(current_directory+"/broken.so") # bro.broken_frame.argtypes = [np.ctypeslib.ndpointer(dtype=np.int16, ndim=1, flags="C_CONTIGUOUS"), # c_int, # np.ctypeslib.ndpointer(dtype=np.float, ndim=1), # # c_int] # bro.broken_frame.restype = c_int def detect_broken_frame(wdata, framerate): ''' To detect broken frame. Parameters ---------- wdata: wave data Type:[array] framerate: sample rate. Type:[int] Returns ---------- bf: broken frame Type:[list] _______ _______ | | | | | | | | | | amp0 | amp1 | | | |_______ | | | amp | |_______|_______|_______| _____________ \ | |_______ _______________ | | | | | | | | | | | amp | _______| | | | amp0 | amp1 | | |_______|_______|_______| _________ / | ________________| ''' # num = 0 # bf = np.zeros(5) # num = bro.broken_frame(wdata,len(wdata),bf,framerate) # if num == 0: # bf = [] # return list(bf) # frame length: 5ms FRAME_LENGTH = 0.005 AMP_THRESHOLD = 4 up_edge = False # print framerate w = int(framerate*FRAME_LENGTH) amp0 = amp1 = 0 bf = [] last_dis = 0 AMP_ARRAY = [] n = 0 for i in xrange(len(wdata)/w): tem = np.sum(np.abs(wdata[i*w:(i+1)*w])) if tem !=0: amp = np.log10(tem) #amplitude else: amp = 0 #Up edge detection if up_edge is False: dis = amp1-amp ldis = amp0-amp if (dis >= AMP_THRESHOLD) and (ldis>=AMP_THRESHOLD):# and (distance1 > 0):#AMP_THRESHOLD-0.2 bft = round((i*w)/float(framerate),3) up_edge = True n = 0 #Falling edge detection else: n += 1 dis = amp1-amp0 ldis = amp-amp0 if (dis >= AMP_THRESHOLD) and (ldis>=AMP_THRESHOLD):#AMP_THRESHOLD-0.2 (distance0 > 0) and # print dis-ldis,i,amp0,amp1,amp up_edge = False n = 0 bf.append(bft) #if detect a falling edge, but it can`t detect a up edge within 5 seconds, we will reset the FLAG elif n%400 == 0: n = 0 up_edge = False #Update amp0 & amp1 amp0 = amp1 amp1 = amp # #Up edge detection # if up_edge is False: # distance0 = amp0-amp # if (distance0 > AMP_THRESHOLD):# and (distance1 > 0):#AMP_THRESHOLD-0.2 # bft = round((i*w)/float(framerate),3) # up_edge = True # #Falling edge detection # else: # distance0 = amp-amp0 # distance1 = amp1-amp0 # if (distance1 > AMP_THRESHOLD):#AMP_THRESHOLD-0.2 (distance0 > 0) and # up_edge = False # bf.append(bft) # #if detect a falling edge, but it can`t detect a up edge within 5 seconds, we will reset the FLAG # elif i%100 == 0: # up_edge = False # #Update amp0 & amp1 # amp0,amp1=amp1,amp # ####################################### # import matplotlib.pyplot as plt # x = range(len(wdata)/w) # plt.title("") # plt.xlabel('Window') # plt.ylabel('Amplitude (log)')# # plt.plot(x,AMP_ARRAY) # plt.show() # ####################################### # import matplotlib.mlab as mlab # import matplotlib.pyplot as plt # num_bins = 90 # # the histogram of the data # n, bins, patches = plt.hist(AMP_ARRAY, num_bins, normed = True, facecolor='green', alpha=0.5) # plt.xlabel('Distance') # plt.ylabel('Probability(100%)') # plt.title(r'Histogram of amplitude') # plt.show() if len(bf) == 0: return 0 else: return bf
[ "numpy.abs", "numpy.log10" ]
[((1532, 1564), 'numpy.abs', 'np.abs', (['wdata[i * w:(i + 1) * w]'], {}), '(wdata[i * w:(i + 1) * w])\n', (1538, 1564), True, 'import numpy as np\n'), ((1584, 1597), 'numpy.log10', 'np.log10', (['tem'], {}), '(tem)\n', (1592, 1597), True, 'import numpy as np\n')]
from os import listdir from os.path import isfile from PIL import Image from tqdm import tqdm import numpy as np import imgaug.augmenters as iaa import os import random from os.path import join import matplotlib.pyplot as plt DATA_DIR = 'DATA DIR' os.chdir(DATA_DIR) IMAGE_DIR = join(DATA_DIR, 'dataset\\PascalVOC-OG-flipped\\JPEGImages') ANN_DIR = join(DATA_DIR, 'dataset\\PascalVOC-OG-flipped\\Annotations') NEW_IMAGE_DIR = join(DATA_DIR, 'dataset\\PascalVOC-OG-all\\JPEGImages') NEW_ANN_DIR = join(DATA_DIR, 'dataset\\PascalVOC-OG-all\\Annotations') NEW_IMAGE_SETS_DIR = join(DATA_DIR, 'dataset\\PascalVOC-OG-all\\ImageSets\\Main') MAX = 2 with open(join(NEW_IMAGE_SETS_DIR, f"pipe-augmented-degrade.txt"), 'w+') as f: pass image_files = [f for f in listdir(IMAGE_DIR) if isfile(join(IMAGE_DIR, f))] shuffled_image_files = random.sample(image_files, len(image_files)) shuffled_image_files = random.sample(image_files, len(shuffled_image_files))[:MAX] seq = iaa.Sequential([ iaa.JpegCompression(compression=(99, 99)) ]) for image in tqdm(shuffled_image_files): if len(image) > 0: # Åpne bildet im = Image.open(join(IMAGE_DIR, image)) # Gjøre om til array med type uint8, (1920, 1080, 3) im = np.asarray(im).astype(np.uint8) # Ekspandere arrayet til å se ut som (1, 1920, 1080, 3), nødvendig siden iaa forventer en 4D matrise im_expand = np.expand_dims(im, 0) # Augmentere bildet augmented_image_array = seq(images=im_expand) # Fjerne ekstra dimensjonen satt på tidligere på første akse, resultat: (1920, 1080, 3) augmented_image_array = np.squeeze(augmented_image_array, axis=0) # Laste inn array som bilde augmented_image = Image.fromarray(augmented_image_array) # Laste inn bildet igjen fra matriseformat. im = Image.fromarray(im) im.save('im1.jpeg') augmented_image.save('im2.jpeg') fig, ax = plt.subplots(nrows=1, ncols=2) # Plotting plt.subplot(1, 2, 1) plt.imshow(im) plt.subplot(1, 2, 2) plt.imshow(augmented_image) plt.show()
[ "matplotlib.pyplot.imshow", "PIL.Image.fromarray", "os.listdir", "tqdm.tqdm", "os.path.join", "numpy.asarray", "numpy.squeeze", "os.chdir", "numpy.expand_dims", "imgaug.augmenters.JpegCompression", "matplotlib.pyplot.subplot", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((265, 283), 'os.chdir', 'os.chdir', (['DATA_DIR'], {}), '(DATA_DIR)\n', (273, 283), False, 'import os\n'), ((301, 360), 'os.path.join', 'join', (['DATA_DIR', '"""dataset\\\\PascalVOC-OG-flipped\\\\JPEGImages"""'], {}), "(DATA_DIR, 'dataset\\\\PascalVOC-OG-flipped\\\\JPEGImages')\n", (305, 360), False, 'from os.path import join\n'), ((372, 432), 'os.path.join', 'join', (['DATA_DIR', '"""dataset\\\\PascalVOC-OG-flipped\\\\Annotations"""'], {}), "(DATA_DIR, 'dataset\\\\PascalVOC-OG-flipped\\\\Annotations')\n", (376, 432), False, 'from os.path import join\n'), ((452, 507), 'os.path.join', 'join', (['DATA_DIR', '"""dataset\\\\PascalVOC-OG-all\\\\JPEGImages"""'], {}), "(DATA_DIR, 'dataset\\\\PascalVOC-OG-all\\\\JPEGImages')\n", (456, 507), False, 'from os.path import join\n'), ((523, 579), 'os.path.join', 'join', (['DATA_DIR', '"""dataset\\\\PascalVOC-OG-all\\\\Annotations"""'], {}), "(DATA_DIR, 'dataset\\\\PascalVOC-OG-all\\\\Annotations')\n", (527, 579), False, 'from os.path import join\n'), ((604, 664), 'os.path.join', 'join', (['DATA_DIR', '"""dataset\\\\PascalVOC-OG-all\\\\ImageSets\\\\Main"""'], {}), "(DATA_DIR, 'dataset\\\\PascalVOC-OG-all\\\\ImageSets\\\\Main')\n", (608, 664), False, 'from os.path import join\n'), ((1095, 1121), 'tqdm.tqdm', 'tqdm', (['shuffled_image_files'], {}), '(shuffled_image_files)\n', (1099, 1121), False, 'from tqdm import tqdm\n'), ((689, 744), 'os.path.join', 'join', (['NEW_IMAGE_SETS_DIR', 'f"""pipe-augmented-degrade.txt"""'], {}), "(NEW_IMAGE_SETS_DIR, f'pipe-augmented-degrade.txt')\n", (693, 744), False, 'from os.path import join\n'), ((797, 815), 'os.listdir', 'listdir', (['IMAGE_DIR'], {}), '(IMAGE_DIR)\n', (804, 815), False, 'from os import listdir\n'), ((1031, 1072), 'imgaug.augmenters.JpegCompression', 'iaa.JpegCompression', ([], {'compression': '(99, 99)'}), '(compression=(99, 99))\n', (1050, 1072), True, 'import imgaug.augmenters as iaa\n'), ((1462, 1483), 'numpy.expand_dims', 'np.expand_dims', (['im', '(0)'], {}), '(im, 0)\n', (1476, 1483), True, 'import numpy as np\n'), ((1702, 1743), 'numpy.squeeze', 'np.squeeze', (['augmented_image_array'], {'axis': '(0)'}), '(augmented_image_array, axis=0)\n', (1712, 1743), True, 'import numpy as np\n'), ((1810, 1848), 'PIL.Image.fromarray', 'Image.fromarray', (['augmented_image_array'], {}), '(augmented_image_array)\n', (1825, 1848), False, 'from PIL import Image\n'), ((1918, 1937), 'PIL.Image.fromarray', 'Image.fromarray', (['im'], {}), '(im)\n', (1933, 1937), False, 'from PIL import Image\n'), ((2028, 2058), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)'}), '(nrows=1, ncols=2)\n', (2040, 2058), True, 'import matplotlib.pyplot as plt\n'), ((2090, 2110), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (2101, 2110), True, 'import matplotlib.pyplot as plt\n'), ((2120, 2134), 'matplotlib.pyplot.imshow', 'plt.imshow', (['im'], {}), '(im)\n', (2130, 2134), True, 'import matplotlib.pyplot as plt\n'), ((2146, 2166), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (2157, 2166), True, 'import matplotlib.pyplot as plt\n'), ((2176, 2203), 'matplotlib.pyplot.imshow', 'plt.imshow', (['augmented_image'], {}), '(augmented_image)\n', (2186, 2203), True, 'import matplotlib.pyplot as plt\n'), ((2213, 2223), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2221, 2223), True, 'import matplotlib.pyplot as plt\n'), ((826, 844), 'os.path.join', 'join', (['IMAGE_DIR', 'f'], {}), '(IMAGE_DIR, f)\n', (830, 844), False, 'from os.path import join\n'), ((1195, 1217), 'os.path.join', 'join', (['IMAGE_DIR', 'image'], {}), '(IMAGE_DIR, image)\n', (1199, 1217), False, 'from os.path import join\n'), ((1297, 1311), 'numpy.asarray', 'np.asarray', (['im'], {}), '(im)\n', (1307, 1311), True, 'import numpy as np\n')]
from typing import Dict import numpy as np def buffer_from_example(example: Dict[str, np.ndarray], leading_dims) -> Dict[str, np.ndarray]: buf = {} for key, value in example.items(): buf[key] = np.zeros(leading_dims + value.shape, dtype=value.dtype) return buf def get_leading_dims(dictionary, n_dims=1): values = iter(dictionary.values()) leading_dims = next(values).shape[:n_dims] if not all(leading_dims == value.shape[:n_dims] for value in values): key, shape = [(key, value.shape[:n_dims]) for key, value in dictionary.items() if leading_dims != value.shape[:n_dims]][0] raise ValueError((f'Dimensions do not match: {leading_dims} vs. ' f'{shape} (for key `{key}`)')) return leading_dims
[ "numpy.zeros" ]
[((237, 292), 'numpy.zeros', 'np.zeros', (['(leading_dims + value.shape)'], {'dtype': 'value.dtype'}), '(leading_dims + value.shape, dtype=value.dtype)\n', (245, 292), True, 'import numpy as np\n')]
import numpy as np import cv2 image = cv2.imread('images/unsharp_bird.jpg') kernel = np.array([ [0, -1, 0], [-1, 5, -1], [0, -1, 0] ]) sharpen_iamge = cv2.filter2D(image, -1, kernel) cv2.imshow("original image", image) cv2.imshow("sharpen image", sharpen_iamge) cv2.waitKey(0) cv2.destroyAllWindows()
[ "cv2.filter2D", "cv2.imshow", "numpy.array", "cv2.destroyAllWindows", "cv2.waitKey", "cv2.imread" ]
[((39, 76), 'cv2.imread', 'cv2.imread', (['"""images/unsharp_bird.jpg"""'], {}), "('images/unsharp_bird.jpg')\n", (49, 76), False, 'import cv2\n'), ((87, 134), 'numpy.array', 'np.array', (['[[0, -1, 0], [-1, 5, -1], [0, -1, 0]]'], {}), '([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])\n', (95, 134), True, 'import numpy as np\n'), ((200, 231), 'cv2.filter2D', 'cv2.filter2D', (['image', '(-1)', 'kernel'], {}), '(image, -1, kernel)\n', (212, 231), False, 'import cv2\n'), ((233, 268), 'cv2.imshow', 'cv2.imshow', (['"""original image"""', 'image'], {}), "('original image', image)\n", (243, 268), False, 'import cv2\n'), ((269, 311), 'cv2.imshow', 'cv2.imshow', (['"""sharpen image"""', 'sharpen_iamge'], {}), "('sharpen image', sharpen_iamge)\n", (279, 311), False, 'import cv2\n'), ((312, 326), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (323, 326), False, 'import cv2\n'), ((327, 350), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (348, 350), False, 'import cv2\n')]
# -*- coding: utf-8 -*- import csv import logging import math import multiprocessing import os import shutil import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import Dict, List, Tuple from django.utils import timezone import numpy as np import pandas as pd import psutil import rpy2.robjects as ro import simplejson as json from rpy2.robjects import pandas2ri, r as rlang from rpy2.robjects.packages import importr from data_refinery_common.logging import get_and_configure_logger from data_refinery_common.models import ComputedFile, Sample from data_refinery_common.utils import get_env_variable from data_refinery_workers.processors import utils MULTIPROCESSING_MAX_THREAD_COUNT = max(1, math.floor(multiprocessing.cpu_count() / 2) - 1) RESULTS_BUCKET = get_env_variable("S3_RESULTS_BUCKET_NAME", "refinebio-results-bucket") S3_BUCKET_NAME = get_env_variable("S3_BUCKET_NAME", "data-refinery") BODY_HTML = ( Path("data_refinery_workers/processors/smasher_email.min.html").read_text().replace("\n", "") ) BODY_ERROR_HTML = ( Path("data_refinery_workers/processors/smasher_email_error.min.html") .read_text() .replace("\n", "") ) BYTES_IN_GB = 1024 * 1024 * 1024 QN_CHUNK_SIZE = 10000 logger = get_and_configure_logger(__name__) ### DEBUG ### logger.setLevel(logging.getLevelName("DEBUG")) def log_state(message, job_id, start_time=False): if logger.isEnabledFor(logging.DEBUG): process = psutil.Process(os.getpid()) ram_in_GB = process.memory_info().rss / BYTES_IN_GB logger.debug(message, total_cpu=psutil.cpu_percent(), process_ram=ram_in_GB, job_id=job_id) if start_time: logger.debug("Duration: %s" % (time.time() - start_time), job_id=job_id) else: return time.time() def prepare_files(job_context: Dict) -> Dict: """ Fetches and prepares the files to smash. """ start_prepare_files = log_state("start prepare files", job_context["job"].id) found_files = False job_context["filtered_samples"] = {} job_context["input_files"] = {} # `key` can either be the species name or experiment accession. for key, samples in job_context["samples"].items(): smashable_files = [] seen_files = set() for sample in samples: smashable_file = sample.get_most_recent_smashable_result_file() if smashable_file is not None and smashable_file not in seen_files: smashable_files = smashable_files + [(smashable_file, sample)] seen_files.add(smashable_file) found_files = True else: sample_metadata = sample.to_metadata_dict() job_context["filtered_samples"][sample.accession_code] = { **sample_metadata, "reason": "This sample did not have a processed file associated with it in our database.", "experiment_accession_code": get_experiment_accession( sample.accession_code, job_context["dataset"].data ), } job_context["input_files"][key] = smashable_files job_context["num_input_files"] = len(job_context["input_files"]) job_context["group_by_keys"] = list(job_context["input_files"].keys()) if not found_files: raise utils.ProcessorJobError( "Couldn't get any files to smash for Smash job!!", success=False, dataset_id=job_context["dataset"].id, num_samples=len(job_context["samples"]), ) dataset_id = str(job_context["dataset"].pk) job_context["work_dir"] = "/home/user/data_store/smashed/" + dataset_id + "/" # Ensure we have a fresh smash directory shutil.rmtree(job_context["work_dir"], ignore_errors=True) os.makedirs(job_context["work_dir"]) job_context["output_dir"] = job_context["work_dir"] + "output/" os.makedirs(job_context["output_dir"]) log_state("end prepare files", job_context["job"].id, start_prepare_files) return job_context def _load_and_sanitize_file(computed_file_path) -> pd.DataFrame: """ Read and sanitize a computed file """ data = pd.read_csv( computed_file_path, sep="\t", header=0, index_col=0, dtype={0: str, 1: np.float32}, error_bad_lines=False, ) # Strip any funky whitespace data.columns = data.columns.str.strip() data = data.dropna(axis="columns", how="all") # Make sure the index type is correct data.index = data.index.map(str) # Ensure that we don't have any dangling Brainarray-generated probe symbols. # BA likes to leave '_at', signifying probe identifiers, # on their converted, non-probe identifiers. It makes no sense. # So, we chop them off and don't worry about it. data.index = data.index.str.replace("_at", "") # Remove any lingering Affymetrix control probes ("AFFX-") data = data[~data.index.str.contains("AFFX-")] # If there are any _versioned_ gene identifiers, remove that # version information. We're using the latest brainarray for everything anyway. # Jackie says this is okay. # She also says that in the future, we may only want to do this # for cross-technology smashes. # This regex needs to be able to handle EGIDs in the form: # ENSGXXXXYYYZZZZ.6 # and # fgenesh2_kg.7__3016__AT5G35080.1 (via http://plants.ensembl.org/Arabidopsis_lyrata/ \ # Gene/Summary?g=fgenesh2_kg.7__3016__AT5G35080.1;r=7:17949732-17952000;t=fgenesh2_kg. \ # 7__3016__AT5G35080.1;db=core) data.index = data.index.str.replace(r"(\.[^.]*)$", "") # Squish duplicated rows together. # XXX/TODO: Is mean the appropriate method here? # We can make this an option in future. # Discussion here: https://github.com/AlexsLemonade/refinebio/issues/186#issuecomment-395516419 data = data.groupby(data.index, sort=False).mean() return data def process_frame(work_dir, computed_file, sample_accession_code, aggregate_by) -> pd.DataFrame: """ Downloads the computed file from S3 and tries to see if it's smashable. Returns a data frame if the file can be processed or False otherwise. """ try: # Download the file to a job-specific location so it # won't disappear while we're using it. computed_file_path = computed_file.get_synced_file_path( path="%s%s" % (work_dir, computed_file.filename) ) # Bail appropriately if this isn't a real file. if not computed_file_path or not os.path.exists(computed_file_path): logger.warning( "Smasher received non-existent file path.", computed_file_path=computed_file_path, computed_file_id=computed_file.id, ) return None data = _load_and_sanitize_file(computed_file_path) if len(data.columns) > 2: # Most of the time, >1 is actually bad, but we also need to support # two-channel samples. I think ultimately those should be given some kind of # special consideration. logger.info( "Found a frame with more than 2 columns - this shouldn't happen!", computed_file_path=computed_file_path, computed_file_id=computed_file.id, ) return None # via https://github.com/AlexsLemonade/refinebio/issues/330: # aggregating by experiment -> return untransformed output from tximport # aggregating by species -> log2(x + 1) tximport output if aggregate_by == "SPECIES" and computed_file.has_been_log2scaled(): data = data + 1 data = np.log2(data) # Ideally done in the NO-OPPER, but sanity check here. if (not computed_file.has_been_log2scaled()) and (data.max() > 100).any(): logger.info("Detected non-log2 microarray data.", computed_file_id=computed_file.id) data = np.log2(data) # Explicitly title this dataframe try: data.columns = [sample_accession_code] except ValueError: # This sample might have multiple channels, or something else. # Don't mess with it. logger.warn( "Smasher found multi-channel column (probably) - skipping!", exc_info=1, computed_file_path=computed_file_path, ) return None except Exception: # Okay, somebody probably forgot to create a SampleComputedFileAssociation # Don't mess with it. logger.warn( "Smasher found very bad column title - skipping!", exc_info=1, computed_file_path=computed_file_path, ) return None except Exception: logger.exception("Unable to smash file", file=computed_file_path) return None # TEMPORARY for iterating on compendia more quickly. # finally: # # Delete before archiving the work dir # if computed_file_path and os.path.exists(computed_file_path): # os.remove(computed_file_path) return data def load_first_pass_data_if_cached(work_dir: str): path = os.path.join(work_dir, "first_pass.csv") try: with open(path, newline="") as csvfile: reader = csv.reader(csvfile) gene_ids = next(reader) microarray_columns = next(reader) rnaseq_columns = next(reader) return { "gene_ids": gene_ids, "microarray_columns": microarray_columns, "rnaseq_columns": rnaseq_columns, } # If the file doesn't exist then the gene ids aren't cached. Any # other exception should be handled and higher in the stack. except FileNotFoundError: return None def cache_first_pass( job_context: Dict, gene_ids: List[str], microarray_columns: List[str], rnaseq_columns: List[str] ): try: path = os.path.join(job_context["work_dir"], "first_pass.csv") logger.info( "Caching gene_ids, microarray_columns, and rnaseq_columns to %s", path, job_id=job_context["job"].id, ) with open(path, "w", newline="") as csvfile: writer = csv.writer(csvfile) writer.writerow(gene_ids) writer.writerow(microarray_columns) writer.writerow(rnaseq_columns) # Nothing in the above try should raise an exception, but if it # does don't waste the work we did in the first pass. except Exception: logger.exception( "Error writing gene identifiers to CSV file.", job_id=job_context["job"].id ) def process_frames_for_key( key: str, input_files: List[Tuple[ComputedFile, Sample]], job_context: Dict ) -> Dict: """Download, read, and chunk processed sample files from s3. `key` is the species or experiment whose samples are contained in `input_files`. Will add to job_context the keys 'microarray_matrix' and 'rnaseq_matrix' with pandas dataframes containing all of the samples' data. Also adds the key 'unsmashable_files' containing a list of paths that were determined to be unsmashable. """ start_gene_ids = log_state( "Collecting all gene identifiers for key {}".format(key), job_context["job"].id ) # Build up a list of gene identifiers because these will be the # rows of our matrices, and we want to preallocate them so we need # to know them all. ## We may have built this list in a previous job, check to see if it's cached: cached_data = load_first_pass_data_if_cached(job_context["work_dir"]) first_pass_was_cached = False if cached_data: logger.info( ( "The data from the first pass was cached, so we're using " "that and skipping the first pass." ), job_id=job_context["job"].id, ) first_pass_was_cached = True all_gene_identifiers = cached_data["gene_ids"] microarray_columns = cached_data["microarray_columns"] rnaseq_columns = cached_data["rnaseq_columns"] else: gene_identifier_counts = {} microarray_columns = [] rnaseq_columns = [] for index, (computed_file, sample) in enumerate(input_files): log_state("1st processing frame {}".format(index), job_context["job"].id) frame_data = process_frame( job_context["work_dir"], computed_file, sample.accession_code, job_context["dataset"].aggregate_by, ) if frame_data is None: # we were unable to process this sample, so we drop logger.warning( "Unable to smash file", computed_file=computed_file.id, dataset_id=job_context["dataset"].id, job_id=job_context["job"].id, ) sample_metadata = sample.to_metadata_dict() job_context["filtered_samples"][sample.accession_code] = { **sample_metadata, "reason": "The file associated with this sample did not pass the QC checks we apply before aggregating.", "filename": computed_file.filename, "experiment_accession_code": get_experiment_accession( sample.accession_code, job_context["dataset"].data ), } continue # Count how many frames are in each tech so we can preallocate # the matrices in both directions. for gene_id in frame_data.index: if gene_id in gene_identifier_counts: gene_identifier_counts[gene_id] += 1 else: gene_identifier_counts[gene_id] = 1 # Each dataframe should only have 1 column, but it's # returned as a list so use extend. if sample.technology == "MICROARRAY": microarray_columns.extend(frame_data.columns) elif sample.technology == "RNA-SEQ": rnaseq_columns.extend(frame_data.columns) # We only want to use gene identifiers which are present # in >50% of the samples. We're doing this because a large # number of gene identifiers present in only a modest # number of experiments have leaked through. We wouldn't # necessarily want to do this if we'd mapped all the data # to ENSEMBL identifiers successfully. total_samples = len(microarray_columns) + len(rnaseq_columns) all_gene_identifiers = [ gene_id for gene_id in gene_identifier_counts if gene_identifier_counts[gene_id] > (total_samples * 0.5) ] all_gene_identifiers.sort() del gene_identifier_counts log_template = ( "Collected {0} gene identifiers for {1} across" " {2} micrarry samples and {3} RNA-Seq samples." ) log_state( log_template.format( len(all_gene_identifiers), key, len(microarray_columns), len(rnaseq_columns) ), job_context["job"].id, start_gene_ids, ) # Temporarily only cache mouse compendia because it may not succeed. if not first_pass_was_cached and key == "MUS_MUSCULUS": cache_first_pass(job_context, all_gene_identifiers, microarray_columns, rnaseq_columns) start_build_matrix = log_state("Beginning to build the full matrices.", job_context["job"].id) # Sort the columns so that the matrices are in predictable orders. microarray_columns.sort() rnaseq_columns.sort() # Preallocate the matrices to be the exact size we will need. This # should prevent any operations from happening while we build it # up, so the only RAM used will be needed. job_context["microarray_matrix"] = pd.DataFrame( data=None, index=all_gene_identifiers, columns=microarray_columns, dtype=np.float32 ) job_context["rnaseq_matrix"] = pd.DataFrame( data=None, index=all_gene_identifiers, columns=rnaseq_columns, dtype=np.float32 ) for index, (computed_file, sample) in enumerate(input_files): log_state("2nd processing frame {}".format(index), job_context["job"].id) frame_data = process_frame( job_context["work_dir"], computed_file, sample.accession_code, job_context["dataset"].aggregate_by, ) if frame_data is None: job_context["unsmashable_files"].append(computed_file.filename) sample_metadata = sample.to_metadata_dict() job_context["filtered_samples"][sample.accession_code] = { **sample_metadata, "reason": "The file associated with this sample did not contain a vector that fit the expected dimensions of the matrix.", "filename": computed_file.filename, "experiment_accession_code": get_experiment_accession( sample.accession_code, job_context["dataset"].data ), } continue frame_data = frame_data.reindex(all_gene_identifiers) # The dataframe for each sample will only have one column # whose header will be the accession code. column = frame_data.columns[0] if sample.technology == "MICROARRAY": job_context["microarray_matrix"][column] = frame_data.values elif sample.technology == "RNA-SEQ": job_context["rnaseq_matrix"][column] = frame_data.values job_context["num_samples"] = 0 if job_context["microarray_matrix"] is not None: job_context["num_samples"] += len(job_context["microarray_matrix"].columns) if job_context["rnaseq_matrix"] is not None: job_context["num_samples"] += len(job_context["rnaseq_matrix"].columns) log_state( "Built full matrices for key {}".format(key), job_context["job"].id, start_build_matrix ) return job_context # Modified from: http://yaoyao.codes/pandas/2018/01/23/pandas-split-a-dataframe-into-chunks def _index_marks(num_columns, chunk_size): return range(chunk_size, math.ceil(num_columns / chunk_size) * chunk_size, chunk_size) def _split_dataframe_columns(dataframe, chunk_size): indices = _index_marks(dataframe.shape[1], chunk_size) return np.split(dataframe, indices, axis=1) def _quantile_normalize_matrix(target_vector, original_matrix): preprocessCore = importr("preprocessCore") as_numeric = rlang("as.numeric") data_matrix = rlang("data.matrix") # Convert the smashed frames to an R numeric Matrix target_vector = as_numeric(target_vector) # Do so in chunks if the matrix is too large. if original_matrix.shape[1] <= QN_CHUNK_SIZE: merged_matrix = data_matrix(original_matrix) normalized_matrix = preprocessCore.normalize_quantiles_use_target( x=merged_matrix, target=target_vector, copy=True ) # And finally convert back to Pandas ar = np.array(normalized_matrix) new_merged = pd.DataFrame(ar, columns=original_matrix.columns, index=original_matrix.index) else: matrix_chunks = _split_dataframe_columns(original_matrix, QN_CHUNK_SIZE) for i, chunk in enumerate(matrix_chunks): R_chunk = data_matrix(chunk) normalized_chunk = preprocessCore.normalize_quantiles_use_target( x=R_chunk, target=target_vector, copy=True ) ar = np.array(normalized_chunk) start_column = i * QN_CHUNK_SIZE end_column = (i + 1) * QN_CHUNK_SIZE original_matrix.iloc[:, start_column:end_column] = ar new_merged = original_matrix return new_merged def _test_qn(merged_matrix): """ Selects a list of 100 random pairs of columns and performs the KS Test on them. Returns a list of tuples with the results of the KN test (statistic, pvalue) """ # Verify this QN, related: # https://github.com/AlexsLemonade/refinebio/issues/599#issuecomment-422132009 data_matrix = rlang("data.matrix") as_numeric = rlang("as.numeric") set_seed = rlang("set.seed") combn = rlang("combn") ncol = rlang("ncol") ks_test = rlang("ks.test") which = rlang("which") merged_R_matrix = data_matrix(merged_matrix) set_seed(123) n = ncol(merged_R_matrix)[0] m = 2 # Not enough columns to perform KS test - either bad smash or single sample smash. if n < m: return None # This wont work with larger matricies # https://github.com/AlexsLemonade/refinebio/issues/1860 ncolumns = ncol(merged_R_matrix) if ncolumns[0] <= 200: # Convert to NP, Shuffle, Return to R combos = combn(ncolumns, 2) ar = np.array(combos) np.random.shuffle(np.transpose(ar)) else: indexes = [*range(ncolumns[0])] np.random.shuffle(indexes) ar = np.array([*zip(indexes[0:100], indexes[100:200])]) nr, nc = ar.shape combos = ro.r.matrix(ar, nrow=nr, ncol=nc) result = [] # adapted from # https://stackoverflow.com/questions/9661469/r-t-test-over-all-columns # apply KS test to randomly selected pairs of columns (samples) for i in range(1, min(ncol(combos)[0], 100)): value1 = combos.rx(1, i)[0] value2 = combos.rx(2, i)[0] test_a = merged_R_matrix.rx(True, value1) test_b = merged_R_matrix.rx(True, value2) # RNA-seq has a lot of zeroes in it, which # breaks the ks_test. Therefore we want to # filter them out. To do this we drop the # lowest half of the values. If there's # still zeroes in there, then that's # probably too many zeroes so it's okay to # fail. median_a = np.median(test_a) median_b = np.median(test_b) # `which` returns indices which are # 1-indexed. Python accesses lists with # zero-indexes, even if that list is # actually an R vector. Therefore subtract # 1 to account for the difference. test_a = [test_a[i - 1] for i in which(test_a > median_a)] test_b = [test_b[i - 1] for i in which(test_b > median_b)] # The python list comprehension gives us a # python list, but ks_test wants an R # vector so let's go back. test_a = as_numeric(test_a) test_b = as_numeric(test_b) ks_res = ks_test(test_a, test_b) statistic = ks_res.rx("statistic")[0][0] pvalue = ks_res.rx("p.value")[0][0] result.append((statistic, pvalue)) return result def quantile_normalize(job_context: Dict, ks_check=True, ks_stat=0.001) -> Dict: """ Apply quantile normalization. """ # Prepare our QN target file organism = job_context["organism"] if not organism.qn_target: raise utils.ProcessorJobError( "Could not find QN target for Organism: " + str(organism), success=False, organism=organism, dataset_id=job_context["dataset"].id, ) qn_target_path = organism.qn_target.computedfile_set.latest().sync_from_s3() qn_target_frame = pd.read_csv( qn_target_path, sep="\t", header=None, index_col=None, error_bad_lines=False ) # Prepare our RPy2 bridge pandas2ri.activate() # Remove un-quantiled normalized matrix from job_context # because we no longer need it. merged_no_qn = job_context.pop("merged_no_qn") # Perform the Actual QN new_merged = _quantile_normalize_matrix(qn_target_frame[0], merged_no_qn) # And add the quantile normalized matrix to job_context. job_context["merged_qn"] = new_merged # For now, don't test the QN for mouse/human. This never fails on # smasher jobs and is OOM-killing our very large compendia # jobs. Let's run this manually after we have a compendia job # actually finish. if organism.name in ["MUS_MUSCULUS", "HOMO_SAPIENS"]: return job_context ks_res = _test_qn(new_merged) if ks_res: for (statistic, pvalue) in ks_res: job_context["ks_statistic"] = statistic job_context["ks_pvalue"] = pvalue # We're unsure of how strigent to be about # the pvalue just yet, so we're extra lax # rather than failing tons of tests. This may need tuning. if ks_check and (statistic > ks_stat or pvalue < 0.8): job_context["ks_warning"] = ( "Failed Kolmogorov Smirnov test! Stat: " + str(statistic) + ", PVal: " + str(pvalue) ) else: logger.warning( "Not enough columns to perform KS test - either bad smash or single sample smash.", dataset_id=job_context["dataset"].id, ) return job_context def compile_metadata(job_context: Dict) -> Dict: """Compiles metadata about the job. Returns a new dict containing the metadata, not the job_context. """ metadata = {} metadata["num_samples"] = job_context["num_samples"] metadata["num_experiments"] = job_context["experiments"].count() metadata["quant_sf_only"] = job_context["dataset"].quant_sf_only if not job_context["dataset"].quant_sf_only: metadata["aggregate_by"] = job_context["dataset"].aggregate_by metadata["scale_by"] = job_context["dataset"].scale_by # https://github.com/AlexsLemonade/refinebio/pull/421#discussion_r203799646 # TODO: do something with these. # metadata['non_aggregated_files'] = job_context["unsmashable_files"] metadata["ks_statistic"] = job_context.get("ks_statistic", None) metadata["ks_pvalue"] = job_context.get("ks_pvalue", None) metadata["ks_warning"] = job_context.get("ks_warning", None) metadata["quantile_normalized"] = job_context["dataset"].quantile_normalize filtered_samples = job_context["filtered_samples"] samples = {} for sample in job_context["dataset"].get_samples(): if sample.accession_code in filtered_samples: # skip the samples that were filtered continue samples[sample.accession_code] = sample.to_metadata_dict() metadata["samples"] = samples experiments = {} for experiment in job_context["dataset"].get_experiments(): experiment_metadata = experiment.to_metadata_dict() # exclude filtered samples from experiment metadata all_samples = experiment_metadata["sample_accession_codes"] all_samples = [code for code in all_samples if code not in filtered_samples] experiment_metadata["sample_accession_codes"] = all_samples experiments[experiment.accession_code] = experiment_metadata metadata["experiments"] = experiments return metadata def write_non_data_files(job_context: Dict) -> Dict: """Writes the files that are not the actual data of the dataset. This include LICENSE.txt and README.md files and the metadata. Adds the key `metadata` to job_context and populates it with all the metadata that needs to be written. """ job_context["metadata"] = compile_metadata(job_context) shutil.copy("README_DATASET.md", job_context["output_dir"] + "README.md") shutil.copy("LICENSE_DATASET.txt", job_context["output_dir"] + "LICENSE.TXT") # Write samples metadata to TSV try: write_tsv_json(job_context) # Metadata to JSON job_context["metadata"]["created_at"] = timezone.now().strftime("%Y-%m-%dT%H:%M:%S") aggregated_metadata_path = os.path.join( job_context["output_dir"], "aggregated_metadata.json" ) with open(aggregated_metadata_path, "w", encoding="utf-8") as metadata_file: json.dump(job_context["metadata"], metadata_file, indent=4, sort_keys=True) if job_context["filtered_samples"]: # generate filtered samples file only if some samples were skipped filtered_samples_path = os.path.join( job_context["output_dir"], "filtered_samples_metadata.json" ) with open(filtered_samples_path, "w", encoding="utf-8") as metadata_file: json.dump(job_context["filtered_samples"], metadata_file, indent=4, sort_keys=True) columns = get_tsv_columns(job_context["filtered_samples"]) filtered_samples_tsv_path = os.path.join( job_context["output_dir"], "filtered_samples_metadata.tsv" ) with open(filtered_samples_tsv_path, "w", encoding="utf-8") as tsv_file: dw = csv.DictWriter(tsv_file, columns, delimiter="\t", extrasaction="ignore") dw.writeheader() for sample_metadata in job_context["filtered_samples"].values(): dw.writerow(get_tsv_row_data(sample_metadata, job_context["dataset"].data)) except Exception: raise utils.ProcessorJobError("Failed to write metadata TSV!", success=False) return job_context def get_experiment_accession(sample_accession_code, dataset_data): for experiment_accession, samples in dataset_data.items(): if sample_accession_code in samples: return experiment_accession return "" # Should never happen, because the sample is by definition in the dataset def _add_annotation_column(annotation_columns, column_name): """Add annotation column names in place. Any column_name that starts with "refinebio_" will be skipped. """ if not column_name.startswith("refinebio_"): annotation_columns.add(column_name) def _add_annotation_value(row_data, col_name, col_value, sample_accession_code): """Adds a new `col_name` key whose value is `col_value` to row_data. If col_name already exists in row_data with different value, print out a warning message. """ # Generate a warning message if annotation field name starts with # "refinebio_". This should rarely (if ever) happen. if col_name.startswith("refinebio_"): logger.warning( "Annotation value skipped", annotation_field=col_name, annotation_value=col_value, sample_accession_code=sample_accession_code, ) elif col_name not in row_data: row_data[col_name] = col_value # Generate a warning message in case of conflicts of annotation values. # (Requested by Dr. <NAME>) elif row_data[col_name] != col_value: logger.warning( "Conflict of values found in column %s: %s vs. %s" % (col_name, row_data[col_name], col_value), sample_accession_code=sample_accession_code, ) def get_tsv_row_data(sample_metadata, dataset_data): """Returns field values based on input sample_metadata. Some annotation fields are treated specially because they are more important. See `get_tsv_columns` function above for details. """ sample_accession_code = sample_metadata.get("refinebio_accession_code", "") row_data = dict() for meta_key, meta_value in sample_metadata.items(): # If the field is a refinebio-specific field, simply copy it. if meta_key != "refinebio_annotations": row_data[meta_key] = meta_value continue # Decompose sample_metadata["refinebio_annotations"], which is # an array of annotations. for annotation in meta_value: for annotation_key, annotation_value in annotation.items(): # "characteristic" in ArrayExpress annotation if ( sample_metadata.get("refinebio_source_database", "") == "ARRAY_EXPRESS" and annotation_key == "characteristic" ): for pair_dict in annotation_value: if "category" in pair_dict and "value" in pair_dict: col_name, col_value = pair_dict["category"], pair_dict["value"] _add_annotation_value( row_data, col_name, col_value, sample_accession_code ) # "variable" in ArrayExpress annotation elif ( sample_metadata.get("refinebio_source_database", "") == "ARRAY_EXPRESS" and annotation_key == "variable" ): for pair_dict in annotation_value: if "name" in pair_dict and "value" in pair_dict: col_name, col_value = pair_dict["name"], pair_dict["value"] _add_annotation_value( row_data, col_name, col_value, sample_accession_code ) # Skip "source" field ArrayExpress sample's annotation elif ( sample_metadata.get("refinebio_source_database", "") == "ARRAY_EXPRESS" and annotation_key == "source" ): continue # "characteristics_ch1" in GEO annotation elif ( sample_metadata.get("refinebio_source_database", "") == "GEO" and annotation_key == "characteristics_ch1" ): # array of strings for pair_str in annotation_value: if ":" in pair_str: col_name, col_value = pair_str.split(":", 1) col_value = col_value.strip() _add_annotation_value( row_data, col_name, col_value, sample_accession_code ) # If annotation_value includes only a 'name' key, extract its value directly: elif ( isinstance(annotation_value, dict) and len(annotation_value) == 1 and "name" in annotation_value ): _add_annotation_value( row_data, annotation_key, annotation_value["name"], sample_accession_code ) # If annotation_value is a single-element array, extract the element directly: elif isinstance(annotation_value, list) and len(annotation_value) == 1: _add_annotation_value( row_data, annotation_key, annotation_value[0], sample_accession_code ) # Otherwise save all annotation fields in separate columns else: _add_annotation_value( row_data, annotation_key, annotation_value, sample_accession_code ) row_data["experiment_accession"] = get_experiment_accession(sample_accession_code, dataset_data) return row_data def get_tsv_columns(samples_metadata): """Returns an array of strings that will be written as a TSV file's header. The columns are based on fields found in samples_metadata. Some nested annotation fields are taken out as separate columns because they are more important than the others. """ refinebio_columns = set() annotation_columns = set() for sample_metadata in samples_metadata.values(): for meta_key, meta_value in sample_metadata.items(): if meta_key != "refinebio_annotations": refinebio_columns.add(meta_key) continue # Decompose sample_metadata["annotations"], which is an array of annotations! for annotation in meta_value: for annotation_key, annotation_value in annotation.items(): # For ArrayExpress samples, take out the fields # nested in "characteristic" as separate columns. if ( sample_metadata.get("refinebio_source_database", "") == "ARRAY_EXPRESS" and annotation_key == "characteristic" ): for pair_dict in annotation_value: if "category" in pair_dict and "value" in pair_dict: _add_annotation_column(annotation_columns, pair_dict["category"]) # For ArrayExpress samples, also take out the fields # nested in "variable" as separate columns. elif ( sample_metadata.get("refinebio_source_database", "") == "ARRAY_EXPRESS" and annotation_key == "variable" ): for pair_dict in annotation_value: if "name" in pair_dict and "value" in pair_dict: _add_annotation_column(annotation_columns, pair_dict["name"]) # For ArrayExpress samples, skip "source" field elif ( sample_metadata.get("refinebio_source_database", "") == "ARRAY_EXPRESS" and annotation_key == "source" ): continue # For GEO samples, take out the fields nested in # "characteristics_ch1" as separate columns. elif ( sample_metadata.get("refinebio_source_database", "") == "GEO" and annotation_key == "characteristics_ch1" ): # array of strings for pair_str in annotation_value: if ":" in pair_str: tokens = pair_str.split(":", 1) _add_annotation_column(annotation_columns, tokens[0]) # Saves all other annotation fields in separate columns else: _add_annotation_column(annotation_columns, annotation_key) # Return sorted columns, in which "refinebio_accession_code" and "experiment_accession" are # always first, followed by the other refinebio columns (in alphabetic order), and # annotation columns (in alphabetic order) at the end. refinebio_columns.discard("refinebio_accession_code") return ( ["refinebio_accession_code", "experiment_accession"] + sorted(refinebio_columns) + sorted(annotation_columns) ) def write_tsv_json(job_context): """Writes tsv files on disk. If the dataset is aggregated by species, also write species-level JSON file. """ # Avoid pulling this out of job_context repeatedly. metadata = job_context["metadata"] # Uniform TSV header per dataset columns = get_tsv_columns(metadata["samples"]) # Per-Experiment Metadata if job_context["dataset"].aggregate_by == "EXPERIMENT": tsv_paths = [] for experiment_title, experiment_data in metadata["experiments"].items(): experiment_dir = job_context["output_dir"] + experiment_title + "/" experiment_dir = experiment_dir.encode("ascii", "ignore") os.makedirs(experiment_dir, exist_ok=True) tsv_path = experiment_dir.decode("utf-8") + "metadata_" + experiment_title + ".tsv" tsv_path = tsv_path.encode("ascii", "ignore") tsv_paths.append(tsv_path) with open(tsv_path, "w", encoding="utf-8") as tsv_file: dw = csv.DictWriter(tsv_file, columns, delimiter="\t", extrasaction="ignore") dw.writeheader() for sample_accession_code, sample_metadata in metadata["samples"].items(): if sample_accession_code in experiment_data["sample_accession_codes"]: row_data = get_tsv_row_data(sample_metadata, job_context["dataset"].data) dw.writerow(row_data) return tsv_paths # Per-Species Metadata elif job_context["dataset"].aggregate_by == "SPECIES": tsv_paths = [] for species in job_context["group_by_keys"]: species_dir = job_context["output_dir"] + species + "/" os.makedirs(species_dir, exist_ok=True) samples_in_species = [] tsv_path = species_dir + "metadata_" + species + ".tsv" tsv_paths.append(tsv_path) with open(tsv_path, "w", encoding="utf-8") as tsv_file: # See http://www.lucainvernizzi.net/blog/2015/08/03/8x-speed-up-for-python-s-csv-dictwriter/ # about extrasaction. dw = csv.DictWriter(tsv_file, columns, delimiter="\t", extrasaction="ignore") dw.writeheader() i = 0 for sample_metadata in metadata["samples"].values(): if sample_metadata.get("refinebio_organism", "") == species: row_data = get_tsv_row_data(sample_metadata, job_context["dataset"].data) dw.writerow(row_data) samples_in_species.append(sample_metadata) i = i + 1 if i % 1000 == 0: progress_template = ( "Done with {0} out of {1} lines of metadata " "for species {2}" ) log_state( progress_template.format(i, len(metadata["samples"]), species), job_context["job"].id, ) # Writes a json file for current species: if len(samples_in_species): species_metadata = {"species": species, "samples": samples_in_species} json_path = species_dir + "metadata_" + species + ".json" with open(json_path, "w", encoding="utf-8") as json_file: json.dump(species_metadata, json_file, indent=4, sort_keys=True) return tsv_paths # All Metadata else: all_dir = job_context["output_dir"] + "ALL/" os.makedirs(all_dir, exist_ok=True) tsv_path = all_dir + "metadata_ALL.tsv" with open(tsv_path, "w", encoding="utf-8") as tsv_file: dw = csv.DictWriter(tsv_file, columns, delimiter="\t", extrasaction="ignore") dw.writeheader() for sample_metadata in metadata["samples"].values(): row_data = get_tsv_row_data(sample_metadata, job_context["dataset"].data) dw.writerow(row_data) return [tsv_path] def download_computed_file(download_tuple: Tuple[ComputedFile, str]): """ this function downloads the latest computed file. Receives a tuple with the computed file and the path where it needs to be downloaded This is used to parallelize downloading quantsf files. """ (latest_computed_file, output_file_path) = download_tuple try: latest_computed_file.get_synced_file_path(path=output_file_path) except: # Let's not fail if there's an error syncing one of the quant.sf files logger.exception("Failed to sync computed file", computed_file_id=latest_computed_file.pk) def sync_quant_files(output_path, samples: List[Sample]): """ Takes a list of ComputedFiles and copies the ones that are quant files to the provided directory. Returns the total number of samples that were included """ num_samples = 0 page_size = 100 # split the samples in groups and download each one individually with ThreadPoolExecutor(max_workers=MULTIPROCESSING_MAX_THREAD_COUNT) as executor: # for each sample we need it's latest quant.sf file we don't want to query the db # for all of them, so we do it in groups of 100, and then download all of the computed_files # in parallel for sample_page in ( samples[i * page_size : i + page_size] for i in range(0, len(samples), page_size) ): sample_and_computed_files = [] for sample in sample_page: latest_computed_file = sample.get_most_recent_quant_sf_file() if not latest_computed_file: continue output_file_path = output_path + sample.accession_code + "_quant.sf" sample_and_computed_files.append((latest_computed_file, output_file_path)) # download this set of files, this will take a few seconds that should also help the db recover executor.map(download_computed_file, sample_and_computed_files) num_samples += len(sample_and_computed_files) return num_samples
[ "csv.DictWriter", "rpy2.robjects.pandas2ri.activate", "pandas.read_csv", "data_refinery_common.logging.get_and_configure_logger", "multiprocessing.cpu_count", "numpy.array", "rpy2.robjects.r", "os.path.exists", "pathlib.Path", "rpy2.robjects.packages.importr", "django.utils.timezone.now", "os.getpid", "pandas.DataFrame", "csv.reader", "psutil.cpu_percent", "csv.writer", "data_refinery_common.utils.get_env_variable", "logging.getLevelName", "simplejson.dump", "shutil.copy", "numpy.log2", "numpy.transpose", "time.time", "data_refinery_workers.processors.utils.ProcessorJobError", "numpy.median", "math.ceil", "os.makedirs", "concurrent.futures.ThreadPoolExecutor", "os.path.join", "rpy2.robjects.r.matrix", "numpy.split", "shutil.rmtree", "numpy.random.shuffle" ]
[((811, 881), 'data_refinery_common.utils.get_env_variable', 'get_env_variable', (['"""S3_RESULTS_BUCKET_NAME"""', '"""refinebio-results-bucket"""'], {}), "('S3_RESULTS_BUCKET_NAME', 'refinebio-results-bucket')\n", (827, 881), False, 'from data_refinery_common.utils import get_env_variable\n'), ((899, 950), 'data_refinery_common.utils.get_env_variable', 'get_env_variable', (['"""S3_BUCKET_NAME"""', '"""data-refinery"""'], {}), "('S3_BUCKET_NAME', 'data-refinery')\n", (915, 950), False, 'from data_refinery_common.utils import get_env_variable\n'), ((1265, 1299), 'data_refinery_common.logging.get_and_configure_logger', 'get_and_configure_logger', (['__name__'], {}), '(__name__)\n', (1289, 1299), False, 'from data_refinery_common.logging import get_and_configure_logger\n'), ((1330, 1359), 'logging.getLevelName', 'logging.getLevelName', (['"""DEBUG"""'], {}), "('DEBUG')\n", (1350, 1359), False, 'import logging\n'), ((3782, 3840), 'shutil.rmtree', 'shutil.rmtree', (["job_context['work_dir']"], {'ignore_errors': '(True)'}), "(job_context['work_dir'], ignore_errors=True)\n", (3795, 3840), False, 'import shutil\n'), ((3845, 3881), 'os.makedirs', 'os.makedirs', (["job_context['work_dir']"], {}), "(job_context['work_dir'])\n", (3856, 3881), False, 'import os\n'), ((3955, 3993), 'os.makedirs', 'os.makedirs', (["job_context['output_dir']"], {}), "(job_context['output_dir'])\n", (3966, 3993), False, 'import os\n'), ((4221, 4347), 'pandas.read_csv', 'pd.read_csv', (['computed_file_path'], {'sep': '"""\t"""', 'header': '(0)', 'index_col': '(0)', 'dtype': '{(0): str, (1): np.float32}', 'error_bad_lines': '(False)'}), "(computed_file_path, sep='\\t', header=0, index_col=0, dtype={(0):\n str, (1): np.float32}, error_bad_lines=False)\n", (4232, 4347), True, 'import pandas as pd\n'), ((9367, 9407), 'os.path.join', 'os.path.join', (['work_dir', '"""first_pass.csv"""'], {}), "(work_dir, 'first_pass.csv')\n", (9379, 9407), False, 'import os\n'), ((16220, 16322), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'None', 'index': 'all_gene_identifiers', 'columns': 'microarray_columns', 'dtype': 'np.float32'}), '(data=None, index=all_gene_identifiers, columns=\n microarray_columns, dtype=np.float32)\n', (16232, 16322), True, 'import pandas as pd\n'), ((16367, 16464), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'None', 'index': 'all_gene_identifiers', 'columns': 'rnaseq_columns', 'dtype': 'np.float32'}), '(data=None, index=all_gene_identifiers, columns=rnaseq_columns,\n dtype=np.float32)\n', (16379, 16464), True, 'import pandas as pd\n'), ((18725, 18761), 'numpy.split', 'np.split', (['dataframe', 'indices'], {'axis': '(1)'}), '(dataframe, indices, axis=1)\n', (18733, 18761), True, 'import numpy as np\n'), ((18849, 18874), 'rpy2.robjects.packages.importr', 'importr', (['"""preprocessCore"""'], {}), "('preprocessCore')\n", (18856, 18874), False, 'from rpy2.robjects.packages import importr\n'), ((18892, 18911), 'rpy2.robjects.r', 'rlang', (['"""as.numeric"""'], {}), "('as.numeric')\n", (18897, 18911), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((18930, 18950), 'rpy2.robjects.r', 'rlang', (['"""data.matrix"""'], {}), "('data.matrix')\n", (18935, 18950), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((20474, 20494), 'rpy2.robjects.r', 'rlang', (['"""data.matrix"""'], {}), "('data.matrix')\n", (20479, 20494), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((20512, 20531), 'rpy2.robjects.r', 'rlang', (['"""as.numeric"""'], {}), "('as.numeric')\n", (20517, 20531), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((20547, 20564), 'rpy2.robjects.r', 'rlang', (['"""set.seed"""'], {}), "('set.seed')\n", (20552, 20564), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((20577, 20591), 'rpy2.robjects.r', 'rlang', (['"""combn"""'], {}), "('combn')\n", (20582, 20591), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((20603, 20616), 'rpy2.robjects.r', 'rlang', (['"""ncol"""'], {}), "('ncol')\n", (20608, 20616), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((20631, 20647), 'rpy2.robjects.r', 'rlang', (['"""ks.test"""'], {}), "('ks.test')\n", (20636, 20647), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((20660, 20674), 'rpy2.robjects.r', 'rlang', (['"""which"""'], {}), "('which')\n", (20665, 20674), True, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((21421, 21454), 'rpy2.robjects.r.matrix', 'ro.r.matrix', (['ar'], {'nrow': 'nr', 'ncol': 'nc'}), '(ar, nrow=nr, ncol=nc)\n', (21432, 21454), True, 'import rpy2.robjects as ro\n'), ((23583, 23676), 'pandas.read_csv', 'pd.read_csv', (['qn_target_path'], {'sep': '"""\t"""', 'header': 'None', 'index_col': 'None', 'error_bad_lines': '(False)'}), "(qn_target_path, sep='\\t', header=None, index_col=None,\n error_bad_lines=False)\n", (23594, 23676), True, 'import pandas as pd\n'), ((23722, 23742), 'rpy2.robjects.pandas2ri.activate', 'pandas2ri.activate', ([], {}), '()\n', (23740, 23742), False, 'from rpy2.robjects import pandas2ri, r as rlang\n'), ((27651, 27724), 'shutil.copy', 'shutil.copy', (['"""README_DATASET.md"""', "(job_context['output_dir'] + 'README.md')"], {}), "('README_DATASET.md', job_context['output_dir'] + 'README.md')\n", (27662, 27724), False, 'import shutil\n'), ((27729, 27806), 'shutil.copy', 'shutil.copy', (['"""LICENSE_DATASET.txt"""', "(job_context['output_dir'] + 'LICENSE.TXT')"], {}), "('LICENSE_DATASET.txt', job_context['output_dir'] + 'LICENSE.TXT')\n", (27740, 27806), False, 'import shutil\n'), ((10147, 10202), 'os.path.join', 'os.path.join', (["job_context['work_dir']", '"""first_pass.csv"""'], {}), "(job_context['work_dir'], 'first_pass.csv')\n", (10159, 10202), False, 'import os\n'), ((19412, 19439), 'numpy.array', 'np.array', (['normalized_matrix'], {}), '(normalized_matrix)\n', (19420, 19439), True, 'import numpy as np\n'), ((19461, 19539), 'pandas.DataFrame', 'pd.DataFrame', (['ar'], {'columns': 'original_matrix.columns', 'index': 'original_matrix.index'}), '(ar, columns=original_matrix.columns, index=original_matrix.index)\n', (19473, 19539), True, 'import pandas as pd\n'), ((21175, 21191), 'numpy.array', 'np.array', (['combos'], {}), '(combos)\n', (21183, 21191), True, 'import numpy as np\n'), ((21294, 21320), 'numpy.random.shuffle', 'np.random.shuffle', (['indexes'], {}), '(indexes)\n', (21311, 21320), True, 'import numpy as np\n'), ((22190, 22207), 'numpy.median', 'np.median', (['test_a'], {}), '(test_a)\n', (22199, 22207), True, 'import numpy as np\n'), ((22227, 22244), 'numpy.median', 'np.median', (['test_b'], {}), '(test_b)\n', (22236, 22244), True, 'import numpy as np\n'), ((28044, 28111), 'os.path.join', 'os.path.join', (["job_context['output_dir']", '"""aggregated_metadata.json"""'], {}), "(job_context['output_dir'], 'aggregated_metadata.json')\n", (28056, 28111), False, 'import os\n'), ((43948, 44012), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': 'MULTIPROCESSING_MAX_THREAD_COUNT'}), '(max_workers=MULTIPROCESSING_MAX_THREAD_COUNT)\n', (43966, 44012), False, 'from concurrent.futures import ThreadPoolExecutor\n'), ((1489, 1500), 'os.getpid', 'os.getpid', ([], {}), '()\n', (1498, 1500), False, 'import os\n'), ((1804, 1815), 'time.time', 'time.time', ([], {}), '()\n', (1813, 1815), False, 'import time\n'), ((7815, 7828), 'numpy.log2', 'np.log2', (['data'], {}), '(data)\n', (7822, 7828), True, 'import numpy as np\n'), ((8092, 8105), 'numpy.log2', 'np.log2', (['data'], {}), '(data)\n', (8099, 8105), True, 'import numpy as np\n'), ((9486, 9505), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (9496, 9505), False, 'import csv\n'), ((10446, 10465), 'csv.writer', 'csv.writer', (['csvfile'], {}), '(csvfile)\n', (10456, 10465), False, 'import csv\n'), ((18538, 18573), 'math.ceil', 'math.ceil', (['(num_columns / chunk_size)'], {}), '(num_columns / chunk_size)\n', (18547, 18573), False, 'import math\n'), ((19890, 19916), 'numpy.array', 'np.array', (['normalized_chunk'], {}), '(normalized_chunk)\n', (19898, 19916), True, 'import numpy as np\n'), ((21218, 21234), 'numpy.transpose', 'np.transpose', (['ar'], {}), '(ar)\n', (21230, 21234), True, 'import numpy as np\n'), ((28231, 28306), 'simplejson.dump', 'json.dump', (["job_context['metadata']", 'metadata_file'], {'indent': '(4)', 'sort_keys': '(True)'}), "(job_context['metadata'], metadata_file, indent=4, sort_keys=True)\n", (28240, 28306), True, 'import simplejson as json\n'), ((28467, 28540), 'os.path.join', 'os.path.join', (["job_context['output_dir']", '"""filtered_samples_metadata.json"""'], {}), "(job_context['output_dir'], 'filtered_samples_metadata.json')\n", (28479, 28540), False, 'import os\n'), ((28869, 28941), 'os.path.join', 'os.path.join', (["job_context['output_dir']", '"""filtered_samples_metadata.tsv"""'], {}), "(job_context['output_dir'], 'filtered_samples_metadata.tsv')\n", (28881, 28941), False, 'import os\n'), ((29397, 29468), 'data_refinery_workers.processors.utils.ProcessorJobError', 'utils.ProcessorJobError', (['"""Failed to write metadata TSV!"""'], {'success': '(False)'}), "('Failed to write metadata TSV!', success=False)\n", (29420, 29468), False, 'from data_refinery_workers.processors import utils\n'), ((39595, 39637), 'os.makedirs', 'os.makedirs', (['experiment_dir'], {'exist_ok': '(True)'}), '(experiment_dir, exist_ok=True)\n', (39606, 39637), False, 'import os\n'), ((42494, 42529), 'os.makedirs', 'os.makedirs', (['all_dir'], {'exist_ok': '(True)'}), '(all_dir, exist_ok=True)\n', (42505, 42529), False, 'import os\n'), ((756, 783), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (781, 783), False, 'import multiprocessing\n'), ((969, 1032), 'pathlib.Path', 'Path', (['"""data_refinery_workers/processors/smasher_email.min.html"""'], {}), "('data_refinery_workers/processors/smasher_email.min.html')\n", (973, 1032), False, 'from pathlib import Path\n'), ((1089, 1158), 'pathlib.Path', 'Path', (['"""data_refinery_workers/processors/smasher_email_error.min.html"""'], {}), "('data_refinery_workers/processors/smasher_email_error.min.html')\n", (1093, 1158), False, 'from pathlib import Path\n'), ((1602, 1622), 'psutil.cpu_percent', 'psutil.cpu_percent', ([], {}), '()\n', (1620, 1622), False, 'import psutil\n'), ((6650, 6684), 'os.path.exists', 'os.path.exists', (['computed_file_path'], {}), '(computed_file_path)\n', (6664, 6684), False, 'import os\n'), ((27964, 27978), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (27976, 27978), False, 'from django.utils import timezone\n'), ((28673, 28760), 'simplejson.dump', 'json.dump', (["job_context['filtered_samples']", 'metadata_file'], {'indent': '(4)', 'sort_keys': '(True)'}), "(job_context['filtered_samples'], metadata_file, indent=4,\n sort_keys=True)\n", (28682, 28760), True, 'import simplejson as json\n'), ((29078, 29150), 'csv.DictWriter', 'csv.DictWriter', (['tsv_file', 'columns'], {'delimiter': '"""\t"""', 'extrasaction': '"""ignore"""'}), "(tsv_file, columns, delimiter='\\t', extrasaction='ignore')\n", (29092, 29150), False, 'import csv\n'), ((39920, 39992), 'csv.DictWriter', 'csv.DictWriter', (['tsv_file', 'columns'], {'delimiter': '"""\t"""', 'extrasaction': '"""ignore"""'}), "(tsv_file, columns, delimiter='\\t', extrasaction='ignore')\n", (39934, 39992), False, 'import csv\n'), ((40619, 40658), 'os.makedirs', 'os.makedirs', (['species_dir'], {'exist_ok': '(True)'}), '(species_dir, exist_ok=True)\n', (40630, 40658), False, 'import os\n'), ((42659, 42731), 'csv.DictWriter', 'csv.DictWriter', (['tsv_file', 'columns'], {'delimiter': '"""\t"""', 'extrasaction': '"""ignore"""'}), "(tsv_file, columns, delimiter='\\t', extrasaction='ignore')\n", (42673, 42731), False, 'import csv\n'), ((41038, 41110), 'csv.DictWriter', 'csv.DictWriter', (['tsv_file', 'columns'], {'delimiter': '"""\t"""', 'extrasaction': '"""ignore"""'}), "(tsv_file, columns, delimiter='\\t', extrasaction='ignore')\n", (41052, 41110), False, 'import csv\n'), ((1729, 1740), 'time.time', 'time.time', ([], {}), '()\n', (1738, 1740), False, 'import time\n'), ((42314, 42378), 'simplejson.dump', 'json.dump', (['species_metadata', 'json_file'], {'indent': '(4)', 'sort_keys': '(True)'}), '(species_metadata, json_file, indent=4, sort_keys=True)\n', (42323, 42378), True, 'import simplejson as json\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function # from smac.env.multiagentenv import MultiAgentEnv # from smac.env.starcraft2.maps import get_map_params from ..multiagentenv import MultiAgentEnv from ..starcraft2.maps import get_map_params import atexit from operator import attrgetter from copy import deepcopy import numpy as np import enum import math, time from absl import logging from pysc2 import maps from pysc2 import run_configs from pysc2.lib import protocol from s2clientprotocol import common_pb2 as sc_common from s2clientprotocol import sc2api_pb2 as sc_pb from s2clientprotocol import raw_pb2 as r_pb from s2clientprotocol import debug_pb2 as d_pb races = { "R": sc_common.Random, "P": sc_common.Protoss, "T": sc_common.Terran, "Z": sc_common.Zerg, } difficulties = { "1": sc_pb.VeryEasy, "2": sc_pb.Easy, "3": sc_pb.Medium, "4": sc_pb.MediumHard, "5": sc_pb.Hard, "6": sc_pb.Harder, "7": sc_pb.VeryHard, "8": sc_pb.CheatVision, "9": sc_pb.CheatMoney, "A": sc_pb.CheatInsane, } actions = { "move": 16, # target: PointOrUnit "attack": 23, # target: PointOrUnit "stop": 4, # target: None "heal": 386, # Unit } class Direction(enum.IntEnum): NORTH = 0 SOUTH = 1 EAST = 2 WEST = 3 class StarCraftWrappedEnv(MultiAgentEnv): """The StarCraft II environment for decentralised multi-agent micromanagement scenarios. """ def __init__( self, map_name="8m", step_mul=8, move_amount=2, difficulty="7", game_version=None, seed=None, continuing_episode=False, obs_all_health=True, obs_own_health=True, obs_last_action=False, obs_pathing_grid=False, obs_terrain_height=False, obs_instead_of_state=False, obs_timestep_number=False, state_last_action=True, state_timestep_number=False, reward_sparse=False, reward_only_positive=True, reward_death_value=10, reward_win=200, reward_defeat=0, reward_negative_scale=0.5, reward_scale=True, reward_scale_rate=20, replay_dir="", replay_prefix="", window_size_x=1920, window_size_y=1200, heuristic_ai=False, debug=False, is_replay=False ): """ Create a StarCraftC2Env environment. Parameters ---------- map_name : str, optional The name of the SC2 map to play (default is "8m"). The full list can be found by running bin/map_list. step_mul : int, optional How many game steps per agent step (default is 8). None indicates to use the default map step_mul. move_amount : float, optional How far away units are ordered to move per step (default is 2). difficulty : str, optional The difficulty of built-in computer AI bot (default is "7"). game_version : str, optional StarCraft II game version (default is None). None indicates the latest version. seed : int, optional Random seed used during game initialisation. This allows to continuing_episode : bool, optional Whether to consider episodes continuing or finished after time limit is reached (default is False). obs_all_health : bool, optional Agents receive the health of all units (in the sight range) as part of observations (default is True). obs_own_health : bool, optional Agents receive their own health as a part of observations (default is False). This flag is ignored when obs_all_health == True. obs_last_action : bool, optional Agents receive the last actions of all units (in the sight range) as part of observations (default is False). obs_pathing_grid : bool, optional Whether observations include pathing values surrounding the agent (default is False). obs_terrain_height : bool, optional Whether observations include terrain height values surrounding the agent (default is False). obs_instead_of_state : bool, optional Use combination of all agents' observations as the global state (default is False). obs_timestep_number : bool, optional Whether observations include the current timestep of the episode (default is False). state_last_action : bool, optional Include the last actions of all agents as part of the global state (default is True). state_timestep_number : bool, optional Whether the state include the current timestep of the episode (default is False). reward_sparse : bool, optional Receive 1/-1 reward for winning/loosing an episode (default is False). Whe rest of reward parameters are ignored if True. reward_only_positive : bool, optional Reward is always positive (default is True). reward_death_value : float, optional The amount of reward received for killing an enemy unit (default is 10). This is also the negative penalty for having an allied unit killed if reward_only_positive == False. reward_win : float, optional The reward for winning in an episode (default is 200). reward_defeat : float, optional The reward for loosing in an episode (default is 0). This value should be nonpositive. reward_negative_scale : float, optional Scaling factor for negative rewards (default is 0.5). This parameter is ignored when reward_only_positive == True. reward_scale : bool, optional Whether or not to scale the reward (default is True). reward_scale_rate : float, optional Reward scale rate (default is 20). When reward_scale == True, the reward received by the agents is divided by (max_reward / reward_scale_rate), where max_reward is the maximum possible reward per episode without considering the shield regeneration of Protoss units. replay_dir : str, optional The directory to save replays (default is None). If None, the replay will be saved in Replays directory where StarCraft II is installed. replay_prefix : str, optional The prefix of the replay to be saved (default is None). If None, the name of the map will be used. window_size_x : int, optional The length of StarCraft II window size (default is 1920). window_size_y: int, optional The height of StarCraft II window size (default is 1200). heuristic_ai: bool, optional Whether or not to use a non-learning heuristic AI (default False). debug: bool, optional Log messages about observations, state, actions and rewards for debugging purposes (default is False). """ # Map arguments print("inside the new env..") time.sleep(100) self.map_name = map_name map_params = get_map_params(self.map_name) self.n_agents = map_params["n_agents"] self.n_enemies = map_params["n_enemies"] self.episode_limit = map_params["limit"] self._move_amount = move_amount self._step_mul = step_mul self.difficulty = difficulty # Observations and state self.obs_own_health = obs_own_health self.obs_all_health = obs_all_health self.obs_instead_of_state = obs_instead_of_state self.obs_last_action = obs_last_action self.obs_pathing_grid = obs_pathing_grid self.obs_terrain_height = obs_terrain_height self.obs_timestep_number = obs_timestep_number self.state_last_action = state_last_action self.state_timestep_number = state_timestep_number if self.obs_all_health: self.obs_own_health = True self.n_obs_pathing = 8 self.n_obs_height = 9 # Rewards args self.reward_sparse = reward_sparse self.reward_only_positive = reward_only_positive self.reward_negative_scale = reward_negative_scale self.reward_death_value = reward_death_value self.reward_win = reward_win self.reward_defeat = reward_defeat self.reward_scale = reward_scale self.reward_scale_rate = reward_scale_rate # Other self.game_version = game_version self.continuing_episode = continuing_episode self._seed = seed self.heuristic_ai = heuristic_ai self.debug = debug self.is_replay = is_replay self.window_size = (window_size_x, window_size_y) self.replay_dir = replay_dir self.replay_prefix = replay_prefix # Actions self.n_actions_no_attack = 6 self.n_actions_move = 4 self.n_actions = self.n_actions_no_attack + self.n_enemies # Map info self._agent_race = map_params["a_race"] self._bot_race = map_params["b_race"] self.shield_bits_ally = 1 if self._agent_race == "P" else 0 self.shield_bits_enemy = 1 if self._bot_race == "P" else 0 self.unit_type_bits = map_params["unit_type_bits"] self.map_type = map_params["map_type"] self.max_reward = ( self.n_enemies * self.reward_death_value + self.reward_win ) self.agents = {} self.enemies = {} self._episode_count = 0 self._episode_steps = 0 self._total_steps = 0 self._obs = None self.battles_won = 0 self.battles_game = 0 self.timeouts = 0 self.force_restarts = 0 self.last_stats = None self.death_tracker_ally = np.zeros(self.n_agents) self.death_tracker_enemy = np.zeros(self.n_enemies) self.previous_ally_units = None self.previous_enemy_units = None self.last_action = np.zeros((self.n_agents, self.n_actions)) self._min_unit_type = 0 self.marine_id = self.marauder_id = self.medivac_id = 0 self.hydralisk_id = self.zergling_id = self.baneling_id = 0 self.stalker_id = self.colossus_id = self.zealot_id = self.sentry_id = 0 self.void_ray_id = 0 self.max_distance_x = 0 self.max_distance_y = 0 self.map_x = 0 self.map_y = 0 self.terrain_height = None self.pathing_grid = None self._run_config = None self._sc2_proc = None self._controller = None # Try to avoid leaking SC2 processes on shutdown atexit.register(lambda: self.close()) def _launch(self): """Launch the StarCraft II game.""" # self._run_config = run_configs.get(version=self.game_version) self._run_config = run_configs.get() _map = maps.get(self.map_name) # Setting up the interface interface_options = sc_pb.InterfaceOptions(raw=True, score=False) self._sc2_proc = self._run_config.start(window_size=self.window_size) self._controller = self._sc2_proc.controller # Request to create the game create = sc_pb.RequestCreateGame( local_map=sc_pb.LocalMap( map_path=_map.path, map_data=self._run_config.map_data(_map.path)), realtime=False, random_seed=self._seed) create.player_setup.add(type=sc_pb.Participant) create.player_setup.add(type=sc_pb.Computer, race=races[self._bot_race], difficulty=difficulties[self.difficulty]) self._controller.create_game(create) join = sc_pb.RequestJoinGame(race=races[self._agent_race], options=interface_options) self._controller.join_game(join) game_info = self._controller.game_info() map_info = game_info.start_raw map_play_area_min = map_info.playable_area.p0 map_play_area_max = map_info.playable_area.p1 self.max_distance_x = map_play_area_max.x - map_play_area_min.x self.max_distance_y = map_play_area_max.y - map_play_area_min.y self.map_x = map_info.map_size.x self.map_y = map_info.map_size.y if map_info.pathing_grid.bits_per_pixel == 1: vals = np.array(list(map_info.pathing_grid.data)).reshape( self.map_x, int(self.map_y / 8)) self.pathing_grid = np.transpose(np.array([ [(b >> i) & 1 for b in row for i in range(7, -1, -1)] for row in vals], dtype=np.bool)) else: self.pathing_grid = np.invert(np.flip(np.transpose(np.array( list(map_info.pathing_grid.data), dtype=np.bool).reshape( self.map_x, self.map_y)), axis=1)) self.terrain_height = np.flip( np.transpose(np.array(list(map_info.terrain_height.data)) .reshape(self.map_x, self.map_y)), 1) / 255 def reset(self): """Reset the environment. Required after each full episode. Returns initial observations and states. """ self._episode_steps = 0 if self._episode_count == 0: # Launch StarCraft II self._launch() else: self._restart() # Information kept for counting the reward self.death_tracker_ally = np.zeros(self.n_agents) self.death_tracker_enemy = np.zeros(self.n_enemies) self.previous_ally_units = None self.previous_enemy_units = None self.win_counted = False self.defeat_counted = False self.last_action = np.zeros((self.n_agents, self.n_actions)) if self.heuristic_ai: self.heuristic_targets = [None] * self.n_agents try: self._obs = self._controller.observe() self.init_units() except (protocol.ProtocolError, protocol.ConnectionError): self.full_restart() if self.debug: logging.debug("Started Episode {}" .format(self._episode_count).center(60, "*")) return self.get_obs(), self.get_state() def _restart(self): """Restart the environment by killing all units on the map. There is a trigger in the SC2Map file, which restarts the episode when there are no units left. """ try: self._kill_all_units() self._controller.step(2) except (protocol.ProtocolError, protocol.ConnectionError): self.full_restart() def full_restart(self): """Full restart. Closes the SC2 process and launches a new one. """ self._sc2_proc.close() self._launch() self.force_restarts += 1 def step(self, actions): """A single environment step. Returns reward, terminated, info.""" if self.is_replay: positions = [] for agent_id in range(self.n_agents): unit = self.get_unit_by_id(agent_id) positions.append([agent_id, unit.pos.x, unit.pos.y, unit.health]) for e_id, e_unit in self.enemies.items(): positions.append([e_id, e_unit.pos.x, e_unit.pos.y, e_unit.health]) # positions.insert(0,self._episode_steps) print(positions, ",") actions = [int(a) for a in actions] self.last_action = np.eye(self.n_actions)[np.array(actions)] # Collect individual actions sc_actions = [] if self.debug: logging.debug("Actions".center(60, "-")) for a_id, action in enumerate(actions): if not self.heuristic_ai: agent_action = self.get_agent_action(a_id, action) else: agent_action = self.get_agent_action_heuristic(a_id, action) if agent_action: sc_actions.append(agent_action) # Send action request req_actions = sc_pb.RequestAction(actions=sc_actions) try: self._controller.actions(req_actions) # Make step in SC2, i.e. apply actions self._controller.step(self._step_mul) # Observe here so that we know if the episode is over. self._obs = self._controller.observe() except (protocol.ProtocolError, protocol.ConnectionError): self.full_restart() return 0, True, {} self._total_steps += 1 self._episode_steps += 1 # Update units game_end_code = self.update_units() terminated = False reward = self.reward_battle() info = {"battle_won": False} if game_end_code is not None: # Battle is over terminated = True self.battles_game += 1 if game_end_code == 1 and not self.win_counted: self.battles_won += 1 self.win_counted = True info["battle_won"] = True if not self.reward_sparse: reward += self.reward_win else: reward = 1 elif game_end_code == -1 and not self.defeat_counted: self.defeat_counted = True if not self.reward_sparse: reward += self.reward_defeat else: reward = -1 elif self._episode_steps >= self.episode_limit: # Episode limit reached terminated = True if self.continuing_episode: info["episode_limit"] = True self.battles_game += 1 self.timeouts += 1 if self.debug: logging.debug("Reward = {}".format(reward).center(60, '-')) if terminated: self._episode_count += 1 if self.is_replay: positions = [] for agent_id in range(self.n_agents): unit = self.get_unit_by_id(agent_id) positions.append([agent_id, unit.pos.x, unit.pos.y, unit.health]) for e_id, e_unit in self.enemies.items(): positions.append([e_id, e_unit.pos.x, e_unit.pos.y, e_unit.health]) # positions.insert(0,self._episode_steps) print(positions, ",") if self.reward_scale: reward /= self.max_reward / self.reward_scale_rate print("type of reward returned from within starcraft is: ", type(reward)) return 2 * reward, terminated, info def get_agent_action(self, a_id, action): """Construct the action for agent a_id.""" avail_actions = self.get_avail_agent_actions(a_id) assert avail_actions[action] == 1, \ "Agent {} cannot perform action {}".format(a_id, action) unit = self.get_unit_by_id(a_id) tag = unit.tag x = unit.pos.x y = unit.pos.y if action == 0: # no-op (valid only when dead) assert unit.health == 0, "No-op only available for dead agents." if self.debug: logging.debug("Agent {}: Dead".format(a_id)) return None elif action == 1: # stop cmd = r_pb.ActionRawUnitCommand( ability_id=actions["stop"], unit_tags=[tag], queue_command=False) if self.debug: logging.debug("Agent {}: Stop".format(a_id)) elif action == 2: # move north cmd = r_pb.ActionRawUnitCommand( ability_id=actions["move"], target_world_space_pos=sc_common.Point2D( x=x, y=y + self._move_amount), unit_tags=[tag], queue_command=False) if self.debug: logging.debug("Agent {}: Move North".format(a_id)) elif action == 3: # move south cmd = r_pb.ActionRawUnitCommand( ability_id=actions["move"], target_world_space_pos=sc_common.Point2D( x=x, y=y - self._move_amount), unit_tags=[tag], queue_command=False) if self.debug: logging.debug("Agent {}: Move South".format(a_id)) elif action == 4: # move east cmd = r_pb.ActionRawUnitCommand( ability_id=actions["move"], target_world_space_pos=sc_common.Point2D( x=x + self._move_amount, y=y), unit_tags=[tag], queue_command=False) if self.debug: logging.debug("Agent {}: Move East".format(a_id)) elif action == 5: # move west cmd = r_pb.ActionRawUnitCommand( ability_id=actions["move"], target_world_space_pos=sc_common.Point2D( x=x - self._move_amount, y=y), unit_tags=[tag], queue_command=False) if self.debug: logging.debug("Agent {}: Move West".format(a_id)) else: # attack/heal units that are in range target_id = action - self.n_actions_no_attack if self.map_type in ["MMM", "GMMM"] and unit.unit_type == self.medivac_id: target_unit = self.agents[target_id] action_name = "heal" else: target_unit = self.enemies[target_id] action_name = "attack" action_id = actions[action_name] target_tag = target_unit.tag cmd = r_pb.ActionRawUnitCommand( ability_id=action_id, target_unit_tag=target_tag, unit_tags=[tag], queue_command=False) if self.debug: logging.debug("Agent {} {}s unit # {}".format( a_id, action_name, target_id)) sc_action = sc_pb.Action(action_raw=r_pb.ActionRaw(unit_command=cmd)) return sc_action def get_agent_action_heuristic(self, a_id, action): unit = self.get_unit_by_id(a_id) tag = unit.tag target = self.heuristic_targets[a_id] if unit.unit_type == self.medivac_id: if (target is None or self.agents[target].health == 0 or self.agents[target].health == self.agents[target].health_max): min_dist = math.hypot(self.max_distance_x, self.max_distance_y) min_id = -1 for al_id, al_unit in self.agents.items(): if al_unit.unit_type == self.medivac_id: continue if (al_unit.health != 0 and al_unit.health != al_unit.health_max): dist = self.distance(unit.pos.x, unit.pos.y, al_unit.pos.x, al_unit.pos.y) if dist < min_dist: min_dist = dist min_id = al_id self.heuristic_targets[a_id] = min_id if min_id == -1: self.heuristic_targets[a_id] = None return None action_id = actions['heal'] target_tag = self.agents[self.heuristic_targets[a_id]].tag else: if target is None or self.enemies[target].health == 0: min_dist = math.hypot(self.max_distance_x, self.max_distance_y) min_id = -1 for e_id, e_unit in self.enemies.items(): if (unit.unit_type == self.marauder_id and e_unit.unit_type == self.medivac_id): continue if e_unit.health > 0: dist = self.distance(unit.pos.x, unit.pos.y, e_unit.pos.x, e_unit.pos.y) if dist < min_dist: min_dist = dist min_id = e_id self.heuristic_targets[a_id] = min_id action_id = actions['attack'] target_tag = self.enemies[self.heuristic_targets[a_id]].tag cmd = r_pb.ActionRawUnitCommand( ability_id=action_id, target_unit_tag=target_tag, unit_tags=[tag], queue_command=False) sc_action = sc_pb.Action(action_raw=r_pb.ActionRaw(unit_command=cmd)) return sc_action def reward_battle(self): """Reward function when self.reward_spare==False. Returns accumulative hit/shield point damage dealt to the enemy + reward_death_value per enemy unit killed, and, in case self.reward_only_positive == False, - (damage dealt to ally units + reward_death_value per ally unit killed) * self.reward_negative_scale """ if self.reward_sparse: return 0 reward = 0 delta_deaths = 0 delta_ally = 0 delta_enemy = 0 neg_scale = self.reward_negative_scale # update deaths for al_id, al_unit in self.agents.items(): if not self.death_tracker_ally[al_id]: # did not die so far prev_health = ( self.previous_ally_units[al_id].health + self.previous_ally_units[al_id].shield ) if al_unit.health == 0: # just died self.death_tracker_ally[al_id] = 1 if not self.reward_only_positive: delta_deaths -= self.reward_death_value * neg_scale delta_ally += prev_health * neg_scale else: # still alive delta_ally += neg_scale * ( prev_health - al_unit.health - al_unit.shield ) for e_id, e_unit in self.enemies.items(): if not self.death_tracker_enemy[e_id]: prev_health = ( self.previous_enemy_units[e_id].health + self.previous_enemy_units[e_id].shield ) if e_unit.health == 0: self.death_tracker_enemy[e_id] = 1 delta_deaths += self.reward_death_value delta_enemy += prev_health else: delta_enemy += prev_health - e_unit.health - e_unit.shield if self.reward_only_positive: reward = abs(delta_enemy + delta_deaths) # shield regeneration else: reward = delta_enemy + delta_deaths - delta_ally return reward def get_total_actions(self): """Returns the total number of actions an agent could ever take.""" return self.n_actions @staticmethod def distance(x1, y1, x2, y2): """Distance between two points.""" return math.hypot(x2 - x1, y2 - y1) def unit_shoot_range(self, agent_id): """Returns the shooting range for an agent.""" return 6 def unit_sight_range(self, agent_id): """Returns the sight range for an agent.""" return 9 def unit_max_cooldown(self, unit): """Returns the maximal cooldown for a unit.""" switcher = { self.marine_id: 15, self.marauder_id: 25, self.medivac_id: 200, # max energy self.stalker_id: 35, self.void_ray_id: 35, self.sentry_id: 22, self.zealot_id: 22, self.colossus_id: 24, self.hydralisk_id: 10, self.zergling_id: 11, self.baneling_id: 1 } return switcher.get(unit.unit_type, 15) def save_replay(self): """Save a replay.""" prefix = self.replay_prefix or self.map_name replay_dir = self.replay_dir or "" replay_path = self._run_config.save_replay( self._controller.save_replay(), replay_dir=replay_dir, prefix=prefix) logging.info("Replay saved at: %s" % replay_path) def unit_max_shield(self, unit): """Returns maximal shield for a given unit.""" if unit.unit_type == 74 or unit.unit_type == self.stalker_id: return 80 # Protoss's Stalker if unit.unit_type == 73 or unit.unit_type == self.zealot_id: return 50 # Protoss's Zealot if unit.unit_type == 4 or unit.unit_type == self.colossus_id: return 150 # Protoss's Colossus if unit.unit_type == 77 or unit.unit_type == self.sentry_id: return 40 # Protoss's Sentry if unit.unit_type == self.void_ray_id: return 100 # Protoss's Void Ray def can_move(self, unit, direction): """Whether a unit can move in a given direction.""" m = self._move_amount / 2 if direction == Direction.NORTH: x, y = int(unit.pos.x), int(unit.pos.y + m) elif direction == Direction.SOUTH: x, y = int(unit.pos.x), int(unit.pos.y - m) elif direction == Direction.EAST: x, y = int(unit.pos.x + m), int(unit.pos.y) else: x, y = int(unit.pos.x - m), int(unit.pos.y) if self.check_bounds(x, y) and self.pathing_grid[x, y]: return True return False def get_surrounding_points(self, unit, include_self=False): """Returns the surrounding points of the unit in 8 directions.""" x = int(unit.pos.x) y = int(unit.pos.y) ma = self._move_amount points = [ (x, y + 2 * ma), (x, y - 2 * ma), (x + 2 * ma, y), (x - 2 * ma, y), (x + ma, y + ma), (x - ma, y - ma), (x + ma, y - ma), (x - ma, y + ma), ] if include_self: points.append((x, y)) return points def check_bounds(self, x, y): """Whether a point is within the map bounds.""" return (0 <= x < self.map_x and 0 <= y < self.map_y) def get_surrounding_pathing(self, unit): """Returns pathing values of the grid surrounding the given unit.""" points = self.get_surrounding_points(unit, include_self=False) vals = [ self.pathing_grid[x, y] if self.check_bounds(x, y) else 1 for x, y in points ] return vals def get_surrounding_height(self, unit): """Returns height values of the grid surrounding the given unit.""" points = self.get_surrounding_points(unit, include_self=True) vals = [ self.terrain_height[x, y] if self.check_bounds(x, y) else 1 for x, y in points ] return vals def get_own_feature_size(self): nf_own = self.unit_type_bits if self.obs_own_health: nf_own += 1 + self.shield_bits_ally return nf_own def get_units_type_id(self): self.reset() type_ids = [] for agent_i in range(self.n_agents): agent = self.get_unit_by_id(agent_i) type_ids.append(self.get_unit_type_id(agent, True)) print('>>>', type_ids) return type_ids def get_obs_agent(self, agent_id): """Returns observation for agent_id. NOTE: Agents should have access only to their local observations during decentralised execution. """ unit = self.get_unit_by_id(agent_id) nf_al = 4 + self.unit_type_bits nf_en = 4 + self.unit_type_bits if self.obs_all_health: nf_al += 1 + self.shield_bits_ally nf_en += 1 + self.shield_bits_enemy if self.obs_last_action: nf_al += self.n_actions nf_own = self.unit_type_bits if self.obs_own_health: nf_own += 1 + self.shield_bits_ally move_feats_len = self.n_actions_move if self.obs_pathing_grid: move_feats_len += self.n_obs_pathing if self.obs_terrain_height: move_feats_len += self.n_obs_height move_feats = np.zeros(move_feats_len, dtype=np.float32) enemy_feats = np.zeros((self.n_enemies, nf_en), dtype=np.float32) ally_feats = np.zeros((self.n_agents - 1, nf_al), dtype=np.float32) own_feats = np.zeros(nf_own, dtype=np.float32) if unit.health > 0: # otherwise dead, return all zeros x = unit.pos.x y = unit.pos.y sight_range = self.unit_sight_range(agent_id) # Movement features avail_actions = self.get_avail_agent_actions(agent_id) for m in range(self.n_actions_move): move_feats[m] = avail_actions[m + 2] ind = self.n_actions_move if self.obs_pathing_grid: move_feats[ ind: ind + self.n_obs_pathing ] = self.get_surrounding_pathing(unit) ind += self.n_obs_pathing if self.obs_terrain_height: move_feats[ind:] = self.get_surrounding_height(unit) # Enemy features for e_id, e_unit in self.enemies.items(): e_x = e_unit.pos.x e_y = e_unit.pos.y dist = self.distance(x, y, e_x, e_y) if ( dist < sight_range and e_unit.health > 0 ): # visible and alive # Sight range > shoot range enemy_feats[e_id, 0] = avail_actions[ self.n_actions_no_attack + e_id ] # available enemy_feats[e_id, 1] = dist / sight_range # distance enemy_feats[e_id, 2] = ( e_x - x ) / sight_range # relative X enemy_feats[e_id, 3] = ( e_y - y ) / sight_range # relative Y ind = 4 if self.obs_all_health: enemy_feats[e_id, ind] = ( e_unit.health / e_unit.health_max ) # health ind += 1 if self.shield_bits_enemy > 0: max_shield = self.unit_max_shield(e_unit) enemy_feats[e_id, ind] = ( e_unit.shield / max_shield ) # shield ind += 1 if self.unit_type_bits > 0: type_id = self.get_unit_type_id(e_unit, False) enemy_feats[e_id, ind + type_id] = 1 # unit type # Ally features al_ids = [ al_id for al_id in range(self.n_agents) if al_id != agent_id ] for i, al_id in enumerate(al_ids): al_unit = self.get_unit_by_id(al_id) al_x = al_unit.pos.x al_y = al_unit.pos.y dist = self.distance(x, y, al_x, al_y) if ( dist < sight_range and al_unit.health > 0 ): # visible and alive ally_feats[i, 0] = 1 # visible ally_feats[i, 1] = dist / sight_range # distance ally_feats[i, 2] = (al_x - x) / sight_range # relative X ally_feats[i, 3] = (al_y - y) / sight_range # relative Y ind = 4 if self.obs_all_health: ally_feats[i, ind] = ( al_unit.health / al_unit.health_max ) # health ind += 1 if self.shield_bits_ally > 0: max_shield = self.unit_max_shield(al_unit) ally_feats[i, ind] = ( al_unit.shield / max_shield ) # shield ind += 1 if self.unit_type_bits > 0: type_id = self.get_unit_type_id(al_unit, True) ally_feats[i, ind + type_id] = 1 ind += self.unit_type_bits if self.obs_last_action: ally_feats[i, ind:] = self.last_action[al_id] # Own features ind = 0 if self.obs_own_health: own_feats[ind] = unit.health / unit.health_max ind += 1 if self.shield_bits_ally > 0: max_shield = self.unit_max_shield(unit) own_feats[ind] = unit.shield / max_shield ind += 1 if self.unit_type_bits > 0: type_id = self.get_unit_type_id(unit, True) own_feats[ind + type_id] = 1 agent_obs = np.concatenate( ( move_feats.flatten(), enemy_feats.flatten(), ally_feats.flatten(), own_feats.flatten(), ) ) if self.obs_timestep_number: agent_obs = np.append(agent_obs, self._episode_steps / self.episode_limit) if self.debug: logging.debug("Obs Agent: {}".format(agent_id).center(60, "-")) logging.debug("Avail. actions {}".format( self.get_avail_agent_actions(agent_id))) logging.debug("Move feats {}".format(move_feats)) logging.debug("Enemy feats {}".format(enemy_feats)) logging.debug("Ally feats {}".format(ally_feats)) logging.debug("Own feats {}".format(own_feats)) return agent_obs def get_obs(self): """Returns all agent observations in a list. NOTE: Agents should have access only to their local observations during decentralised execution. """ agents_obs = [self.get_obs_agent(i) for i in range(self.n_agents)] return agents_obs def get_state(self): """Returns the global state. NOTE: This functon should not be used during decentralised execution. """ if self.obs_instead_of_state: obs_concat = np.concatenate(self.get_obs(), axis=0).astype( np.float32 ) return obs_concat nf_al = 4 + self.shield_bits_ally + self.unit_type_bits nf_en = 3 + self.shield_bits_enemy + self.unit_type_bits ally_state = np.zeros((self.n_agents, nf_al)) enemy_state = np.zeros((self.n_enemies, nf_en)) center_x = self.map_x / 2 center_y = self.map_y / 2 for al_id, al_unit in self.agents.items(): if al_unit.health > 0: x = al_unit.pos.x y = al_unit.pos.y max_cd = self.unit_max_cooldown(al_unit) ally_state[al_id, 0] = ( al_unit.health / al_unit.health_max ) # health if ( self.map_type in ["MMM", "GMMM"] and al_unit.unit_type == self.medivac_id ): ally_state[al_id, 1] = al_unit.energy / max_cd # energy else: ally_state[al_id, 1] = ( al_unit.weapon_cooldown / max_cd ) # cooldown ally_state[al_id, 2] = ( x - center_x ) / self.max_distance_x # relative X ally_state[al_id, 3] = ( y - center_y ) / self.max_distance_y # relative Y ind = 4 if self.shield_bits_ally > 0: max_shield = self.unit_max_shield(al_unit) ally_state[al_id, ind] = ( al_unit.shield / max_shield ) # shield ind += 1 if self.unit_type_bits > 0: type_id = self.get_unit_type_id(al_unit, True) ally_state[al_id, ind + type_id] = 1 for e_id, e_unit in self.enemies.items(): if e_unit.health > 0: x = e_unit.pos.x y = e_unit.pos.y enemy_state[e_id, 0] = ( e_unit.health / e_unit.health_max ) # health enemy_state[e_id, 1] = ( x - center_x ) / self.max_distance_x # relative X enemy_state[e_id, 2] = ( y - center_y ) / self.max_distance_y # relative Y ind = 3 if self.shield_bits_enemy > 0: max_shield = self.unit_max_shield(e_unit) enemy_state[e_id, ind] = ( e_unit.shield / max_shield ) # shield ind += 1 if self.unit_type_bits > 0: type_id = self.get_unit_type_id(e_unit, False) enemy_state[e_id, ind + type_id] = 1 state = np.append(ally_state.flatten(), enemy_state.flatten()) if self.state_last_action: state = np.append(state, self.last_action.flatten()) if self.state_timestep_number: state = np.append(state, self._episode_steps / self.episode_limit) state = state.astype(dtype=np.float32) if self.debug: logging.debug("STATE".center(60, "-")) logging.debug("Ally state {}".format(ally_state)) logging.debug("Enemy state {}".format(enemy_state)) if self.state_last_action: logging.debug("Last actions {}".format(self.last_action)) return state def get_obs_size(self): """Returns the size of the observation.""" nf_al = 4 + self.unit_type_bits nf_en = 4 + self.unit_type_bits if self.obs_all_health: nf_al += 1 + self.shield_bits_ally nf_en += 1 + self.shield_bits_enemy own_feats = self.unit_type_bits if self.obs_own_health: own_feats += 1 + self.shield_bits_ally if self.obs_timestep_number: own_feats += 1 if self.obs_last_action: nf_al += self.n_actions move_feats = self.n_actions_move if self.obs_pathing_grid: move_feats += self.n_obs_pathing if self.obs_terrain_height: move_feats += self.n_obs_height enemy_feats = self.n_enemies * nf_en ally_feats = (self.n_agents - 1) * nf_al return move_feats + enemy_feats + ally_feats + own_feats def get_state_size(self): """Returns the size of the global state.""" if self.obs_instead_of_state: return self.get_obs_size() * self.n_agents nf_al = 4 + self.shield_bits_ally + self.unit_type_bits nf_en = 3 + self.shield_bits_enemy + self.unit_type_bits enemy_state = self.n_enemies * nf_en ally_state = self.n_agents * nf_al size = enemy_state + ally_state if self.state_last_action: size += self.n_agents * self.n_actions if self.state_timestep_number: size += 1 return size def get_unit_type_id(self, unit, ally): """Returns the ID of unit type in the given scenario.""" if ally: # use new SC2 unit types type_id = unit.unit_type - self._min_unit_type else: # use default SC2 unit types if self.map_type == "stalkers_and_zealots": # id(Stalker) = 74, id(Zealot) = 73 type_id = unit.unit_type - 73 if self.map_type == "bane_vs_sz": # id(Stalker) = 74, id(Zealot) = 73 type_id = unit.unit_type - 73 if self.map_type == "stalkers_and_zealots_vs_zb": # id(Stalker) = 74, id() = if unit.unit_type == 9: type_id = 0 else: type_id = 1 elif self.map_type == "colossi_stalkers_zealots": # id(Stalker) = 74, id(Zealot) = 73, id(Colossus) = 4 if unit.unit_type == 4: type_id = 0 elif unit.unit_type == 74: type_id = 1 else: type_id = 2 elif self.map_type == "stalkers_and_sentries": # id(Stalker) = 74, id(Sentry) = 77 if unit.unit_type == 77: type_id = 1 elif unit.unit_type == 74: type_id = 0 elif self.map_type == "zv_mb": # id(Battlecrusier) = 57, id(Marine) = 48 if unit.unit_type == 57: type_id = 1 elif unit.unit_type == 48: type_id = 0 elif self.map_type == "bane": if unit.unit_type == 9: type_id = 0 else: type_id = 1 elif self.map_type == "MMM": if unit.unit_type == 51: type_id = 0 elif unit.unit_type == 48: type_id = 1 else: type_id = 2 elif self.map_type == "GMMM": if unit.unit_type == 51: type_id = 0 elif unit.unit_type == 48: type_id = 1 elif unit.unit_type == 54: type_id = 2 else: type_id = 3 return type_id def get_avail_agent_actions(self, agent_id): """Returns the available actions for agent_id.""" unit = self.get_unit_by_id(agent_id) if unit.health > 0: # cannot choose no-op when alive avail_actions = [0] * self.n_actions # stop should be allowed avail_actions[1] = 1 # see if we can move if self.can_move(unit, Direction.NORTH): avail_actions[2] = 1 if self.can_move(unit, Direction.SOUTH): avail_actions[3] = 1 if self.can_move(unit, Direction.EAST): avail_actions[4] = 1 if self.can_move(unit, Direction.WEST): avail_actions[5] = 1 # Can attack only alive units that are alive in the shooting range shoot_range = self.unit_shoot_range(agent_id) target_items = self.enemies.items() if self.map_type in ["MMM", "GMMM"] and unit.unit_type == self.medivac_id: # Medivacs cannot heal themselves or other flying units target_items = [ (t_id, t_unit) for (t_id, t_unit) in self.agents.items() if t_unit.unit_type != self.medivac_id ] for t_id, t_unit in target_items: if t_unit.health > 0: dist = self.distance( unit.pos.x, unit.pos.y, t_unit.pos.x, t_unit.pos.y ) if dist <= shoot_range: avail_actions[t_id + self.n_actions_no_attack] = 1 return avail_actions else: # only no-op allowed return [1] + [0] * (self.n_actions - 1) def get_avail_actions(self): """Returns the available actions of all agents in a list.""" avail_actions = [] for agent_id in range(self.n_agents): avail_agent = self.get_avail_agent_actions(agent_id) avail_actions.append(avail_agent) return avail_actions def close(self): """Close StarCraft II.""" if self._sc2_proc: self._sc2_proc.close() def seed(self): """Returns the random seed used by the environment.""" return self._seed def render(self): """Not implemented.""" pass def _kill_all_units(self): """Kill all units on the map.""" units_alive = [ unit.tag for unit in self.agents.values() if unit.health > 0 ] + [unit.tag for unit in self.enemies.values() if unit.health > 0] debug_command = [ d_pb.DebugCommand(kill_unit=d_pb.DebugKillUnit(tag=units_alive)) ] self._controller.debug(debug_command) def init_units(self): """Initialise the units.""" while True: # Sometimes not all units have yet been created by SC2 self.agents = {} self.enemies = {} ally_units = [ unit for unit in self._obs.observation.raw_data.units if unit.owner == 1 ] ally_units_sorted = sorted( ally_units, key=attrgetter("unit_type", "pos.x", "pos.y"), reverse=False, ) for i in range(len(ally_units_sorted)): self.agents[i] = ally_units_sorted[i] if self.debug: logging.debug( "Unit {} is {}, x = {}, y = {}".format( len(self.agents), self.agents[i].unit_type, self.agents[i].pos.x, self.agents[i].pos.y, ) ) for unit in self._obs.observation.raw_data.units: if unit.owner == 2: self.enemies[len(self.enemies)] = unit if self._episode_count == 0: self.max_reward += unit.health_max + unit.shield_max if self._episode_count == 0: min_unit_type = min( unit.unit_type for unit in self.agents.values() ) self._init_ally_unit_types(min_unit_type) all_agents_created = (len(self.agents) == self.n_agents) all_enemies_created = (len(self.enemies) == self.n_enemies) if all_agents_created and all_enemies_created: # all good return try: self._controller.step(1) self._obs = self._controller.observe() except (protocol.ProtocolError, protocol.ConnectionError): self.full_restart() self.reset() def update_units(self): """Update units after an environment step. This function assumes that self._obs is up-to-date. """ n_ally_alive = 0 n_enemy_alive = 0 # Store previous state self.previous_ally_units = deepcopy(self.agents) self.previous_enemy_units = deepcopy(self.enemies) for al_id, al_unit in self.agents.items(): updated = False for unit in self._obs.observation.raw_data.units: if al_unit.tag == unit.tag: self.agents[al_id] = unit updated = True n_ally_alive += 1 break if not updated: # dead al_unit.health = 0 for e_id, e_unit in self.enemies.items(): updated = False for unit in self._obs.observation.raw_data.units: if e_unit.tag == unit.tag: self.enemies[e_id] = unit updated = True n_enemy_alive += 1 break if not updated: # dead e_unit.health = 0 if (n_ally_alive == 0 and n_enemy_alive > 0 or self.only_medivac_left(ally=True)): return -1 # lost if (n_ally_alive > 0 and n_enemy_alive == 0 or self.only_medivac_left(ally=False)): return 1 # won if n_ally_alive == 0 and n_enemy_alive == 0: return 0 return None def _init_ally_unit_types(self, min_unit_type): """Initialise ally unit types. Should be called once from the init_units function. """ self._min_unit_type = min_unit_type if self.map_type == "marines": self.marine_id = min_unit_type elif self.map_type == "stalkers_and_zealots": self.stalker_id = min_unit_type self.zealot_id = min_unit_type + 1 elif self.map_type == "stalkers_and_zealots_vs_zb": self.stalker_id = min_unit_type self.zealot_id = min_unit_type + 1 elif self.map_type == "stalkers_and_sentries": self.stalker_id = min_unit_type + 1 self.sentry_id = min_unit_type elif self.map_type == "colossi_stalkers_zealots": self.colossus_id = min_unit_type self.stalker_id = min_unit_type + 1 self.zealot_id = min_unit_type + 2 elif self.map_type == "zv_mb": self.void_ray_id = min_unit_type self.zealot_id = min_unit_type + 1 elif self.map_type == "MMM": self.marauder_id = min_unit_type self.marine_id = min_unit_type + 1 self.medivac_id = min_unit_type + 2 elif self.map_type == 'GMMM': self.marauder_id = min_unit_type self.marine_id = min_unit_type + 1 self.medivac_id = min_unit_type + 2 self.ghost_id = min_unit_type + 3 elif self.map_type == "zealots": self.zealot_id = min_unit_type elif self.map_type == "hydralisks": self.hydralisk_id = min_unit_type elif self.map_type == "stalkers": self.stalker_id = min_unit_type elif self.map_type == "colossus": self.colossus_id = min_unit_type elif self.map_type == "bane": self.baneling_id = min_unit_type self.zergling_id = min_unit_type + 1 elif self.map_type == "bane_vs_sz": self.baneling_id = min_unit_type self.zergling_id = min_unit_type + 1 def only_medivac_left(self, ally): """Check if only Medivac units are left.""" if self.map_type not in ["MMM", "GMMM"]: return False if ally: units_alive = [ a for a in self.agents.values() if (a.health > 0 and a.unit_type != self.medivac_id) ] if len(units_alive) == 0: return True return False else: units_alive = [ a for a in self.enemies.values() if (a.health > 0 and a.unit_type != self.medivac_id) ] if len(units_alive) == 1 and units_alive[0].unit_type == 54: return True return False def get_unit_by_id(self, a_id): """Get unit by ID.""" return self.agents[a_id] def get_stats(self): stats = { "battles_won": self.battles_won, "battles_game": self.battles_game, "battles_draw": self.timeouts, "win_rate": self.battles_won / self.battles_game, "timeouts": self.timeouts, "restarts": self.force_restarts, } return stats
[ "operator.attrgetter", "numpy.eye", "s2clientprotocol.raw_pb2.ActionRawUnitCommand", "copy.deepcopy", "s2clientprotocol.sc2api_pb2.InterfaceOptions", "s2clientprotocol.sc2api_pb2.RequestJoinGame", "absl.logging.info", "time.sleep", "s2clientprotocol.raw_pb2.ActionRaw", "numpy.append", "numpy.array", "numpy.zeros", "pysc2.maps.get", "s2clientprotocol.debug_pb2.DebugKillUnit", "pysc2.run_configs.get", "s2clientprotocol.sc2api_pb2.RequestAction", "math.hypot", "s2clientprotocol.common_pb2.Point2D" ]
[((7454, 7469), 'time.sleep', 'time.sleep', (['(100)'], {}), '(100)\n', (7464, 7469), False, 'import math, time\n'), ((10200, 10223), 'numpy.zeros', 'np.zeros', (['self.n_agents'], {}), '(self.n_agents)\n', (10208, 10223), True, 'import numpy as np\n'), ((10259, 10283), 'numpy.zeros', 'np.zeros', (['self.n_enemies'], {}), '(self.n_enemies)\n', (10267, 10283), True, 'import numpy as np\n'), ((10392, 10433), 'numpy.zeros', 'np.zeros', (['(self.n_agents, self.n_actions)'], {}), '((self.n_agents, self.n_actions))\n', (10400, 10433), True, 'import numpy as np\n'), ((11251, 11268), 'pysc2.run_configs.get', 'run_configs.get', ([], {}), '()\n', (11266, 11268), False, 'from pysc2 import run_configs\n'), ((11284, 11307), 'pysc2.maps.get', 'maps.get', (['self.map_name'], {}), '(self.map_name)\n', (11292, 11307), False, 'from pysc2 import maps\n'), ((11372, 11417), 's2clientprotocol.sc2api_pb2.InterfaceOptions', 'sc_pb.InterfaceOptions', ([], {'raw': '(True)', 'score': '(False)'}), '(raw=True, score=False)\n', (11394, 11417), True, 'from s2clientprotocol import sc2api_pb2 as sc_pb\n'), ((12103, 12181), 's2clientprotocol.sc2api_pb2.RequestJoinGame', 'sc_pb.RequestJoinGame', ([], {'race': 'races[self._agent_race]', 'options': 'interface_options'}), '(race=races[self._agent_race], options=interface_options)\n', (12124, 12181), True, 'from s2clientprotocol import sc2api_pb2 as sc_pb\n'), ((13834, 13857), 'numpy.zeros', 'np.zeros', (['self.n_agents'], {}), '(self.n_agents)\n', (13842, 13857), True, 'import numpy as np\n'), ((13893, 13917), 'numpy.zeros', 'np.zeros', (['self.n_enemies'], {}), '(self.n_enemies)\n', (13901, 13917), True, 'import numpy as np\n'), ((14096, 14137), 'numpy.zeros', 'np.zeros', (['(self.n_agents, self.n_actions)'], {}), '((self.n_agents, self.n_actions))\n', (14104, 14137), True, 'import numpy as np\n'), ((16410, 16449), 's2clientprotocol.sc2api_pb2.RequestAction', 'sc_pb.RequestAction', ([], {'actions': 'sc_actions'}), '(actions=sc_actions)\n', (16429, 16449), True, 'from s2clientprotocol import sc2api_pb2 as sc_pb\n'), ((24693, 24810), 's2clientprotocol.raw_pb2.ActionRawUnitCommand', 'r_pb.ActionRawUnitCommand', ([], {'ability_id': 'action_id', 'target_unit_tag': 'target_tag', 'unit_tags': '[tag]', 'queue_command': '(False)'}), '(ability_id=action_id, target_unit_tag=target_tag,\n unit_tags=[tag], queue_command=False)\n', (24718, 24810), True, 'from s2clientprotocol import raw_pb2 as r_pb\n'), ((27446, 27474), 'math.hypot', 'math.hypot', (['(x2 - x1)', '(y2 - y1)'], {}), '(x2 - x1, y2 - y1)\n', (27456, 27474), False, 'import math, time\n'), ((28551, 28600), 'absl.logging.info', 'logging.info', (["('Replay saved at: %s' % replay_path)"], {}), "('Replay saved at: %s' % replay_path)\n", (28563, 28600), False, 'from absl import logging\n'), ((32616, 32658), 'numpy.zeros', 'np.zeros', (['move_feats_len'], {'dtype': 'np.float32'}), '(move_feats_len, dtype=np.float32)\n', (32624, 32658), True, 'import numpy as np\n'), ((32681, 32732), 'numpy.zeros', 'np.zeros', (['(self.n_enemies, nf_en)'], {'dtype': 'np.float32'}), '((self.n_enemies, nf_en), dtype=np.float32)\n', (32689, 32732), True, 'import numpy as np\n'), ((32754, 32808), 'numpy.zeros', 'np.zeros', (['(self.n_agents - 1, nf_al)'], {'dtype': 'np.float32'}), '((self.n_agents - 1, nf_al), dtype=np.float32)\n', (32762, 32808), True, 'import numpy as np\n'), ((32829, 32863), 'numpy.zeros', 'np.zeros', (['nf_own'], {'dtype': 'np.float32'}), '(nf_own, dtype=np.float32)\n', (32837, 32863), True, 'import numpy as np\n'), ((39210, 39242), 'numpy.zeros', 'np.zeros', (['(self.n_agents, nf_al)'], {}), '((self.n_agents, nf_al))\n', (39218, 39242), True, 'import numpy as np\n'), ((39265, 39298), 'numpy.zeros', 'np.zeros', (['(self.n_enemies, nf_en)'], {}), '((self.n_enemies, nf_en))\n', (39273, 39298), True, 'import numpy as np\n'), ((51741, 51762), 'copy.deepcopy', 'deepcopy', (['self.agents'], {}), '(self.agents)\n', (51749, 51762), False, 'from copy import deepcopy\n'), ((51799, 51821), 'copy.deepcopy', 'deepcopy', (['self.enemies'], {}), '(self.enemies)\n', (51807, 51821), False, 'from copy import deepcopy\n'), ((15851, 15873), 'numpy.eye', 'np.eye', (['self.n_actions'], {}), '(self.n_actions)\n', (15857, 15873), True, 'import numpy as np\n'), ((15874, 15891), 'numpy.array', 'np.array', (['actions'], {}), '(actions)\n', (15882, 15891), True, 'import numpy as np\n'), ((37839, 37901), 'numpy.append', 'np.append', (['agent_obs', '(self._episode_steps / self.episode_limit)'], {}), '(agent_obs, self._episode_steps / self.episode_limit)\n', (37848, 37901), True, 'import numpy as np\n'), ((42266, 42324), 'numpy.append', 'np.append', (['state', '(self._episode_steps / self.episode_limit)'], {}), '(state, self._episode_steps / self.episode_limit)\n', (42275, 42324), True, 'import numpy as np\n'), ((19662, 19757), 's2clientprotocol.raw_pb2.ActionRawUnitCommand', 'r_pb.ActionRawUnitCommand', ([], {'ability_id': "actions['stop']", 'unit_tags': '[tag]', 'queue_command': '(False)'}), "(ability_id=actions['stop'], unit_tags=[tag],\n queue_command=False)\n", (19687, 19757), True, 'from s2clientprotocol import raw_pb2 as r_pb\n'), ((22425, 22457), 's2clientprotocol.raw_pb2.ActionRaw', 'r_pb.ActionRaw', ([], {'unit_command': 'cmd'}), '(unit_command=cmd)\n', (22439, 22457), True, 'from s2clientprotocol import raw_pb2 as r_pb\n'), ((22877, 22929), 'math.hypot', 'math.hypot', (['self.max_distance_x', 'self.max_distance_y'], {}), '(self.max_distance_x, self.max_distance_y)\n', (22887, 22929), False, 'import math, time\n'), ((23895, 23947), 'math.hypot', 'math.hypot', (['self.max_distance_x', 'self.max_distance_y'], {}), '(self.max_distance_x, self.max_distance_y)\n', (23905, 23947), False, 'import math, time\n'), ((24901, 24933), 's2clientprotocol.raw_pb2.ActionRaw', 'r_pb.ActionRaw', ([], {'unit_command': 'cmd'}), '(unit_command=cmd)\n', (24915, 24933), True, 'from s2clientprotocol import raw_pb2 as r_pb\n'), ((49351, 49386), 's2clientprotocol.debug_pb2.DebugKillUnit', 'd_pb.DebugKillUnit', ([], {'tag': 'units_alive'}), '(tag=units_alive)\n', (49369, 49386), True, 'from s2clientprotocol import debug_pb2 as d_pb\n'), ((49904, 49945), 'operator.attrgetter', 'attrgetter', (['"""unit_type"""', '"""pos.x"""', '"""pos.y"""'], {}), "('unit_type', 'pos.x', 'pos.y')\n", (49914, 49945), False, 'from operator import attrgetter\n'), ((20071, 20118), 's2clientprotocol.common_pb2.Point2D', 'sc_common.Point2D', ([], {'x': 'x', 'y': '(y + self._move_amount)'}), '(x=x, y=y + self._move_amount)\n', (20088, 20118), True, 'from s2clientprotocol import common_pb2 as sc_common\n'), ((20485, 20532), 's2clientprotocol.common_pb2.Point2D', 'sc_common.Point2D', ([], {'x': 'x', 'y': '(y - self._move_amount)'}), '(x=x, y=y - self._move_amount)\n', (20502, 20532), True, 'from s2clientprotocol import common_pb2 as sc_common\n'), ((22059, 22176), 's2clientprotocol.raw_pb2.ActionRawUnitCommand', 'r_pb.ActionRawUnitCommand', ([], {'ability_id': 'action_id', 'target_unit_tag': 'target_tag', 'unit_tags': '[tag]', 'queue_command': '(False)'}), '(ability_id=action_id, target_unit_tag=target_tag,\n unit_tags=[tag], queue_command=False)\n', (22084, 22176), True, 'from s2clientprotocol import raw_pb2 as r_pb\n'), ((20898, 20945), 's2clientprotocol.common_pb2.Point2D', 'sc_common.Point2D', ([], {'x': '(x + self._move_amount)', 'y': 'y'}), '(x=x + self._move_amount, y=y)\n', (20915, 20945), True, 'from s2clientprotocol import common_pb2 as sc_common\n'), ((21310, 21357), 's2clientprotocol.common_pb2.Point2D', 'sc_common.Point2D', ([], {'x': '(x - self._move_amount)', 'y': 'y'}), '(x=x - self._move_amount, y=y)\n', (21327, 21357), True, 'from s2clientprotocol import common_pb2 as sc_common\n')]
import numbers from typing import Any, Dict, List, Optional, Sequence, Tuple, Union import numpy as np import torch from PIL import Image, ImageOps, ImageEnhance from typing_extensions import Literal try: import accimage except ImportError: accimage = None @torch.jit.unused def _is_pil_image(img: Any) -> bool: if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) @torch.jit.unused def get_image_size(img: Any) -> List[int]: if _is_pil_image(img): return list(img.size) raise TypeError(f"Unexpected type {type(img)}") @torch.jit.unused def get_image_num_channels(img: Any) -> int: if _is_pil_image(img): return 1 if img.mode == "L" else 3 raise TypeError(f"Unexpected type {type(img)}") @torch.jit.unused def hflip(img: Image.Image) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return img.transpose(Image.FLIP_LEFT_RIGHT) @torch.jit.unused def vflip(img: Image.Image) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return img.transpose(Image.FLIP_TOP_BOTTOM) @torch.jit.unused def adjust_brightness(img: Image.Image, brightness_factor: float) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") enhancer = ImageEnhance.Brightness(img) img = enhancer.enhance(brightness_factor) return img @torch.jit.unused def adjust_contrast(img: Image.Image, contrast_factor: float) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(contrast_factor) return img @torch.jit.unused def adjust_saturation(img: Image.Image, saturation_factor: float) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") enhancer = ImageEnhance.Color(img) img = enhancer.enhance(saturation_factor) return img @torch.jit.unused def adjust_hue(img: Image.Image, hue_factor: float) -> Image.Image: if not (-0.5 <= hue_factor <= 0.5): raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].") if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") input_mode = img.mode if input_mode in {"L", "1", "I", "F"}: return img h, s, v = img.convert("HSV").split() np_h = np.array(h, dtype=np.uint8) # uint8 addition take cares of rotation across boundaries with np.errstate(over="ignore"): np_h += np.uint8(hue_factor * 255) h = Image.fromarray(np_h, "L") img = Image.merge("HSV", (h, s, v)).convert(input_mode) return img @torch.jit.unused def adjust_gamma( img: Image.Image, gamma: float, gain: float = 1.0, ) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") if gamma < 0: raise ValueError("Gamma should be a non-negative real number") input_mode = img.mode img = img.convert("RGB") gamma_map = [int((255 + 1 - 1e-3) * gain * pow(ele / 255.0, gamma)) for ele in range(256)] * 3 img = img.point(gamma_map) # use PIL's point-function to accelerate this part img = img.convert(input_mode) return img @torch.jit.unused def pad( img: Image.Image, padding: Union[int, List[int], Tuple[int, ...]], fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0, padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant", ) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") if not isinstance(padding, (numbers.Number, tuple, list)): raise TypeError("Got inappropriate padding arg") if not isinstance(fill, (numbers.Number, str, tuple)): raise TypeError("Got inappropriate fill arg") if not isinstance(padding_mode, str): raise TypeError("Got inappropriate padding_mode arg") if isinstance(padding, list): padding = tuple(padding) if isinstance(padding, tuple) and len(padding) not in [1, 2, 4]: raise ValueError(f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple") if isinstance(padding, tuple) and len(padding) == 1: # Compatibility with `functional_tensor.pad` padding = padding[0] if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") if padding_mode == "constant": opts = _parse_fill(fill, img, name="fill") if img.mode == "P": palette = img.getpalette() image = ImageOps.expand(img, border=padding, **opts) image.putpalette(palette) return image return ImageOps.expand(img, border=padding, **opts) else: if isinstance(padding, int): pad_left = pad_right = pad_top = pad_bottom = padding if isinstance(padding, tuple) and len(padding) == 2: pad_left = pad_right = padding[0] pad_top = pad_bottom = padding[1] if isinstance(padding, tuple) and len(padding) == 4: pad_left = padding[0] pad_top = padding[1] pad_right = padding[2] pad_bottom = padding[3] p = [pad_left, pad_top, pad_right, pad_bottom] cropping = -np.minimum(p, 0) if cropping.any(): crop_left, crop_top, crop_right, crop_bottom = cropping img = img.crop((crop_left, crop_top, img.width - crop_right, img.height - crop_bottom)) pad_left, pad_top, pad_right, pad_bottom = np.maximum(p, 0) if img.mode == "P": palette = img.getpalette() img = np.asarray(img) img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), mode=padding_mode) img = Image.fromarray(img) img.putpalette(palette) return img img = np.asarray(img) # RGB image if len(img.shape) == 3: img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode) # Grayscale image if len(img.shape) == 2: img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode) return Image.fromarray(img) @torch.jit.unused def crop( img: Image.Image, top: int, left: int, height: int, width: int, ) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return img.crop((left, top, left + width, top + height)) @torch.jit.unused def resize( img: Image.Image, size: Union[Sequence[int], int], interpolation: int = Image.BILINEAR, max_size: Optional[int] = None, ) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") if not (isinstance(size, int) or (isinstance(size, Sequence) and len(size) in (1, 2))): raise TypeError(f"Got inappropriate size arg: {size}") if isinstance(size, Sequence) and len(size) == 1: size = size[0] if isinstance(size, int): w, h = img.size short, long = (w, h) if w <= h else (h, w) if short == size: return img new_short, new_long = size, int(size * long / short) if max_size is not None: if max_size <= size: raise ValueError( f"max_size = {max_size} must be strictly greater than the requested " f"size for the smaller edge size = {size}" ) if new_long > max_size: new_short, new_long = int(max_size * new_short / new_long), max_size new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short) return img.resize((new_w, new_h), interpolation) else: if max_size is not None: raise ValueError( "max_size should only be passed if size specifies the length of the smaller edge, " "i.e. size should be an int or a sequence of length 1 in torchscript mode." ) return img.resize(size[::-1], interpolation) @torch.jit.unused def _parse_fill( fill: Optional[Union[float, List[float], Tuple[float, ...]]], img: Image.Image, name: str = "fillcolor", ) -> Dict[str, Optional[Union[float, List[float], Tuple[float, ...]]]]: # Process fill color for affine transforms num_bands = len(img.getbands()) if fill is None: fill = 0 if isinstance(fill, (int, float)) and num_bands > 1: fill = tuple([fill] * num_bands) if isinstance(fill, (list, tuple)): if len(fill) != num_bands: msg = "The number of elements in 'fill' does not match the number of bands of the image ({} != {})" raise ValueError(msg.format(len(fill), num_bands)) fill = tuple(fill) return {name: fill} @torch.jit.unused def affine( img: Image.Image, matrix: List[float], interpolation: int = Image.NEAREST, fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0, ) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") output_size = img.size opts = _parse_fill(fill, img) return img.transform(output_size, Image.AFFINE, matrix, interpolation, **opts) @torch.jit.unused def rotate( img: Image.Image, angle: float, interpolation: int = Image.NEAREST, expand: bool = False, center: Optional[Tuple[int, int]] = None, fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0, ) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") opts = _parse_fill(fill, img) return img.rotate(angle, interpolation, expand, center, **opts) @torch.jit.unused def perspective( img: Image.Image, perspective_coeffs: float, interpolation: int = Image.BICUBIC, fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0, ) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") opts = _parse_fill(fill, img) return img.transform(img.size, Image.PERSPECTIVE, perspective_coeffs, interpolation, **opts) @torch.jit.unused def to_grayscale(img: Image.Image, num_output_channels: int) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") if num_output_channels == 1: img = img.convert("L") elif num_output_channels == 3: img = img.convert("L") np_img = np.array(img, dtype=np.uint8) np_img = np.dstack([np_img, np_img, np_img]) img = Image.fromarray(np_img, "RGB") else: raise ValueError("num_output_channels should be either 1 or 3") return img @torch.jit.unused def invert(img: Image.Image) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return ImageOps.invert(img) @torch.jit.unused def posterize(img: Image.Image, bits: int) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return ImageOps.posterize(img, bits) @torch.jit.unused def solarize(img: Image.Image, threshold: int) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return ImageOps.solarize(img, threshold) @torch.jit.unused def adjust_sharpness(img: Image.Image, sharpness_factor: float) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") enhancer = ImageEnhance.Sharpness(img) img = enhancer.enhance(sharpness_factor) return img @torch.jit.unused def autocontrast(img: Image.Image) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return ImageOps.autocontrast(img) @torch.jit.unused def equalize(img: Image.Image) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return ImageOps.equalize(img)
[ "numpy.uint8", "PIL.ImageEnhance.Contrast", "numpy.array", "PIL.ImageOps.posterize", "PIL.ImageOps.autocontrast", "PIL.ImageOps.expand", "numpy.asarray", "PIL.ImageEnhance.Sharpness", "PIL.ImageEnhance.Color", "PIL.ImageOps.invert", "numpy.maximum", "PIL.ImageOps.equalize", "PIL.ImageOps.solarize", "PIL.ImageEnhance.Brightness", "numpy.dstack", "PIL.Image.fromarray", "numpy.minimum", "numpy.errstate", "numpy.pad", "PIL.Image.merge" ]
[((1472, 1500), 'PIL.ImageEnhance.Brightness', 'ImageEnhance.Brightness', (['img'], {}), '(img)\n', (1495, 1500), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((1776, 1802), 'PIL.ImageEnhance.Contrast', 'ImageEnhance.Contrast', (['img'], {}), '(img)\n', (1797, 1802), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((2080, 2103), 'PIL.ImageEnhance.Color', 'ImageEnhance.Color', (['img'], {}), '(img)\n', (2098, 2103), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((2615, 2642), 'numpy.array', 'np.array', (['h'], {'dtype': 'np.uint8'}), '(h, dtype=np.uint8)\n', (2623, 2642), True, 'import numpy as np\n'), ((2793, 2819), 'PIL.Image.fromarray', 'Image.fromarray', (['np_h', '"""L"""'], {}), "(np_h, 'L')\n", (2808, 2819), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((11381, 11401), 'PIL.ImageOps.invert', 'ImageOps.invert', (['img'], {}), '(img)\n', (11396, 11401), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((11592, 11621), 'PIL.ImageOps.posterize', 'ImageOps.posterize', (['img', 'bits'], {}), '(img, bits)\n', (11610, 11621), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((11816, 11849), 'PIL.ImageOps.solarize', 'ImageOps.solarize', (['img', 'threshold'], {}), '(img, threshold)\n', (11833, 11849), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((12066, 12093), 'PIL.ImageEnhance.Sharpness', 'ImageEnhance.Sharpness', (['img'], {}), '(img)\n', (12088, 12093), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((12336, 12362), 'PIL.ImageOps.autocontrast', 'ImageOps.autocontrast', (['img'], {}), '(img)\n', (12357, 12362), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((12541, 12563), 'PIL.ImageOps.equalize', 'ImageOps.equalize', (['img'], {}), '(img)\n', (12558, 12563), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((2714, 2740), 'numpy.errstate', 'np.errstate', ([], {'over': '"""ignore"""'}), "(over='ignore')\n", (2725, 2740), True, 'import numpy as np\n'), ((2758, 2784), 'numpy.uint8', 'np.uint8', (['(hue_factor * 255)'], {}), '(hue_factor * 255)\n', (2766, 2784), True, 'import numpy as np\n'), ((5072, 5116), 'PIL.ImageOps.expand', 'ImageOps.expand', (['img'], {'border': 'padding'}), '(img, border=padding, **opts)\n', (5087, 5116), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((5923, 5939), 'numpy.maximum', 'np.maximum', (['p', '(0)'], {}), '(p, 0)\n', (5933, 5939), True, 'import numpy as np\n'), ((6252, 6267), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (6262, 6267), True, 'import numpy as np\n'), ((6586, 6606), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (6601, 6606), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((2831, 2860), 'PIL.Image.merge', 'Image.merge', (['"""HSV"""', '(h, s, v)'], {}), "('HSV', (h, s, v))\n", (2842, 2860), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((4948, 4992), 'PIL.ImageOps.expand', 'ImageOps.expand', (['img'], {'border': 'padding'}), '(img, border=padding, **opts)\n', (4963, 4992), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((5658, 5674), 'numpy.minimum', 'np.minimum', (['p', '(0)'], {}), '(p, 0)\n', (5668, 5674), True, 'import numpy as np\n'), ((6026, 6041), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (6036, 6041), True, 'import numpy as np\n'), ((6060, 6138), 'numpy.pad', 'np.pad', (['img', '((pad_top, pad_bottom), (pad_left, pad_right))'], {'mode': 'padding_mode'}), '(img, ((pad_top, pad_bottom), (pad_left, pad_right)), mode=padding_mode)\n', (6066, 6138), True, 'import numpy as np\n'), ((6157, 6177), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (6172, 6177), False, 'from PIL import Image, ImageOps, ImageEnhance\n'), ((6338, 6423), 'numpy.pad', 'np.pad', (['img', '((pad_top, pad_bottom), (pad_left, pad_right), (0, 0))', 'padding_mode'], {}), '(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)),\n padding_mode)\n', (6344, 6423), True, 'import numpy as np\n'), ((6496, 6569), 'numpy.pad', 'np.pad', (['img', '((pad_top, pad_bottom), (pad_left, pad_right))', 'padding_mode'], {}), '(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode)\n', (6502, 6569), True, 'import numpy as np\n'), ((10979, 11008), 'numpy.array', 'np.array', (['img'], {'dtype': 'np.uint8'}), '(img, dtype=np.uint8)\n', (10987, 11008), True, 'import numpy as np\n'), ((11026, 11061), 'numpy.dstack', 'np.dstack', (['[np_img, np_img, np_img]'], {}), '([np_img, np_img, np_img])\n', (11035, 11061), True, 'import numpy as np\n'), ((11076, 11106), 'PIL.Image.fromarray', 'Image.fromarray', (['np_img', '"""RGB"""'], {}), "(np_img, 'RGB')\n", (11091, 11106), False, 'from PIL import Image, ImageOps, ImageEnhance\n')]
import numpy as np from pyray.shapes.twod.paraboloid import * from pyray.shapes.twod.functional import * from pyray.rotation import * from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib as mpl import os basedir = '.\\Images\\RotatingCube\\' if os.name == 'posix': basedir = 'Images/RotatingCube/' def draw_cubic(): fn = lambda x,y: x**3+y**3 for i in range(20): im = Image.new("RGB", (2048, 2048), "black") draw = ImageDraw.Draw(im, 'RGBA') r = general_rotation(np.array([1,0,0]),np.pi/120*i) #drawFunctionalXYGridInCircle(draw, r, fn=fn, scale=10.0) im.save(basedir + 'im' + str(i) + '.png') def three_d_grid(): fig = plt.figure() ax = fig.gca(projection='3d') # Make data. X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = (X**3 + Y**3) Z = R # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. #ax.set_zlim(-1.01, 1.01) #ax.zaxis.set_major_locator(LinearLocator(10)) #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') theta = np.linspace(0, 2 * np.pi, 100) for r in np.arange(0.1,1.0,0.1): #r = 1.0 x = r * np.sin(theta) y = r * np.cos(theta) z = x**3+y**3 ax.plot(x, y, z, label='parametric curve') #ax.legend() plt.show() def paraboloid_w_grad(im_ind=0, scale=200, shift=np.array([1000,1000,0]), opacity=60, basepath='.\\'): r1 = np.eye(4) rot = general_rotation(np.array([0,0,1]), np.pi/20.0 * (8 + im_ind/3.0)) j=4 r = rotation(3, 2 * np.pi* j /30.0) rr = general_rotation(np.array([0,1,0]), np.pi/20.0 * (im_ind/7.0)) r = np.dot(r,rr) r = np.dot(r, rot) r1[:3,:3] = r im = Image.new("RGB", (2048, 2048), "black") draw = ImageDraw.Draw(im, 'RGBA') render_scene_4d_axis(draw, r1, 4, scale, shift) # This is what draws the pink paraboloid. for z in np.arange(0.001, 3.5, 0.02): point1 = np.array([np.sqrt(z),0,z]) generalized_arc(draw, r, center=np.array([0,0,z]), vec=np.array([0,0,1]), point=point1, radius=np.sqrt(z), prcnt=1.0, rgba=(255,20,147,50)) xax1=np.array([-100.0,0,0.0]);xax1=np.dot(r,xax1)*scale+shift xax2=np.array([100.0,0,0.0]);xax2=np.dot(r,xax2)*scale+shift draw.line((xax1[0], xax1[1], xax2[0], xax2[1]), fill=(255,255,0), width=4) xax1=np.array([0.0,-100,0.0]);xax1=np.dot(r,xax1)*scale+shift xax2=np.array([0.0,100,0.0]);xax2=np.dot(r,xax2)*scale+shift draw.line((xax1[0], xax1[1], xax2[0], xax2[1]), fill=(255,255,0), width=4) #gradients(draw,r) pt = shift draw.ellipse((pt[0]-10, pt[1]-10, pt[0]+10, pt[1]+10), fill = (0,255,0)) draw_paraboloid_plane(draw,r,3.3) draw_paraboloid_plane(draw,r,2.0,extent=1.4) draw_paraboloid_plane(draw,r,1.0,extent=1.0) im.save(basepath + 'im' + str(im_ind) + '.png') def gradients(draw,r): #for z in [0.3,1.3,2.3,3.3]: for z in [3.3,2.0,1.0]: x = np.sqrt(z) for x in np.arange(-x,x,x/2): y = np.sqrt(z-x*x) arrowV1(draw,r,np.array([y,x,z]), np.array([1.5*y,1.5*x,z]), (204,102,255)) if z>3.0: arrowV1(draw,r,np.array([-y,x,z]), np.array([-1.5*y,1.5*x,z]), (204,102,255)) def draw_paraboloid_plane(draw,r,z=3.3,scale=200,shift=np.array([1000,1000,0]),extent=2): pt1=np.array([extent,extent,z]);pt1=np.dot(r,pt1)*scale+shift pt2=np.array([extent,-extent,z]);pt2=np.dot(r,pt2)*scale+shift pt3=np.array([-extent,-extent,z]);pt3=np.dot(r,pt3)*scale+shift pt4=np.array([-extent,extent,z]);pt4=np.dot(r,pt4)*scale+shift draw.polygon([(pt1[0], pt1[1]), (pt2[0], pt2[1]), (pt3[0], pt3[1]), (pt4[0], pt4[1])],\ (0,102,255,50)) point1 = np.array([np.sqrt(z),0,z]) generalized_arc(draw, r, center=np.array([0,0,z]), vec=np.array([0,0,1]), point=point1, radius=np.sqrt(z), prcnt=1.0,scale=scale, rgba=(255,20,10,100),width=10) def plane_w_arrows(im_ind=0, scale=200,\ shift=np.array([824,824,0]),\ basepath='.\\'): r1 = np.eye(4) rot = general_rotation(np.array([0,0,1]), np.pi/20.0*(8 + im_ind/3.0)) j=4 r = rotation(3, 2*np.pi*j/30.0) rr = general_rotation(np.array([0,1,0]), np.pi/20.0*(im_ind/7.0)) r = np.dot(r,rr) r = np.dot(r, rot) r1[:3,:3] = r im = Image.new("RGB", (1648, 1648), "black") draw = ImageDraw.Draw(im, 'RGBA') pt1 = 3*np.array([1.0,-1.0,0]); pt2 = 3*np.array([1.0,1.0,0]) z = 1.2**2+1 pt3 = 3*np.array([-1.0,1.0,0]); pt4 = 3*np.array([-1.0,-1.0,0]) pt1 = np.dot(r,pt1)*scale+shift; pt2 = np.dot(r,pt2)*scale+shift pt3 = np.dot(r,pt3)*scale+shift; pt4 = np.dot(r,pt4)*scale+shift draw.polygon([(pt1[0], pt1[1]), (pt2[0], pt2[1]), (pt3[0], pt3[1]), (pt4[0], pt4[1])],\ (0,102,255,50)) draw_arrows(draw,r,rgba=(255,250,47),shift=shift) draw_arrows(draw,r,rot_angl=np.pi/2.0, rgba=(73,200,250),shift=shift) draw_arrows(draw,r,rot_angl=np.pi/2.0+np.pi/3, rgba=(255,20,147),shift=shift) arrowV1(draw,r,np.array([0,0,0]), np.array([0,0,2.5]), shift=shift,rgb=(20,200,25)) arrowV1(draw,r,np.array([0,0,0]), np.array([0,0,-2.5]), shift=shift,rgb=(255,20,25)) im.save(basepath + 'im' + str(im_ind) + '.png') def draw_arrows(draw,r,rot_angl=np.pi/6.0,rgba=(255,20,147),shift=np.array([1000,1000,0])): base = np.array([0,0,1.5]) for theta in np.arange(0,np.pi*2,2*np.pi/3): a = np.array([np.cos(theta),np.sin(theta),0]) rr = general_rotation(a, rot_angl) arrow1 = np.dot(rr,base) arrowV1(draw,r,np.array([0,0,0]), arrow1, rgb=rgba,shift=shift) rgba = rgba+(150,) generalized_arc(draw, r, center=np.array([0,0,1.5*np.cos(rot_angl)]), vec=np.array([0,0,1]), point=1.5*np.array([0,np.sin(rot_angl),np.cos(rot_angl)]), radius=100, prcnt=1.0, rgba=rgba,shift=shift) ##################### ## Paraboloid with Lagrange visualized. im = Image.new("RGB", (2048, 2048), (1, 1, 1)) draw = ImageDraw.Draw(im, 'RGBA') scale=5.0; ind=0; sep = 24; i = 2.0; base_coeff = 0.02; start_line = -12.0 shift = np.array([1000.0, 1000.0, 0.0]) r1 = np.eye(4); j=24 r = rotation(3, np.pi/30*j) r1[:3,:3] = r render_scene_4d_axis(draw, r1, 4) fn = lambda x, y : paraboloid(x, y, coeff=i*base_coeff, intercept=i) drawFunctionalXYGrid(draw, r, scale=scale, fn=fn, extent=60, rgba2=(255,20,147,80), saperatingPlane=np.array([-1,-1,sep])) three_d_parabola(draw, r, r2) im.save(basedir + 'im' + str(0) + '.png')
[ "numpy.eye", "numpy.sqrt", "numpy.array", "matplotlib.pyplot.figure", "numpy.linspace", "numpy.dot", "numpy.cos", "numpy.sin", "numpy.meshgrid", "numpy.arange", "matplotlib.pyplot.show" ]
[((1463, 1475), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1473, 1475), True, 'import matplotlib.pyplot as plt\n'), ((1514, 1544), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(100)'], {}), '(0, 2 * np.pi, 100)\n', (1525, 1544), True, 'import numpy as np\n'), ((1555, 1579), 'numpy.arange', 'np.arange', (['(0.1)', '(1.0)', '(0.1)'], {}), '(0.1, 1.0, 0.1)\n', (1564, 1579), True, 'import numpy as np\n'), ((1727, 1737), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1735, 1737), True, 'import matplotlib.pyplot as plt\n'), ((6730, 6761), 'numpy.array', 'np.array', (['[1000.0, 1000.0, 0.0]'], {}), '([1000.0, 1000.0, 0.0])\n', (6738, 6761), True, 'import numpy as np\n'), ((6768, 6777), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (6774, 6777), True, 'import numpy as np\n'), ((809, 821), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (819, 821), True, 'import matplotlib.pyplot as plt\n'), ((882, 904), 'numpy.arange', 'np.arange', (['(-5)', '(5)', '(0.25)'], {}), '(-5, 5, 0.25)\n', (891, 904), True, 'import numpy as np\n'), ((913, 935), 'numpy.arange', 'np.arange', (['(-5)', '(5)', '(0.25)'], {}), '(-5, 5, 0.25)\n', (922, 935), True, 'import numpy as np\n'), ((947, 964), 'numpy.meshgrid', 'np.meshgrid', (['X', 'Y'], {}), '(X, Y)\n', (958, 964), True, 'import numpy as np\n'), ((1406, 1416), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1414, 1416), True, 'import matplotlib.pyplot as plt\n'), ((1789, 1814), 'numpy.array', 'np.array', (['[1000, 1000, 0]'], {}), '([1000, 1000, 0])\n', (1797, 1814), True, 'import numpy as np\n'), ((1872, 1881), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (1878, 1881), True, 'import numpy as np\n'), ((2087, 2100), 'numpy.dot', 'np.dot', (['r', 'rr'], {}), '(r, rr)\n', (2093, 2100), True, 'import numpy as np\n'), ((2108, 2122), 'numpy.dot', 'np.dot', (['r', 'rot'], {}), '(r, rot)\n', (2114, 2122), True, 'import numpy as np\n'), ((2339, 2366), 'numpy.arange', 'np.arange', (['(0.001)', '(3.5)', '(0.02)'], {}), '(0.001, 3.5, 0.02)\n', (2348, 2366), True, 'import numpy as np\n'), ((2619, 2645), 'numpy.array', 'np.array', (['[-100.0, 0, 0.0]'], {}), '([-100.0, 0, 0.0])\n', (2627, 2645), True, 'import numpy as np\n'), ((2685, 2710), 'numpy.array', 'np.array', (['[100.0, 0, 0.0]'], {}), '([100.0, 0, 0.0])\n', (2693, 2710), True, 'import numpy as np\n'), ((2829, 2855), 'numpy.array', 'np.array', (['[0.0, -100, 0.0]'], {}), '([0.0, -100, 0.0])\n', (2837, 2855), True, 'import numpy as np\n'), ((2895, 2920), 'numpy.array', 'np.array', (['[0.0, 100, 0.0]'], {}), '([0.0, 100, 0.0])\n', (2903, 2920), True, 'import numpy as np\n'), ((3772, 3797), 'numpy.array', 'np.array', (['[1000, 1000, 0]'], {}), '([1000, 1000, 0])\n', (3780, 3797), True, 'import numpy as np\n'), ((3815, 3844), 'numpy.array', 'np.array', (['[extent, extent, z]'], {}), '([extent, extent, z])\n', (3823, 3844), True, 'import numpy as np\n'), ((3881, 3911), 'numpy.array', 'np.array', (['[extent, -extent, z]'], {}), '([extent, -extent, z])\n', (3889, 3911), True, 'import numpy as np\n'), ((3948, 3979), 'numpy.array', 'np.array', (['[-extent, -extent, z]'], {}), '([-extent, -extent, z])\n', (3956, 3979), True, 'import numpy as np\n'), ((4016, 4046), 'numpy.array', 'np.array', (['[-extent, extent, z]'], {}), '([-extent, extent, z])\n', (4024, 4046), True, 'import numpy as np\n'), ((4526, 4549), 'numpy.array', 'np.array', (['[824, 824, 0]'], {}), '([824, 824, 0])\n', (4534, 4549), True, 'import numpy as np\n'), ((4596, 4605), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (4602, 4605), True, 'import numpy as np\n'), ((4803, 4816), 'numpy.dot', 'np.dot', (['r', 'rr'], {}), '(r, rr)\n', (4809, 4816), True, 'import numpy as np\n'), ((4824, 4838), 'numpy.dot', 'np.dot', (['r', 'rot'], {}), '(r, rot)\n', (4830, 4838), True, 'import numpy as np\n'), ((5870, 5895), 'numpy.array', 'np.array', (['[1000, 1000, 0]'], {}), '([1000, 1000, 0])\n', (5878, 5895), True, 'import numpy as np\n'), ((5907, 5928), 'numpy.array', 'np.array', (['[0, 0, 1.5]'], {}), '([0, 0, 1.5])\n', (5915, 5928), True, 'import numpy as np\n'), ((5944, 5982), 'numpy.arange', 'np.arange', (['(0)', '(np.pi * 2)', '(2 * np.pi / 3)'], {}), '(0, np.pi * 2, 2 * np.pi / 3)\n', (5953, 5982), True, 'import numpy as np\n'), ((1604, 1617), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1610, 1617), True, 'import numpy as np\n'), ((1630, 1643), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (1636, 1643), True, 'import numpy as np\n'), ((1909, 1928), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (1917, 1928), True, 'import numpy as np\n'), ((2033, 2052), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (2041, 2052), True, 'import numpy as np\n'), ((3431, 3441), 'numpy.sqrt', 'np.sqrt', (['z'], {}), '(z)\n', (3438, 3441), True, 'import numpy as np\n'), ((3459, 3482), 'numpy.arange', 'np.arange', (['(-x)', 'x', '(x / 2)'], {}), '(-x, x, x / 2)\n', (3468, 3482), True, 'import numpy as np\n'), ((4633, 4652), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (4641, 4652), True, 'import numpy as np\n'), ((4751, 4770), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (4759, 4770), True, 'import numpy as np\n'), ((4956, 4980), 'numpy.array', 'np.array', (['[1.0, -1.0, 0]'], {}), '([1.0, -1.0, 0])\n', (4964, 4980), True, 'import numpy as np\n'), ((4988, 5011), 'numpy.array', 'np.array', (['[1.0, 1.0, 0]'], {}), '([1.0, 1.0, 0])\n', (4996, 5011), True, 'import numpy as np\n'), ((5039, 5063), 'numpy.array', 'np.array', (['[-1.0, 1.0, 0]'], {}), '([-1.0, 1.0, 0])\n', (5047, 5063), True, 'import numpy as np\n'), ((5071, 5096), 'numpy.array', 'np.array', (['[-1.0, -1.0, 0]'], {}), '([-1.0, -1.0, 0])\n', (5079, 5096), True, 'import numpy as np\n'), ((5592, 5611), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (5600, 5611), True, 'import numpy as np\n'), ((5611, 5632), 'numpy.array', 'np.array', (['[0, 0, 2.5]'], {}), '([0, 0, 2.5])\n', (5619, 5632), True, 'import numpy as np\n'), ((5680, 5699), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (5688, 5699), True, 'import numpy as np\n'), ((5699, 5721), 'numpy.array', 'np.array', (['[0, 0, -2.5]'], {}), '([0, 0, -2.5])\n', (5707, 5721), True, 'import numpy as np\n'), ((6090, 6106), 'numpy.dot', 'np.dot', (['rr', 'base'], {}), '(rr, base)\n', (6096, 6106), True, 'import numpy as np\n'), ((7065, 7088), 'numpy.array', 'np.array', (['[-1, -1, sep]'], {}), '([-1, -1, sep])\n', (7073, 7088), True, 'import numpy as np\n'), ((630, 649), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (638, 649), True, 'import numpy as np\n'), ((2649, 2664), 'numpy.dot', 'np.dot', (['r', 'xax1'], {}), '(r, xax1)\n', (2655, 2664), True, 'import numpy as np\n'), ((2714, 2729), 'numpy.dot', 'np.dot', (['r', 'xax2'], {}), '(r, xax2)\n', (2720, 2729), True, 'import numpy as np\n'), ((2859, 2874), 'numpy.dot', 'np.dot', (['r', 'xax1'], {}), '(r, xax1)\n', (2865, 2874), True, 'import numpy as np\n'), ((2924, 2939), 'numpy.dot', 'np.dot', (['r', 'xax2'], {}), '(r, xax2)\n', (2930, 2939), True, 'import numpy as np\n'), ((3496, 3514), 'numpy.sqrt', 'np.sqrt', (['(z - x * x)'], {}), '(z - x * x)\n', (3503, 3514), True, 'import numpy as np\n'), ((3847, 3861), 'numpy.dot', 'np.dot', (['r', 'pt1'], {}), '(r, pt1)\n', (3853, 3861), True, 'import numpy as np\n'), ((3914, 3928), 'numpy.dot', 'np.dot', (['r', 'pt2'], {}), '(r, pt2)\n', (3920, 3928), True, 'import numpy as np\n'), ((3982, 3996), 'numpy.dot', 'np.dot', (['r', 'pt3'], {}), '(r, pt3)\n', (3988, 3996), True, 'import numpy as np\n'), ((4049, 4063), 'numpy.dot', 'np.dot', (['r', 'pt4'], {}), '(r, pt4)\n', (4055, 4063), True, 'import numpy as np\n'), ((4226, 4236), 'numpy.sqrt', 'np.sqrt', (['z'], {}), '(z)\n', (4233, 4236), True, 'import numpy as np\n'), ((4279, 4298), 'numpy.array', 'np.array', (['[0, 0, z]'], {}), '([0, 0, z])\n', (4287, 4298), True, 'import numpy as np\n'), ((4302, 4321), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (4310, 4321), True, 'import numpy as np\n'), ((4367, 4377), 'numpy.sqrt', 'np.sqrt', (['z'], {}), '(z)\n', (4374, 4377), True, 'import numpy as np\n'), ((5105, 5119), 'numpy.dot', 'np.dot', (['r', 'pt1'], {}), '(r, pt1)\n', (5111, 5119), True, 'import numpy as np\n'), ((5138, 5152), 'numpy.dot', 'np.dot', (['r', 'pt2'], {}), '(r, pt2)\n', (5144, 5152), True, 'import numpy as np\n'), ((5174, 5188), 'numpy.dot', 'np.dot', (['r', 'pt3'], {}), '(r, pt3)\n', (5180, 5188), True, 'import numpy as np\n'), ((5207, 5221), 'numpy.dot', 'np.dot', (['r', 'pt4'], {}), '(r, pt4)\n', (5213, 5221), True, 'import numpy as np\n'), ((6129, 6148), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (6137, 6148), True, 'import numpy as np\n'), ((6303, 6322), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (6311, 6322), True, 'import numpy as np\n'), ((2395, 2405), 'numpy.sqrt', 'np.sqrt', (['z'], {}), '(z)\n', (2402, 2405), True, 'import numpy as np\n'), ((2452, 2471), 'numpy.array', 'np.array', (['[0, 0, z]'], {}), '([0, 0, z])\n', (2460, 2471), True, 'import numpy as np\n'), ((2475, 2494), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (2483, 2494), True, 'import numpy as np\n'), ((2540, 2550), 'numpy.sqrt', 'np.sqrt', (['z'], {}), '(z)\n', (2547, 2550), True, 'import numpy as np\n'), ((3538, 3557), 'numpy.array', 'np.array', (['[y, x, z]'], {}), '([y, x, z])\n', (3546, 3557), True, 'import numpy as np\n'), ((3557, 3588), 'numpy.array', 'np.array', (['[1.5 * y, 1.5 * x, z]'], {}), '([1.5 * y, 1.5 * x, z])\n', (3565, 3588), True, 'import numpy as np\n'), ((5998, 6011), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6004, 6011), True, 'import numpy as np\n'), ((6012, 6025), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6018, 6025), True, 'import numpy as np\n'), ((3652, 3672), 'numpy.array', 'np.array', (['[-y, x, z]'], {}), '([-y, x, z])\n', (3660, 3672), True, 'import numpy as np\n'), ((3672, 3704), 'numpy.array', 'np.array', (['[-1.5 * y, 1.5 * x, z]'], {}), '([-1.5 * y, 1.5 * x, z])\n', (3680, 3704), True, 'import numpy as np\n'), ((6255, 6271), 'numpy.cos', 'np.cos', (['rot_angl'], {}), '(rot_angl)\n', (6261, 6271), True, 'import numpy as np\n'), ((6368, 6384), 'numpy.sin', 'np.sin', (['rot_angl'], {}), '(rot_angl)\n', (6374, 6384), True, 'import numpy as np\n'), ((6385, 6401), 'numpy.cos', 'np.cos', (['rot_angl'], {}), '(rot_angl)\n', (6391, 6401), True, 'import numpy as np\n')]
import os import numpy as np from vmaf import plt from vmaf.core.cross_validation import ModelCrossValidation from vmaf.core.feature_assembler import FeatureAssembler from vmaf.core.quality_runner import VmafQualityRunner from vmaf.core.result_store import FileSystemResultStore from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension from vmaf.config import VmafConfig, DisplayConfig from vmaf.core.asset import Asset from vmaf.core.train_test_model import TrainTestModel, RegressorMixin, ClassifierMixin from vmaf.core.local_explainer import LocalExplainer __copyright__ = "Copyright 2016-2020, Netflix, Inc." __license__ = "BSD+Patent" def read_dataset(dataset, **kwargs): groundtruth_key = kwargs['groundtruth_key'] if 'groundtruth_key' in kwargs else None skip_asset_with_none_groundtruth = kwargs['skip_asset_with_none_groundtruth'] \ if 'skip_asset_with_none_groundtruth' in kwargs else False content_ids = kwargs['content_ids'] if 'content_ids' in kwargs else None asset_ids = kwargs['asset_ids'] if 'asset_ids' in kwargs else None workdir_root = kwargs['workdir_root'] if 'workdir_root' in kwargs else VmafConfig.workdir_path() # asserts, can add more to the list... assert hasattr(dataset, 'dataset_name') assert hasattr(dataset, 'ref_videos') assert hasattr(dataset, 'dis_videos') assert hasattr(dataset, 'yuv_fmt') or all(['yuv_fmt' in ref_video for ref_video in dataset.ref_videos]) data_set_name = dataset.dataset_name ref_videos = dataset.ref_videos dis_videos = dataset.dis_videos width = dataset.width if hasattr(dataset, 'width') else None height = dataset.height if hasattr(dataset, 'height') else None yuv_fmt = dataset.yuv_fmt if hasattr(dataset, 'yuv_fmt') else None quality_width = dataset.quality_width if hasattr(dataset, 'quality_width') else None quality_height = dataset.quality_height if hasattr(dataset, 'quality_height') else None resampling_type = dataset.resampling_type if hasattr(dataset, 'resampling_type') else None crop_cmd = dataset.crop_cmd if hasattr(dataset, 'crop_cmd') else None pad_cmd = dataset.pad_cmd if hasattr(dataset, 'pad_cmd') else None workfile_yuv_type = dataset.workfile_yuv_type if hasattr(dataset, 'workfile_yuv_type') else None duration_sec = dataset.duration_sec if hasattr(dataset, 'duration_sec') else None fps = dataset.fps if hasattr(dataset, 'fps') else None start_frame = dataset.start_frame if hasattr(dataset, 'start_frame') else None end_frame = dataset.end_frame if hasattr(dataset, 'end_frame') else None ref_dict = {} # dictionary of content_id -> path for ref videos for ref_video in ref_videos: ref_dict[ref_video['content_id']] = ref_video assets = [] for dis_video in dis_videos: if content_ids is not None and dis_video['content_id'] not in content_ids: continue if asset_ids is not None and dis_video['asset_id'] not in asset_ids: continue if groundtruth_key is not None: groundtruth = dis_video[groundtruth_key] else: if 'dmos' in dis_video: groundtruth = dis_video['dmos'] elif 'mos' in dis_video: groundtruth = dis_video['mos'] elif 'groundtruth' in dis_video: groundtruth = dis_video['groundtruth'] else: groundtruth = None if 'os' in dis_video: raw_groundtruth = dis_video['os'] else: raw_groundtruth = None if 'groundtruth_std' in dis_video: groundtruth_std = dis_video['groundtruth_std'] else: groundtruth_std = None if 'rebuf_indices' in dis_video: rebuf_indices = dis_video['rebuf_indices'] else: rebuf_indices = None ref_video = ref_dict[dis_video['content_id']] ref_path = ref_video['path'] ref_yuv_fmt_ = yuv_fmt if yuv_fmt is not None else ref_dict[dis_video['content_id']]['yuv_fmt'] dis_yuv_fmt_ = dis_video['yuv_fmt'] if 'yuv_fmt' in dis_video else ref_yuv_fmt_ if width is not None: width_ = width elif 'width' in ref_video and 'width' not in dis_video: width_ = ref_video['width'] elif 'width' in dis_video and 'width' not in ref_video: width_ = dis_video['width'] elif 'width' in ref_video and 'width' in dis_video: assert ref_video['width'] == dis_video['width'] width_ = ref_video['width'] else: width_ = None if height is not None: height_ = height elif 'height' in ref_video and 'height' not in dis_video: height_ = ref_video['height'] elif 'height' in dis_video and 'height' not in ref_video: height_ = dis_video['height'] elif 'height' in ref_video and 'height' in dis_video: assert ref_video['height'] == dis_video['height'] height_ = ref_video['height'] else: height_ = None if quality_width is not None: quality_width_ = quality_width elif 'quality_width' in dis_video: quality_width_ = dis_video['quality_width'] else: quality_width_ = None if quality_height is not None: quality_height_ = quality_height elif 'quality_height' in dis_video: quality_height_ = dis_video['quality_height'] else: quality_height_ = None if resampling_type is not None: resampling_type_ = resampling_type elif 'resampling_type' in dis_video: resampling_type_ = dis_video['resampling_type'] else: resampling_type_ = None if crop_cmd is not None: ref_crop_cmd_ = crop_cmd dis_crop_cmd_ = crop_cmd else: if 'crop_cmd' in ref_video: ref_crop_cmd_ = ref_video['crop_cmd'] else: ref_crop_cmd_ = None if 'crop_cmd' in dis_video: dis_crop_cmd_ = dis_video['crop_cmd'] else: dis_crop_cmd_ = None if pad_cmd is not None: ref_pad_cmd_ = pad_cmd dis_pad_cmd_ = pad_cmd else: if 'pad_cmd' in ref_video: ref_pad_cmd_ = ref_video['pad_cmd'] else: ref_pad_cmd_ = None if 'pad_cmd' in dis_video: dis_pad_cmd_ = dis_video['pad_cmd'] else: dis_pad_cmd_ = None if duration_sec is not None: duration_sec_ = duration_sec elif 'duration_sec' in dis_video: duration_sec_ = dis_video['duration_sec'] else: duration_sec_ = None if fps is not None: fps_ = fps elif 'fps' in dis_video: fps_ = dis_video['fps'] else: fps_ = None if start_frame is not None: start_frame_ = start_frame elif 'start_frame' in dis_video: start_frame_ = dis_video['start_frame'] else: start_frame_ = None if end_frame is not None: end_frame_ = end_frame elif 'end_frame' in dis_video: end_frame_ = dis_video['end_frame'] else: end_frame_ = None asset_dict = {'ref_yuv_type': ref_yuv_fmt_, 'dis_yuv_type': dis_yuv_fmt_} if width_ is not None: if asset_dict['ref_yuv_type'] != 'notyuv': asset_dict['ref_width'] = width_ if asset_dict['dis_yuv_type'] != 'notyuv': asset_dict['dis_width'] = width_ if height_ is not None: if asset_dict['ref_yuv_type'] != 'notyuv': asset_dict['ref_height'] = height_ if asset_dict['dis_yuv_type'] != 'notyuv': asset_dict['dis_height'] = height_ if groundtruth is not None: asset_dict['groundtruth'] = groundtruth if raw_groundtruth is not None: asset_dict['raw_groundtruth'] = raw_groundtruth if groundtruth_std is not None: asset_dict['groundtruth_std'] = groundtruth_std if quality_width_ is not None: asset_dict['quality_width'] = quality_width_ if quality_height_ is not None: asset_dict['quality_height'] = quality_height_ if resampling_type_ is not None: asset_dict['resampling_type'] = resampling_type_ if ref_crop_cmd_ is not None: asset_dict['ref_crop_cmd'] = ref_crop_cmd_ if dis_crop_cmd_ is not None: asset_dict['dis_crop_cmd'] = dis_crop_cmd_ if ref_pad_cmd_ is not None: asset_dict['ref_pad_cmd'] = ref_pad_cmd_ if dis_pad_cmd_ is not None: asset_dict['dis_pad_cmd'] = dis_pad_cmd_ if duration_sec_ is not None: asset_dict['duration_sec'] = duration_sec_ if workfile_yuv_type is not None: asset_dict['workfile_yuv_type'] = workfile_yuv_type if rebuf_indices is not None: asset_dict['rebuf_indices'] = rebuf_indices if fps_ is not None: asset_dict['fps'] = fps_ if start_frame_ is not None: asset_dict['start_frame'] = start_frame_ if end_frame_ is not None: asset_dict['end_frame'] = end_frame_ if groundtruth is None and skip_asset_with_none_groundtruth: pass else: asset = Asset(dataset=data_set_name, content_id=dis_video['content_id'], asset_id=dis_video['asset_id'], workdir_root=workdir_root, ref_path=ref_path, dis_path=dis_video['path'], asset_dict=asset_dict, ) assets.append(asset) return assets def run_test_on_dataset(test_dataset, runner_class, ax, result_store, model_filepath, parallelize=True, fifo_mode=True, aggregate_method=np.mean, type='regressor', **kwargs): test_assets = read_dataset(test_dataset, **kwargs) test_raw_assets = None try: for test_asset in test_assets: assert test_asset.groundtruth is not None except AssertionError: # no groundtruth, try do subjective modeling from sureal.dataset_reader import RawDatasetReader from sureal.subjective_model import DmosModel subj_model_class = kwargs['subj_model_class'] if 'subj_model_class' in kwargs and kwargs['subj_model_class'] is not None else DmosModel dataset_reader_class = kwargs['dataset_reader_class'] if 'dataset_reader_class' in kwargs else RawDatasetReader subjective_model = subj_model_class(dataset_reader_class(test_dataset)) subjective_model.run_modeling(**kwargs) test_dataset_aggregate = subjective_model.to_aggregated_dataset(**kwargs) test_raw_assets = test_assets test_assets = read_dataset(test_dataset_aggregate, **kwargs) if model_filepath is not None: optional_dict = {'model_filepath': model_filepath} if 'model_720_filepath' in kwargs and kwargs['model_720_filepath'] is not None: optional_dict['720model_filepath'] = kwargs['model_720_filepath'] if 'model_480_filepath' in kwargs and kwargs['model_480_filepath'] is not None: optional_dict['480model_filepath'] = kwargs['model_480_filepath'] else: optional_dict = None if 'enable_transform_score' in kwargs and kwargs['enable_transform_score'] is not None: if not optional_dict: optional_dict = {} optional_dict['enable_transform_score'] = kwargs['enable_transform_score'] if 'disable_clip_score' in kwargs and kwargs['disable_clip_score'] is not None: if not optional_dict: optional_dict = {} optional_dict['disable_clip_score'] = kwargs['disable_clip_score'] if 'subsample' in kwargs and kwargs['subsample'] is not None: if not optional_dict: optional_dict = {} optional_dict['subsample'] = kwargs['subsample'] # run runner = runner_class( test_assets, None, fifo_mode=fifo_mode, delete_workdir=True, result_store=result_store, optional_dict=optional_dict, optional_dict2=None, ) runner.run(parallelize=parallelize) results = runner.results for result in results: result.set_score_aggregate_method(aggregate_method) try: model_type = runner.get_train_test_model_class() except: if type == 'regressor': model_type = RegressorMixin elif type == 'classifier': model_type = ClassifierMixin else: assert False split_test_indices_for_perf_ci = kwargs['split_test_indices_for_perf_ci'] \ if 'split_test_indices_for_perf_ci' in kwargs else False # plot groundtruths = list(map(lambda asset: asset.groundtruth, test_assets)) predictions = list(map(lambda result: result[runner_class.get_score_key()], results)) raw_grountruths = None if test_raw_assets is None else \ list(map(lambda asset: asset.raw_groundtruth, test_raw_assets)) groundtruths_std = None if test_assets is None else \ list(map(lambda asset: asset.groundtruth_std, test_assets)) try: predictions_bagging = list(map(lambda result: result[runner_class.get_bagging_score_key()], results)) predictions_stddev = list(map(lambda result: result[runner_class.get_stddev_score_key()], results)) predictions_ci95_low = list(map(lambda result: result[runner_class.get_ci95_low_score_key()], results)) predictions_ci95_high = list(map(lambda result: result[runner_class.get_ci95_high_score_key()], results)) predictions_all_models = list(map(lambda result: result[runner_class.get_all_models_score_key()], results)) # need to revert the list of lists, so that the outer list has the predictions for each model separately predictions_all_models = np.array(predictions_all_models).T.tolist() num_models = np.shape(predictions_all_models)[0] stats = model_type.get_stats(groundtruths, predictions, ys_label_raw=raw_grountruths, ys_label_pred_bagging=predictions_bagging, ys_label_pred_stddev=predictions_stddev, ys_label_pred_ci95_low=predictions_ci95_low, ys_label_pred_ci95_high=predictions_ci95_high, ys_label_pred_all_models=predictions_all_models, ys_label_stddev=groundtruths_std, split_test_indices_for_perf_ci=split_test_indices_for_perf_ci) except Exception as e: print('Stats calculation failed, using default stats calculation. Error cause: ') print(e) stats = model_type.get_stats(groundtruths, predictions, ys_label_raw=raw_grountruths, ys_label_stddev=groundtruths_std, split_test_indices_for_perf_ci=split_test_indices_for_perf_ci) num_models = 1 print('Stats on testing data: {}'.format(model_type.format_stats_for_print(stats))) # printing stats if multiple models are present if 'SRCC_across_model_distribution' in stats \ and 'PCC_across_model_distribution' in stats \ and 'RMSE_across_model_distribution' in stats: print('Stats on testing data (across multiple models, using all test indices): {}'.format( model_type.format_across_model_stats_for_print(model_type.extract_across_model_stats(stats)))) if split_test_indices_for_perf_ci: print('Stats on testing data (single model, multiple test sets): {}' .format(model_type.format_stats_across_test_splits_for_print(model_type.extract_across_test_splits_stats(stats)))) if ax is not None: content_ids = list(map(lambda asset: asset.content_id, test_assets)) if 'point_label' in kwargs: if kwargs['point_label'] == 'asset_id': point_labels = list(map(lambda asset: asset.asset_id, test_assets)) elif kwargs['point_label'] == 'dis_path': point_labels = list(map(lambda asset: get_file_name_without_extension(asset.dis_path), test_assets)) else: raise AssertionError("Unknown point_label {}".format(kwargs['point_label'])) else: point_labels = None model_type.plot_scatter(ax, stats, content_ids=content_ids, point_labels=point_labels, **kwargs) ax.set_xlabel('True Score') ax.set_ylabel("Predicted Score") ax.grid() ax.set_title("{runner}{num_models}\n{stats}".format( dataset=test_assets[0].dataset, runner=runner_class.TYPE, stats=model_type.format_stats_for_plot(stats), num_models=", {} models".format(num_models) if num_models > 1 else "", )) return test_assets, results def print_matplotlib_warning(): print("Warning: cannot import matplotlib, no picture displayed. " \ "If you are on Mac OS and have installed matplotlib, you " \ "possibly need to run: \nsudo pip uninstall python-dateutil \n" \ "sudo pip install python-dateutil==2.2 \n" \ "Refer to: http://stackoverflow.com/questions/27630114/matplotlib-issue-on-os-x-importerror-cannot-import-name-thread") def train_test_vmaf_on_dataset(train_dataset, test_dataset, feature_param, model_param, train_ax, test_ax, result_store, parallelize=True, logger=None, fifo_mode=True, output_model_filepath=None, aggregate_method=np.mean, **kwargs): train_assets = read_dataset(train_dataset, **kwargs) train_raw_assets = None try: for train_asset in train_assets: assert train_asset.groundtruth is not None except AssertionError: # no groundtruth, try do subjective modeling from sureal.dataset_reader import RawDatasetReader from sureal.subjective_model import DmosModel subj_model_class = kwargs['subj_model_class'] if 'subj_model_class' in kwargs and kwargs['subj_model_class'] is not None else DmosModel dataset_reader_class = kwargs['dataset_reader_class'] if 'dataset_reader_class' in kwargs else RawDatasetReader subjective_model = subj_model_class(dataset_reader_class(train_dataset)) subjective_model.run_modeling(**kwargs) train_dataset_aggregate = subjective_model.to_aggregated_dataset(**kwargs) train_raw_assets = train_assets train_assets = read_dataset(train_dataset_aggregate, **kwargs) train_fassembler = FeatureAssembler( feature_dict=feature_param.feature_dict, feature_option_dict=None, assets=train_assets, logger=logger, fifo_mode=fifo_mode, delete_workdir=True, result_store=result_store, optional_dict=None, optional_dict2=None, parallelize=parallelize, ) train_fassembler.run() train_features = train_fassembler.results for result in train_features: result.set_score_aggregate_method(aggregate_method) model_type = model_param.model_type model_param_dict = model_param.model_param_dict model_class = TrainTestModel.find_subclass(model_type) train_xys = model_class.get_xys_from_results(train_features) train_xs = model_class.get_xs_from_results(train_features) train_ys = model_class.get_ys_from_results(train_features) model = model_class(model_param_dict, logger) model.train(train_xys, **kwargs) # append additional information to model before saving, so that # VmafQualityRunner can read and process model.append_info('feature_dict', feature_param.feature_dict) if 'score_clip' in model_param_dict: VmafQualityRunner.set_clip_score(model, model_param_dict['score_clip']) if 'score_transform' in model_param_dict: VmafQualityRunner.set_transform_score(model, model_param_dict['score_transform']) train_ys_pred = VmafQualityRunner.predict_with_model(model, train_xs, **kwargs)['ys_pred'] raw_groundtruths = None if train_raw_assets is None else \ list(map(lambda asset: asset.raw_groundtruth, train_raw_assets)) train_stats = model.get_stats(train_ys['label'], train_ys_pred, ys_label_raw=raw_groundtruths) log = 'Stats on training data: {}'.format(model.format_stats_for_print(train_stats)) if logger: logger.info(log) else: print(log) # save model if output_model_filepath is not None: model.to_file(output_model_filepath) if train_ax is not None: train_content_ids = list(map(lambda asset: asset.content_id, train_assets)) model_class.plot_scatter(train_ax, train_stats, content_ids=train_content_ids) train_ax.set_xlabel('True Score') train_ax.set_ylabel("Predicted Score") train_ax.grid() train_ax.set_title("Dataset: {dataset}, Model: {model}\n{stats}".format( dataset=train_dataset.dataset_name, model=model.model_id, stats=model_class.format_stats_for_plot(train_stats) )) # === test model on test dataset === if test_dataset is None: test_assets = None test_stats = None test_fassembler = None else: test_assets = read_dataset(test_dataset, **kwargs) test_raw_assets = None try: for test_asset in test_assets: assert test_asset.groundtruth is not None except AssertionError: # no groundtruth, try do subjective modeling from sureal.dataset_reader import RawDatasetReader from sureal.subjective_model import DmosModel subj_model_class = kwargs['subj_model_class'] if 'subj_model_class' in kwargs and kwargs['subj_model_class'] is not None else DmosModel dataset_reader_class = kwargs['dataset_reader_class'] if 'dataset_reader_class' in kwargs else RawDatasetReader subjective_model = subj_model_class(dataset_reader_class(test_dataset)) subjective_model.run_modeling(**kwargs) test_dataset_aggregate = subjective_model.to_aggregated_dataset(**kwargs) test_raw_assets = test_assets test_assets = read_dataset(test_dataset_aggregate, **kwargs) test_fassembler = FeatureAssembler( feature_dict=feature_param.feature_dict, feature_option_dict=None, assets=test_assets, logger=logger, fifo_mode=fifo_mode, delete_workdir=True, result_store=result_store, optional_dict=None, optional_dict2=None, parallelize=True, ) test_fassembler.run() test_features = test_fassembler.results for result in test_features: result.set_score_aggregate_method(aggregate_method) test_xs = model_class.get_xs_from_results(test_features) test_ys = model_class.get_ys_from_results(test_features) test_ys_pred = VmafQualityRunner.predict_with_model(model, test_xs, **kwargs)['ys_pred'] raw_groundtruths = None if test_raw_assets is None else \ list(map(lambda asset: asset.raw_groundtruth, test_raw_assets)) test_stats = model.get_stats(test_ys['label'], test_ys_pred, ys_label_raw=raw_groundtruths) log = 'Stats on testing data: {}'.format(model_class.format_stats_for_print(test_stats)) if logger: logger.info(log) else: print(log) if test_ax is not None: test_content_ids = list(map(lambda asset: asset.content_id, test_assets)) model_class.plot_scatter(test_ax, test_stats, content_ids=test_content_ids) test_ax.set_xlabel('True Score') test_ax.set_ylabel("Predicted Score") test_ax.grid() test_ax.set_title("Dataset: {dataset}, Model: {model}\n{stats}".format( dataset=test_dataset.dataset_name, model=model.model_id, stats=model_class.format_stats_for_plot(test_stats) )) return train_fassembler, train_assets, train_stats, test_fassembler, test_assets, test_stats, model def construct_kfold_list(assets, contentid_groups): # construct cross validation kfold input list content_ids = list(map(lambda asset: asset.content_id, assets)) kfold = [] for curr_content_group in contentid_groups: curr_indices = indices(content_ids, lambda x: x in curr_content_group) kfold.append(curr_indices) return kfold def cv_on_dataset(dataset, feature_param, model_param, ax, result_store, contentid_groups, logger=None, aggregate_method=np.mean): assets = read_dataset(dataset) kfold = construct_kfold_list(assets, contentid_groups) fassembler = FeatureAssembler( feature_dict=feature_param.feature_dict, feature_option_dict=None, assets=assets, logger=logger, delete_workdir=True, result_store=result_store, optional_dict=None, optional_dict2=None, parallelize=True, fifo_mode=True, # parallelize=False, fifo_mode=False, # VQM ) fassembler.run() results = fassembler.results for result in results: result.set_score_aggregate_method(aggregate_method) model_class = TrainTestModel.find_subclass(model_param.model_type) # run nested kfold cv for each combintation cv_output = ModelCrossValidation.run_kfold_cross_validation( model_class, model_param.model_param_dict, results, kfold, logger=logger, ) print('Feature parameters: {}'.format(feature_param.feature_dict)) print('Model type: {}'.format(model_param.model_type)) print('Model parameters: {}'.format(model_param.model_param_dict)) print('Stats: {}'.format(model_class.format_stats_for_print(cv_output['aggr_stats']))) if ax is not None: model_class.plot_scatter(ax, cv_output['aggr_stats'], cv_output['contentids']) ax.set_xlabel('True Score') ax.set_ylabel("Predicted Score") ax.grid() ax.set_title("Dataset: {dataset}, Model: {model},\n{stats}".format( dataset=dataset.dataset_name, model=model_param.model_type, stats=model_class.format_stats_for_plot(cv_output['aggr_stats']) )) return assets, cv_output def run_remove_results_for_dataset(result_store, dataset, executor_class): assets = read_dataset(dataset) executor = executor_class(assets=assets, logger=None, result_store=result_store) executor.remove_results() def run_vmaf_cv(train_dataset_filepath, test_dataset_filepath, param_filepath, output_model_filepath=None, **kwargs): result_store_dir = kwargs['result_store_dir'] if 'result_store_dir' in kwargs else VmafConfig.file_result_store_path() logger = get_stdout_logger() result_store = FileSystemResultStore(result_store_dir) train_dataset = import_python_file(train_dataset_filepath) test_dataset = import_python_file(test_dataset_filepath) if test_dataset_filepath is not None else None param = import_python_file(param_filepath) # === plot scatter === nrows = 1 ncols = 2 fig, axs = plt.subplots(figsize=(5*ncols, 5*nrows), nrows=nrows, ncols=ncols) train_test_vmaf_on_dataset(train_dataset, test_dataset, param, param, axs[0], axs[1], result_store, parallelize=True, logger=None, output_model_filepath=output_model_filepath, **kwargs) if 'xlim' in kwargs: axs[0].set_xlim(kwargs['xlim']) axs[1].set_xlim(kwargs['xlim']) if 'ylim' in kwargs: axs[0].set_ylim(kwargs['ylim']) axs[1].set_ylim(kwargs['ylim']) bbox = {'facecolor':'white', 'alpha':1, 'pad':20} axs[0].annotate('Training Set', xy=(0.1, 0.85), xycoords='axes fraction', bbox=bbox) axs[1].annotate('Testing Set', xy=(0.1, 0.85), xycoords='axes fraction', bbox=bbox) plt.tight_layout() # === clean up === close_logger(logger) def run_vmaf_kfold_cv(dataset_filepath, contentid_groups, param_filepath, aggregate_method, result_store_dir=VmafConfig.file_result_store_path(), ): logger = get_stdout_logger() result_store = FileSystemResultStore(result_store_dir) dataset = import_python_file(dataset_filepath) param = import_python_file(param_filepath) fig, ax = plt.subplots(figsize=(5, 5), nrows=1, ncols=1) cv_on_dataset(dataset, param, param, ax, result_store, contentid_groups, logger, aggregate_method) ax.set_xlim([0, 120]) ax.set_ylim([0, 120]) plt.tight_layout() # === clean up === close_logger(logger) def explain_model_on_dataset(model, test_assets_selected_indexs, test_dataset_filepath, result_store_dir=VmafConfig.file_result_store_path()): def print_assets(test_assets): print('\n'.join(map( lambda tasset: "Asset {i}: {name}".format( i=tasset[0], name=get_file_name_without_extension(tasset[1].dis_path)), enumerate(test_assets) ))) test_dataset = import_python_file(test_dataset_filepath) test_assets = read_dataset(test_dataset) print_assets(test_assets) print("Assets selected for local explanation: {}".format( test_assets_selected_indexs)) result_store = FileSystemResultStore(result_store_dir) test_assets = [test_assets[i] for i in test_assets_selected_indexs] test_fassembler = FeatureAssembler( feature_dict=model.model_dict['feature_dict'], feature_option_dict=None, assets=test_assets, logger=None, fifo_mode=True, delete_workdir=True, result_store=result_store, optional_dict=None, optional_dict2=None, parallelize=True, ) test_fassembler.run() test_feature_results = test_fassembler.results test_xs = model.get_xs_from_results(test_feature_results) test_ys = model.get_ys_from_results(test_feature_results) test_ys_pred = model.predict(test_xs)['ys_label_pred'] explainer = LocalExplainer(neighbor_samples=1000) test_exps = explainer.explain(model, test_xs) explainer.print_explanations(test_exps, assets=test_assets, ys=test_ys, ys_pred=test_ys_pred) explainer.plot_explanations(test_exps, assets=test_assets, ys=test_ys, ys_pred=test_ys_pred) DisplayConfig.show() def generate_dataset_from_raw(raw_dataset_filepath, output_dataset_filepath, **kwargs): if raw_dataset_filepath: from sureal.subjective_model import DmosModel subj_model_class = kwargs['subj_model_class'] if 'subj_model_class' in kwargs else DmosModel content_ids = kwargs['content_ids'] if 'content_ids' in kwargs else None asset_ids = kwargs['asset_ids'] if 'asset_ids' in kwargs else None subjective_model = subj_model_class.from_dataset_file(raw_dataset_filepath, content_ids=content_ids, asset_ids=asset_ids) subjective_model.run_modeling(**kwargs) subjective_model.to_aggregated_dataset_file(output_dataset_filepath, **kwargs) def run_vmaf_cv_from_raw(train_dataset_raw_filepath, test_dataset_raw_filepath, param_filepath, output_model_filepath, **kwargs): if 'train_quality_wh' in kwargs and kwargs['train_quality_wh'] is not None: train_quality_width, train_quality_height = kwargs['train_quality_wh'] else: train_quality_width = None train_quality_height = None if 'test_quality_wh' in kwargs and kwargs['test_quality_wh'] is not None: test_quality_width, test_quality_height = kwargs['test_quality_wh'] else: test_quality_width = None test_quality_height = None if 'train_transform_final' in kwargs and kwargs['train_transform_final'] is not None: train_transform_final = kwargs['train_transform_final'] else: train_transform_final = None if 'test_transform_final' in kwargs and kwargs['test_transform_final'] is not None: test_transform_final = kwargs['test_transform_final'] else: test_transform_final = None workspace_path = kwargs['workspace_path'] if 'workspace_path' in kwargs else VmafConfig.workspace_path() train_output_dataset_filepath = os.path.join(workspace_path, 'dataset', 'train_dataset.py') generate_dataset_from_raw(raw_dataset_filepath=train_dataset_raw_filepath, output_dataset_filepath=train_output_dataset_filepath, quality_width=train_quality_width, quality_height=train_quality_height, transform_final=train_transform_final, **kwargs) test_output_dataset_filepath = os.path.join(workspace_path, 'dataset', 'test_dataset.py') \ if test_dataset_raw_filepath is not None else None generate_dataset_from_raw(raw_dataset_filepath=test_dataset_raw_filepath, output_dataset_filepath=test_output_dataset_filepath, quality_width=test_quality_width, quality_height=test_quality_height, transform_final=test_transform_final, **kwargs) run_vmaf_cv( train_dataset_filepath=train_output_dataset_filepath, test_dataset_filepath=test_output_dataset_filepath, param_filepath=param_filepath, output_model_filepath=output_model_filepath, **kwargs )
[ "vmaf.core.train_test_model.TrainTestModel.find_subclass", "vmaf.core.quality_runner.VmafQualityRunner.predict_with_model", "numpy.array", "vmaf.core.local_explainer.LocalExplainer", "vmaf.config.VmafConfig.file_result_store_path", "vmaf.config.VmafConfig.workspace_path", "vmaf.plt.subplots", "vmaf.core.feature_assembler.FeatureAssembler", "vmaf.core.cross_validation.ModelCrossValidation.run_kfold_cross_validation", "vmaf.config.DisplayConfig.show", "vmaf.tools.misc.get_stdout_logger", "numpy.shape", "vmaf.tools.misc.import_python_file", "vmaf.core.quality_runner.VmafQualityRunner.set_clip_score", "vmaf.core.asset.Asset", "vmaf.plt.tight_layout", "vmaf.tools.misc.close_logger", "vmaf.core.result_store.FileSystemResultStore", "os.path.join", "vmaf.config.VmafConfig.workdir_path", "vmaf.core.quality_runner.VmafQualityRunner.set_transform_score", "vmaf.tools.misc.get_file_name_without_extension", "vmaf.tools.misc.indices" ]
[((19415, 19682), 'vmaf.core.feature_assembler.FeatureAssembler', 'FeatureAssembler', ([], {'feature_dict': 'feature_param.feature_dict', 'feature_option_dict': 'None', 'assets': 'train_assets', 'logger': 'logger', 'fifo_mode': 'fifo_mode', 'delete_workdir': '(True)', 'result_store': 'result_store', 'optional_dict': 'None', 'optional_dict2': 'None', 'parallelize': 'parallelize'}), '(feature_dict=feature_param.feature_dict,\n feature_option_dict=None, assets=train_assets, logger=logger, fifo_mode\n =fifo_mode, delete_workdir=True, result_store=result_store,\n optional_dict=None, optional_dict2=None, parallelize=parallelize)\n', (19431, 19682), False, 'from vmaf.core.feature_assembler import FeatureAssembler\n'), ((20037, 20077), 'vmaf.core.train_test_model.TrainTestModel.find_subclass', 'TrainTestModel.find_subclass', (['model_type'], {}), '(model_type)\n', (20065, 20077), False, 'from vmaf.core.train_test_model import TrainTestModel, RegressorMixin, ClassifierMixin\n'), ((25696, 25946), 'vmaf.core.feature_assembler.FeatureAssembler', 'FeatureAssembler', ([], {'feature_dict': 'feature_param.feature_dict', 'feature_option_dict': 'None', 'assets': 'assets', 'logger': 'logger', 'delete_workdir': '(True)', 'result_store': 'result_store', 'optional_dict': 'None', 'optional_dict2': 'None', 'parallelize': '(True)', 'fifo_mode': '(True)'}), '(feature_dict=feature_param.feature_dict,\n feature_option_dict=None, assets=assets, logger=logger, delete_workdir=\n True, result_store=result_store, optional_dict=None, optional_dict2=\n None, parallelize=True, fifo_mode=True)\n', (25712, 25946), False, 'from vmaf.core.feature_assembler import FeatureAssembler\n'), ((26225, 26277), 'vmaf.core.train_test_model.TrainTestModel.find_subclass', 'TrainTestModel.find_subclass', (['model_param.model_type'], {}), '(model_param.model_type)\n', (26253, 26277), False, 'from vmaf.core.train_test_model import TrainTestModel, RegressorMixin, ClassifierMixin\n'), ((26342, 26468), 'vmaf.core.cross_validation.ModelCrossValidation.run_kfold_cross_validation', 'ModelCrossValidation.run_kfold_cross_validation', (['model_class', 'model_param.model_param_dict', 'results', 'kfold'], {'logger': 'logger'}), '(model_class, model_param.\n model_param_dict, results, kfold, logger=logger)\n', (26389, 26468), False, 'from vmaf.core.cross_validation import ModelCrossValidation\n'), ((27837, 27856), 'vmaf.tools.misc.get_stdout_logger', 'get_stdout_logger', ([], {}), '()\n', (27854, 27856), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((27876, 27915), 'vmaf.core.result_store.FileSystemResultStore', 'FileSystemResultStore', (['result_store_dir'], {}), '(result_store_dir)\n', (27897, 27915), False, 'from vmaf.core.result_store import FileSystemResultStore\n'), ((27937, 27979), 'vmaf.tools.misc.import_python_file', 'import_python_file', (['train_dataset_filepath'], {}), '(train_dataset_filepath)\n', (27955, 27979), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((28101, 28135), 'vmaf.tools.misc.import_python_file', 'import_python_file', (['param_filepath'], {}), '(param_filepath)\n', (28119, 28135), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((28208, 28278), 'vmaf.plt.subplots', 'plt.subplots', ([], {'figsize': '(5 * ncols, 5 * nrows)', 'nrows': 'nrows', 'ncols': 'ncols'}), '(figsize=(5 * ncols, 5 * nrows), nrows=nrows, ncols=ncols)\n', (28220, 28278), False, 'from vmaf import plt\n'), ((29008, 29026), 'vmaf.plt.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (29024, 29026), False, 'from vmaf import plt\n'), ((29055, 29075), 'vmaf.tools.misc.close_logger', 'close_logger', (['logger'], {}), '(logger)\n', (29067, 29075), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((29275, 29310), 'vmaf.config.VmafConfig.file_result_store_path', 'VmafConfig.file_result_store_path', ([], {}), '()\n', (29308, 29310), False, 'from vmaf.config import VmafConfig, DisplayConfig\n'), ((29351, 29370), 'vmaf.tools.misc.get_stdout_logger', 'get_stdout_logger', ([], {}), '()\n', (29368, 29370), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((29390, 29429), 'vmaf.core.result_store.FileSystemResultStore', 'FileSystemResultStore', (['result_store_dir'], {}), '(result_store_dir)\n', (29411, 29429), False, 'from vmaf.core.result_store import FileSystemResultStore\n'), ((29444, 29480), 'vmaf.tools.misc.import_python_file', 'import_python_file', (['dataset_filepath'], {}), '(dataset_filepath)\n', (29462, 29480), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((29493, 29527), 'vmaf.tools.misc.import_python_file', 'import_python_file', (['param_filepath'], {}), '(param_filepath)\n', (29511, 29527), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((29543, 29589), 'vmaf.plt.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)', 'nrows': '(1)', 'ncols': '(1)'}), '(figsize=(5, 5), nrows=1, ncols=1)\n', (29555, 29589), False, 'from vmaf import plt\n'), ((29769, 29787), 'vmaf.plt.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (29785, 29787), False, 'from vmaf import plt\n'), ((29816, 29836), 'vmaf.tools.misc.close_logger', 'close_logger', (['logger'], {}), '(logger)\n', (29828, 29836), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((30002, 30037), 'vmaf.config.VmafConfig.file_result_store_path', 'VmafConfig.file_result_store_path', ([], {}), '()\n', (30035, 30037), False, 'from vmaf.config import VmafConfig, DisplayConfig\n'), ((30315, 30356), 'vmaf.tools.misc.import_python_file', 'import_python_file', (['test_dataset_filepath'], {}), '(test_dataset_filepath)\n', (30333, 30356), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((30551, 30590), 'vmaf.core.result_store.FileSystemResultStore', 'FileSystemResultStore', (['result_store_dir'], {}), '(result_store_dir)\n', (30572, 30590), False, 'from vmaf.core.result_store import FileSystemResultStore\n'), ((30685, 30944), 'vmaf.core.feature_assembler.FeatureAssembler', 'FeatureAssembler', ([], {'feature_dict': "model.model_dict['feature_dict']", 'feature_option_dict': 'None', 'assets': 'test_assets', 'logger': 'None', 'fifo_mode': '(True)', 'delete_workdir': '(True)', 'result_store': 'result_store', 'optional_dict': 'None', 'optional_dict2': 'None', 'parallelize': '(True)'}), "(feature_dict=model.model_dict['feature_dict'],\n feature_option_dict=None, assets=test_assets, logger=None, fifo_mode=\n True, delete_workdir=True, result_store=result_store, optional_dict=\n None, optional_dict2=None, parallelize=True)\n", (30701, 30944), False, 'from vmaf.core.feature_assembler import FeatureAssembler\n'), ((31294, 31331), 'vmaf.core.local_explainer.LocalExplainer', 'LocalExplainer', ([], {'neighbor_samples': '(1000)'}), '(neighbor_samples=1000)\n', (31308, 31331), False, 'from vmaf.core.local_explainer import LocalExplainer\n'), ((31582, 31602), 'vmaf.config.DisplayConfig.show', 'DisplayConfig.show', ([], {}), '()\n', (31600, 31602), False, 'from vmaf.config import VmafConfig, DisplayConfig\n'), ((33594, 33653), 'os.path.join', 'os.path.join', (['workspace_path', '"""dataset"""', '"""train_dataset.py"""'], {}), "(workspace_path, 'dataset', 'train_dataset.py')\n", (33606, 33653), False, 'import os\n'), ((1210, 1235), 'vmaf.config.VmafConfig.workdir_path', 'VmafConfig.workdir_path', ([], {}), '()\n', (1233, 1235), False, 'from vmaf.config import VmafConfig, DisplayConfig\n'), ((20588, 20659), 'vmaf.core.quality_runner.VmafQualityRunner.set_clip_score', 'VmafQualityRunner.set_clip_score', (['model', "model_param_dict['score_clip']"], {}), "(model, model_param_dict['score_clip'])\n", (20620, 20659), False, 'from vmaf.core.quality_runner import VmafQualityRunner\n'), ((20714, 20800), 'vmaf.core.quality_runner.VmafQualityRunner.set_transform_score', 'VmafQualityRunner.set_transform_score', (['model', "model_param_dict['score_transform']"], {}), "(model, model_param_dict[\n 'score_transform'])\n", (20751, 20800), False, 'from vmaf.core.quality_runner import VmafQualityRunner\n'), ((20817, 20880), 'vmaf.core.quality_runner.VmafQualityRunner.predict_with_model', 'VmafQualityRunner.predict_with_model', (['model', 'train_xs'], {}), '(model, train_xs, **kwargs)\n', (20853, 20880), False, 'from vmaf.core.quality_runner import VmafQualityRunner\n'), ((23162, 23421), 'vmaf.core.feature_assembler.FeatureAssembler', 'FeatureAssembler', ([], {'feature_dict': 'feature_param.feature_dict', 'feature_option_dict': 'None', 'assets': 'test_assets', 'logger': 'logger', 'fifo_mode': 'fifo_mode', 'delete_workdir': '(True)', 'result_store': 'result_store', 'optional_dict': 'None', 'optional_dict2': 'None', 'parallelize': '(True)'}), '(feature_dict=feature_param.feature_dict,\n feature_option_dict=None, assets=test_assets, logger=logger, fifo_mode=\n fifo_mode, delete_workdir=True, result_store=result_store,\n optional_dict=None, optional_dict2=None, parallelize=True)\n', (23178, 23421), False, 'from vmaf.core.feature_assembler import FeatureAssembler\n'), ((25324, 25379), 'vmaf.tools.misc.indices', 'indices', (['content_ids', '(lambda x: x in curr_content_group)'], {}), '(content_ids, lambda x: x in curr_content_group)\n', (25331, 25379), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((27787, 27822), 'vmaf.config.VmafConfig.file_result_store_path', 'VmafConfig.file_result_store_path', ([], {}), '()\n', (27820, 27822), False, 'from vmaf.config import VmafConfig, DisplayConfig\n'), ((27999, 28040), 'vmaf.tools.misc.import_python_file', 'import_python_file', (['test_dataset_filepath'], {}), '(test_dataset_filepath)\n', (28017, 28040), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((33529, 33556), 'vmaf.config.VmafConfig.workspace_path', 'VmafConfig.workspace_path', ([], {}), '()\n', (33554, 33556), False, 'from vmaf.config import VmafConfig, DisplayConfig\n'), ((34050, 34108), 'os.path.join', 'os.path.join', (['workspace_path', '"""dataset"""', '"""test_dataset.py"""'], {}), "(workspace_path, 'dataset', 'test_dataset.py')\n", (34062, 34108), False, 'import os\n'), ((9667, 9869), 'vmaf.core.asset.Asset', 'Asset', ([], {'dataset': 'data_set_name', 'content_id': "dis_video['content_id']", 'asset_id': "dis_video['asset_id']", 'workdir_root': 'workdir_root', 'ref_path': 'ref_path', 'dis_path': "dis_video['path']", 'asset_dict': 'asset_dict'}), "(dataset=data_set_name, content_id=dis_video['content_id'], asset_id=\n dis_video['asset_id'], workdir_root=workdir_root, ref_path=ref_path,\n dis_path=dis_video['path'], asset_dict=asset_dict)\n", (9672, 9869), False, 'from vmaf.core.asset import Asset\n'), ((14458, 14490), 'numpy.shape', 'np.shape', (['predictions_all_models'], {}), '(predictions_all_models)\n', (14466, 14490), True, 'import numpy as np\n'), ((23875, 23937), 'vmaf.core.quality_runner.VmafQualityRunner.predict_with_model', 'VmafQualityRunner.predict_with_model', (['model', 'test_xs'], {}), '(model, test_xs, **kwargs)\n', (23911, 23937), False, 'from vmaf.core.quality_runner import VmafQualityRunner\n'), ((14393, 14425), 'numpy.array', 'np.array', (['predictions_all_models'], {}), '(predictions_all_models)\n', (14401, 14425), True, 'import numpy as np\n'), ((16811, 16858), 'vmaf.tools.misc.get_file_name_without_extension', 'get_file_name_without_extension', (['asset.dis_path'], {}), '(asset.dis_path)\n', (16842, 16858), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n'), ((30194, 30245), 'vmaf.tools.misc.get_file_name_without_extension', 'get_file_name_without_extension', (['tasset[1].dis_path'], {}), '(tasset[1].dis_path)\n', (30225, 30245), False, 'from vmaf.tools.misc import indices, get_stdout_logger, import_python_file, close_logger, get_file_name_without_extension\n')]
# Copyright (c) 2018 PaddlePaddle Authors. 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. from __future__ import print_function import os import unittest import paddle.fluid as fluid import paddle.fluid.core as core from paddle.fluid.dygraph.nn import Embedding, Linear import paddle.fluid.framework as framework from paddle.fluid.optimizer import Adam from paddle.fluid.dygraph.base import to_variable from paddle.fluid.dygraph.learning_rate_scheduler import LearningRateDecay from test_imperative_base import new_program_scope import numpy as np import six class SimpleLSTMRNN(fluid.Layer): def __init__(self, hidden_size, num_steps, num_layers=2, init_scale=0.1, dropout=None): super(SimpleLSTMRNN, self).__init__() self._hidden_size = hidden_size self._num_layers = num_layers self._init_scale = init_scale self._dropout = dropout self._input = None self._num_steps = num_steps self.cell_array = [] self.hidden_array = [] self.weight_1_arr = [] self.weight_2_arr = [] self.bias_arr = [] self.mask_array = [] for i in range(self._num_layers): weight_1 = self.create_parameter( attr=fluid.ParamAttr( initializer=fluid.initializer.UniformInitializer( low=-self._init_scale, high=self._init_scale)), shape=[self._hidden_size * 2, self._hidden_size * 4], dtype="float32", default_initializer=fluid.initializer.UniformInitializer( low=-self._init_scale, high=self._init_scale)) self.weight_1_arr.append(self.add_parameter('w_%d' % i, weight_1)) bias_1 = self.create_parameter( attr=fluid.ParamAttr( initializer=fluid.initializer.UniformInitializer( low=-self._init_scale, high=self._init_scale)), shape=[self._hidden_size * 4], dtype="float32", default_initializer=fluid.initializer.Constant(0.0)) self.bias_arr.append(self.add_parameter('b_%d' % i, bias_1)) def forward(self, input_embedding, init_hidden=None, init_cell=None): self.cell_array = [] self.hidden_array = [] for i in range(self._num_layers): pre_hidden = fluid.layers.slice( init_hidden, axes=[0], starts=[i], ends=[i + 1]) pre_cell = fluid.layers.slice( init_cell, axes=[0], starts=[i], ends=[i + 1]) pre_hidden = fluid.layers.reshape( pre_hidden, shape=[-1, self._hidden_size]) pre_cell = fluid.layers.reshape( pre_cell, shape=[-1, self._hidden_size]) self.hidden_array.append(pre_hidden) self.cell_array.append(pre_cell) res = [] for index in range(self._num_steps): self._input = fluid.layers.slice( input_embedding, axes=[1], starts=[index], ends=[index + 1]) self._input = fluid.layers.reshape( self._input, shape=[-1, self._hidden_size]) for k in range(self._num_layers): pre_hidden = self.hidden_array[k] pre_cell = self.cell_array[k] weight_1 = self.weight_1_arr[k] bias = self.bias_arr[k] nn = fluid.layers.concat([self._input, pre_hidden], 1) gate_input = fluid.layers.matmul(x=nn, y=weight_1) gate_input = fluid.layers.elementwise_add(gate_input, bias) i, j, f, o = fluid.layers.split( gate_input, num_or_sections=4, dim=-1) c = pre_cell * fluid.layers.sigmoid(f) + fluid.layers.sigmoid( i) * fluid.layers.tanh(j) m = fluid.layers.tanh(c) * fluid.layers.sigmoid(o) self.hidden_array[k] = m self.cell_array[k] = c self._input = m if self._dropout is not None and self._dropout > 0.0: self._input = fluid.layers.dropout( self._input, dropout_prob=self._dropout, dropout_implementation='upscale_in_train') res.append( fluid.layers.reshape( self._input, shape=[1, -1, self._hidden_size])) real_res = fluid.layers.concat(res, 0) real_res = fluid.layers.transpose(x=real_res, perm=[1, 0, 2]) last_hidden = fluid.layers.concat(self.hidden_array, 1) last_hidden = fluid.layers.reshape( last_hidden, shape=[-1, self._num_layers, self._hidden_size]) last_hidden = fluid.layers.transpose(x=last_hidden, perm=[1, 0, 2]) last_cell = fluid.layers.concat(self.cell_array, 1) last_cell = fluid.layers.reshape( last_cell, shape=[-1, self._num_layers, self._hidden_size]) last_cell = fluid.layers.transpose(x=last_cell, perm=[1, 0, 2]) return real_res, last_hidden, last_cell class PtbModel(fluid.Layer): def __init__(self, hidden_size, vocab_size, num_layers=2, num_steps=20, init_scale=0.1, dropout=None): super(PtbModel, self).__init__() self.hidden_size = hidden_size self.vocab_size = vocab_size self.init_scale = init_scale self.num_layers = num_layers self.num_steps = num_steps self.dropout = dropout self.simple_lstm_rnn = SimpleLSTMRNN( hidden_size, num_steps, num_layers=num_layers, init_scale=init_scale, dropout=dropout) self.embedding = Embedding( size=[vocab_size, hidden_size], dtype='float32', is_sparse=False, param_attr=fluid.ParamAttr( name='embedding_para', initializer=fluid.initializer.UniformInitializer( low=-init_scale, high=init_scale))) self.softmax_weight = self.create_parameter( attr=fluid.ParamAttr(), shape=[self.hidden_size, self.vocab_size], dtype="float32", default_initializer=fluid.initializer.UniformInitializer( low=-self.init_scale, high=self.init_scale)) self.softmax_bias = self.create_parameter( attr=fluid.ParamAttr(), shape=[self.vocab_size], dtype="float32", default_initializer=fluid.initializer.UniformInitializer( low=-self.init_scale, high=self.init_scale)) def forward(self, input, label, init_hidden, init_cell): init_h = fluid.layers.reshape( init_hidden, shape=[self.num_layers, -1, self.hidden_size]) init_c = fluid.layers.reshape( init_cell, shape=[self.num_layers, -1, self.hidden_size]) x_emb = self.embedding(input) x_emb = fluid.layers.reshape( x_emb, shape=[-1, self.num_steps, self.hidden_size]) if self.dropout is not None and self.dropout > 0.0: x_emb = fluid.layers.dropout( x_emb, dropout_prob=self.drop_out, dropout_implementation='upscale_in_train') rnn_out, last_hidden, last_cell = self.simple_lstm_rnn(x_emb, init_h, init_c) rnn_out = fluid.layers.reshape( rnn_out, shape=[-1, self.num_steps, self.hidden_size]) projection = fluid.layers.matmul(rnn_out, self.softmax_weight) projection = fluid.layers.elementwise_add(projection, self.softmax_bias) projection = fluid.layers.reshape( projection, shape=[-1, self.vocab_size]) loss = fluid.layers.softmax_with_cross_entropy( logits=projection, label=label, soft_label=False) loss = fluid.layers.reshape(loss, shape=[-1, self.num_steps]) loss = fluid.layers.reduce_mean(loss, dim=[0]) loss = fluid.layers.reduce_sum(loss) return loss, last_hidden, last_cell class TestDygraphPtbRnn(unittest.TestCase): def setUp(self): seed = 90 hidden_size = 10 vocab_size = 1000 num_layers = 1 num_steps = 3 init_scale = 0.1 batch_size = 4 batch_num = 200 with fluid.dygraph.guard(): fluid.default_startup_program().random_seed = seed fluid.default_main_program().random_seed = seed # TODO: marsyang1993 Change seed to ptb_model = PtbModel( hidden_size=hidden_size, vocab_size=vocab_size, num_layers=num_layers, num_steps=num_steps, init_scale=init_scale) bd = [] lr_arr = [1.0] # this a fake lr decay strategy for i in range(1, 10): bd.append(100 * i) new_lr = 1.0 lr_arr.append(new_lr) place = fluid.CPUPlace() if not core.is_compiled_with_cuda( ) else fluid.CUDAPlace(0) adam = Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=bd, values=lr_arr), parameter_list=ptb_model.parameters()) dy_param_updated = dict() dy_param_init = dict() dy_loss = None last_hidden = None last_cell = None for i in range(batch_num): x_data = np.arange(12).reshape(4, 3).astype('int64') y_data = np.arange(1, 13).reshape(4, 3).astype('int64') y_data = y_data.reshape((-1, 1)) init_hidden_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') init_cell_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') x = to_variable(x_data) y = to_variable(y_data) init_hidden = to_variable(init_hidden_data) init_cell = to_variable(init_cell_data) dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden, init_cell) if i == 0: for param in ptb_model.parameters(): dy_param_init[param.name] = param.numpy() dy_loss.backward() adam.minimize(dy_loss) ptb_model.clear_gradients() if i == batch_num - 1: for param in ptb_model.parameters(): dy_param_updated[param.name] = param.numpy() # check optimizer self.opti_dict = adam.state_dict() self.base_opti = {} for k, v in self.opti_dict.items(): self.base_opti[v.name] = v.numpy() self.assertTrue(np.sum(np.abs(v.numpy())) != 0) fluid.save_dygraph(self.opti_dict, "./test_dy") self.state_dict = ptb_model.state_dict() self.model_base = {} for k, v in self.state_dict.items(): np_t = v.numpy() self.model_base[k] = np_t fluid.save_dygraph(self.state_dict, "./test_dy") def testLoadAndSetVarBase(self): seed = 90 hidden_size = 10 vocab_size = 1000 num_layers = 1 num_steps = 3 init_scale = 0.1 batch_size = 4 batch_num = 200 with fluid.dygraph.guard(): fluid.default_startup_program().random_seed = seed fluid.default_main_program().random_seed = seed # TODO: marsyang1993 Change seed to ptb_model = PtbModel( hidden_size=hidden_size, vocab_size=vocab_size, num_layers=num_layers, num_steps=num_steps, init_scale=init_scale) bd = [] lr_arr = [1.0] # this a fake lr decay strategy for i in range(1, 10): bd.append(100 * i) new_lr = 1.0 lr_arr.append(new_lr) place = fluid.CPUPlace() if not core.is_compiled_with_cuda( ) else fluid.CUDAPlace(0) adam = Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=bd, values=lr_arr), parameter_list=ptb_model.parameters()) dy_param_updated = dict() dy_param_init = dict() dy_loss = None last_hidden = None last_cell = None for i in range(batch_num): x_data = np.arange(12).reshape(4, 3).astype('int64') y_data = np.arange(1, 13).reshape(4, 3).astype('int64') y_data = y_data.reshape((-1, 1)) init_hidden_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') init_cell_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') x = to_variable(x_data) y = to_variable(y_data) init_hidden = to_variable(init_hidden_data) init_cell = to_variable(init_cell_data) dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden, init_cell) if i == 0: for param in ptb_model.parameters(): dy_param_init[param.name] = param.numpy() dy_loss.backward() adam.minimize(dy_loss) ptb_model.clear_gradients() if i == batch_num - 1: for param in ptb_model.parameters(): dy_param_updated[param.name] = param.numpy() # check optimizer opti_dict = adam.state_dict() # set to zero for k, v in opti_dict.items(): np_t = v.numpy() var = v.value().get_tensor() var.set(np.zeros_like(np_t), place) self.assertTrue(np.sum(np.abs(v.numpy())) == 0) if isinstance(adam._learning_rate, LearningRateDecay): adam._learning_rate.step_num = 0 para_state_dict, opti_state_dict = fluid.load_dygraph("./test_dy") adam.set_dict(opti_state_dict) opti_dict = adam.state_dict() for k, v in opti_dict.items(): self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name])) # check parameter state_dict = ptb_model.state_dict() for k, v in state_dict.items(): np_t = v.numpy() var = v.value().get_tensor() var.set(np.zeros_like(np_t), place) ptb_model.set_dict(para_state_dict) state_dict = ptb_model.state_dict() for k, v in state_dict.items(): new_t = v.numpy() base_t = self.model_base[k] self.assertTrue(np.array_equal(new_t, base_t)) def testSetVariable(self): seed = 90 hidden_size = 10 vocab_size = 1000 num_layers = 1 num_steps = 3 init_scale = 0.1 batch_size = 4 batch_num = 200 with fluid.dygraph.guard(): fluid.default_startup_program().random_seed = seed fluid.default_main_program().random_seed = seed # TODO: marsyang1993 Change seed to ptb_model = PtbModel( hidden_size=hidden_size, vocab_size=vocab_size, num_layers=num_layers, num_steps=num_steps, init_scale=init_scale) bd = [] lr_arr = [1.0] # this a fake lr decay strategy for i in range(1, 10): bd.append(100 * i) new_lr = 1.0 lr_arr.append(new_lr) place = fluid.CPUPlace() if not core.is_compiled_with_cuda( ) else fluid.CUDAPlace(0) adam = Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=bd, values=lr_arr), parameter_list=ptb_model.parameters()) dy_param_updated = dict() dy_param_init = dict() dy_loss = None last_hidden = None last_cell = None for i in range(batch_num): x_data = np.arange(12).reshape(4, 3).astype('int64') y_data = np.arange(1, 13).reshape(4, 3).astype('int64') y_data = y_data.reshape((-1, 1)) init_hidden_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') init_cell_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') x = to_variable(x_data) y = to_variable(y_data) init_hidden = to_variable(init_hidden_data) init_cell = to_variable(init_cell_data) dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden, init_cell) if i == 0: for param in ptb_model.parameters(): dy_param_init[param.name] = param.numpy() dy_loss.backward() adam.minimize(dy_loss) ptb_model.clear_gradients() if i == batch_num - 1: for param in ptb_model.parameters(): dy_param_updated[param.name] = param.numpy() # check optimizer opti_dict = adam.state_dict() # set to zero for k, v in opti_dict.items(): np_t = v.numpy() var = v.value().get_tensor() var.set(np.zeros_like(np_t), place) self.assertTrue(np.sum(np.abs(v.numpy())) == 0) if isinstance(adam._learning_rate, LearningRateDecay): adam._learning_rate.step_num = 0 adam.set_dict(self.opti_dict) opti_dict = adam.state_dict() for k, v in opti_dict.items(): self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name])) # check parameter state_dict = ptb_model.state_dict() for k, v in state_dict.items(): np_t = v.numpy() var = v.value().get_tensor() var.set(np.zeros_like(np_t), place) ptb_model.set_dict(self.state_dict) state_dict = ptb_model.state_dict() for k, v in state_dict.items(): new_t = v.numpy() base_t = self.model_base[k] self.assertTrue(np.array_equal(new_t, base_t)) def testSetNumpy(self): seed = 90 hidden_size = 10 vocab_size = 1000 num_layers = 1 num_steps = 3 init_scale = 0.1 batch_size = 4 batch_num = 200 with fluid.dygraph.guard(): fluid.default_startup_program().random_seed = seed fluid.default_main_program().random_seed = seed # TODO: marsyang1993 Change seed to ptb_model = PtbModel( hidden_size=hidden_size, vocab_size=vocab_size, num_layers=num_layers, num_steps=num_steps, init_scale=init_scale) bd = [] lr_arr = [1.0] # this a fake lr decay strategy for i in range(1, 10): bd.append(100 * i) new_lr = 1.0 lr_arr.append(new_lr) place = fluid.CPUPlace() if not core.is_compiled_with_cuda( ) else fluid.CUDAPlace(0) adam = Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=bd, values=lr_arr), parameter_list=ptb_model.parameters()) dy_param_updated = dict() dy_param_init = dict() dy_loss = None last_hidden = None last_cell = None for i in range(batch_num): x_data = np.arange(12).reshape(4, 3).astype('int64') y_data = np.arange(1, 13).reshape(4, 3).astype('int64') y_data = y_data.reshape((-1, 1)) init_hidden_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') init_cell_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') x = to_variable(x_data) y = to_variable(y_data) init_hidden = to_variable(init_hidden_data) init_cell = to_variable(init_cell_data) dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden, init_cell) if i == 0: for param in ptb_model.parameters(): dy_param_init[param.name] = param.numpy() dy_loss.backward() adam.minimize(dy_loss) ptb_model.clear_gradients() if i == batch_num - 1: for param in ptb_model.parameters(): dy_param_updated[param.name] = param.numpy() # check optimizer opti_dict = adam.state_dict() np_opti_dict = {} # set to zero for k, v in opti_dict.items(): np_t = v.numpy() np_opti_dict[v.name] = np_t var = v.value().get_tensor() var.set(np.zeros_like(np_t), place) self.assertTrue(np.sum(np.abs(v.numpy())) == 0) if isinstance(adam._learning_rate, LearningRateDecay): adam._learning_rate.step_num = 0 adam.set_dict(np_opti_dict) opti_dict = adam.state_dict() for k, v in opti_dict.items(): self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name])) # check parameter state_dict = ptb_model.state_dict() np_state_dict = {} for k, v in state_dict.items(): np_t = v.numpy() np_state_dict[k] = np_t var = v.value().get_tensor() var.set(np.zeros_like(np_t), place) ptb_model.set_dict(np_state_dict) state_dict = ptb_model.state_dict() for k, v in state_dict.items(): new_t = v.numpy() base_t = self.model_base[k] self.assertTrue(np.array_equal(new_t, base_t)) def testSetVariableBeforeTrain(self): seed = 90 hidden_size = 10 vocab_size = 1000 num_layers = 1 num_steps = 3 init_scale = 0.1 batch_size = 4 batch_num = 200 with fluid.dygraph.guard(): fluid.default_startup_program().random_seed = seed fluid.default_main_program().random_seed = seed # TODO: marsyang1993 Change seed to ptb_model = PtbModel( hidden_size=hidden_size, vocab_size=vocab_size, num_layers=num_layers, num_steps=num_steps, init_scale=init_scale) place = fluid.CPUPlace() if not core.is_compiled_with_cuda( ) else fluid.CUDAPlace(0) adam = Adam( learning_rate=0.0, beta1=0.8, beta2=0.6, parameter_list=ptb_model.parameters()) dy_param_updated = dict() dy_param_init = dict() dy_loss = None last_hidden = None last_cell = None adam.set_dict(self.opti_dict) ptb_model.set_dict(self.state_dict) for i in range(1): x_data = np.arange(12).reshape(4, 3).astype('int64') y_data = np.arange(1, 13).reshape(4, 3).astype('int64') y_data = y_data.reshape((-1, 1)) init_hidden_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') init_cell_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') x = to_variable(x_data) y = to_variable(y_data) init_hidden = to_variable(init_hidden_data) init_cell = to_variable(init_cell_data) dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden, init_cell) dy_loss.backward() adam.minimize(dy_loss) ptb_model.clear_gradients() opti_dict = adam.state_dict() for k, v in opti_dict.items(): if k == "global_step": self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] + 1)) if k.find("beta1_pow_acc_0") > 0: self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] * adam._beta1)) if k.find("beta2_pow_acc_0") > 0: self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] * adam._beta2)) state_dict = ptb_model.state_dict() for k, v in state_dict.items(): new_t = v.numpy() base_t = self.model_base[k] self.assertTrue(np.array_equal(new_t, base_t)) def testLoadAndSetVarBaseBeforeTrain(self): seed = 90 hidden_size = 10 vocab_size = 1000 num_layers = 1 num_steps = 3 init_scale = 0.1 batch_size = 4 batch_num = 200 with fluid.dygraph.guard(): fluid.default_startup_program().random_seed = seed fluid.default_main_program().random_seed = seed # TODO: marsyang1993 Change seed to ptb_model = PtbModel( hidden_size=hidden_size, vocab_size=vocab_size, num_layers=num_layers, num_steps=num_steps, init_scale=init_scale) bd = [] lr_arr = [0.0] # this a fake lr decay strategy for i in range(1, 10): bd.append(100 * i) # set lr to zero not update parameter new_lr = 0.0 lr_arr.append(new_lr) place = fluid.CPUPlace() if not core.is_compiled_with_cuda( ) else fluid.CUDAPlace(0) adam = Adam( learning_rate=0.0, beta1=0.8, beta2=0.6, parameter_list=ptb_model.parameters()) dy_param_updated = dict() dy_param_init = dict() dy_loss = None last_hidden = None last_cell = None state_dict, opti_dict = fluid.load_dygraph("./test_dy") adam.set_dict(opti_dict) ptb_model.set_dict(state_dict) for i in range(1): x_data = np.arange(12).reshape(4, 3).astype('int64') y_data = np.arange(1, 13).reshape(4, 3).astype('int64') y_data = y_data.reshape((-1, 1)) init_hidden_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') init_cell_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') x = to_variable(x_data) y = to_variable(y_data) init_hidden = to_variable(init_hidden_data) init_cell = to_variable(init_cell_data) dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden, init_cell) dy_loss.backward() adam.minimize(dy_loss) ptb_model.clear_gradients() opti_dict = adam.state_dict() for k, v in opti_dict.items(): if k == "global_step": self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] + 1)) if k.find("beta1_pow_acc_0") > 0: self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] * adam._beta1)) if k.find("beta2_pow_acc_0") > 0: self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] * adam._beta2)) # check parameter state_dict = ptb_model.state_dict() for k, v in state_dict.items(): new_t = v.numpy() base_t = self.model_base[k] self.assertTrue(np.array_equal(new_t, base_t)) def testSetNumpyBeforeTrain(self): seed = 90 hidden_size = 10 vocab_size = 1000 num_layers = 1 num_steps = 3 init_scale = 0.1 batch_size = 4 batch_num = 200 with fluid.dygraph.guard(): fluid.default_startup_program().random_seed = seed fluid.default_main_program().random_seed = seed # TODO: marsyang1993 Change seed to ptb_model = PtbModel( hidden_size=hidden_size, vocab_size=vocab_size, num_layers=num_layers, num_steps=num_steps, init_scale=init_scale) bd = [] lr_arr = [0.0] # this a fake lr decay strategy for i in range(1, 10): bd.append(100 * i) # set lr to 0.0, not update parameter new_lr = 0.0 lr_arr.append(new_lr) place = fluid.CPUPlace() if not core.is_compiled_with_cuda( ) else fluid.CUDAPlace(0) adam = Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=bd, values=lr_arr), beta1=0.8, beta2=0.6, parameter_list=ptb_model.parameters()) dy_param_updated = dict() dy_param_init = dict() dy_loss = None last_hidden = None last_cell = None np_opti_dict = {} np_state_dict = {} for k, v in self.opti_dict.items(): np_opti_dict[v.name] = v.numpy() for k, v in self.state_dict.items(): np_state_dict[k] = v.numpy() adam.set_dict(np_opti_dict) ptb_model.set_dict(np_state_dict) for i in range(1): x_data = np.arange(12).reshape(4, 3).astype('int64') y_data = np.arange(1, 13).reshape(4, 3).astype('int64') y_data = y_data.reshape((-1, 1)) init_hidden_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') init_cell_data = np.zeros( (num_layers, batch_size, hidden_size), dtype='float32') x = to_variable(x_data) y = to_variable(y_data) init_hidden = to_variable(init_hidden_data) init_cell = to_variable(init_cell_data) dy_loss, last_hidden, last_cell = ptb_model(x, y, init_hidden, init_cell) dy_loss.backward() adam.minimize(dy_loss) ptb_model.clear_gradients() opti_dict = adam.state_dict() for k, v in opti_dict.items(): if k == "global_step": self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] + 1)) if k.find("beta1_pow_acc_0") > 0: self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] * adam._beta1)) if k.find("beta2_pow_acc_0") > 0: self.assertTrue( np.array_equal(v.numpy(), self.base_opti[v.name] * adam._beta2)) # check parameter state_dict = ptb_model.state_dict() for k, v in state_dict.items(): new_t = v.numpy() base_t = self.model_base[k] self.assertTrue(np.array_equal(new_t, base_t)) def testOnlyLoadParams(self): with fluid.dygraph.guard(): emb = fluid.dygraph.Embedding([10, 10]) state_dict = emb.state_dict() fluid.save_dygraph(state_dict, os.path.join('saved_dy', 'emb_dy')) para_state_dict, opti_state_dict = fluid.load_dygraph( os.path.join('saved_dy', 'emb_dy')) self.assertTrue(opti_state_dict == None) if __name__ == '__main__': unittest.main()
[ "paddle.fluid.dygraph.guard", "paddle.fluid.dygraph.Embedding", "paddle.fluid.layers.split", "paddle.fluid.layers.piecewise_decay", "unittest.main", "paddle.fluid.layers.transpose", "paddle.fluid.layers.matmul", "numpy.arange", "paddle.fluid.layers.reshape", "paddle.fluid.save_dygraph", "paddle.fluid.layers.reduce_mean", "paddle.fluid.layers.tanh", "paddle.fluid.default_startup_program", "paddle.fluid.layers.reduce_sum", "paddle.fluid.default_main_program", "paddle.fluid.core.is_compiled_with_cuda", "paddle.fluid.layers.elementwise_add", "paddle.fluid.ParamAttr", "paddle.fluid.load_dygraph", "paddle.fluid.dygraph.base.to_variable", "paddle.fluid.layers.dropout", "paddle.fluid.CPUPlace", "paddle.fluid.layers.sigmoid", "paddle.fluid.layers.softmax_with_cross_entropy", "paddle.fluid.layers.concat", "paddle.fluid.layers.slice", "os.path.join", "paddle.fluid.initializer.Constant", "paddle.fluid.initializer.UniformInitializer", "numpy.zeros", "numpy.array_equal", "paddle.fluid.CUDAPlace", "numpy.zeros_like" ]
[((34298, 34313), 'unittest.main', 'unittest.main', ([], {}), '()\n', (34311, 34313), False, 'import unittest\n'), ((5049, 5076), 'paddle.fluid.layers.concat', 'fluid.layers.concat', (['res', '(0)'], {}), '(res, 0)\n', (5068, 5076), True, 'import paddle.fluid as fluid\n'), ((5096, 5146), 'paddle.fluid.layers.transpose', 'fluid.layers.transpose', ([], {'x': 'real_res', 'perm': '[1, 0, 2]'}), '(x=real_res, perm=[1, 0, 2])\n', (5118, 5146), True, 'import paddle.fluid as fluid\n'), ((5169, 5210), 'paddle.fluid.layers.concat', 'fluid.layers.concat', (['self.hidden_array', '(1)'], {}), '(self.hidden_array, 1)\n', (5188, 5210), True, 'import paddle.fluid as fluid\n'), ((5233, 5320), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['last_hidden'], {'shape': '[-1, self._num_layers, self._hidden_size]'}), '(last_hidden, shape=[-1, self._num_layers, self.\n _hidden_size])\n', (5253, 5320), True, 'import paddle.fluid as fluid\n'), ((5351, 5404), 'paddle.fluid.layers.transpose', 'fluid.layers.transpose', ([], {'x': 'last_hidden', 'perm': '[1, 0, 2]'}), '(x=last_hidden, perm=[1, 0, 2])\n', (5373, 5404), True, 'import paddle.fluid as fluid\n'), ((5425, 5464), 'paddle.fluid.layers.concat', 'fluid.layers.concat', (['self.cell_array', '(1)'], {}), '(self.cell_array, 1)\n', (5444, 5464), True, 'import paddle.fluid as fluid\n'), ((5485, 5570), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['last_cell'], {'shape': '[-1, self._num_layers, self._hidden_size]'}), '(last_cell, shape=[-1, self._num_layers, self._hidden_size]\n )\n', (5505, 5570), True, 'import paddle.fluid as fluid\n'), ((5599, 5650), 'paddle.fluid.layers.transpose', 'fluid.layers.transpose', ([], {'x': 'last_cell', 'perm': '[1, 0, 2]'}), '(x=last_cell, perm=[1, 0, 2])\n', (5621, 5650), True, 'import paddle.fluid as fluid\n'), ((7396, 7481), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['init_hidden'], {'shape': '[self.num_layers, -1, self.hidden_size]'}), '(init_hidden, shape=[self.num_layers, -1, self.hidden_size]\n )\n', (7416, 7481), True, 'import paddle.fluid as fluid\n'), ((7508, 7586), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['init_cell'], {'shape': '[self.num_layers, -1, self.hidden_size]'}), '(init_cell, shape=[self.num_layers, -1, self.hidden_size])\n', (7528, 7586), True, 'import paddle.fluid as fluid\n'), ((7655, 7728), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['x_emb'], {'shape': '[-1, self.num_steps, self.hidden_size]'}), '(x_emb, shape=[-1, self.num_steps, self.hidden_size])\n', (7675, 7728), True, 'import paddle.fluid as fluid\n'), ((8137, 8212), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['rnn_out'], {'shape': '[-1, self.num_steps, self.hidden_size]'}), '(rnn_out, shape=[-1, self.num_steps, self.hidden_size])\n', (8157, 8212), True, 'import paddle.fluid as fluid\n'), ((8248, 8297), 'paddle.fluid.layers.matmul', 'fluid.layers.matmul', (['rnn_out', 'self.softmax_weight'], {}), '(rnn_out, self.softmax_weight)\n', (8267, 8297), True, 'import paddle.fluid as fluid\n'), ((8319, 8378), 'paddle.fluid.layers.elementwise_add', 'fluid.layers.elementwise_add', (['projection', 'self.softmax_bias'], {}), '(projection, self.softmax_bias)\n', (8347, 8378), True, 'import paddle.fluid as fluid\n'), ((8400, 8461), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['projection'], {'shape': '[-1, self.vocab_size]'}), '(projection, shape=[-1, self.vocab_size])\n', (8420, 8461), True, 'import paddle.fluid as fluid\n'), ((8490, 8583), 'paddle.fluid.layers.softmax_with_cross_entropy', 'fluid.layers.softmax_with_cross_entropy', ([], {'logits': 'projection', 'label': 'label', 'soft_label': '(False)'}), '(logits=projection, label=label,\n soft_label=False)\n', (8529, 8583), True, 'import paddle.fluid as fluid\n'), ((8608, 8662), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['loss'], {'shape': '[-1, self.num_steps]'}), '(loss, shape=[-1, self.num_steps])\n', (8628, 8662), True, 'import paddle.fluid as fluid\n'), ((8678, 8717), 'paddle.fluid.layers.reduce_mean', 'fluid.layers.reduce_mean', (['loss'], {'dim': '[0]'}), '(loss, dim=[0])\n', (8702, 8717), True, 'import paddle.fluid as fluid\n'), ((8733, 8762), 'paddle.fluid.layers.reduce_sum', 'fluid.layers.reduce_sum', (['loss'], {}), '(loss)\n', (8756, 8762), True, 'import paddle.fluid as fluid\n'), ((2972, 3039), 'paddle.fluid.layers.slice', 'fluid.layers.slice', (['init_hidden'], {'axes': '[0]', 'starts': '[i]', 'ends': '[i + 1]'}), '(init_hidden, axes=[0], starts=[i], ends=[i + 1])\n', (2990, 3039), True, 'import paddle.fluid as fluid\n'), ((3080, 3145), 'paddle.fluid.layers.slice', 'fluid.layers.slice', (['init_cell'], {'axes': '[0]', 'starts': '[i]', 'ends': '[i + 1]'}), '(init_cell, axes=[0], starts=[i], ends=[i + 1])\n', (3098, 3145), True, 'import paddle.fluid as fluid\n'), ((3188, 3251), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['pre_hidden'], {'shape': '[-1, self._hidden_size]'}), '(pre_hidden, shape=[-1, self._hidden_size])\n', (3208, 3251), True, 'import paddle.fluid as fluid\n'), ((3292, 3353), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['pre_cell'], {'shape': '[-1, self._hidden_size]'}), '(pre_cell, shape=[-1, self._hidden_size])\n', (3312, 3353), True, 'import paddle.fluid as fluid\n'), ((3554, 3633), 'paddle.fluid.layers.slice', 'fluid.layers.slice', (['input_embedding'], {'axes': '[1]', 'starts': '[index]', 'ends': '[index + 1]'}), '(input_embedding, axes=[1], starts=[index], ends=[index + 1])\n', (3572, 3633), True, 'import paddle.fluid as fluid\n'), ((3677, 3741), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['self._input'], {'shape': '[-1, self._hidden_size]'}), '(self._input, shape=[-1, self._hidden_size])\n', (3697, 3741), True, 'import paddle.fluid as fluid\n'), ((7822, 7924), 'paddle.fluid.layers.dropout', 'fluid.layers.dropout', (['x_emb'], {'dropout_prob': 'self.drop_out', 'dropout_implementation': '"""upscale_in_train"""'}), "(x_emb, dropout_prob=self.drop_out,\n dropout_implementation='upscale_in_train')\n", (7842, 7924), True, 'import paddle.fluid as fluid\n'), ((9075, 9096), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (9094, 9096), True, 'import paddle.fluid as fluid\n'), ((11724, 11771), 'paddle.fluid.save_dygraph', 'fluid.save_dygraph', (['self.opti_dict', '"""./test_dy"""'], {}), "(self.opti_dict, './test_dy')\n", (11742, 11771), True, 'import paddle.fluid as fluid\n'), ((11997, 12045), 'paddle.fluid.save_dygraph', 'fluid.save_dygraph', (['self.state_dict', '"""./test_dy"""'], {}), "(self.state_dict, './test_dy')\n", (12015, 12045), True, 'import paddle.fluid as fluid\n'), ((12284, 12305), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (12303, 12305), True, 'import paddle.fluid as fluid\n'), ((15149, 15180), 'paddle.fluid.load_dygraph', 'fluid.load_dygraph', (['"""./test_dy"""'], {}), "('./test_dy')\n", (15167, 15180), True, 'import paddle.fluid as fluid\n'), ((16186, 16207), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (16205, 16207), True, 'import paddle.fluid as fluid\n'), ((20005, 20026), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (20024, 20026), True, 'import paddle.fluid as fluid\n'), ((23979, 24000), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (23998, 24000), True, 'import paddle.fluid as fluid\n'), ((27017, 27038), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (27036, 27038), True, 'import paddle.fluid as fluid\n'), ((28200, 28231), 'paddle.fluid.load_dygraph', 'fluid.load_dygraph', (['"""./test_dy"""'], {}), "('./test_dy')\n", (28218, 28231), True, 'import paddle.fluid as fluid\n'), ((30418, 30439), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (30437, 30439), True, 'import paddle.fluid as fluid\n'), ((33895, 33916), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (33914, 33916), True, 'import paddle.fluid as fluid\n'), ((33936, 33969), 'paddle.fluid.dygraph.Embedding', 'fluid.dygraph.Embedding', (['[10, 10]'], {}), '([10, 10])\n', (33959, 33969), True, 'import paddle.fluid as fluid\n'), ((4011, 4060), 'paddle.fluid.layers.concat', 'fluid.layers.concat', (['[self._input, pre_hidden]', '(1)'], {}), '([self._input, pre_hidden], 1)\n', (4030, 4060), True, 'import paddle.fluid as fluid\n'), ((4090, 4127), 'paddle.fluid.layers.matmul', 'fluid.layers.matmul', ([], {'x': 'nn', 'y': 'weight_1'}), '(x=nn, y=weight_1)\n', (4109, 4127), True, 'import paddle.fluid as fluid\n'), ((4158, 4204), 'paddle.fluid.layers.elementwise_add', 'fluid.layers.elementwise_add', (['gate_input', 'bias'], {}), '(gate_input, bias)\n', (4186, 4204), True, 'import paddle.fluid as fluid\n'), ((4234, 4291), 'paddle.fluid.layers.split', 'fluid.layers.split', (['gate_input'], {'num_or_sections': '(4)', 'dim': '(-1)'}), '(gate_input, num_or_sections=4, dim=-1)\n', (4252, 4291), True, 'import paddle.fluid as fluid\n'), ((4940, 5007), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['self._input'], {'shape': '[1, -1, self._hidden_size]'}), '(self._input, shape=[1, -1, self._hidden_size])\n', (4960, 5007), True, 'import paddle.fluid as fluid\n'), ((6799, 6816), 'paddle.fluid.ParamAttr', 'fluid.ParamAttr', ([], {}), '()\n', (6814, 6816), True, 'import paddle.fluid as fluid\n'), ((6934, 7019), 'paddle.fluid.initializer.UniformInitializer', 'fluid.initializer.UniformInitializer', ([], {'low': '(-self.init_scale)', 'high': 'self.init_scale'}), '(low=-self.init_scale, high=self.init_scale\n )\n', (6970, 7019), True, 'import paddle.fluid as fluid\n'), ((7101, 7118), 'paddle.fluid.ParamAttr', 'fluid.ParamAttr', ([], {}), '()\n', (7116, 7118), True, 'import paddle.fluid as fluid\n'), ((7218, 7303), 'paddle.fluid.initializer.UniformInitializer', 'fluid.initializer.UniformInitializer', ([], {'low': '(-self.init_scale)', 'high': 'self.init_scale'}), '(low=-self.init_scale, high=self.init_scale\n )\n', (7254, 7303), True, 'import paddle.fluid as fluid\n'), ((9110, 9141), 'paddle.fluid.default_startup_program', 'fluid.default_startup_program', ([], {}), '()\n', (9139, 9141), True, 'import paddle.fluid as fluid\n'), ((9173, 9201), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (9199, 9201), True, 'import paddle.fluid as fluid\n'), ((9748, 9764), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (9762, 9764), True, 'import paddle.fluid as fluid\n'), ((9819, 9837), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (9834, 9837), True, 'import paddle.fluid as fluid\n'), ((10454, 10518), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (10462, 10518), True, 'import numpy as np\n'), ((10573, 10637), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (10581, 10637), True, 'import numpy as np\n'), ((10679, 10698), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['x_data'], {}), '(x_data)\n', (10690, 10698), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((10719, 10738), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['y_data'], {}), '(y_data)\n', (10730, 10738), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((10769, 10798), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_hidden_data'], {}), '(init_hidden_data)\n', (10780, 10798), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((10827, 10854), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_cell_data'], {}), '(init_cell_data)\n', (10838, 10854), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((12319, 12350), 'paddle.fluid.default_startup_program', 'fluid.default_startup_program', ([], {}), '()\n', (12348, 12350), True, 'import paddle.fluid as fluid\n'), ((12382, 12410), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (12408, 12410), True, 'import paddle.fluid as fluid\n'), ((12957, 12973), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (12971, 12973), True, 'import paddle.fluid as fluid\n'), ((13028, 13046), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (13043, 13046), True, 'import paddle.fluid as fluid\n'), ((13663, 13727), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (13671, 13727), True, 'import numpy as np\n'), ((13782, 13846), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (13790, 13846), True, 'import numpy as np\n'), ((13888, 13907), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['x_data'], {}), '(x_data)\n', (13899, 13907), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((13928, 13947), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['y_data'], {}), '(y_data)\n', (13939, 13947), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((13978, 14007), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_hidden_data'], {}), '(init_hidden_data)\n', (13989, 14007), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((14036, 14063), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_cell_data'], {}), '(init_cell_data)\n', (14047, 14063), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((16221, 16252), 'paddle.fluid.default_startup_program', 'fluid.default_startup_program', ([], {}), '()\n', (16250, 16252), True, 'import paddle.fluid as fluid\n'), ((16284, 16312), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (16310, 16312), True, 'import paddle.fluid as fluid\n'), ((16859, 16875), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (16873, 16875), True, 'import paddle.fluid as fluid\n'), ((16930, 16948), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (16945, 16948), True, 'import paddle.fluid as fluid\n'), ((17565, 17629), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (17573, 17629), True, 'import numpy as np\n'), ((17684, 17748), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (17692, 17748), True, 'import numpy as np\n'), ((17790, 17809), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['x_data'], {}), '(x_data)\n', (17801, 17809), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((17830, 17849), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['y_data'], {}), '(y_data)\n', (17841, 17849), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((17880, 17909), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_hidden_data'], {}), '(init_hidden_data)\n', (17891, 17909), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((17938, 17965), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_cell_data'], {}), '(init_cell_data)\n', (17949, 17965), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((20040, 20071), 'paddle.fluid.default_startup_program', 'fluid.default_startup_program', ([], {}), '()\n', (20069, 20071), True, 'import paddle.fluid as fluid\n'), ((20103, 20131), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (20129, 20131), True, 'import paddle.fluid as fluid\n'), ((20678, 20694), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (20692, 20694), True, 'import paddle.fluid as fluid\n'), ((20749, 20767), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (20764, 20767), True, 'import paddle.fluid as fluid\n'), ((21384, 21448), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (21392, 21448), True, 'import numpy as np\n'), ((21503, 21567), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (21511, 21567), True, 'import numpy as np\n'), ((21609, 21628), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['x_data'], {}), '(x_data)\n', (21620, 21628), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((21649, 21668), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['y_data'], {}), '(y_data)\n', (21660, 21668), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((21699, 21728), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_hidden_data'], {}), '(init_hidden_data)\n', (21710, 21728), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((21757, 21784), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_cell_data'], {}), '(init_cell_data)\n', (21768, 21784), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((24014, 24045), 'paddle.fluid.default_startup_program', 'fluid.default_startup_program', ([], {}), '()\n', (24043, 24045), True, 'import paddle.fluid as fluid\n'), ((24077, 24105), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (24103, 24105), True, 'import paddle.fluid as fluid\n'), ((24423, 24439), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (24437, 24439), True, 'import paddle.fluid as fluid\n'), ((24494, 24512), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (24509, 24512), True, 'import paddle.fluid as fluid\n'), ((25190, 25254), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (25198, 25254), True, 'import numpy as np\n'), ((25309, 25373), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (25317, 25373), True, 'import numpy as np\n'), ((25415, 25434), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['x_data'], {}), '(x_data)\n', (25426, 25434), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((25455, 25474), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['y_data'], {}), '(y_data)\n', (25466, 25474), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((25505, 25534), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_hidden_data'], {}), '(init_hidden_data)\n', (25516, 25534), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((25563, 25590), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_cell_data'], {}), '(init_cell_data)\n', (25574, 25590), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((27052, 27083), 'paddle.fluid.default_startup_program', 'fluid.default_startup_program', ([], {}), '()\n', (27081, 27083), True, 'import paddle.fluid as fluid\n'), ((27115, 27143), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (27141, 27143), True, 'import paddle.fluid as fluid\n'), ((27744, 27760), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (27758, 27760), True, 'import paddle.fluid as fluid\n'), ((27815, 27833), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (27830, 27833), True, 'import paddle.fluid as fluid\n'), ((28569, 28633), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (28577, 28633), True, 'import numpy as np\n'), ((28688, 28752), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (28696, 28752), True, 'import numpy as np\n'), ((28794, 28813), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['x_data'], {}), '(x_data)\n', (28805, 28813), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((28834, 28853), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['y_data'], {}), '(y_data)\n', (28845, 28853), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((28884, 28913), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_hidden_data'], {}), '(init_hidden_data)\n', (28895, 28913), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((28942, 28969), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_cell_data'], {}), '(init_cell_data)\n', (28953, 28969), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((30453, 30484), 'paddle.fluid.default_startup_program', 'fluid.default_startup_program', ([], {}), '()\n', (30482, 30484), True, 'import paddle.fluid as fluid\n'), ((30516, 30544), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (30542, 30544), True, 'import paddle.fluid as fluid\n'), ((31145, 31161), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (31159, 31161), True, 'import paddle.fluid as fluid\n'), ((31216, 31234), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (31231, 31234), True, 'import paddle.fluid as fluid\n'), ((32238, 32302), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (32246, 32302), True, 'import numpy as np\n'), ((32357, 32421), 'numpy.zeros', 'np.zeros', (['(num_layers, batch_size, hidden_size)'], {'dtype': '"""float32"""'}), "((num_layers, batch_size, hidden_size), dtype='float32')\n", (32365, 32421), True, 'import numpy as np\n'), ((32463, 32482), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['x_data'], {}), '(x_data)\n', (32474, 32482), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((32503, 32522), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['y_data'], {}), '(y_data)\n', (32514, 32522), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((32553, 32582), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_hidden_data'], {}), '(init_hidden_data)\n', (32564, 32582), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((32611, 32638), 'paddle.fluid.dygraph.base.to_variable', 'to_variable', (['init_cell_data'], {}), '(init_cell_data)\n', (32622, 32638), False, 'from paddle.fluid.dygraph.base import to_variable\n'), ((34055, 34089), 'os.path.join', 'os.path.join', (['"""saved_dy"""', '"""emb_dy"""'], {}), "('saved_dy', 'emb_dy')\n", (34067, 34089), False, 'import os\n'), ((34175, 34209), 'os.path.join', 'os.path.join', (['"""saved_dy"""', '"""emb_dy"""'], {}), "('saved_dy', 'emb_dy')\n", (34187, 34209), False, 'import os\n'), ((2139, 2226), 'paddle.fluid.initializer.UniformInitializer', 'fluid.initializer.UniformInitializer', ([], {'low': '(-self._init_scale)', 'high': 'self._init_scale'}), '(low=-self._init_scale, high=self.\n _init_scale)\n', (2175, 2226), True, 'import paddle.fluid as fluid\n'), ((2663, 2694), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', (['(0.0)'], {}), '(0.0)\n', (2689, 2694), True, 'import paddle.fluid as fluid\n'), ((4458, 4478), 'paddle.fluid.layers.tanh', 'fluid.layers.tanh', (['c'], {}), '(c)\n', (4475, 4478), True, 'import paddle.fluid as fluid\n'), ((4481, 4504), 'paddle.fluid.layers.sigmoid', 'fluid.layers.sigmoid', (['o'], {}), '(o)\n', (4501, 4504), True, 'import paddle.fluid as fluid\n'), ((4722, 4830), 'paddle.fluid.layers.dropout', 'fluid.layers.dropout', (['self._input'], {'dropout_prob': 'self._dropout', 'dropout_implementation': '"""upscale_in_train"""'}), "(self._input, dropout_prob=self._dropout,\n dropout_implementation='upscale_in_train')\n", (4742, 4830), True, 'import paddle.fluid as fluid\n'), ((9772, 9800), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (9798, 9800), True, 'import paddle.fluid.core as core\n'), ((9893, 9951), 'paddle.fluid.layers.piecewise_decay', 'fluid.layers.piecewise_decay', ([], {'boundaries': 'bd', 'values': 'lr_arr'}), '(boundaries=bd, values=lr_arr)\n', (9921, 9951), True, 'import paddle.fluid as fluid\n'), ((12981, 13009), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (13007, 13009), True, 'import paddle.fluid.core as core\n'), ((13102, 13160), 'paddle.fluid.layers.piecewise_decay', 'fluid.layers.piecewise_decay', ([], {'boundaries': 'bd', 'values': 'lr_arr'}), '(boundaries=bd, values=lr_arr)\n', (13130, 13160), True, 'import paddle.fluid as fluid\n'), ((14891, 14910), 'numpy.zeros_like', 'np.zeros_like', (['np_t'], {}), '(np_t)\n', (14904, 14910), True, 'import numpy as np\n'), ((15640, 15659), 'numpy.zeros_like', 'np.zeros_like', (['np_t'], {}), '(np_t)\n', (15653, 15659), True, 'import numpy as np\n'), ((15923, 15952), 'numpy.array_equal', 'np.array_equal', (['new_t', 'base_t'], {}), '(new_t, base_t)\n', (15937, 15952), True, 'import numpy as np\n'), ((16883, 16911), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (16909, 16911), True, 'import paddle.fluid.core as core\n'), ((17004, 17062), 'paddle.fluid.layers.piecewise_decay', 'fluid.layers.piecewise_decay', ([], {'boundaries': 'bd', 'values': 'lr_arr'}), '(boundaries=bd, values=lr_arr)\n', (17032, 17062), True, 'import paddle.fluid as fluid\n'), ((18793, 18812), 'numpy.zeros_like', 'np.zeros_like', (['np_t'], {}), '(np_t)\n', (18806, 18812), True, 'import numpy as np\n'), ((19462, 19481), 'numpy.zeros_like', 'np.zeros_like', (['np_t'], {}), '(np_t)\n', (19475, 19481), True, 'import numpy as np\n'), ((19745, 19774), 'numpy.array_equal', 'np.array_equal', (['new_t', 'base_t'], {}), '(new_t, base_t)\n', (19759, 19774), True, 'import numpy as np\n'), ((20702, 20730), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (20728, 20730), True, 'import paddle.fluid.core as core\n'), ((20823, 20881), 'paddle.fluid.layers.piecewise_decay', 'fluid.layers.piecewise_decay', ([], {'boundaries': 'bd', 'values': 'lr_arr'}), '(boundaries=bd, values=lr_arr)\n', (20851, 20881), True, 'import paddle.fluid as fluid\n'), ((22686, 22705), 'numpy.zeros_like', 'np.zeros_like', (['np_t'], {}), '(np_t)\n', (22699, 22705), True, 'import numpy as np\n'), ((23424, 23443), 'numpy.zeros_like', 'np.zeros_like', (['np_t'], {}), '(np_t)\n', (23437, 23443), True, 'import numpy as np\n'), ((23705, 23734), 'numpy.array_equal', 'np.array_equal', (['new_t', 'base_t'], {}), '(new_t, base_t)\n', (23719, 23734), True, 'import numpy as np\n'), ((24447, 24475), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (24473, 24475), True, 'import paddle.fluid.core as core\n'), ((26737, 26766), 'numpy.array_equal', 'np.array_equal', (['new_t', 'base_t'], {}), '(new_t, base_t)\n', (26751, 26766), True, 'import numpy as np\n'), ((27768, 27796), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (27794, 27796), True, 'import paddle.fluid.core as core\n'), ((30147, 30176), 'numpy.array_equal', 'np.array_equal', (['new_t', 'base_t'], {}), '(new_t, base_t)\n', (30161, 30176), True, 'import numpy as np\n'), ((31169, 31197), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (31195, 31197), True, 'import paddle.fluid.core as core\n'), ((31290, 31348), 'paddle.fluid.layers.piecewise_decay', 'fluid.layers.piecewise_decay', ([], {'boundaries': 'bd', 'values': 'lr_arr'}), '(boundaries=bd, values=lr_arr)\n', (31318, 31348), True, 'import paddle.fluid as fluid\n'), ((33816, 33845), 'numpy.array_equal', 'np.array_equal', (['new_t', 'base_t'], {}), '(new_t, base_t)\n', (33830, 33845), True, 'import numpy as np\n'), ((4344, 4367), 'paddle.fluid.layers.sigmoid', 'fluid.layers.sigmoid', (['f'], {}), '(f)\n', (4364, 4367), True, 'import paddle.fluid as fluid\n'), ((4370, 4393), 'paddle.fluid.layers.sigmoid', 'fluid.layers.sigmoid', (['i'], {}), '(i)\n', (4390, 4393), True, 'import paddle.fluid as fluid\n'), ((4417, 4437), 'paddle.fluid.layers.tanh', 'fluid.layers.tanh', (['j'], {}), '(j)\n', (4434, 4437), True, 'import paddle.fluid as fluid\n'), ((6634, 6704), 'paddle.fluid.initializer.UniformInitializer', 'fluid.initializer.UniformInitializer', ([], {'low': '(-init_scale)', 'high': 'init_scale'}), '(low=-init_scale, high=init_scale)\n', (6670, 6704), True, 'import paddle.fluid as fluid\n'), ((1890, 1977), 'paddle.fluid.initializer.UniformInitializer', 'fluid.initializer.UniformInitializer', ([], {'low': '(-self._init_scale)', 'high': 'self._init_scale'}), '(low=-self._init_scale, high=self.\n _init_scale)\n', (1926, 1977), True, 'import paddle.fluid as fluid\n'), ((2437, 2524), 'paddle.fluid.initializer.UniformInitializer', 'fluid.initializer.UniformInitializer', ([], {'low': '(-self._init_scale)', 'high': 'self._init_scale'}), '(low=-self._init_scale, high=self.\n _init_scale)\n', (2473, 2524), True, 'import paddle.fluid as fluid\n'), ((10254, 10267), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (10263, 10267), True, 'import numpy as np\n'), ((10323, 10339), 'numpy.arange', 'np.arange', (['(1)', '(13)'], {}), '(1, 13)\n', (10332, 10339), True, 'import numpy as np\n'), ((13463, 13476), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (13472, 13476), True, 'import numpy as np\n'), ((13532, 13548), 'numpy.arange', 'np.arange', (['(1)', '(13)'], {}), '(1, 13)\n', (13541, 13548), True, 'import numpy as np\n'), ((17365, 17378), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (17374, 17378), True, 'import numpy as np\n'), ((17434, 17450), 'numpy.arange', 'np.arange', (['(1)', '(13)'], {}), '(1, 13)\n', (17443, 17450), True, 'import numpy as np\n'), ((21184, 21197), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (21193, 21197), True, 'import numpy as np\n'), ((21253, 21269), 'numpy.arange', 'np.arange', (['(1)', '(13)'], {}), '(1, 13)\n', (21262, 21269), True, 'import numpy as np\n'), ((24990, 25003), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (24999, 25003), True, 'import numpy as np\n'), ((25059, 25075), 'numpy.arange', 'np.arange', (['(1)', '(13)'], {}), '(1, 13)\n', (25068, 25075), True, 'import numpy as np\n'), ((28369, 28382), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (28378, 28382), True, 'import numpy as np\n'), ((28438, 28454), 'numpy.arange', 'np.arange', (['(1)', '(13)'], {}), '(1, 13)\n', (28447, 28454), True, 'import numpy as np\n'), ((32038, 32051), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (32047, 32051), True, 'import numpy as np\n'), ((32107, 32123), 'numpy.arange', 'np.arange', (['(1)', '(13)'], {}), '(1, 13)\n', (32116, 32123), True, 'import numpy as np\n')]
# Copyright (c) 2016 PaddlePaddle Authors. 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. import image_util from paddle.utils.image_util import * import random from PIL import Image import numpy as np import xml.etree.ElementTree import os class Settings(object): def __init__(self, data_dir, label_file, resize_h, resize_w, mean_value, apply_distort, apply_expand): self._data_dir = data_dir self._label_list = [] label_fpath = os.path.join(data_dir, label_file) for line in open(label_fpath): self._label_list.append(line.strip()) self._apply_distort = apply_distort self._apply_expand = apply_expand self._resize_height = resize_h self._resize_width = resize_w self._img_mean = np.array(mean_value)[:, np.newaxis, np.newaxis].astype( 'float32') self._expand_prob = 0.5 self._expand_max_ratio = 4 self._hue_prob = 0.5 self._hue_delta = 18 self._contrast_prob = 0.5 self._contrast_delta = 0.5 self._saturation_prob = 0.5 self._saturation_delta = 0.5 self._brightness_prob = 0.5 self._brightness_delta = 0.125 @property def apply_distort(self): return self._apply_expand @property def apply_distort(self): return self._apply_distort @property def data_dir(self): return self._data_dir @property def label_list(self): return self._label_list @property def resize_h(self): return self._resize_height @property def resize_w(self): return self._resize_width @property def img_mean(self): return self._img_mean def _reader_creator(settings, file_list, mode, shuffle): def reader(): with open(file_list) as flist: lines = [line.strip() for line in flist] if shuffle: random.shuffle(lines) for line in lines: if mode == 'train' or mode == 'test': img_path, label_path = line.split() img_path = os.path.join(settings.data_dir, img_path) label_path = os.path.join(settings.data_dir, label_path) elif mode == 'infer': img_path = os.path.join(settings.data_dir, line) img = Image.open(img_path) img_width, img_height = img.size # layout: label | xmin | ymin | xmax | ymax | difficult if mode == 'train' or mode == 'test': bbox_labels = [] root = xml.etree.ElementTree.parse(label_path).getroot() for object in root.findall('object'): bbox_sample = [] # start from 1 bbox_sample.append( float( settings.label_list.index( object.find('name').text))) bbox = object.find('bndbox') difficult = float(object.find('difficult').text) bbox_sample.append( float(bbox.find('xmin').text) / img_width) bbox_sample.append( float(bbox.find('ymin').text) / img_height) bbox_sample.append( float(bbox.find('xmax').text) / img_width) bbox_sample.append( float(bbox.find('ymax').text) / img_height) bbox_sample.append(difficult) bbox_labels.append(bbox_sample) sample_labels = bbox_labels if mode == 'train': if settings._apply_distort: img = image_util.distort_image(img, settings) if settings._apply_expand: img, bbox_labels = image_util.expand_image( img, bbox_labels, img_width, img_height, settings) batch_sampler = [] # hard-code here batch_sampler.append( image_util.sampler(1, 1, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0)) batch_sampler.append( image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.1, 0.0)) batch_sampler.append( image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.3, 0.0)) batch_sampler.append( image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.5, 0.0)) batch_sampler.append( image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.7, 0.0)) batch_sampler.append( image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.9, 0.0)) batch_sampler.append( image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.0, 1.0)) """ random crop """ sampled_bbox = image_util.generate_batch_samples( batch_sampler, bbox_labels, img_width, img_height) img = np.array(img) if len(sampled_bbox) > 0: idx = int(random.uniform(0, len(sampled_bbox))) img, sample_labels = image_util.crop_image( img, bbox_labels, sampled_bbox[idx], img_width, img_height) img = Image.fromarray(img) img = img.resize((settings.resize_w, settings.resize_h), Image.ANTIALIAS) img = np.array(img) if mode == 'train': mirror = int(random.uniform(0, 2)) if mirror == 1: img = img[:, ::-1, :] for i in xrange(len(sample_labels)): tmp = sample_labels[i][1] sample_labels[i][1] = 1 - sample_labels[i][3] sample_labels[i][3] = 1 - tmp if len(img.shape) == 3: img = np.swapaxes(img, 1, 2) img = np.swapaxes(img, 1, 0) img = img[[2, 1, 0], :, :] img = img.astype('float32') img -= settings.img_mean img = img.flatten() img = img * 0.007843 sample_labels = np.array(sample_labels) if mode == 'train' or mode == 'test': if mode == 'train' and len(sample_labels) == 0: continue yield img.astype( 'float32' ), sample_labels[:, 1:5], sample_labels[:, 0].astype( 'int32'), sample_labels[:, -1].astype('int32') elif mode == 'infer': yield img.astype('float32') return reader def train(settings, file_list, shuffle=True): return _reader_creator(settings, file_list, 'train', shuffle) def test(settings, file_list): return _reader_creator(settings, file_list, 'test', False) def infer(settings, file_list): return _reader_creator(settings, file_list, 'infer', False)
[ "image_util.expand_image", "PIL.Image.fromarray", "PIL.Image.open", "random.uniform", "random.shuffle", "image_util.sampler", "image_util.generate_batch_samples", "image_util.distort_image", "os.path.join", "numpy.swapaxes", "numpy.array", "image_util.crop_image" ]
[((996, 1030), 'os.path.join', 'os.path.join', (['data_dir', 'label_file'], {}), '(data_dir, label_file)\n', (1008, 1030), False, 'import os\n'), ((2454, 2475), 'random.shuffle', 'random.shuffle', (['lines'], {}), '(lines)\n', (2468, 2475), False, 'import random\n'), ((2897, 2917), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (2907, 2917), False, 'from PIL import Image\n'), ((6789, 6802), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (6797, 6802), True, 'import numpy as np\n'), ((7598, 7621), 'numpy.array', 'np.array', (['sample_labels'], {}), '(sample_labels)\n', (7606, 7621), True, 'import numpy as np\n'), ((1309, 1329), 'numpy.array', 'np.array', (['mean_value'], {}), '(mean_value)\n', (1317, 1329), True, 'import numpy as np\n'), ((2648, 2689), 'os.path.join', 'os.path.join', (['settings.data_dir', 'img_path'], {}), '(settings.data_dir, img_path)\n', (2660, 2689), False, 'import os\n'), ((2723, 2766), 'os.path.join', 'os.path.join', (['settings.data_dir', 'label_path'], {}), '(settings.data_dir, label_path)\n', (2735, 2766), False, 'import os\n'), ((7291, 7313), 'numpy.swapaxes', 'np.swapaxes', (['img', '(1)', '(2)'], {}), '(img, 1, 2)\n', (7302, 7313), True, 'import numpy as np\n'), ((7340, 7362), 'numpy.swapaxes', 'np.swapaxes', (['img', '(1)', '(0)'], {}), '(img, 1, 0)\n', (7351, 7362), True, 'import numpy as np\n'), ((2836, 2873), 'os.path.join', 'os.path.join', (['settings.data_dir', 'line'], {}), '(settings.data_dir, line)\n', (2848, 2873), False, 'import os\n'), ((6111, 6199), 'image_util.generate_batch_samples', 'image_util.generate_batch_samples', (['batch_sampler', 'bbox_labels', 'img_width', 'img_height'], {}), '(batch_sampler, bbox_labels, img_width,\n img_height)\n', (6144, 6199), False, 'import image_util\n'), ((6256, 6269), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (6264, 6269), True, 'import numpy as np\n'), ((6623, 6643), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (6638, 6643), False, 'from PIL import Image\n'), ((6873, 6893), 'random.uniform', 'random.uniform', (['(0)', '(2)'], {}), '(0, 2)\n', (6887, 6893), False, 'import random\n'), ((4421, 4460), 'image_util.distort_image', 'image_util.distort_image', (['img', 'settings'], {}), '(img, settings)\n', (4445, 4460), False, 'import image_util\n'), ((4559, 4633), 'image_util.expand_image', 'image_util.expand_image', (['img', 'bbox_labels', 'img_width', 'img_height', 'settings'], {}), '(img, bbox_labels, img_width, img_height, settings)\n', (4582, 4633), False, 'import image_util\n'), ((4857, 4911), 'image_util.sampler', 'image_util.sampler', (['(1)', '(1)', '(1.0)', '(1.0)', '(1.0)', '(1.0)', '(0.0)', '(0.0)'], {}), '(1, 1, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0)\n', (4875, 4911), False, 'import image_util\n'), ((5034, 5089), 'image_util.sampler', 'image_util.sampler', (['(1)', '(50)', '(0.3)', '(1.0)', '(0.5)', '(2.0)', '(0.1)', '(0.0)'], {}), '(1, 50, 0.3, 1.0, 0.5, 2.0, 0.1, 0.0)\n', (5052, 5089), False, 'import image_util\n'), ((5212, 5267), 'image_util.sampler', 'image_util.sampler', (['(1)', '(50)', '(0.3)', '(1.0)', '(0.5)', '(2.0)', '(0.3)', '(0.0)'], {}), '(1, 50, 0.3, 1.0, 0.5, 2.0, 0.3, 0.0)\n', (5230, 5267), False, 'import image_util\n'), ((5390, 5445), 'image_util.sampler', 'image_util.sampler', (['(1)', '(50)', '(0.3)', '(1.0)', '(0.5)', '(2.0)', '(0.5)', '(0.0)'], {}), '(1, 50, 0.3, 1.0, 0.5, 2.0, 0.5, 0.0)\n', (5408, 5445), False, 'import image_util\n'), ((5568, 5623), 'image_util.sampler', 'image_util.sampler', (['(1)', '(50)', '(0.3)', '(1.0)', '(0.5)', '(2.0)', '(0.7)', '(0.0)'], {}), '(1, 50, 0.3, 1.0, 0.5, 2.0, 0.7, 0.0)\n', (5586, 5623), False, 'import image_util\n'), ((5746, 5801), 'image_util.sampler', 'image_util.sampler', (['(1)', '(50)', '(0.3)', '(1.0)', '(0.5)', '(2.0)', '(0.9)', '(0.0)'], {}), '(1, 50, 0.3, 1.0, 0.5, 2.0, 0.9, 0.0)\n', (5764, 5801), False, 'import image_util\n'), ((5924, 5979), 'image_util.sampler', 'image_util.sampler', (['(1)', '(50)', '(0.3)', '(1.0)', '(0.5)', '(2.0)', '(0.0)', '(1.0)'], {}), '(1, 50, 0.3, 1.0, 0.5, 2.0, 0.0, 1.0)\n', (5942, 5979), False, 'import image_util\n'), ((6445, 6530), 'image_util.crop_image', 'image_util.crop_image', (['img', 'bbox_labels', 'sampled_bbox[idx]', 'img_width', 'img_height'], {}), '(img, bbox_labels, sampled_bbox[idx], img_width,\n img_height)\n', (6466, 6530), False, 'import image_util\n')]
import torch import unittest import numpy as np from torch.autograd import Variable from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM from losses.functional import Topk_Smooth_SVM from tests.utils import assert_all_close, V from tests.py_ref import svm_topk_smooth_py_1, svm_topk_smooth_py_2,\ smooth_svm_py, max_svm_py, svm_topk_max_py from torch.autograd.gradcheck import gradcheck class TestMaxSVM(unittest.TestCase): def setUp(self): torch.manual_seed(1234) np.random.seed(1234) self.n_samples = 20 self.n_classes = 7 self.alpha = 1. self.x = torch.randn(self.n_samples, self.n_classes) self.y = torch.from_numpy(np.random.randint(0, self.n_classes, size=self.n_samples)) self.k = 3 def testMaxSVM(self): max_svm_th = MaxTop1SVM(self.n_classes, alpha=self.alpha) res_th = max_svm_th(V(self.x), V(self.y)) res_py = max_svm_py(V(self.x), V(self.y), alpha=self.alpha) assert_all_close(res_th, res_py) def testMaxSVMtopk(self): max_svm_th = MaxTopkSVM(self.n_classes, k=self.k) res_th = max_svm_th(V(self.x), V(self.y)) res_py = svm_topk_max_py(V(self.x), V(self.y), k=self.k) assert_all_close(res_th, res_py) class TestSmoothSVM(unittest.TestCase): def setUp(self): torch.manual_seed(1234) np.random.seed(1234) self.n_samples = 20 self.n_classes = 7 self.tau = float(2.) self.x = torch.randn(self.n_samples, self.n_classes) self.y = torch.from_numpy(np.random.randint(0, self.n_classes, size=self.n_samples)) def testSmoothSVM(self): smooth_svm_th = SmoothTop1SVM(self.n_classes, tau=self.tau) res_th = smooth_svm_th(V(self.x), V(self.y)) res_py = smooth_svm_py(V(self.x), V(self.y), self.tau) assert_all_close(res_th, res_py) class TestSmoothSVMTopk(unittest.TestCase): def setUp(self): torch.manual_seed(1234) np.random.seed(1234) self.n_samples = 2 self.n_classes = 7 self.k = 5 self.tau = float(2.) self.x = torch.randn(self.n_samples, self.n_classes) self.y = torch.from_numpy(np.random.randint(0, self.n_classes, size=self.n_samples)) self.labels = torch.from_numpy(np.arange(self.n_classes)) def testSmoothSVMpy(self): res_py_1 = svm_topk_smooth_py_1(V(self.x), V(self.y), self.tau, self.k) res_py_2 = svm_topk_smooth_py_2(V(self.x), V(self.y), self.tau, self.k) assert_all_close(res_py_1, res_py_2) def testSmoothSVMth_functional(self): F = Topk_Smooth_SVM(self.labels, self.k, self.tau) res_th = F(V(self.x), V(self.y)) res_py = svm_topk_smooth_py_1(V(self.x), V(self.y), self.tau, self.k) assert_all_close(res_th, res_py) def testSmoothSVMth_loss(self): svm_topk_smooth_th = SmoothTopkSVM(self.n_classes, tau=self.tau, k=self.k) res_th = svm_topk_smooth_th(V(self.x), V(self.y)) res_py = svm_topk_smooth_py_1(V(self.x), V(self.y), self.tau, self.k).mean() assert_all_close(res_th, res_py) def testSmoothSVMth_loss_scales(self): svm_topk_smooth_th = SmoothTopkSVM(self.n_classes, tau=self.tau, k=self.k) for scale in (1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3): x = self.x * scale res_th = svm_topk_smooth_th(V(x), V(self.y)) res_py = svm_topk_smooth_py_1(V(x), V(self.y), self.tau, self.k).mean() assert_all_close(res_th, res_py) def testGradSmoothSVMth_loss(self): svm_topk_smooth_th = SmoothTopkSVM(self.n_classes, tau=self.tau, k=self.k) for scale in (1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4): x = self.x * scale x = Variable(x, requires_grad=True) assert gradcheck(lambda x: svm_topk_smooth_th(x, V(self.y)), (x,), atol=1e-2, rtol=1e-3, eps=max(1e-4 * scale, 1e-2)), \ "failed with scale {}".format(scale)
[ "torch.manual_seed", "numpy.arange", "losses.svm.MaxTopkSVM", "tests.utils.assert_all_close", "losses.functional.Topk_Smooth_SVM", "numpy.random.randint", "tests.utils.V", "numpy.random.seed", "losses.svm.MaxTop1SVM", "torch.autograd.Variable", "torch.randn", "losses.svm.SmoothTop1SVM", "losses.svm.SmoothTopkSVM" ]
[((486, 509), 'torch.manual_seed', 'torch.manual_seed', (['(1234)'], {}), '(1234)\n', (503, 509), False, 'import torch\n'), ((518, 538), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (532, 538), True, 'import numpy as np\n'), ((636, 679), 'torch.randn', 'torch.randn', (['self.n_samples', 'self.n_classes'], {}), '(self.n_samples, self.n_classes)\n', (647, 679), False, 'import torch\n'), ((893, 937), 'losses.svm.MaxTop1SVM', 'MaxTop1SVM', (['self.n_classes'], {'alpha': 'self.alpha'}), '(self.n_classes, alpha=self.alpha)\n', (903, 937), False, 'from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM\n'), ((1065, 1097), 'tests.utils.assert_all_close', 'assert_all_close', (['res_th', 'res_py'], {}), '(res_th, res_py)\n', (1081, 1097), False, 'from tests.utils import assert_all_close, V\n'), ((1151, 1187), 'losses.svm.MaxTopkSVM', 'MaxTopkSVM', (['self.n_classes'], {'k': 'self.k'}), '(self.n_classes, k=self.k)\n', (1161, 1187), False, 'from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM\n'), ((1312, 1344), 'tests.utils.assert_all_close', 'assert_all_close', (['res_th', 'res_py'], {}), '(res_th, res_py)\n', (1328, 1344), False, 'from tests.utils import assert_all_close, V\n'), ((1418, 1441), 'torch.manual_seed', 'torch.manual_seed', (['(1234)'], {}), '(1234)\n', (1435, 1441), False, 'import torch\n'), ((1450, 1470), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (1464, 1470), True, 'import numpy as np\n'), ((1573, 1616), 'torch.randn', 'torch.randn', (['self.n_samples', 'self.n_classes'], {}), '(self.n_samples, self.n_classes)\n', (1584, 1616), False, 'import torch\n'), ((1817, 1860), 'losses.svm.SmoothTop1SVM', 'SmoothTop1SVM', (['self.n_classes'], {'tau': 'self.tau'}), '(self.n_classes, tau=self.tau)\n', (1830, 1860), False, 'from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM\n'), ((1986, 2018), 'tests.utils.assert_all_close', 'assert_all_close', (['res_th', 'res_py'], {}), '(res_th, res_py)\n', (2002, 2018), False, 'from tests.utils import assert_all_close, V\n'), ((2096, 2119), 'torch.manual_seed', 'torch.manual_seed', (['(1234)'], {}), '(1234)\n', (2113, 2119), False, 'import torch\n'), ((2128, 2148), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (2142, 2148), True, 'import numpy as np\n'), ((2269, 2312), 'torch.randn', 'torch.randn', (['self.n_samples', 'self.n_classes'], {}), '(self.n_samples, self.n_classes)\n', (2280, 2312), False, 'import torch\n'), ((2726, 2762), 'tests.utils.assert_all_close', 'assert_all_close', (['res_py_1', 'res_py_2'], {}), '(res_py_1, res_py_2)\n', (2742, 2762), False, 'from tests.utils import assert_all_close, V\n'), ((2819, 2865), 'losses.functional.Topk_Smooth_SVM', 'Topk_Smooth_SVM', (['self.labels', 'self.k', 'self.tau'], {}), '(self.labels, self.k, self.tau)\n', (2834, 2865), False, 'from losses.functional import Topk_Smooth_SVM\n'), ((2994, 3026), 'tests.utils.assert_all_close', 'assert_all_close', (['res_th', 'res_py'], {}), '(res_th, res_py)\n', (3010, 3026), False, 'from tests.utils import assert_all_close, V\n'), ((3094, 3147), 'losses.svm.SmoothTopkSVM', 'SmoothTopkSVM', (['self.n_classes'], {'tau': 'self.tau', 'k': 'self.k'}), '(self.n_classes, tau=self.tau, k=self.k)\n', (3107, 3147), False, 'from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM\n'), ((3419, 3451), 'tests.utils.assert_all_close', 'assert_all_close', (['res_th', 'res_py'], {}), '(res_th, res_py)\n', (3435, 3451), False, 'from tests.utils import assert_all_close, V\n'), ((3526, 3579), 'losses.svm.SmoothTopkSVM', 'SmoothTopkSVM', (['self.n_classes'], {'tau': 'self.tau', 'k': 'self.k'}), '(self.n_classes, tau=self.tau, k=self.k)\n', (3539, 3579), False, 'from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM\n'), ((3935, 3988), 'losses.svm.SmoothTopkSVM', 'SmoothTopkSVM', (['self.n_classes'], {'tau': 'self.tau', 'k': 'self.k'}), '(self.n_classes, tau=self.tau, k=self.k)\n', (3948, 3988), False, 'from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM\n'), ((714, 771), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.n_classes'], {'size': 'self.n_samples'}), '(0, self.n_classes, size=self.n_samples)\n', (731, 771), True, 'import numpy as np\n'), ((966, 975), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (967, 975), False, 'from tests.utils import assert_all_close, V\n'), ((977, 986), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (978, 986), False, 'from tests.utils import assert_all_close, V\n'), ((1016, 1025), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (1017, 1025), False, 'from tests.utils import assert_all_close, V\n'), ((1027, 1036), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (1028, 1036), False, 'from tests.utils import assert_all_close, V\n'), ((1216, 1225), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (1217, 1225), False, 'from tests.utils import assert_all_close, V\n'), ((1227, 1236), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (1228, 1236), False, 'from tests.utils import assert_all_close, V\n'), ((1271, 1280), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (1272, 1280), False, 'from tests.utils import assert_all_close, V\n'), ((1282, 1291), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (1283, 1291), False, 'from tests.utils import assert_all_close, V\n'), ((1651, 1708), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.n_classes'], {'size': 'self.n_samples'}), '(0, self.n_classes, size=self.n_samples)\n', (1668, 1708), True, 'import numpy as np\n'), ((1892, 1901), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (1893, 1901), False, 'from tests.utils import assert_all_close, V\n'), ((1903, 1912), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (1904, 1912), False, 'from tests.utils import assert_all_close, V\n'), ((1945, 1954), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (1946, 1954), False, 'from tests.utils import assert_all_close, V\n'), ((1956, 1965), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (1957, 1965), False, 'from tests.utils import assert_all_close, V\n'), ((2347, 2404), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.n_classes'], {'size': 'self.n_samples'}), '(0, self.n_classes, size=self.n_samples)\n', (2364, 2404), True, 'import numpy as np\n'), ((2497, 2522), 'numpy.arange', 'np.arange', (['self.n_classes'], {}), '(self.n_classes)\n', (2506, 2522), True, 'import numpy as np\n'), ((2597, 2606), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (2598, 2606), False, 'from tests.utils import assert_all_close, V\n'), ((2608, 2617), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (2609, 2617), False, 'from tests.utils import assert_all_close, V\n'), ((2677, 2686), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (2678, 2686), False, 'from tests.utils import assert_all_close, V\n'), ((2688, 2697), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (2689, 2697), False, 'from tests.utils import assert_all_close, V\n'), ((2885, 2894), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (2886, 2894), False, 'from tests.utils import assert_all_close, V\n'), ((2896, 2905), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (2897, 2905), False, 'from tests.utils import assert_all_close, V\n'), ((2945, 2954), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (2946, 2954), False, 'from tests.utils import assert_all_close, V\n'), ((2956, 2965), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (2957, 2965), False, 'from tests.utils import assert_all_close, V\n'), ((3227, 3236), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (3228, 3236), False, 'from tests.utils import assert_all_close, V\n'), ((3238, 3247), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (3239, 3247), False, 'from tests.utils import assert_all_close, V\n'), ((3831, 3863), 'tests.utils.assert_all_close', 'assert_all_close', (['res_th', 'res_py'], {}), '(res_th, res_py)\n', (3847, 3863), False, 'from tests.utils import assert_all_close, V\n'), ((4108, 4139), 'torch.autograd.Variable', 'Variable', (['x'], {'requires_grad': '(True)'}), '(x, requires_grad=True)\n', (4116, 4139), False, 'from torch.autograd import Variable\n'), ((3718, 3722), 'tests.utils.V', 'V', (['x'], {}), '(x)\n', (3719, 3722), False, 'from tests.utils import assert_all_close, V\n'), ((3724, 3733), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (3725, 3733), False, 'from tests.utils import assert_all_close, V\n'), ((3287, 3296), 'tests.utils.V', 'V', (['self.x'], {}), '(self.x)\n', (3288, 3296), False, 'from tests.utils import assert_all_close, V\n'), ((3336, 3345), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (3337, 3345), False, 'from tests.utils import assert_all_close, V\n'), ((3777, 3781), 'tests.utils.V', 'V', (['x'], {}), '(x)\n', (3778, 3781), False, 'from tests.utils import assert_all_close, V\n'), ((3783, 3792), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (3784, 3792), False, 'from tests.utils import assert_all_close, V\n'), ((4201, 4210), 'tests.utils.V', 'V', (['self.y'], {}), '(self.y)\n', (4202, 4210), False, 'from tests.utils import assert_all_close, V\n')]
# pylint: disable=g-bad-file-header # Copyright 2019 DeepMind Technologies Limited. 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. # ============================================================================ """Tests for bsuite.experiments.mnist.""" # Import all required packages from absl.testing import absltest from bsuite.experiments.mnist import mnist from dm_env import test_utils import numpy as np class CatchInterfaceTest(test_utils.EnvironmentTestMixin, absltest.TestCase): def make_object_under_test(self): return mnist.MNISTBandit(seed=101) def make_action_sequence(self): num_actions = self.environment.action_spec().num_values rng = np.random.RandomState(42) for _ in range(100): yield rng.randint(num_actions) if __name__ == '__main__': absltest.main()
[ "bsuite.experiments.mnist.mnist.MNISTBandit", "absl.testing.absltest.main", "numpy.random.RandomState" ]
[((1312, 1327), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (1325, 1327), False, 'from absl.testing import absltest\n'), ((1060, 1087), 'bsuite.experiments.mnist.mnist.MNISTBandit', 'mnist.MNISTBandit', ([], {'seed': '(101)'}), '(seed=101)\n', (1077, 1087), False, 'from bsuite.experiments.mnist import mnist\n'), ((1193, 1218), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (1214, 1218), True, 'import numpy as np\n')]
# Copyright 2018 The TensorFlow Authors. 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. # ============================================================================== """extenders tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from tensorflow.python.data.ops import dataset_ops from tensorflow.python.feature_column import feature_column_lib as fc from tensorflow.python.framework import constant_op from tensorflow.python.keras import metrics as metrics_module from tensorflow.python.platform import test from tensorflow_estimator.python.estimator import extenders from tensorflow_estimator.python.estimator import run_config from tensorflow_estimator.python.estimator.canned import linear def get_input_fn(x, y): def input_fn(): dataset = tf.compat.v1.data.Dataset.from_tensor_slices({'x': x, 'y': y}) iterator = tf.compat.v1.data.make_one_shot_iterator(dataset) features = iterator.get_next() labels = features.pop('y') return features, labels return input_fn class AddMetricsTest(tf.test.TestCase): def test_should_add_metrics(self): def _test_metric_fn(metric_fn): input_fn = get_input_fn( x=np.arange(4)[:, None, None], y=np.ones(4)[:, None]) config = run_config.RunConfig(log_step_count_steps=1) estimator = linear.LinearClassifierV2([tf.feature_column.numeric_column('x')], config=config) estimator = extenders.add_metrics(estimator, metric_fn) estimator.train(input_fn=input_fn) metrics = estimator.evaluate(input_fn=input_fn) self.assertIn('mean_x', metrics) self.assertEqual(1.5, metrics['mean_x']) # assert that it keeps original estimators metrics self.assertIn('auc', metrics) def metric_fn(features): metric = metrics_module.Mean() metric.update_state(features['x']) return {'mean_x': metric} _test_metric_fn(metric_fn) def test_should_error_out_for_not_recognized_args(self): estimator = linear.LinearClassifierV2([tf.feature_column.numeric_column('x')]) def metric_fn(features, not_recognized): _, _ = features, not_recognized return {} with self.assertRaisesRegexp(ValueError, 'not_recognized'): estimator = extenders.add_metrics(estimator, metric_fn) def test_all_supported_args(self): input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]]) estimator = linear.LinearClassifierV2([tf.feature_column.numeric_column('x')]) def metric_fn(features, predictions, labels, config): self.assertIn('x', features) self.assertIsNotNone(labels) self.assertIn('logistic', predictions) self.assertTrue(isinstance(config, run_config.RunConfig)) return {} estimator = extenders.add_metrics(estimator, metric_fn) estimator.train(input_fn=input_fn) estimator.evaluate(input_fn=input_fn) def test_all_supported_args_in_different_order(self): input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]]) estimator = linear.LinearClassifierV2([tf.feature_column.numeric_column('x')]) def metric_fn(labels, config, features, predictions): self.assertIn('x', features) self.assertIsNotNone(labels) self.assertIn('logistic', predictions) self.assertTrue(isinstance(config, run_config.RunConfig)) return {} estimator = extenders.add_metrics(estimator, metric_fn) estimator.train(input_fn=input_fn) estimator.evaluate(input_fn=input_fn) def test_all_args_are_optional(self): def _test_metric_fn(metric_fn): input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]]) estimator = linear.LinearClassifierV2([tf.feature_column.numeric_column('x')]) estimator = extenders.add_metrics(estimator, metric_fn) estimator.train(input_fn=input_fn) metrics = estimator.evaluate(input_fn=input_fn) self.assertEqual(2., metrics['two']) def metric_fn(): metric = metrics_module.Mean() metric.update_state(tf.constant([2.])) return {'two': metric} _test_metric_fn(metric_fn) def test_overrides_existing_metrics(self): def _test_metric_fn(metric_fn): input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]]) estimator = linear.LinearClassifierV2([tf.feature_column.numeric_column('x')]) estimator.train(input_fn=input_fn) metrics = estimator.evaluate(input_fn=input_fn) self.assertNotEqual(2., metrics['auc']) estimator = extenders.add_metrics(estimator, metric_fn) metrics = estimator.evaluate(input_fn=input_fn) self.assertEqual(2., metrics['auc']) def metric_fn(): metric = metrics_module.Mean() metric.update_state(tf.constant([2.])) return {'auc': metric} _test_metric_fn(metric_fn) if __name__ == '__main__': tf.test.main()
[ "tensorflow_estimator.python.estimator.run_config.RunConfig", "tensorflow.python.keras.metrics.Mean", "numpy.ones", "tensorflow.compat.v1.data.make_one_shot_iterator", "tensorflow.test.main", "tensorflow.feature_column.numeric_column", "tensorflow.compat.v1.data.Dataset.from_tensor_slices", "tensorflow.constant", "tensorflow_estimator.python.estimator.extenders.add_metrics", "numpy.arange" ]
[((5382, 5396), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (5394, 5396), True, 'import tensorflow as tf\n'), ((1391, 1453), 'tensorflow.compat.v1.data.Dataset.from_tensor_slices', 'tf.compat.v1.data.Dataset.from_tensor_slices', (["{'x': x, 'y': y}"], {}), "({'x': x, 'y': y})\n", (1435, 1453), True, 'import tensorflow as tf\n'), ((1469, 1518), 'tensorflow.compat.v1.data.make_one_shot_iterator', 'tf.compat.v1.data.make_one_shot_iterator', (['dataset'], {}), '(dataset)\n', (1509, 1518), True, 'import tensorflow as tf\n'), ((3370, 3413), 'tensorflow_estimator.python.estimator.extenders.add_metrics', 'extenders.add_metrics', (['estimator', 'metric_fn'], {}), '(estimator, metric_fn)\n', (3391, 3413), False, 'from tensorflow_estimator.python.estimator import extenders\n'), ((3958, 4001), 'tensorflow_estimator.python.estimator.extenders.add_metrics', 'extenders.add_metrics', (['estimator', 'metric_fn'], {}), '(estimator, metric_fn)\n', (3979, 4001), False, 'from tensorflow_estimator.python.estimator import extenders\n'), ((1858, 1902), 'tensorflow_estimator.python.estimator.run_config.RunConfig', 'run_config.RunConfig', ([], {'log_step_count_steps': '(1)'}), '(log_step_count_steps=1)\n', (1878, 1902), False, 'from tensorflow_estimator.python.estimator import run_config\n'), ((2066, 2109), 'tensorflow_estimator.python.estimator.extenders.add_metrics', 'extenders.add_metrics', (['estimator', 'metric_fn'], {}), '(estimator, metric_fn)\n', (2087, 2109), False, 'from tensorflow_estimator.python.estimator import extenders\n'), ((2430, 2451), 'tensorflow.python.keras.metrics.Mean', 'metrics_module.Mean', ([], {}), '()\n', (2449, 2451), True, 'from tensorflow.python.keras import metrics as metrics_module\n'), ((2883, 2926), 'tensorflow_estimator.python.estimator.extenders.add_metrics', 'extenders.add_metrics', (['estimator', 'metric_fn'], {}), '(estimator, metric_fn)\n', (2904, 2926), False, 'from tensorflow_estimator.python.estimator import extenders\n'), ((4317, 4360), 'tensorflow_estimator.python.estimator.extenders.add_metrics', 'extenders.add_metrics', (['estimator', 'metric_fn'], {}), '(estimator, metric_fn)\n', (4338, 4360), False, 'from tensorflow_estimator.python.estimator import extenders\n'), ((4537, 4558), 'tensorflow.python.keras.metrics.Mean', 'metrics_module.Mean', ([], {}), '()\n', (4556, 4558), True, 'from tensorflow.python.keras import metrics as metrics_module\n'), ((5045, 5088), 'tensorflow_estimator.python.estimator.extenders.add_metrics', 'extenders.add_metrics', (['estimator', 'metric_fn'], {}), '(estimator, metric_fn)\n', (5066, 5088), False, 'from tensorflow_estimator.python.estimator import extenders\n'), ((5223, 5244), 'tensorflow.python.keras.metrics.Mean', 'metrics_module.Mean', ([], {}), '()\n', (5242, 5244), True, 'from tensorflow.python.keras import metrics as metrics_module\n'), ((2660, 2697), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""x"""'], {}), "('x')\n", (2692, 2697), True, 'import tensorflow as tf\n'), ((3059, 3096), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""x"""'], {}), "('x')\n", (3091, 3096), True, 'import tensorflow as tf\n'), ((3647, 3684), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""x"""'], {}), "('x')\n", (3679, 3684), True, 'import tensorflow as tf\n'), ((4585, 4603), 'tensorflow.constant', 'tf.constant', (['[2.0]'], {}), '([2.0])\n', (4596, 4603), True, 'import tensorflow as tf\n'), ((5271, 5289), 'tensorflow.constant', 'tf.constant', (['[2.0]'], {}), '([2.0])\n', (5282, 5289), True, 'import tensorflow as tf\n'), ((1948, 1985), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""x"""'], {}), "('x')\n", (1980, 1985), True, 'import tensorflow as tf\n'), ((4259, 4296), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""x"""'], {}), "('x')\n", (4291, 4296), True, 'import tensorflow as tf\n'), ((4845, 4882), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""x"""'], {}), "('x')\n", (4877, 4882), True, 'import tensorflow as tf\n'), ((1791, 1803), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (1800, 1803), True, 'import numpy as np\n'), ((1822, 1832), 'numpy.ones', 'np.ones', (['(4)'], {}), '(4)\n', (1829, 1832), True, 'import numpy as np\n')]
import numpy as np from scipy.sparse import csc_matrix, save_npz, hstack import time import argparse import gzip from pysam import VariantFile, TabixFile import json import os import itertools parser = argparse.ArgumentParser(description='Pull genotypes.') parser.add_argument('vcf_file', type=str, help='VCF file to pull from.') parser.add_argument('assembly', type=str, help='Human genome reference used.') parser.add_argument('out_directory', type=str, help='Output directory.') parser.add_argument('chrom', type=str, help='Chromosome of interest.') parser.add_argument('--batch_size', type=int, default=-1, help='Restrict number of positions per file to batch_size.') parser.add_argument('--batch_num', type=int, default=0, help='To be used along with batch_size to restrict positions per file. Will include positions >= batch_num*batch_size and <= (batch_num+1)*batch_size') parser.add_argument('--maxsize', type=int, default=500000000, help='Amount of memory per block.') parser.add_argument('--additional_vcf_files', type=str, nargs='+', help='Additional VCF files to pull data from.') parser.add_argument('--id_mapper_file', type=str, default=None, help='File that maps old ids to new ones.') parser.add_argument('--id_mapper_sep', type=str, default='\t', help='Separater to parse id_mapper_file.') parser.add_argument('--old_id_index', type=int, default=0, help='Index of old_id in id_mapper_file.') parser.add_argument('--new_id_index', type=int, default=1, help='Index of new_id in id_mapper_file.') args = parser.parse_args() t0 = time.time() chrom_int = 23 if args.chrom == 'X' else 24 if args.chrom == 'Y' else 25 if args.chrom == 'MT' else int(args.chrom) gen_mapping = {'./.': -1, '0/0': 0, '0|0': 0, '0/1': 1, '0|1': 1, '1/0': 1, '1|0': 1, '1/1': 2, '1|1': 2} def process_header(vcf): sample_ids = [x.replace('.', '_') for x in vcf.header.samples] if args.id_mapper_file is not None: old_id_to_new_id = dict() with open(args.id_mapper_file, 'r') as f: for line in f: pieces = line.strip().split(args.id_mapper_sep) if len(pieces)>args.old_id_index and len(pieces)>args.new_id_index: old_id_to_new_id[pieces[args.old_id_index]] = pieces[args.new_id_index] sample_ids = [old_id_to_new_id[x] for x in sample_ids] sample_file = '%s/samples.json' % args.out_directory if os.path.isfile(sample_file): with open(sample_file, 'r') as f: stored_sample_ids = json.load(f) assert sample_ids == stored_sample_ids else: with open(sample_file, 'w+') as f: json.dump(sample_ids, f) return sample_ids, vcf.header.contigs def process_body(records, sample_ids): data, indices, indptr, index = np.zeros((args.maxsize,), dtype=np.int8), np.zeros((args.maxsize,), dtype=int), [0], 0 chrom_coord = [] with gzip.open('%s/chr.%s.%d.gen.variants.txt.gz' % (args.out_directory, args.chrom, args.batch_num), 'wt') as variant_f: for line in records: pieces = line.strip().split('\t') fmt = pieces[8].strip().split(':') # Write variant to file variant_f.write('\t'.join(pieces[:9]) + '\n') # pull chrom_coord information pos, _, ref, alt = pieces[1:5] is_biallelic_snp = 1 if len(ref) == 1 and len(alt) == 1 and ref != '.' and alt != '.' else 0 is_pass = pieces[6] == 'PASS' chrom_coord.append((chrom_int, int(pos), is_biallelic_snp, is_pass)) # pull genotypes gen_index = fmt.index('GT') for i, piece in enumerate(pieces[9:]): segment = piece.split(':', maxsplit=gen_index+1) gt = gen_mapping.get(segment[gen_index], -1) # For now we mark multi-base loci as unknown if gt != 0: indices[index] = i data[index] = gt index += 1 indptr.append(index) gen = csc_matrix((data[:index], indices[:index], indptr), shape=(len(sample_ids), len(indptr)-1), dtype=np.int8) # Save to file save_npz('%s/chr.%s.%d.gen' % (args.out_directory, args.chrom, args.batch_num), gen) np.save('%s/chr.%s.%d.gen.coordinates' % (args.out_directory, args.chrom, args.batch_num), np.asarray(np.asarray(chrom_coord, dtype=int), dtype=int)) print('Completed in ', time.time()-t0, 'sec') with open('%s/info.json' % args.out_directory, 'w+') as f: json.dump({'assembly': args.assembly, 'batch_size': args.batch_size, 'vcf_directory': '/'.join(args.vcf_file.split('/')[:-1])}, f) vcf = VariantFile(args.vcf_file) sample_ids, contigs = process_header(vcf) if args.additional_vcf_files is not None: for vcf_file in args.additional_vcf_files: if os.path.isfile(vcf_file): new_vcf = VariantFile(vcf_file) new_sample_ids, _ = process_header(new_vcf) assert sample_ids == new_sample_ids else: print(vcf_file, 'does not exist') contig = None if args.chrom in contigs: contig = contigs[args.chrom] elif 'chr%s' % args.chrom in contigs: contig = contigs['chr%s' % args.chrom] else: raise Exception('Trouble finding contig', args.chrom, 'in', contigs) print('Chrom length', contig.length) vcf_files = [args.vcf_file] if args.additional_vcf_files is not None: vcf_files.extend(args.additional_vcf_files) if np.all([os.path.isfile(vcf_file + '.tbi') for vcf_file in vcf_files]): vcfs = [TabixFile(vcf_file, parser=None) for vcf_file in vcf_files] if args.batch_size != -1: start_pos, end_pos = args.batch_num*args.batch_size, (args.batch_num+1)*args.batch_size print('Interval', start_pos, end_pos) if start_pos < contig.length: process_body(itertools.chain(*[vcf.fetch(reference=contig.name, start=start_pos, end=end_pos) for vcf in vcfs]), sample_ids) else: print('Interval (%d-%d) is longer than chromosome (length=%d).' % (start_pos, end_pos, contig.length)) else: process_body(itertools.chain(*[vcf.fetch(reference=contig.name) for vcf in vcfs]), sample_ids) else: print('Error, .tbi files are missing.')
[ "pysam.VariantFile", "argparse.ArgumentParser", "gzip.open", "numpy.asarray", "os.path.isfile", "numpy.zeros", "pysam.TabixFile", "json.load", "scipy.sparse.save_npz", "time.time", "json.dump" ]
[((204, 258), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Pull genotypes."""'}), "(description='Pull genotypes.')\n", (227, 258), False, 'import argparse\n'), ((1546, 1557), 'time.time', 'time.time', ([], {}), '()\n', (1555, 1557), False, 'import time\n'), ((4632, 4658), 'pysam.VariantFile', 'VariantFile', (['args.vcf_file'], {}), '(args.vcf_file)\n', (4643, 4658), False, 'from pysam import VariantFile, TabixFile\n'), ((2395, 2422), 'os.path.isfile', 'os.path.isfile', (['sample_file'], {}), '(sample_file)\n', (2409, 2422), False, 'import os\n'), ((4141, 4230), 'scipy.sparse.save_npz', 'save_npz', (["('%s/chr.%s.%d.gen' % (args.out_directory, args.chrom, args.batch_num))", 'gen'], {}), "('%s/chr.%s.%d.gen' % (args.out_directory, args.chrom, args.\n batch_num), gen)\n", (4149, 4230), False, 'from scipy.sparse import csc_matrix, save_npz, hstack\n'), ((2771, 2811), 'numpy.zeros', 'np.zeros', (['(args.maxsize,)'], {'dtype': 'np.int8'}), '((args.maxsize,), dtype=np.int8)\n', (2779, 2811), True, 'import numpy as np\n'), ((2813, 2849), 'numpy.zeros', 'np.zeros', (['(args.maxsize,)'], {'dtype': 'int'}), '((args.maxsize,), dtype=int)\n', (2821, 2849), True, 'import numpy as np\n'), ((2889, 2996), 'gzip.open', 'gzip.open', (["('%s/chr.%s.%d.gen.variants.txt.gz' % (args.out_directory, args.chrom, args\n .batch_num))", '"""wt"""'], {}), "('%s/chr.%s.%d.gen.variants.txt.gz' % (args.out_directory, args.\n chrom, args.batch_num), 'wt')\n", (2898, 2996), False, 'import gzip\n'), ((4802, 4826), 'os.path.isfile', 'os.path.isfile', (['vcf_file'], {}), '(vcf_file)\n', (4816, 4826), False, 'import os\n'), ((5439, 5472), 'os.path.isfile', 'os.path.isfile', (["(vcf_file + '.tbi')"], {}), "(vcf_file + '.tbi')\n", (5453, 5472), False, 'import os\n'), ((5514, 5546), 'pysam.TabixFile', 'TabixFile', (['vcf_file'], {'parser': 'None'}), '(vcf_file, parser=None)\n', (5523, 5546), False, 'from pysam import VariantFile, TabixFile\n'), ((2498, 2510), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2507, 2510), False, 'import json\n'), ((2627, 2651), 'json.dump', 'json.dump', (['sample_ids', 'f'], {}), '(sample_ids, f)\n', (2636, 2651), False, 'import json\n'), ((4332, 4366), 'numpy.asarray', 'np.asarray', (['chrom_coord'], {'dtype': 'int'}), '(chrom_coord, dtype=int)\n', (4342, 4366), True, 'import numpy as np\n'), ((4407, 4418), 'time.time', 'time.time', ([], {}), '()\n', (4416, 4418), False, 'import time\n'), ((4850, 4871), 'pysam.VariantFile', 'VariantFile', (['vcf_file'], {}), '(vcf_file)\n', (4861, 4871), False, 'from pysam import VariantFile, TabixFile\n')]
# Copyright (c) 2020 PaddlePaddle Authors. 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. from pathlib import Path import numpy as np import pandas as pd import librosa import csv from paddle import fluid from parakeet import g2p from parakeet import audio from parakeet.data.sampler import * from parakeet.data.datacargo import DataCargo from parakeet.data.batch import TextIDBatcher, SpecBatcher from parakeet.data.dataset import DatasetMixin, TransformDataset, CacheDataset, SliceDataset from parakeet.models.transformer_tts.utils import * class LJSpeechLoader: def __init__(self, config, args, nranks, rank, is_vocoder=False, shuffle=True): place = fluid.CUDAPlace(rank) if args.use_gpu else fluid.CPUPlace() LJSPEECH_ROOT = Path(args.data_path) metadata = LJSpeechMetaData(LJSPEECH_ROOT) transformer = LJSpeech(config) dataset = TransformDataset(metadata, transformer) dataset = CacheDataset(dataset) sampler = DistributedSampler( len(dataset), nranks, rank, shuffle=shuffle) assert args.batch_size % nranks == 0 each_bs = args.batch_size // nranks if is_vocoder: dataloader = DataCargo( dataset, sampler=sampler, batch_size=each_bs, shuffle=shuffle, batch_fn=batch_examples_vocoder, drop_last=True) else: dataloader = DataCargo( dataset, sampler=sampler, batch_size=each_bs, shuffle=shuffle, batch_fn=batch_examples, drop_last=True) self.reader = fluid.io.DataLoader.from_generator( capacity=32, iterable=True, use_double_buffer=True, return_list=True) self.reader.set_batch_generator(dataloader, place) class LJSpeechMetaData(DatasetMixin): def __init__(self, root): self.root = Path(root) self._wav_dir = self.root.joinpath("wavs") csv_path = self.root.joinpath("metadata.csv") self._table = pd.read_csv( csv_path, sep="|", header=None, quoting=csv.QUOTE_NONE, names=["fname", "raw_text", "normalized_text"]) def get_example(self, i): fname, raw_text, normalized_text = self._table.iloc[i] fname = str(self._wav_dir.joinpath(fname + ".wav")) return fname, raw_text, normalized_text def __len__(self): return len(self._table) class LJSpeech(object): def __init__(self, config): super(LJSpeech, self).__init__() self.config = config self._ljspeech_processor = audio.AudioProcessor( sample_rate=config['audio']['sr'], num_mels=config['audio']['num_mels'], min_level_db=config['audio']['min_level_db'], ref_level_db=config['audio']['ref_level_db'], n_fft=config['audio']['n_fft'], win_length=config['audio']['win_length'], hop_length=config['audio']['hop_length'], power=config['audio']['power'], preemphasis=config['audio']['preemphasis'], signal_norm=True, symmetric_norm=False, max_norm=1., mel_fmin=0, mel_fmax=None, clip_norm=True, griffin_lim_iters=60, do_trim_silence=False, sound_norm=False) def __call__(self, metadatum): """All the code for generating an Example from a metadatum. If you want a different preprocessing pipeline, you can override this method. This method may require several processor, each of which has a lot of options. In this case, you'd better pass a composed transform and pass it to the init method. """ fname, raw_text, normalized_text = metadatum # load -> trim -> preemphasis -> stft -> magnitude -> mel_scale -> logscale -> normalize wav = self._ljspeech_processor.load_wav(str(fname)) mag = self._ljspeech_processor.spectrogram(wav).astype(np.float32) mel = self._ljspeech_processor.melspectrogram(wav).astype(np.float32) phonemes = np.array( g2p.en.text_to_sequence(normalized_text), dtype=np.int64) return (mag, mel, phonemes ) # maybe we need to implement it as a map in the future def batch_examples(batch): texts = [] mels = [] mel_inputs = [] mel_lens = [] text_lens = [] pos_texts = [] pos_mels = [] for data in batch: _, mel, text = data mel_inputs.append( np.concatenate( [np.zeros([mel.shape[0], 1], np.float32), mel[:, :-1]], axis=-1)) mel_lens.append(mel.shape[1]) text_lens.append(len(text)) pos_texts.append(np.arange(1, len(text) + 1)) pos_mels.append(np.arange(1, mel.shape[1] + 1)) mels.append(mel) texts.append(text) # Sort by text_len in descending order texts = [ i for i, _ in sorted( zip(texts, text_lens), key=lambda x: x[1], reverse=True) ] mels = [ i for i, _ in sorted( zip(mels, text_lens), key=lambda x: x[1], reverse=True) ] mel_inputs = [ i for i, _ in sorted( zip(mel_inputs, text_lens), key=lambda x: x[1], reverse=True) ] mel_lens = [ i for i, _ in sorted( zip(mel_lens, text_lens), key=lambda x: x[1], reverse=True) ] pos_texts = [ i for i, _ in sorted( zip(pos_texts, text_lens), key=lambda x: x[1], reverse=True) ] pos_mels = [ i for i, _ in sorted( zip(pos_mels, text_lens), key=lambda x: x[1], reverse=True) ] text_lens = sorted(text_lens, reverse=True) # Pad sequence with largest len of the batch texts = TextIDBatcher(pad_id=0)(texts) #(B, T) pos_texts = TextIDBatcher(pad_id=0)(pos_texts) #(B,T) pos_mels = TextIDBatcher(pad_id=0)(pos_mels) #(B,T) mels = np.transpose( SpecBatcher(pad_value=0.)(mels), axes=(0, 2, 1)) #(B,T,num_mels) mel_inputs = np.transpose( SpecBatcher(pad_value=0.)(mel_inputs), axes=(0, 2, 1)) #(B,T,num_mels) enc_slf_mask = get_attn_key_pad_mask(pos_texts).astype(np.float32) enc_query_mask = get_non_pad_mask(pos_texts).astype(np.float32) dec_slf_mask = get_dec_attn_key_pad_mask(pos_mels, mel_inputs).astype(np.float32) enc_dec_mask = get_attn_key_pad_mask(enc_query_mask[:, :, 0]).astype( np.float32) dec_query_slf_mask = get_non_pad_mask(pos_mels).astype(np.float32) dec_query_mask = get_non_pad_mask(pos_mels).astype(np.float32) return (texts, mels, mel_inputs, pos_texts, pos_mels, np.array(text_lens), np.array(mel_lens), enc_slf_mask, enc_query_mask, dec_slf_mask, enc_dec_mask, dec_query_slf_mask, dec_query_mask) def batch_examples_vocoder(batch): mels = [] mags = [] for data in batch: mag, mel, _ = data mels.append(mel) mags.append(mag) mels = np.transpose(SpecBatcher(pad_value=0.)(mels), axes=(0, 2, 1)) mags = np.transpose(SpecBatcher(pad_value=0.)(mags), axes=(0, 2, 1)) return (mels, mags)
[ "parakeet.data.datacargo.DataCargo", "parakeet.data.dataset.TransformDataset", "parakeet.audio.AudioProcessor", "pandas.read_csv", "pathlib.Path", "paddle.fluid.io.DataLoader.from_generator", "parakeet.g2p.en.text_to_sequence", "paddle.fluid.CPUPlace", "numpy.array", "parakeet.data.batch.TextIDBatcher", "parakeet.data.dataset.CacheDataset", "numpy.zeros", "paddle.fluid.CUDAPlace", "parakeet.data.batch.SpecBatcher", "numpy.arange" ]
[((1375, 1395), 'pathlib.Path', 'Path', (['args.data_path'], {}), '(args.data_path)\n', (1379, 1395), False, 'from pathlib import Path\n'), ((1504, 1543), 'parakeet.data.dataset.TransformDataset', 'TransformDataset', (['metadata', 'transformer'], {}), '(metadata, transformer)\n', (1520, 1543), False, 'from parakeet.data.dataset import DatasetMixin, TransformDataset, CacheDataset, SliceDataset\n'), ((1562, 1583), 'parakeet.data.dataset.CacheDataset', 'CacheDataset', (['dataset'], {}), '(dataset)\n', (1574, 1583), False, 'from parakeet.data.dataset import DatasetMixin, TransformDataset, CacheDataset, SliceDataset\n'), ((2309, 2417), 'paddle.fluid.io.DataLoader.from_generator', 'fluid.io.DataLoader.from_generator', ([], {'capacity': '(32)', 'iterable': '(True)', 'use_double_buffer': '(True)', 'return_list': '(True)'}), '(capacity=32, iterable=True,\n use_double_buffer=True, return_list=True)\n', (2343, 2417), False, 'from paddle import fluid\n'), ((2612, 2622), 'pathlib.Path', 'Path', (['root'], {}), '(root)\n', (2616, 2622), False, 'from pathlib import Path\n'), ((2750, 2870), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {'sep': '"""|"""', 'header': 'None', 'quoting': 'csv.QUOTE_NONE', 'names': "['fname', 'raw_text', 'normalized_text']"}), "(csv_path, sep='|', header=None, quoting=csv.QUOTE_NONE, names=[\n 'fname', 'raw_text', 'normalized_text'])\n", (2761, 2870), True, 'import pandas as pd\n'), ((3348, 3917), 'parakeet.audio.AudioProcessor', 'audio.AudioProcessor', ([], {'sample_rate': "config['audio']['sr']", 'num_mels': "config['audio']['num_mels']", 'min_level_db': "config['audio']['min_level_db']", 'ref_level_db': "config['audio']['ref_level_db']", 'n_fft': "config['audio']['n_fft']", 'win_length': "config['audio']['win_length']", 'hop_length': "config['audio']['hop_length']", 'power': "config['audio']['power']", 'preemphasis': "config['audio']['preemphasis']", 'signal_norm': '(True)', 'symmetric_norm': '(False)', 'max_norm': '(1.0)', 'mel_fmin': '(0)', 'mel_fmax': 'None', 'clip_norm': '(True)', 'griffin_lim_iters': '(60)', 'do_trim_silence': '(False)', 'sound_norm': '(False)'}), "(sample_rate=config['audio']['sr'], num_mels=config[\n 'audio']['num_mels'], min_level_db=config['audio']['min_level_db'],\n ref_level_db=config['audio']['ref_level_db'], n_fft=config['audio'][\n 'n_fft'], win_length=config['audio']['win_length'], hop_length=config[\n 'audio']['hop_length'], power=config['audio']['power'], preemphasis=\n config['audio']['preemphasis'], signal_norm=True, symmetric_norm=False,\n max_norm=1.0, mel_fmin=0, mel_fmax=None, clip_norm=True,\n griffin_lim_iters=60, do_trim_silence=False, sound_norm=False)\n", (3368, 3917), False, 'from parakeet import audio\n'), ((6602, 6625), 'parakeet.data.batch.TextIDBatcher', 'TextIDBatcher', ([], {'pad_id': '(0)'}), '(pad_id=0)\n', (6615, 6625), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((6658, 6681), 'parakeet.data.batch.TextIDBatcher', 'TextIDBatcher', ([], {'pad_id': '(0)'}), '(pad_id=0)\n', (6671, 6681), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((6716, 6739), 'parakeet.data.batch.TextIDBatcher', 'TextIDBatcher', ([], {'pad_id': '(0)'}), '(pad_id=0)\n', (6729, 6739), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((7530, 7549), 'numpy.array', 'np.array', (['text_lens'], {}), '(text_lens)\n', (7538, 7549), True, 'import numpy as np\n'), ((7563, 7581), 'numpy.array', 'np.array', (['mel_lens'], {}), '(mel_lens)\n', (7571, 7581), True, 'import numpy as np\n'), ((1290, 1311), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['rank'], {}), '(rank)\n', (1305, 1311), False, 'from paddle import fluid\n'), ((1333, 1349), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (1347, 1349), False, 'from paddle import fluid\n'), ((1818, 1943), 'parakeet.data.datacargo.DataCargo', 'DataCargo', (['dataset'], {'sampler': 'sampler', 'batch_size': 'each_bs', 'shuffle': 'shuffle', 'batch_fn': 'batch_examples_vocoder', 'drop_last': '(True)'}), '(dataset, sampler=sampler, batch_size=each_bs, shuffle=shuffle,\n batch_fn=batch_examples_vocoder, drop_last=True)\n', (1827, 1943), False, 'from parakeet.data.datacargo import DataCargo\n'), ((2076, 2193), 'parakeet.data.datacargo.DataCargo', 'DataCargo', (['dataset'], {'sampler': 'sampler', 'batch_size': 'each_bs', 'shuffle': 'shuffle', 'batch_fn': 'batch_examples', 'drop_last': '(True)'}), '(dataset, sampler=sampler, batch_size=each_bs, shuffle=shuffle,\n batch_fn=batch_examples, drop_last=True)\n', (2085, 2193), False, 'from parakeet.data.datacargo import DataCargo\n'), ((4899, 4939), 'parakeet.g2p.en.text_to_sequence', 'g2p.en.text_to_sequence', (['normalized_text'], {}), '(normalized_text)\n', (4922, 4939), False, 'from parakeet import g2p\n'), ((5574, 5604), 'numpy.arange', 'np.arange', (['(1)', '(mel.shape[1] + 1)'], {}), '(1, mel.shape[1] + 1)\n', (5583, 5604), True, 'import numpy as np\n'), ((6791, 6817), 'parakeet.data.batch.SpecBatcher', 'SpecBatcher', ([], {'pad_value': '(0.0)'}), '(pad_value=0.0)\n', (6802, 6817), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((6896, 6922), 'parakeet.data.batch.SpecBatcher', 'SpecBatcher', ([], {'pad_value': '(0.0)'}), '(pad_value=0.0)\n', (6907, 6922), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((7879, 7905), 'parakeet.data.batch.SpecBatcher', 'SpecBatcher', ([], {'pad_value': '(0.0)'}), '(pad_value=0.0)\n', (7890, 7905), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((7952, 7978), 'parakeet.data.batch.SpecBatcher', 'SpecBatcher', ([], {'pad_value': '(0.0)'}), '(pad_value=0.0)\n', (7963, 7978), False, 'from parakeet.data.batch import TextIDBatcher, SpecBatcher\n'), ((5341, 5380), 'numpy.zeros', 'np.zeros', (['[mel.shape[0], 1]', 'np.float32'], {}), '([mel.shape[0], 1], np.float32)\n', (5349, 5380), True, 'import numpy as np\n')]
import numpy as np import geocoder def process_df(df): """ df: pd.DataFrame """ df.dropna(subset=['lat', 'lon'], axis=0, inplace=True) df.reset_index(drop=True, inplace=True) # Add new column to hold the years df["year"] = [int(x.split("-")[0]) for x in df['date']] # Convert coordinates to decimal degrees ISO 6709 format i.e:(14.76º, # -23.2234º) lat_flip = np.logical_and(df["lat-dir"] == "S", df["lat"] >= 0) df.loc[lat_flip, "lat"] *= -1 lon_flip = np.logical_and(df["lon-dir"] == "W", df["lon"] >= 0) df.loc[lon_flip, "lon"] *= -1 legend = [] print('Starting to pull data from Google Geolocation API') for i in range(len(df['impact-e'])): print(i+1, "of {}".format(len(df)+1)) g = geocoder.google([df['lat'][i], df['lon'][i]], method='reverse') city = '{}'.format(g.city) if g.city else "N/A" country = '{}'.format(g.country) if g.country else "N/A" if city is not None and country is not None: location = "Location: {},{}<br>".format(city, country) if df['impact-e'][i] < 10: legend.append('{}<10 kt<br>{}'.format(location, str(df['date'][i]))) else: legend.append('{}{} kt<br>{}'.format(location, df['impact-e'][i], str(df['date'][i]))) df['legend'] = legend return df
[ "geocoder.google", "numpy.logical_and" ]
[((409, 461), 'numpy.logical_and', 'np.logical_and', (["(df['lat-dir'] == 'S')", "(df['lat'] >= 0)"], {}), "(df['lat-dir'] == 'S', df['lat'] >= 0)\n", (423, 461), True, 'import numpy as np\n'), ((511, 563), 'numpy.logical_and', 'np.logical_and', (["(df['lon-dir'] == 'W')", "(df['lon'] >= 0)"], {}), "(df['lon-dir'] == 'W', df['lon'] >= 0)\n", (525, 563), True, 'import numpy as np\n'), ((777, 840), 'geocoder.google', 'geocoder.google', (["[df['lat'][i], df['lon'][i]]"], {'method': '"""reverse"""'}), "([df['lat'][i], df['lon'][i]], method='reverse')\n", (792, 840), False, 'import geocoder\n')]
""" Offset Mirror Classes. This module contains all the classes relating to the offset mirrors used in the FEE and XRT. Each offset mirror contains a stepper motor and piezo motor to control the pitch, and two pairs of motors to control the horizontal and vertical gantries. """ import logging import numpy as np from ophyd import Component as Cpt from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import FormattedComponent as FCpt from ophyd import PVPositioner from .device import GroupDevice from .doc_stubs import basic_positioner_init from .epics_motor import BeckhoffAxisNoOffset from .inout import InOutRecordPositioner from .interface import BaseInterface, FltMvInterface from .pmps import TwinCATStatePMPS from .signal import PytmcSignal from .utils import get_status_value logger = logging.getLogger(__name__) class OMMotor(FltMvInterface, PVPositioner): """Base class for each motor in the LCLS offset mirror system.""" __doc__ += basic_positioner_init # position readback = Cpt(EpicsSignalRO, ':RBV', auto_monitor=True, kind='hinted') setpoint = Cpt(EpicsSignal, ':VAL', auto_monitor=True, limits=True, kind='normal') done = Cpt(EpicsSignalRO, ':DMOV', auto_monitor=True, kind='omitted') motor_egu = Cpt(EpicsSignal, ':RBV.EGU', kind='omitted') # status interlock = Cpt(EpicsSignalRO, ':INTERLOCK', kind='omitted') enabled = Cpt(EpicsSignalRO, ':ENABLED', kind='omitted') # limit switches low_limit_switch = Cpt(EpicsSignalRO, ":LLS", kind='omitted') high_limit_switch = Cpt(EpicsSignalRO, ":HLS", kind='omitted') @property def egu(self): """ Returns the Engineering Units of the readback PV, as reported by EPICS. """ return self.motor_egu.get() def check_value(self, position): """ Checks that the value is both valid and within the motor's soft limits. Parameters ---------- position : float Position to check for validity. Raises ------ ValueError If position is `None`, `~numpy.NaN` or `~numpy.Inf`. LimitError If the position is outside the soft limits. """ # Check that we do not have a NaN or an Inf as those will # will make the PLC very unhappy ... if position is None or np.isnan(position) or np.isinf(position): raise ValueError("Invalid value inputted: '{0}'".format(position)) # Use the built-in PVPositioner check_value super().check_value(position) class Pitch(OMMotor): """ HOMS Pitch Mechanism. The axis is actually a piezo actuator and a stepper motor in series, and this is reflected in the PV naming. """ __doc__ += basic_positioner_init piezo_volts = FCpt(EpicsSignalRO, "{self._piezo}:VRBV", kind='normal') stop_signal = FCpt(EpicsSignal, "{self._piezo}:STOP", kind='omitted') # TODO: Limits will be added soon, but not present yet def __init__(self, prefix, **kwargs): # Predict the prefix of all piezo pvs self._piezo = prefix.replace('MIRR', 'PIEZO') super().__init__(prefix, **kwargs) class Gantry(OMMotor): """ Gantry Axis. The horizontal and vertical motion of the OffsetMirror are controlled by two coupled stepper motors. Instructions are sent to both by simply requesting a move on the primary so they are represented here as a single motor with additional diagnostics and interlock. Parameters ---------- prefix : str Base prefix for both stepper motors e.g. 'XRT:M1H'. Do not include the 'P' or 'S' to indicate primary or secondary steppers. gantry_prefix : str, optional Prefix for the shared gantry diagnostics if it is different than the stepper motor prefix. """ # Readbacks for gantry information gantry_difference = FCpt(EpicsSignalRO, '{self.gantry_prefix}:GDIF', kind='normal') decoupled = FCpt(EpicsSignalRO, '{self.gantry_prefix}:DECOUPLE', kind='config') # Readbacks for the secondary motor follower_readback = FCpt(EpicsSignalRO, '{self.follow_prefix}:RBV', kind='normal') follower_low_limit_switch = FCpt(EpicsSignalRO, '{self.follow_prefix}:LLS', kind='omitted') follower_high_limit_switch = FCpt(EpicsSignalRO, '{self.follow_prefix}:HLS', kind='omitted') def __init__(self, prefix, *, gantry_prefix=None, **kwargs): self.gantry_prefix = gantry_prefix or 'GANTRY:' + prefix self.follow_prefix = prefix + ':S' super().__init__(prefix + ':P', **kwargs) def check_value(self, pos): """ Add additional check for the gantry coupling. This is not a safety measure, but instead just here largely for bookkeeping and to give the operator further feedback on why the requested move is not completed. """ # Check that the gantry is not decoupled if self.decoupled.get(): raise PermissionError("The gantry is not currently coupled") # Allow OMMotor to check the value super().check_value(pos) class OffsetMirror(BaseInterface, GroupDevice): """ X-ray Offset Mirror class. This is for each individual mirror system used in the FEE and XRT. Controls for the pitch, and primary gantry x- and y-motors are included. When controlling the pitch motor, if the piezo is set to 'PID' mode, then the pitch mechanism is setup to first move the stepper as close to the desired position, then the piezo will kick in to constantly try and correct any positional changes. Parameters ---------- prefix : str The EPICS base PV of the pitch motor. prefix_xy : str The EPICS base PV of the gantry x and y gantry motors. xgantry_prefix : str The name of the horizontal gantry if not identical to the prefix. name : str The name of the offset mirror. """ # Pitch Motor pitch = FCpt(Pitch, "MIRR:{self.prefix}", kind='hinted') # Gantry motors xgantry = FCpt(Gantry, "{self._prefix_xy}:X", gantry_prefix="{self._xgantry}", add_prefix=['suffix', 'gantry_prefix'], kind='normal') ygantry = FCpt(Gantry, "{self._prefix_xy}:Y", gantry_prefix='GANTRY:{self.prefix}:Y', add_prefix=['suffix', 'gantry_prefix'], kind='config') # Transmission for Lightpath Interface transmission = 1.0 # QIcon for UX _icon = 'fa.minus-square' # Subscription types SUB_STATE = 'state' tab_whitelist = ['pitch', 'xgantry', 'ygantry'] def __init__(self, prefix, *, prefix_xy=None, xgantry_prefix=None, **kwargs): # Handle prefix mangling self._prefix_xy = prefix_xy or prefix self._xgantry = xgantry_prefix or 'GANTRY:' + prefix + ':X' super().__init__(prefix, **kwargs) @property def inserted(self): """Returns `True`. Treats OffsetMirror as always inserted.""" return True @property def removed(self): """Returns :keyword:`False`. Treats OffsetMirror as always inserted.""" return False def format_status_info(self, status_info): """ Override status info handler to render the `OffsetMirror`. Display `OffsetMirror` status info in the ipython terminal. Parameters ---------- status_info: dict Nested dictionary. Each level has keys name, kind, and is_device. If is_device is True, subdevice dictionaries may follow. Otherwise, the only other key in the dictionary will be value. Returns ------- status: str Formatted string with all relevant status information. """ # happi metadata try: md = self.root.md except AttributeError: name = f'{self.prefix}' else: beamline = get_status_value(md, 'beamline') functional_group = get_status_value(md, 'functional_group') if functional_group is not None: name = f'{self.prefix} ({beamline} {functional_group})' else: name = f'{self.prefix} ({beamline})' p_position = get_status_value(status_info, 'pitch', 'position') p_setpoint = get_status_value(status_info, 'pitch', 'setpoint', 'value') p_units = get_status_value(status_info, 'pitch', 'setpoint', 'units') return f"""\ {name} ------ pitch: ({self.pitch.prefix}) ------ position: {p_position} setpoint: {p_setpoint} [{p_units}] """ class PointingMirror(InOutRecordPositioner, OffsetMirror): """ Retractable `OffsetMirror`. Both XRT M1H and XRT M2H can be completely removed from the beam depending on the beam destination. In this case, the X gantry can be controlled via the standard PCDS states record. This class has all the functionality of `OffsetMirror` with the addition of the records that control the overall state. Parameters ---------- in_lines : list, optional List of beamlines that are delivered beam when the mirror is in. out_lines : list, optional List of beamlines thate are delivered beam when the mirror is out. """ # Reverse state order as PointingMirror is non-standard states_list = ['OUT', 'IN'] # Moving PointingMirror moves the x gantry stage_group = [OffsetMirror.xgantry] def __init__(self, prefix, *, out_lines=None, in_lines=None, **kwargs): # Branching pattern self.in_lines = in_lines or list() self.out_lines = out_lines or list() super().__init__(prefix, **kwargs) @property def destination(self): """Current list of destinations the mirror currently supports.""" # Inserted if self.inserted and not self.removed: return self.in_lines # Removed elif self.removed and not self.inserted: return self.out_lines # Unknown else: return [] @property def branches(self): """Return all possible beamlines for mirror destinations.""" return self.in_lines + self.out_lines def check_value(self, pos): """Check that our gantry is coupled before state moves.""" # Check the X gantry if self.xgantry.decoupled.get(): raise PermissionError("Can not move the horizontal gantry is " "uncoupled") # Allow StatePositioner to check the state return super().check_value(pos) class XOffsetMirror(BaseInterface, GroupDevice): """ X-ray Offset Mirror. 1st and 2nd gen Axilon designs with LCLS-II Beckhoff motion architecture. Parameters ---------- prefix : str Base PV for the mirror. name : str Alias for the device. """ # UI representation _icon = 'fa.minus-square' # Motor components: can read/write positions y_up = Cpt(BeckhoffAxisNoOffset, ':MMS:YUP', kind='hinted', doc='Yupstream master axis [um]') x_up = Cpt(BeckhoffAxisNoOffset, ':MMS:XUP', kind='hinted', doc='Xupstream master [um]') pitch = Cpt(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted', doc='Pitch stepper and piezo axes [urad]') bender = Cpt(BeckhoffAxisNoOffset, ':MMS:BENDER', kind='normal', doc='Bender motor [um]') y_dwn = Cpt(BeckhoffAxisNoOffset, ':MMS:YDWN', kind='config', doc='Ydwnstream slave axis [um]') x_dwn = Cpt(BeckhoffAxisNoOffset, ':MMS:XDWN', kind='config', doc='Xdwnstream slave axis [um]') # Gantry components gantry_x = Cpt(PytmcSignal, ':GANTRY_X', io='i', kind='normal', doc='X gantry difference [um]') gantry_y = Cpt(PytmcSignal, ':GANTRY_Y', io='i', kind='normal', doc='Y gantry difference [um]') couple_y = Cpt(PytmcSignal, ':COUPLE_Y', io='o', kind='config', doc='Couple Y motors [bool]') couple_x = Cpt(PytmcSignal, ':COUPLE_X', io='o', kind='config', doc='Couple X motors [bool]') decouple_y = Cpt(PytmcSignal, ':DECOUPLE_Y', io='o', kind='config', doc='Decouple Y motors [bool]') decouple_x = Cpt(PytmcSignal, ':DECOUPLE_X', io='o', kind='config', doc='Decouple X motors [bool]') couple_status_y = Cpt(PytmcSignal, ':ALREADY_COUPLED_Y', io='i', kind='normal') couple_status_x = Cpt(PytmcSignal, ':ALREADY_COUPLED_X', io='i', kind='normal') # RMS Cpts: y_enc_rms = Cpt(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal', doc='Yup encoder RMS deviation [um]') x_enc_rms = Cpt(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal', doc='Xup encoder RMS deviation [um]') pitch_enc_rms = Cpt(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal', doc='Pitch encoder RMS deviation [urad]') bender_enc_rms = Cpt(PytmcSignal, ':ENC:BENDER:RMS', io='i', kind='normal', doc='Bender encoder RMS deviation [um]') # Lightpath config: implement inserted, removed, transmission, subscribe # For now, keep it simple. Some mirrors need more than this, but it is # sufficient for MR1L0 and MR2L0 for today. inserted = True removed = False transmission = 1 SUB_STATE = 'state' def format_status_info(self, status_info): """ Override status info handler to render the Hard X-ray Offset Mirror. Display homs status info in the ipython terminal. Parameters ---------- status_info: dict Nested dictionary. Each level has keys name, kind, and is_device. If is_device is True, subdevice dictionaries may follow. Otherwise, the only other key in the dictionary will be value. Returns ------- status: str Formatted string with all relevant status information. """ # happi metadata try: md = self.root.md except AttributeError: name = f'{self.prefix}' else: beamline = get_status_value(md, 'beamline') functional_group = get_status_value(md, 'functional_group') if functional_group is not None: name = f'{self.prefix} ({beamline} {functional_group})' else: name = f'{self.prefix} ({beamline})' x_position = get_status_value(status_info, 'x_up', 'position') x_user_setpoint = get_status_value(status_info, 'x_up', 'user_setpoint', 'value') x_units = get_status_value(status_info, 'x_up', 'user_setpoint', 'units') x_description = get_status_value(status_info, 'x_up', 'description', 'value') p_position = get_status_value(status_info, 'pitch', 'position') p_user_setpoint = get_status_value(status_info, 'pitch', 'user_setpoint', 'value') p_units = get_status_value(status_info, 'pitch', 'user_setpoint', 'units') p_description = get_status_value(status_info, 'pitch', 'description', 'value') p_enc_rms = get_status_value(status_info, 'pitch_enc_rms', 'value') return f"""\ {name} ------ x_up: ({self.x_up.prefix}) ------ position: {x_position} user_setpoint: {x_user_setpoint} [{x_units}] description: {x_description} ------ pitch: ({self.pitch.prefix}) ------ position: {p_position} user_setpoint: {p_user_setpoint} [{p_units}] description: {p_description} pitch_enc_rms: {p_enc_rms} """ class XOffsetMirrorBend(XOffsetMirror): """ X-ray Offset Mirror with 2 bender acutators. 1st and 2nd gen Axilon designs with LCLS-II Beckhoff motion architecture. Parameters ---------- prefix : str Base PV for the mirror. name : str Alias for the device. """ # UI representation _icon = 'fa.minus-square' # Do a dumb thing and kill inherited single bender bender = None bender_enc_rms = None # Motor components: can read/write positions bender_us = Cpt(BeckhoffAxisNoOffset, ':MMS:US', kind='hinted') bender_ds = Cpt(BeckhoffAxisNoOffset, ':MMS:DS', kind='hinted') # RMS Cpts: bender_us_enc_rms = Cpt(PytmcSignal, ':ENC:US:RMS', io='i', kind='normal') bender_ds_enc_rms = Cpt(PytmcSignal, ':ENC:DS:RMS', io='i', kind='normal') # Bender RTD Cpts: us_rtd = Cpt(EpicsSignalRO, ':RTD:US:1_RBV', kind='normal') ds_rtd = Cpt(EpicsSignalRO, ':RTD:DS:1_RBV', kind='normal') # Maintain backward compatibility XOffsetMirror2 = XOffsetMirrorBend class XOffsetMirrorSwitch(XOffsetMirror): """ X-ray Offset Mirror with Yleft/Yright 1st and 2nd gen Axilon designs with LCLS-II Beckhoff motion architecture. Parameters ---------- prefix : str Base PV for the mirror. name : str Alias for the device. """ # UI representation _icon = 'fa.minus-square' # Do a dumb thing and kill inherited/unused components y_up = None y_dwn = None bender = None bender_enc_rms = None # Motor components: can read/write positions y_left = Cpt(BeckhoffAxisNoOffset, ':MMS:YLEFT', kind='hinted', doc='Yleft master axis [um]') y_right = Cpt(BeckhoffAxisNoOffset, ':MMS:YRIGHT', kind='config', doc='Yright slave axis [um]') class KBOMirror(BaseInterface, GroupDevice): """ Kirkpatrick-Baez Mirror with Bender Axes. 1st gen Toyama designs with LCLS-II Beckhoff motion architecture. Parameters ---------- prefix : str Base PV for the mirror. name : str Alias for the device. """ # UI representation _icon = 'fa.minus-square' # Motor components: can read/write positions x = Cpt(BeckhoffAxisNoOffset, ':MMS:X', kind='hinted') y = Cpt(BeckhoffAxisNoOffset, ':MMS:Y', kind='hinted') pitch = Cpt(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted') bender_us = Cpt(BeckhoffAxisNoOffset, ':MMS:BEND:US', kind='hinted') bender_ds = Cpt(BeckhoffAxisNoOffset, ':MMS:BEND:DS', kind='hinted') # RMS Cpts: x_enc_rms = Cpt(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal') y_enc_rms = Cpt(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal') pitch_enc_rms = Cpt(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal') bender_us_enc_rms = Cpt(PytmcSignal, ':ENC:BEND:US:RMS', io='i', kind='normal') bender_ds_enc_rms = Cpt(PytmcSignal, ':ENC:BEND:DS:RMS', io='i', kind='normal') # Bender RTD Cpts: us_rtd = Cpt(EpicsSignalRO, ':RTD:BEND:US:1_RBV', kind='normal') ds_rtd = Cpt(EpicsSignalRO, ':RTD:BEND:DS:1_RBV', kind='normal') # Lightpath config: implement inserted, removed, transmission, subscribe inserted = True removed = False transmission = 1 SUB_STATE = 'state' def format_status_info(self, status_info): """ Override status info handler to render the `KBOMirror`. Display `KBOMirror` status info in the ipython terminal. Parameters ---------- status_info: dict Nested dictionary. Each level has keys name, kind, and is_device. If is_device is True, subdevice dictionaries may follow. Otherwise, the only other key in the dictionary will be value. Returns ------- status: str Formatted string with all relevant status information. """ # happi metadata try: md = self.root.md except AttributeError: name = f'{self.prefix}' else: beamline = get_status_value(md, 'beamline') functional_group = get_status_value(md, 'functional_group') if functional_group is not None: name = f'{self.prefix} ({beamline} {functional_group})' else: name = f'{self.prefix} ({beamline})' x_position = get_status_value(status_info, 'x', 'position') x_user_setpoint = get_status_value(status_info, 'x', 'user_setpoint', 'value') x_units = get_status_value(status_info, 'x', 'user_setpoint', 'units') x_description = get_status_value(status_info, 'x', 'description', 'value') p_position = get_status_value(status_info, 'pitch', 'position') p_user_setpoint = get_status_value(status_info, 'pitch', 'user_setpoint', 'value') p_units = get_status_value(status_info, 'pitch', 'user_setpoint', 'units') p_description = get_status_value(status_info, 'pitch', 'description', 'value') p_enc_rms = get_status_value(status_info, 'pitch_enc_rms', 'value') b_us_position = get_status_value(status_info, 'bender_us', 'position') b_us_setpoint = get_status_value(status_info, 'bender_us', 'user_setpoint', 'value') b_us_units = get_status_value(status_info, 'bender_us', 'user_setpoint', 'units') b_us_description = get_status_value(status_info, 'bender_us', 'description', 'value') b_us_enc_rms = get_status_value(status_info, 'bender_us_enc_rms', 'value') b_ds_position = get_status_value(status_info, 'bender_ds', 'position') b_ds_setpoint = get_status_value(status_info, 'bender_ds', 'user_setpoint', 'value') b_ds_units = get_status_value(status_info, 'bender_ds', 'user_setpoint', 'units') b_ds_description = get_status_value(status_info, 'bender_ds', 'description', 'value') b_ds_enc_rms = get_status_value(status_info, 'bender_ds_enc_rms', 'value') return f"""\ {name} ------ x_up: ({self.x.prefix}) ------ position: {x_position} user_setpoint: {x_user_setpoint} [{x_units}] description: {x_description} ------ pitch: ({self.pitch.prefix}) ------ position: {p_position} user_setpoint: {p_user_setpoint} [{p_units}] description: {p_description} pitch_enc_rms: {p_enc_rms} --------- bender_us ({self.bender_us.prefix}) --------- position {b_us_position} user_setpoint: {b_us_setpoint} [{b_us_units}] description: {b_us_description} bender_us_enc_rms: {b_us_enc_rms} --------- bender_ds ({self.bender_ds.prefix}) --------- position: {b_ds_position} user_setpoint: {b_ds_setpoint} [{b_ds_units}] description: {b_ds_description} bender_ds_enc_rms: {b_ds_enc_rms} """ class FFMirror(BaseInterface, GroupDevice): """ Fixed Focus Kirkpatrick-Baez Mirror. 1st gen Toyama designs with LCLS-II Beckhoff motion architecture. Parameters ---------- prefix : str Base PV for the mirror. name : str Alias for the device. """ # UI representation _icon = 'fa.minus-square' # Motor components: can read/write positions x = Cpt(BeckhoffAxisNoOffset, ':MMS:X', kind='hinted') y = Cpt(BeckhoffAxisNoOffset, ':MMS:Y', kind='hinted') pitch = Cpt(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted') # RMS Cpts: x_enc_rms = Cpt(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal') y_enc_rms = Cpt(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal') pitch_enc_rms = Cpt(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal') # Lightpath config: implement inserted, removed, transmission, subscribe inserted = True removed = False transmission = 1 SUB_STATE = 'state' def format_status_info(self, status_info): """ Override status info handler to render the `FFMirror`. Display `FFMirror` status info in the ipython terminal. Parameters ---------- status_info: dict Nested dictionary. Each level has keys name, kind, and is_device. If is_device is True, subdevice dictionaries may follow. Otherwise, the only other key in the dictionary will be value. Returns ------- status: str Formatted string with all relevant status information. """ # happi metadata try: md = self.root.md except AttributeError: name = f'{self.prefix}' else: beamline = get_status_value(md, 'beamline') functional_group = get_status_value(md, 'functional_group') if functional_group is not None: name = f'{self.prefix} ({beamline} {functional_group})' else: name = f'{self.prefix} ({beamline})' x_position = get_status_value(status_info, 'x', 'position') x_user_setpoint = get_status_value(status_info, 'x', 'user_setpoint', 'value') x_units = get_status_value(status_info, 'x', 'user_setpoint', 'units') x_description = get_status_value(status_info, 'x', 'description', 'value') p_position = get_status_value(status_info, 'pitch', 'position') p_user_setpoint = get_status_value(status_info, 'pitch', 'user_setpoint', 'value') p_units = get_status_value(status_info, 'pitch', 'user_setpoint', 'units') p_description = get_status_value(status_info, 'pitch', 'description', 'value') p_enc_rms = get_status_value(status_info, 'pitch_enc_rms', 'value') return f"""\ {name} ------ x_up: ({self.x.prefix}) ------ position: {x_position} user_setpoint: {x_user_setpoint} [{x_units}] description: {x_description} ------ pitch: ({self.pitch.prefix}) ------ position: {p_position} user_setpoint: {p_user_setpoint} [{p_units}] description: {p_description} pitch_enc_rms: {p_enc_rms} """ class TwinCATMirrorStripe(TwinCATStatePMPS): """ Subclass of TwinCATStatePMPS for the mirror coatings. Unless most TwinCATStatePMPS, we have: - Only in_states - No in_states block the beam We also clear the states_list and set _in_if_not_out to True to automatically pick up the coatings from each mirror enum. """ states_list = [] in_states = [] out_states = [] _in_if_not_out = True @property def transmission(self): """The mirror coating never blocks the beam.""" return 1 class CoatingState(Device): """ Extra parent class to put "coating" as the first device in order. This makes it appear at the top of the screen in typhos. """ coating = Cpt(TwinCATMirrorStripe, ':COATING:STATE', kind='hinted', doc='Control of the coating states via saved positions.') class XOffsetMirrorState(XOffsetMirror, CoatingState): """ X-ray Offset Mirror with Yleft/Yright 1st and 2nd gen Axilon designs with LCLS-II Beckhoff motion architecture. With Coating State selection implemented Parameters ---------- prefix : str Base PV for the mirror. name : str Alias for the device. """ # UI representation _icon = 'fa.minus-square'
[ "logging.getLogger", "ophyd.Component", "numpy.isnan", "numpy.isinf", "ophyd.FormattedComponent" ]
[((810, 837), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (827, 837), False, 'import logging\n'), ((1023, 1083), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RBV"""'], {'auto_monitor': '(True)', 'kind': '"""hinted"""'}), "(EpicsSignalRO, ':RBV', auto_monitor=True, kind='hinted')\n", (1026, 1083), True, 'from ophyd import Component as Cpt\n'), ((1099, 1170), 'ophyd.Component', 'Cpt', (['EpicsSignal', '""":VAL"""'], {'auto_monitor': '(True)', 'limits': '(True)', 'kind': '"""normal"""'}), "(EpicsSignal, ':VAL', auto_monitor=True, limits=True, kind='normal')\n", (1102, 1170), True, 'from ophyd import Component as Cpt\n'), ((1201, 1263), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":DMOV"""'], {'auto_monitor': '(True)', 'kind': '"""omitted"""'}), "(EpicsSignalRO, ':DMOV', auto_monitor=True, kind='omitted')\n", (1204, 1263), True, 'from ophyd import Component as Cpt\n'), ((1280, 1324), 'ophyd.Component', 'Cpt', (['EpicsSignal', '""":RBV.EGU"""'], {'kind': '"""omitted"""'}), "(EpicsSignal, ':RBV.EGU', kind='omitted')\n", (1283, 1324), True, 'from ophyd import Component as Cpt\n'), ((1355, 1403), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":INTERLOCK"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, ':INTERLOCK', kind='omitted')\n", (1358, 1403), True, 'from ophyd import Component as Cpt\n'), ((1418, 1464), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":ENABLED"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, ':ENABLED', kind='omitted')\n", (1421, 1464), True, 'from ophyd import Component as Cpt\n'), ((1509, 1551), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":LLS"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, ':LLS', kind='omitted')\n", (1512, 1551), True, 'from ophyd import Component as Cpt\n'), ((1576, 1618), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":HLS"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, ':HLS', kind='omitted')\n", (1579, 1618), True, 'from ophyd import Component as Cpt\n'), ((2829, 2885), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self._piezo}:VRBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, '{self._piezo}:VRBV', kind='normal')\n", (2833, 2885), True, 'from ophyd import FormattedComponent as FCpt\n'), ((2904, 2959), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignal', '"""{self._piezo}:STOP"""'], {'kind': '"""omitted"""'}), "(EpicsSignal, '{self._piezo}:STOP', kind='omitted')\n", (2908, 2959), True, 'from ophyd import FormattedComponent as FCpt\n'), ((3939, 4002), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.gantry_prefix}:GDIF"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, '{self.gantry_prefix}:GDIF', kind='normal')\n", (3943, 4002), True, 'from ophyd import FormattedComponent as FCpt\n'), ((4048, 4115), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.gantry_prefix}:DECOUPLE"""'], {'kind': '"""config"""'}), "(EpicsSignalRO, '{self.gantry_prefix}:DECOUPLE', kind='config')\n", (4052, 4115), True, 'from ophyd import FormattedComponent as FCpt\n'), ((4201, 4263), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.follow_prefix}:RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, '{self.follow_prefix}:RBV', kind='normal')\n", (4205, 4263), True, 'from ophyd import FormattedComponent as FCpt\n'), ((4325, 4388), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.follow_prefix}:LLS"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, '{self.follow_prefix}:LLS', kind='omitted')\n", (4329, 4388), True, 'from ophyd import FormattedComponent as FCpt\n'), ((4459, 4522), 'ophyd.FormattedComponent', 'FCpt', (['EpicsSignalRO', '"""{self.follow_prefix}:HLS"""'], {'kind': '"""omitted"""'}), "(EpicsSignalRO, '{self.follow_prefix}:HLS', kind='omitted')\n", (4463, 4522), True, 'from ophyd import FormattedComponent as FCpt\n'), ((6229, 6277), 'ophyd.FormattedComponent', 'FCpt', (['Pitch', '"""MIRR:{self.prefix}"""'], {'kind': '"""hinted"""'}), "(Pitch, 'MIRR:{self.prefix}', kind='hinted')\n", (6233, 6277), True, 'from ophyd import FormattedComponent as FCpt\n'), ((6312, 6439), 'ophyd.FormattedComponent', 'FCpt', (['Gantry', '"""{self._prefix_xy}:X"""'], {'gantry_prefix': '"""{self._xgantry}"""', 'add_prefix': "['suffix', 'gantry_prefix']", 'kind': '"""normal"""'}), "(Gantry, '{self._prefix_xy}:X', gantry_prefix='{self._xgantry}',\n add_prefix=['suffix', 'gantry_prefix'], kind='normal')\n", (6316, 6439), True, 'from ophyd import FormattedComponent as FCpt\n'), ((6507, 6641), 'ophyd.FormattedComponent', 'FCpt', (['Gantry', '"""{self._prefix_xy}:Y"""'], {'gantry_prefix': '"""GANTRY:{self.prefix}:Y"""', 'add_prefix': "['suffix', 'gantry_prefix']", 'kind': '"""config"""'}), "(Gantry, '{self._prefix_xy}:Y', gantry_prefix='GANTRY:{self.prefix}:Y',\n add_prefix=['suffix', 'gantry_prefix'], kind='config')\n", (6511, 6641), True, 'from ophyd import FormattedComponent as FCpt\n'), ((11405, 11496), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:YUP"""'], {'kind': '"""hinted"""', 'doc': '"""Yupstream master axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:YUP', kind='hinted', doc=\n 'Yupstream master axis [um]')\n", (11408, 11496), True, 'from ophyd import Component as Cpt\n'), ((11518, 11604), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:XUP"""'], {'kind': '"""hinted"""', 'doc': '"""Xupstream master [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:XUP', kind='hinted', doc=\n 'Xupstream master [um]')\n", (11521, 11604), True, 'from ophyd import Component as Cpt\n'), ((11627, 11729), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:PITCH"""'], {'kind': '"""hinted"""', 'doc': '"""Pitch stepper and piezo axes [urad]"""'}), "(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted', doc=\n 'Pitch stepper and piezo axes [urad]')\n", (11630, 11729), True, 'from ophyd import Component as Cpt\n'), ((11754, 11839), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:BENDER"""'], {'kind': '"""normal"""', 'doc': '"""Bender motor [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:BENDER', kind='normal', doc='Bender motor [um]'\n )\n", (11757, 11839), True, 'from ophyd import Component as Cpt\n'), ((11864, 11956), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:YDWN"""'], {'kind': '"""config"""', 'doc': '"""Ydwnstream slave axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:YDWN', kind='config', doc=\n 'Ydwnstream slave axis [um]')\n", (11867, 11956), True, 'from ophyd import Component as Cpt\n'), ((11980, 12072), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:XDWN"""'], {'kind': '"""config"""', 'doc': '"""Xdwnstream slave axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:XDWN', kind='config', doc=\n 'Xdwnstream slave axis [um]')\n", (11983, 12072), True, 'from ophyd import Component as Cpt\n'), ((12124, 12213), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":GANTRY_X"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""X gantry difference [um]"""'}), "(PytmcSignal, ':GANTRY_X', io='i', kind='normal', doc=\n 'X gantry difference [um]')\n", (12127, 12213), True, 'from ophyd import Component as Cpt\n'), ((12243, 12332), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":GANTRY_Y"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Y gantry difference [um]"""'}), "(PytmcSignal, ':GANTRY_Y', io='i', kind='normal', doc=\n 'Y gantry difference [um]')\n", (12246, 12332), True, 'from ophyd import Component as Cpt\n'), ((12362, 12449), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":COUPLE_Y"""'], {'io': '"""o"""', 'kind': '"""config"""', 'doc': '"""Couple Y motors [bool]"""'}), "(PytmcSignal, ':COUPLE_Y', io='o', kind='config', doc=\n 'Couple Y motors [bool]')\n", (12365, 12449), True, 'from ophyd import Component as Cpt\n'), ((12479, 12566), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":COUPLE_X"""'], {'io': '"""o"""', 'kind': '"""config"""', 'doc': '"""Couple X motors [bool]"""'}), "(PytmcSignal, ':COUPLE_X', io='o', kind='config', doc=\n 'Couple X motors [bool]')\n", (12482, 12566), True, 'from ophyd import Component as Cpt\n'), ((12598, 12689), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":DECOUPLE_Y"""'], {'io': '"""o"""', 'kind': '"""config"""', 'doc': '"""Decouple Y motors [bool]"""'}), "(PytmcSignal, ':DECOUPLE_Y', io='o', kind='config', doc=\n 'Decouple Y motors [bool]')\n", (12601, 12689), True, 'from ophyd import Component as Cpt\n'), ((12723, 12814), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":DECOUPLE_X"""'], {'io': '"""o"""', 'kind': '"""config"""', 'doc': '"""Decouple X motors [bool]"""'}), "(PytmcSignal, ':DECOUPLE_X', io='o', kind='config', doc=\n 'Decouple X motors [bool]')\n", (12726, 12814), True, 'from ophyd import Component as Cpt\n'), ((12853, 12914), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ALREADY_COUPLED_Y"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ALREADY_COUPLED_Y', io='i', kind='normal')\n", (12856, 12914), True, 'from ophyd import Component as Cpt\n'), ((12963, 13024), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ALREADY_COUPLED_X"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ALREADY_COUPLED_X', io='i', kind='normal')\n", (12966, 13024), True, 'from ophyd import Component as Cpt\n'), ((13083, 13179), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:Y:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Yup encoder RMS deviation [um]"""'}), "(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal', doc=\n 'Yup encoder RMS deviation [um]')\n", (13086, 13179), True, 'from ophyd import Component as Cpt\n'), ((13211, 13307), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:X:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Xup encoder RMS deviation [um]"""'}), "(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal', doc=\n 'Xup encoder RMS deviation [um]')\n", (13214, 13307), True, 'from ophyd import Component as Cpt\n'), ((13343, 13447), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:PITCH:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Pitch encoder RMS deviation [urad]"""'}), "(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal', doc=\n 'Pitch encoder RMS deviation [urad]')\n", (13346, 13447), True, 'from ophyd import Component as Cpt\n'), ((13488, 13592), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:BENDER:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""', 'doc': '"""Bender encoder RMS deviation [um]"""'}), "(PytmcSignal, ':ENC:BENDER:RMS', io='i', kind='normal', doc=\n 'Bender encoder RMS deviation [um]')\n", (13491, 13592), True, 'from ophyd import Component as Cpt\n'), ((16880, 16931), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:US"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:US', kind='hinted')\n", (16883, 16931), True, 'from ophyd import Component as Cpt\n'), ((16948, 16999), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:DS"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:DS', kind='hinted')\n", (16951, 16999), True, 'from ophyd import Component as Cpt\n'), ((17041, 17095), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:US:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:US:RMS', io='i', kind='normal')\n", (17044, 17095), True, 'from ophyd import Component as Cpt\n'), ((17148, 17202), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:DS:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:DS:RMS', io='i', kind='normal')\n", (17151, 17202), True, 'from ophyd import Component as Cpt\n'), ((17268, 17318), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RTD:US:1_RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, ':RTD:US:1_RBV', kind='normal')\n", (17271, 17318), True, 'from ophyd import Component as Cpt\n'), ((17332, 17382), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RTD:DS:1_RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, ':RTD:DS:1_RBV', kind='normal')\n", (17335, 17382), True, 'from ophyd import Component as Cpt\n'), ((18015, 18104), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:YLEFT"""'], {'kind': '"""hinted"""', 'doc': '"""Yleft master axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:YLEFT', kind='hinted', doc=\n 'Yleft master axis [um]')\n", (18018, 18104), True, 'from ophyd import Component as Cpt\n'), ((18131, 18221), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:YRIGHT"""'], {'kind': '"""config"""', 'doc': '"""Yright slave axis [um]"""'}), "(BeckhoffAxisNoOffset, ':MMS:YRIGHT', kind='config', doc=\n 'Yright slave axis [um]')\n", (18134, 18221), True, 'from ophyd import Component as Cpt\n'), ((18653, 18703), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:X"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:X', kind='hinted')\n", (18656, 18703), True, 'from ophyd import Component as Cpt\n'), ((18712, 18762), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:Y"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:Y', kind='hinted')\n", (18715, 18762), True, 'from ophyd import Component as Cpt\n'), ((18775, 18829), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:PITCH"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted')\n", (18778, 18829), True, 'from ophyd import Component as Cpt\n'), ((18846, 18902), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:BEND:US"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:BEND:US', kind='hinted')\n", (18849, 18902), True, 'from ophyd import Component as Cpt\n'), ((18919, 18975), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:BEND:DS"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:BEND:DS', kind='hinted')\n", (18922, 18975), True, 'from ophyd import Component as Cpt\n'), ((19009, 19062), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:X:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal')\n", (19012, 19062), True, 'from ophyd import Component as Cpt\n'), ((19079, 19132), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:Y:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal')\n", (19082, 19132), True, 'from ophyd import Component as Cpt\n'), ((19153, 19210), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:PITCH:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal')\n", (19156, 19210), True, 'from ophyd import Component as Cpt\n'), ((19235, 19294), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:BEND:US:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:BEND:US:RMS', io='i', kind='normal')\n", (19238, 19294), True, 'from ophyd import Component as Cpt\n'), ((19347, 19406), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:BEND:DS:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:BEND:DS:RMS', io='i', kind='normal')\n", (19350, 19406), True, 'from ophyd import Component as Cpt\n'), ((19472, 19527), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RTD:BEND:US:1_RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, ':RTD:BEND:US:1_RBV', kind='normal')\n", (19475, 19527), True, 'from ophyd import Component as Cpt\n'), ((19541, 19596), 'ophyd.Component', 'Cpt', (['EpicsSignalRO', '""":RTD:BEND:DS:1_RBV"""'], {'kind': '"""normal"""'}), "(EpicsSignalRO, ':RTD:BEND:DS:1_RBV', kind='normal')\n", (19544, 19596), True, 'from ophyd import Component as Cpt\n'), ((24196, 24246), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:X"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:X', kind='hinted')\n", (24199, 24246), True, 'from ophyd import Component as Cpt\n'), ((24255, 24305), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:Y"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:Y', kind='hinted')\n", (24258, 24305), True, 'from ophyd import Component as Cpt\n'), ((24318, 24372), 'ophyd.Component', 'Cpt', (['BeckhoffAxisNoOffset', '""":MMS:PITCH"""'], {'kind': '"""hinted"""'}), "(BeckhoffAxisNoOffset, ':MMS:PITCH', kind='hinted')\n", (24321, 24372), True, 'from ophyd import Component as Cpt\n'), ((24406, 24459), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:X:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:X:RMS', io='i', kind='normal')\n", (24409, 24459), True, 'from ophyd import Component as Cpt\n'), ((24476, 24529), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:Y:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:Y:RMS', io='i', kind='normal')\n", (24479, 24529), True, 'from ophyd import Component as Cpt\n'), ((24550, 24607), 'ophyd.Component', 'Cpt', (['PytmcSignal', '""":ENC:PITCH:RMS"""'], {'io': '"""i"""', 'kind': '"""normal"""'}), "(PytmcSignal, ':ENC:PITCH:RMS', io='i', kind='normal')\n", (24553, 24607), True, 'from ophyd import Component as Cpt\n'), ((27917, 28037), 'ophyd.Component', 'Cpt', (['TwinCATMirrorStripe', '""":COATING:STATE"""'], {'kind': '"""hinted"""', 'doc': '"""Control of the coating states via saved positions."""'}), "(TwinCATMirrorStripe, ':COATING:STATE', kind='hinted', doc=\n 'Control of the coating states via saved positions.')\n", (27920, 28037), True, 'from ophyd import Component as Cpt\n'), ((2377, 2395), 'numpy.isnan', 'np.isnan', (['position'], {}), '(position)\n', (2385, 2395), True, 'import numpy as np\n'), ((2399, 2417), 'numpy.isinf', 'np.isinf', (['position'], {}), '(position)\n', (2407, 2417), True, 'import numpy as np\n')]
# Copyright (c) 2020 <NAME> from baselines.common import Dataset, explained_variance, fmt_row, zipsame from baselines import logger import baselines.common.tf_util as U import tensorflow as tf, numpy as np import time from baselines.common.mpi_adam import MpiAdam from baselines.common.mpi_moments import mpi_moments from mpi4py import MPI from collections import deque import pdb import os import shutil from scipy import spatial import gym def traj_segment_generator(pi, env, horizon, stochastic, num_options,saves,results,rewbuffer,dc): # sample state action pairs, i.e. sample rollouts on the real system max_action = env.action_space.high t = 0 glob_count = 0 glob_count_thresh = -1 ac = env.action_space.sample() # not used, just so we have the datatype new = True # marks if we're on first timestep of an episode ob = env.reset() ob_env_shape = np.shape(ob) ac_env_shape = np.shape(ac) ac = pi.reset_last_act().eval() ob = np.concatenate((ob,ac)) cur_ep_ret = 0 # return in current episode cur_ep_len = 0 # len of current episode ep_rets = [] # returns of completed episodes in this segment ep_lens = [] # lengths of ... # Initialize history arrays obs = np.array([ob for _ in range(horizon)]) rews = np.zeros(horizon, 'float32') realrews = np.zeros(horizon, 'float32') vpreds = np.zeros(horizon, 'float32') news = np.zeros(horizon, 'int32') opts = np.zeros(horizon, 'int32') acs = np.array([ac for _ in range(horizon)]) prevacs = acs.copy() option = pi.get_option(ob) if (glob_count<glob_count_thresh): option = 1 optpol_p=[] term_p=[] value_val=[] opt_duration = [[] for _ in range(num_options)] logstds = [[] for _ in range(num_options)] curr_opt_duration = 0. while True: # in here collect the state action pairs: prevac = ac # remember u[k-1] ob[ob_env_shape[0]:] = ac # evaluate policy and recieve action ac, vpred, feats,logstd = pi.act(stochastic, ob, option) logstds[option].append(logstd) # Slight weirdness here because we need value function at time T # before returning segment [0, T-1] so we get the correct # terminal value if t > 0 and t % horizon == 0: yield {"ob" : obs, "rew" : rews, "realrew": realrews, "vpred" : vpreds, "new" : news, "ac" : acs, "opts" : opts, "prevac" : prevacs, "nextvpred": vpred * (1 - new), "ep_rets" : ep_rets, "ep_lens" : ep_lens, 'term_p': term_p, 'value_val': value_val, "opt_dur": opt_duration, "optpol_p":optpol_p, "logstds": logstds} # Be careful!!! if you change the downstream algorithm to aggregate # several of these batches, then be sure to do a deepcopy ep_rets = [] ep_lens = [] term_p = [] value_val=[] opt_duration = [[] for _ in range(num_options)] logstds = [[] for _ in range(num_options)] curr_opt_duration = 0. glob_count += 1 i = t % horizon obs[i] = ob vpreds[i] = vpred news[i] = new opts[i] = option acs[i] = ac prevacs[i] = prevac # Careful: Without this "copy" operation the variable ac is actually modified... # Apply the action to the environment ob[:ob_env_shape[0]], rew, new, _ = env.step(max_action*np.copy(ac)) # IMPORTANT: here there is no triggering decision rew = rew*1.0 rew = rew/10 if num_options > 1 else rew # To stabilize learning. rews[i] = rew realrews[i] = rew curr_opt_duration += 1 ### Book-keeping t_p = [] v_val = [] for oopt in range(num_options): v_val.append(pi.get_vpred([ob],[oopt])[0][0]) t_p.append(pi.get_tpred([ob],[oopt])[0][0]) term_p.append(t_p) optpol_p.append(pi._get_op([ob])[0][0]) value_val.append(v_val) term = pi.get_term([ob],[option])[0][0] # in case of termination, decide which option to execute next: if term: opt_duration[option].append(curr_opt_duration) curr_opt_duration = 0. option = pi.get_option(ob) if (glob_count<glob_count_thresh): option = 1 cur_ep_ret += rew*10 if num_options > 1 else rew cur_ep_len += 1 if new: # if new rollout starts -> reset last action and start anew ep_rets.append(cur_ep_ret) ep_lens.append(cur_ep_len) cur_ep_ret = 0 cur_ep_len = 0 ob[:ob_env_shape[0]] = env.reset() ob[ob_env_shape[0]:] = pi.reset_last_act().eval() ac = pi.reset_last_act().eval() option = pi.get_option(ob) if (glob_count<glob_count_thresh): option = 1 t += 1 def add_vtarg_and_adv(seg, gamma, lam): """ Compute target value using TD(lambda) estimator, and advantage with GAE(lambda) """ new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1 vpred = np.append(seg["vpred"], seg["nextvpred"]) T = len(seg["rew"]) seg["adv"] = gaelam = np.empty(T, 'float32') rew = seg["rew"] lastgaelam = 0 for t in reversed(range(T)): nonterminal = 1-new[t+1] delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t] gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam seg["tdlamret"] = seg["adv"] + seg["vpred"] def learn(env, policy_func, *, timesteps_per_batch, # timesteps per actor per update clip_param, entcoeff, # clipping parameter epsilon, entropy coeff optim_epochs, optim_stepsize, optim_batchsize,# optimization hypers gamma, lam, # advantage estimation max_timesteps=0, max_episodes=0, max_iters=0, max_seconds=0, # time constraint callback=None, # you can do anything in the callback, since it takes locals(), globals() adam_epsilon=1e-5, schedule='constant', # annealing for stepsize parameters (epsilon and adam) num_options=1, app='', saves=False, wsaves=False, epoch=-1, seed=1, dc=0 ): optim_batchsize_ideal = optim_batchsize np.random.seed(seed) tf.set_random_seed(seed) env.seed(seed) ### Book-keeping gamename = env.spec.id[:-3].lower() gamename += 'seed' + str(seed) gamename += app # This variable: "version name, defines the name of the training" version_name = 'NORM-ACT-LOWER-LR-len-400-wNoise-update1-ppo-ESCH-1-own-impl-both-equal' dirname = '{}_{}_{}opts_saves/'.format(version_name,gamename,num_options) print (dirname) # retrieve everything using relative paths. Create a train_results folder where the repo has been cloned dirname_rel = os.path.dirname(__file__) splitted = dirname_rel.split("/") dirname_rel = ("/".join(dirname_rel.split("/")[:len(splitted)-3])+"/") dirname = dirname_rel + "train_results/" + dirname # if saving -> create the necessary directories if wsaves: first=True if not os.path.exists(dirname): os.makedirs(dirname) first = False # copy also the original files into the folder where the training results are stored files = ['pposgd_simple.py','mlp_policy.py','run_mujoco.py'] first = True for i in range(len(files)): src = os.path.join(dirname_rel,'baselines/baselines/ppo1/') + files[i] print (src) #dest = os.path.join('/home/nfunk/results_NEW/ppo1/') + dirname dest = dirname + "src_code/" if (first): os.makedirs(dest) first = False print (dest) shutil.copy2(src,dest) # brute force copy normal env file at end of copying process: src = os.path.join(dirname_rel,'nfunk/envs_nf/pendulum_nf.py') shutil.copy2(src,dest) shutil.copy2(src,dest) os.makedirs(dest+"assets/") src = os.path.join(dirname_rel,'nfunk/envs_nf/assets/clockwise.png') shutil.copy2(src,dest+"assets/") ### # Setup losses and stuff # ---------------------------------------- ob_space = env.observation_space ac_space = env.action_space max_action = env.action_space.high # add the dimension in the observation space! ob_space.shape =((ob_space.shape[0] + ac_space.shape[0]),) print (ob_space.shape) print (ac_space.shape) pi = policy_func("pi", ob_space, ac_space) # Construct network for new policy oldpi = policy_func("oldpi", ob_space, ac_space) # Network for old policy atarg = tf.placeholder(dtype=tf.float32, shape=[None]) # Target advantage function ret = tf.placeholder(dtype=tf.float32, shape=[None]) # Empirical return pol_ov_op_ent = tf.placeholder(dtype=tf.float32, shape=None) # Entropy coefficient for policy over options lrmult = tf.placeholder(name='lrmult', dtype=tf.float32, shape=[]) # learning rate multiplier, updated with schedule clip_param = clip_param * lrmult # Annealed cliping parameter epislon for PPO # setup observation, option and terminal advantace ob = U.get_placeholder_cached(name="ob") option = U.get_placeholder_cached(name="option") term_adv = U.get_placeholder(name='term_adv', dtype=tf.float32, shape=[None]) # create variable for action ac = pi.pdtype.sample_placeholder([None]) kloldnew = oldpi.pd.kl(pi.pd) ent = pi.pd.entropy() meankl = U.mean(kloldnew) meanent = U.mean(ent) pol_entpen = (-entcoeff) * meanent # propability of choosing action under new policy vs old policy (PPO) ratio = tf.exp(pi.pd.logp(ac) - oldpi.pd.logp(ac)) # advantage of choosing the action atarg_clip = atarg # surrogate 1: surr1 = ratio * atarg_clip #atarg # surrogate from conservative policy iteration # surrogate 2: surr2 = U.clip(ratio, 1.0 - clip_param, 1.0 + clip_param) * atarg_clip # PPO's pessimistic surrogate (L^CLIP) pol_surr = - U.mean(tf.minimum(surr1, surr2)) # Loss on the Q-function vf_loss = U.mean(tf.square(pi.vpred - ret)) # calculate the total loss total_loss = pol_surr + vf_loss losses = [pol_surr, pol_entpen, vf_loss, meankl, meanent] loss_names = ["pol_surr", "pol_entpen", "vf_loss", "kl", "ent"] # calculate logarithm of propability of policy over options log_pi = tf.log(tf.clip_by_value(pi.op_pi, 1e-5, 1.0)) # calculate logarithm of propability of policy over options old parameter old_log_pi = tf.log(tf.clip_by_value(oldpi.op_pi, 1e-5, 1.0)) # calculate entropy of policy over options entropy = -tf.reduce_sum(pi.op_pi * log_pi, reduction_indices=1) # calculate the ppo update for the policy over options: ratio_pol_ov_op = tf.exp(tf.transpose(log_pi)[option[0]] - tf.transpose(old_log_pi)[option[0]]) # pnew / pold term_adv_clip = term_adv surr1_pol_ov_op = ratio_pol_ov_op * term_adv_clip # surrogate from conservative policy iteration surr2_pol_ov_op = U.clip(ratio_pol_ov_op, 1.0 - clip_param, 1.0 + clip_param) * term_adv_clip # pol_surr_pol_ov_op = - U.mean(tf.minimum(surr1_pol_ov_op, surr2_pol_ov_op)) # PPO's pessimistic surrogate (L^CLIP) op_loss = pol_surr_pol_ov_op - pol_ov_op_ent*tf.reduce_sum(entropy) # add loss of policy over options to total loss total_loss += op_loss var_list = pi.get_trainable_variables() term_list = var_list[6:8] # define function that we will later do gradien descent on lossandgrad = U.function([ob, ac, atarg, ret, lrmult,option, term_adv,pol_ov_op_ent], losses + [U.flatgrad(total_loss, var_list)]) # define adam optimizer adam = MpiAdam(var_list, epsilon=adam_epsilon) # define function that will assign the current parameters to the old policy assign_old_eq_new = U.function([],[], updates=[tf.assign(oldv, newv) for (oldv, newv) in zipsame(oldpi.get_variables(), pi.get_variables())]) compute_losses = U.function([ob, ac, atarg, ret, lrmult, option], losses) U.initialize() adam.sync() # NOW: all the stuff for training was defined, from here on we start with the execution: # initialize "savers" which will store the results saver = tf.train.Saver(max_to_keep=10000) saver_best = tf.train.Saver(max_to_keep=1) ### Define the names of the .csv files that are going to be stored results=[] if saves: results = open(dirname + version_name + '_' + gamename +'_'+str(num_options)+'opts_'+'_results.csv','w') results_best_model = open(dirname + version_name + '_' + gamename +'_'+str(num_options)+'opts_'+'_bestmodel.csv','w') out = 'epoch,avg_reward' for opt in range(num_options): out += ',option {} dur'.format(opt) for opt in range(num_options): out += ',option {} std'.format(opt) for opt in range(num_options): out += ',option {} term'.format(opt) for opt in range(num_options): out += ',option {} adv'.format(opt) out+='\n' results.write(out) # results.write('epoch,avg_reward,option 1 dur, option 2 dur, option 1 term, option 2 term\n') results.flush() # speciality: if running the training with epoch argument -> a model is loaded if epoch >= 0: dirname = '{}_{}opts_saves/'.format(gamename,num_options) print("Loading weights from iteration: " + str(epoch)) filename = dirname + '{}_epoch_{}.ckpt'.format(gamename,epoch) saver.restore(U.get_session(),filename) ### # start training episodes_so_far = 0 timesteps_so_far = 0 global iters_so_far iters_so_far = 0 des_pol_op_ent = 0.1 # define policy over options entropy scheduling max_val = -100000 # define max_val, this will be updated to always store the best model tstart = time.time() lenbuffer = deque(maxlen=100) # rolling buffer for episode lengths rewbuffer = deque(maxlen=100) # rolling buffer for episode rewards assert sum([max_iters>0, max_timesteps>0, max_episodes>0, max_seconds>0])==1, "Only one time constraint permitted" # Prepare for rollouts # ---------------------------------------- seg_gen = traj_segment_generator(pi, env, timesteps_per_batch, stochastic=True, num_options=num_options,saves=saves,results=results,rewbuffer=rewbuffer,dc=dc) datas = [0 for _ in range(num_options)] while True: if callback: callback(locals(), globals()) if max_timesteps and timesteps_so_far >= max_timesteps: break elif max_episodes and episodes_so_far >= max_episodes: break elif max_iters and iters_so_far >= max_iters: break elif max_seconds and time.time() - tstart >= max_seconds: break if schedule == 'constant': cur_lrmult = 1.0 elif schedule == 'linear': cur_lrmult = max(1.0 - float(timesteps_so_far) / max_timesteps, 0) else: raise NotImplementedError logger.log("********** Iteration %i ************"%iters_so_far) # Sample (s,a)-Transitions seg = seg_gen.__next__() # Calculate A(s,a,o) using GAE add_vtarg_and_adv(seg, gamma, lam) # calculate information for logging opt_d = [] for i in range(num_options): dur = np.mean(seg['opt_dur'][i]) if len(seg['opt_dur'][i]) > 0 else 0. opt_d.append(dur) std = [] for i in range(num_options): logstd = np.mean(seg['logstds'][i]) if len(seg['logstds'][i]) > 0 else 0. std.append(np.exp(logstd)) print("mean opt dur:", opt_d) print("mean op pol:", np.mean(np.array(seg['optpol_p']),axis=0)) print("mean term p:", np.mean(np.array(seg['term_p']),axis=0)) print("mean value val:", np.mean(np.array(seg['value_val']),axis=0)) ob, ac, opts, atarg, tdlamret = seg["ob"], seg["ac"], seg["opts"], seg["adv"], seg["tdlamret"] vpredbefore = seg["vpred"] # predicted value function before udpate atarg = (atarg - atarg.mean()) / atarg.std() # standardized advantage function estimate if hasattr(pi, "ob_rms"): pi.ob_rms.update(ob) # update running mean/std for policy if hasattr(pi, "ob_rms_only"): pi.ob_rms_only.update(ob[:,:-ac_space.shape[0]]) # update running mean/std for policy assign_old_eq_new() # set old parameter values to new parameter values # if iterations modulo 1000 -> adapt entropy scheduling coefficient if (iters_so_far+1)%1000 == 0: des_pol_op_ent = des_pol_op_ent/10 # every 50 epochs save the best model if iters_so_far % 50 == 0 and wsaves: print("weights are saved...") filename = dirname + '{}_epoch_{}.ckpt'.format(gamename,iters_so_far) save_path = saver.save(U.get_session(),filename) # adaptively save best model -> if current reward is highest, save the model if (np.mean(rewbuffer)>max_val) and wsaves: max_val = np.mean(rewbuffer) results_best_model.write('epoch: '+str(iters_so_far) + 'rew: ' + str(np.mean(rewbuffer)) + '\n') results_best_model.flush() filename = dirname + 'best.ckpt'.format(gamename,iters_so_far) save_path = saver_best.save(U.get_session(),filename) # minimum batch size: min_batch=160 t_advs = [[] for _ in range(num_options)] # select all the samples concering one of the options # Note: so far the update is that we first use all samples from option 0 to update, then we use all samples from option 1 to update for opt in range(num_options): indices = np.where(opts==opt)[0] print("batch size:",indices.size) opt_d[opt] = indices.size if not indices.size: t_advs[opt].append(0.) continue ### This part is only necessasry when we use options. We proceed to these verifications in order not to discard any collected trajectories. if datas[opt] != 0: if (indices.size < min_batch and datas[opt].n > min_batch): datas[opt] = Dataset(dict(ob=ob[indices], ac=ac[indices], atarg=atarg[indices], vtarg=tdlamret[indices]), shuffle=not pi.recurrent) t_advs[opt].append(0.) continue elif indices.size + datas[opt].n < min_batch: # pdb.set_trace() oldmap = datas[opt].data_map cat_ob = np.concatenate((oldmap['ob'],ob[indices])) cat_ac = np.concatenate((oldmap['ac'],ac[indices])) cat_atarg = np.concatenate((oldmap['atarg'],atarg[indices])) cat_vtarg = np.concatenate((oldmap['vtarg'],tdlamret[indices])) datas[opt] = Dataset(dict(ob=cat_ob, ac=cat_ac, atarg=cat_atarg, vtarg=cat_vtarg), shuffle=not pi.recurrent) t_advs[opt].append(0.) continue elif (indices.size + datas[opt].n > min_batch and datas[opt].n < min_batch) or (indices.size > min_batch and datas[opt].n < min_batch): oldmap = datas[opt].data_map cat_ob = np.concatenate((oldmap['ob'],ob[indices])) cat_ac = np.concatenate((oldmap['ac'],ac[indices])) cat_atarg = np.concatenate((oldmap['atarg'],atarg[indices])) cat_vtarg = np.concatenate((oldmap['vtarg'],tdlamret[indices])) datas[opt] = d = Dataset(dict(ob=cat_ob, ac=cat_ac, atarg=cat_atarg, vtarg=cat_vtarg), shuffle=not pi.recurrent) if (indices.size > min_batch and datas[opt].n > min_batch): datas[opt] = d = Dataset(dict(ob=ob[indices], ac=ac[indices], atarg=atarg[indices], vtarg=tdlamret[indices]), shuffle=not pi.recurrent) elif datas[opt] == 0: datas[opt] = d = Dataset(dict(ob=ob[indices], ac=ac[indices], atarg=atarg[indices], vtarg=tdlamret[indices]), shuffle=not pi.recurrent) ### # define the batchsize of the optimizer: optim_batchsize = optim_batchsize or ob.shape[0] print("optim epochs:", optim_epochs) logger.log("Optimizing...") # Here we do a bunch of optimization epochs over the data for _ in range(optim_epochs): losses = [] # list of tuples, each of which gives the loss for a minibatch for batch in d.iterate_once(optim_batchsize): # Calculate advantage for using specific option here tadv,nodc_adv = pi.get_opt_adv(batch["ob"],[opt]) tadv = tadv if num_options > 1 else np.zeros_like(tadv) t_advs[opt].append(nodc_adv) # calculate the gradient *newlosses, grads = lossandgrad(batch["ob"], batch["ac"], batch["atarg"], batch["vtarg"], cur_lrmult, [opt], tadv,des_pol_op_ent) # perform gradient update adam.update(grads, optim_stepsize * cur_lrmult) losses.append(newlosses) # do logging: lrlocal = (seg["ep_lens"], seg["ep_rets"]) # local values listoflrpairs = MPI.COMM_WORLD.allgather(lrlocal) # list of tuples lens, rews = map(flatten_lists, zip(*listoflrpairs)) lenbuffer.extend(lens) rewbuffer.extend(rews) logger.record_tabular("EpLenMean", np.mean(lenbuffer)) logger.record_tabular("EpRewMean", np.mean(rewbuffer)) logger.record_tabular("EpThisIter", len(lens)) episodes_so_far += len(lens) timesteps_so_far += sum(lens) iters_so_far += 1 logger.record_tabular("EpisodesSoFar", episodes_so_far) logger.record_tabular("TimestepsSoFar", timesteps_so_far) logger.record_tabular("TimeElapsed", time.time() - tstart) if MPI.COMM_WORLD.Get_rank()==0: logger.dump_tabular() ### Book keeping if saves: out = "{},{}" for _ in range(num_options): out+=",{},{},{},{}" out+="\n" info = [iters_so_far, np.mean(rewbuffer)] for i in range(num_options): info.append(opt_d[i]) for i in range(num_options): info.append(std[i]) for i in range(num_options): info.append(np.mean(np.array(seg['term_p']),axis=0)[i]) for i in range(num_options): info.append(np.mean(t_advs[i])) results.write(out.format(*info)) results.flush() ### def flatten_lists(listoflists): return [el for list_ in listoflists for el in list_]
[ "baselines.common.tf_util.get_session", "baselines.common.mpi_adam.MpiAdam", "tensorflow.transpose", "tensorflow.reduce_sum", "mpi4py.MPI.COMM_WORLD.allgather", "numpy.array", "baselines.logger.log", "tensorflow.set_random_seed", "baselines.common.tf_util.get_placeholder_cached", "baselines.common.tf_util.clip", "baselines.common.tf_util.get_placeholder", "os.path.exists", "numpy.mean", "collections.deque", "shutil.copy2", "numpy.where", "tensorflow.placeholder", "numpy.exp", "tensorflow.assign", "baselines.common.tf_util.mean", "numpy.empty", "numpy.random.seed", "numpy.concatenate", "tensorflow.square", "tensorflow.clip_by_value", "baselines.common.tf_util.flatgrad", "os.path.dirname", "baselines.common.tf_util.initialize", "numpy.shape", "time.time", "tensorflow.minimum", "numpy.copy", "baselines.logger.record_tabular", "os.makedirs", "tensorflow.train.Saver", "os.path.join", "baselines.logger.dump_tabular", "numpy.append", "numpy.zeros", "numpy.zeros_like", "mpi4py.MPI.COMM_WORLD.Get_rank", "baselines.common.tf_util.function" ]
[((895, 907), 'numpy.shape', 'np.shape', (['ob'], {}), '(ob)\n', (903, 907), True, 'import tensorflow as tf, numpy as np\n'), ((927, 939), 'numpy.shape', 'np.shape', (['ac'], {}), '(ac)\n', (935, 939), True, 'import tensorflow as tf, numpy as np\n'), ((987, 1011), 'numpy.concatenate', 'np.concatenate', (['(ob, ac)'], {}), '((ob, ac))\n', (1001, 1011), True, 'import tensorflow as tf, numpy as np\n'), ((1295, 1323), 'numpy.zeros', 'np.zeros', (['horizon', '"""float32"""'], {}), "(horizon, 'float32')\n", (1303, 1323), True, 'import tensorflow as tf, numpy as np\n'), ((1339, 1367), 'numpy.zeros', 'np.zeros', (['horizon', '"""float32"""'], {}), "(horizon, 'float32')\n", (1347, 1367), True, 'import tensorflow as tf, numpy as np\n'), ((1381, 1409), 'numpy.zeros', 'np.zeros', (['horizon', '"""float32"""'], {}), "(horizon, 'float32')\n", (1389, 1409), True, 'import tensorflow as tf, numpy as np\n'), ((1421, 1447), 'numpy.zeros', 'np.zeros', (['horizon', '"""int32"""'], {}), "(horizon, 'int32')\n", (1429, 1447), True, 'import tensorflow as tf, numpy as np\n'), ((1459, 1485), 'numpy.zeros', 'np.zeros', (['horizon', '"""int32"""'], {}), "(horizon, 'int32')\n", (1467, 1485), True, 'import tensorflow as tf, numpy as np\n'), ((5192, 5216), 'numpy.append', 'np.append', (["seg['new']", '(0)'], {}), "(seg['new'], 0)\n", (5201, 5216), True, 'import tensorflow as tf, numpy as np\n'), ((5314, 5355), 'numpy.append', 'np.append', (["seg['vpred']", "seg['nextvpred']"], {}), "(seg['vpred'], seg['nextvpred'])\n", (5323, 5355), True, 'import tensorflow as tf, numpy as np\n'), ((5406, 5428), 'numpy.empty', 'np.empty', (['T', '"""float32"""'], {}), "(T, 'float32')\n", (5414, 5428), True, 'import tensorflow as tf, numpy as np\n'), ((6507, 6527), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (6521, 6527), True, 'import tensorflow as tf, numpy as np\n'), ((6532, 6556), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (6550, 6556), True, 'import tensorflow as tf, numpy as np\n'), ((7084, 7109), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (7099, 7109), False, 'import os\n'), ((8949, 8995), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None]'}), '(dtype=tf.float32, shape=[None])\n', (8963, 8995), True, 'import tensorflow as tf, numpy as np\n'), ((9035, 9081), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None]'}), '(dtype=tf.float32, shape=[None])\n', (9049, 9081), True, 'import tensorflow as tf, numpy as np\n'), ((9121, 9165), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': 'None'}), '(dtype=tf.float32, shape=None)\n', (9135, 9165), True, 'import tensorflow as tf, numpy as np\n'), ((9227, 9284), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""lrmult"""', 'dtype': 'tf.float32', 'shape': '[]'}), "(name='lrmult', dtype=tf.float32, shape=[])\n", (9241, 9284), True, 'import tensorflow as tf, numpy as np\n'), ((9483, 9518), 'baselines.common.tf_util.get_placeholder_cached', 'U.get_placeholder_cached', ([], {'name': '"""ob"""'}), "(name='ob')\n", (9507, 9518), True, 'import baselines.common.tf_util as U\n'), ((9532, 9571), 'baselines.common.tf_util.get_placeholder_cached', 'U.get_placeholder_cached', ([], {'name': '"""option"""'}), "(name='option')\n", (9556, 9571), True, 'import baselines.common.tf_util as U\n'), ((9587, 9653), 'baselines.common.tf_util.get_placeholder', 'U.get_placeholder', ([], {'name': '"""term_adv"""', 'dtype': 'tf.float32', 'shape': '[None]'}), "(name='term_adv', dtype=tf.float32, shape=[None])\n", (9604, 9653), True, 'import baselines.common.tf_util as U\n'), ((9808, 9824), 'baselines.common.tf_util.mean', 'U.mean', (['kloldnew'], {}), '(kloldnew)\n', (9814, 9824), True, 'import baselines.common.tf_util as U\n'), ((9839, 9850), 'baselines.common.tf_util.mean', 'U.mean', (['ent'], {}), '(ent)\n', (9845, 9850), True, 'import baselines.common.tf_util as U\n'), ((12038, 12077), 'baselines.common.mpi_adam.MpiAdam', 'MpiAdam', (['var_list'], {'epsilon': 'adam_epsilon'}), '(var_list, epsilon=adam_epsilon)\n', (12045, 12077), False, 'from baselines.common.mpi_adam import MpiAdam\n'), ((12334, 12390), 'baselines.common.tf_util.function', 'U.function', (['[ob, ac, atarg, ret, lrmult, option]', 'losses'], {}), '([ob, ac, atarg, ret, lrmult, option], losses)\n', (12344, 12390), True, 'import baselines.common.tf_util as U\n'), ((12397, 12411), 'baselines.common.tf_util.initialize', 'U.initialize', ([], {}), '()\n', (12409, 12411), True, 'import baselines.common.tf_util as U\n'), ((12591, 12624), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': '(10000)'}), '(max_to_keep=10000)\n', (12605, 12624), True, 'import tensorflow as tf, numpy as np\n'), ((12642, 12671), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': '(1)'}), '(max_to_keep=1)\n', (12656, 12671), True, 'import tensorflow as tf, numpy as np\n'), ((14199, 14210), 'time.time', 'time.time', ([], {}), '()\n', (14208, 14210), False, 'import time\n'), ((14227, 14244), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (14232, 14244), False, 'from collections import deque\n'), ((14298, 14315), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (14303, 14315), False, 'from collections import deque\n'), ((8141, 8198), 'os.path.join', 'os.path.join', (['dirname_rel', '"""nfunk/envs_nf/pendulum_nf.py"""'], {}), "(dirname_rel, 'nfunk/envs_nf/pendulum_nf.py')\n", (8153, 8198), False, 'import os\n'), ((8206, 8229), 'shutil.copy2', 'shutil.copy2', (['src', 'dest'], {}), '(src, dest)\n', (8218, 8229), False, 'import shutil\n'), ((8237, 8260), 'shutil.copy2', 'shutil.copy2', (['src', 'dest'], {}), '(src, dest)\n', (8249, 8260), False, 'import shutil\n'), ((8268, 8297), 'os.makedirs', 'os.makedirs', (["(dest + 'assets/')"], {}), "(dest + 'assets/')\n", (8279, 8297), False, 'import os\n'), ((8310, 8373), 'os.path.join', 'os.path.join', (['dirname_rel', '"""nfunk/envs_nf/assets/clockwise.png"""'], {}), "(dirname_rel, 'nfunk/envs_nf/assets/clockwise.png')\n", (8322, 8373), False, 'import os\n'), ((8381, 8416), 'shutil.copy2', 'shutil.copy2', (['src', "(dest + 'assets/')"], {}), "(src, dest + 'assets/')\n", (8393, 8416), False, 'import shutil\n'), ((10218, 10267), 'baselines.common.tf_util.clip', 'U.clip', (['ratio', '(1.0 - clip_param)', '(1.0 + clip_param)'], {}), '(ratio, 1.0 - clip_param, 1.0 + clip_param)\n', (10224, 10267), True, 'import baselines.common.tf_util as U\n'), ((10427, 10452), 'tensorflow.square', 'tf.square', (['(pi.vpred - ret)'], {}), '(pi.vpred - ret)\n', (10436, 10452), True, 'import tensorflow as tf, numpy as np\n'), ((10736, 10774), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['pi.op_pi', '(1e-05)', '(1.0)'], {}), '(pi.op_pi, 1e-05, 1.0)\n', (10752, 10774), True, 'import tensorflow as tf, numpy as np\n'), ((10877, 10918), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['oldpi.op_pi', '(1e-05)', '(1.0)'], {}), '(oldpi.op_pi, 1e-05, 1.0)\n', (10893, 10918), True, 'import tensorflow as tf, numpy as np\n'), ((10981, 11034), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(pi.op_pi * log_pi)'], {'reduction_indices': '(1)'}), '(pi.op_pi * log_pi, reduction_indices=1)\n', (10994, 11034), True, 'import tensorflow as tf, numpy as np\n'), ((11363, 11422), 'baselines.common.tf_util.clip', 'U.clip', (['ratio_pol_ov_op', '(1.0 - clip_param)', '(1.0 + clip_param)'], {}), '(ratio_pol_ov_op, 1.0 - clip_param, 1.0 + clip_param)\n', (11369, 11422), True, 'import baselines.common.tf_util as U\n'), ((15384, 15449), 'baselines.logger.log', 'logger.log', (["('********** Iteration %i ************' % iters_so_far)"], {}), "('********** Iteration %i ************' % iters_so_far)\n", (15394, 15449), False, 'from baselines import logger\n'), ((21787, 21820), 'mpi4py.MPI.COMM_WORLD.allgather', 'MPI.COMM_WORLD.allgather', (['lrlocal'], {}), '(lrlocal)\n', (21811, 21820), False, 'from mpi4py import MPI\n'), ((22251, 22306), 'baselines.logger.record_tabular', 'logger.record_tabular', (['"""EpisodesSoFar"""', 'episodes_so_far'], {}), "('EpisodesSoFar', episodes_so_far)\n", (22272, 22306), False, 'from baselines import logger\n'), ((22315, 22372), 'baselines.logger.record_tabular', 'logger.record_tabular', (['"""TimestepsSoFar"""', 'timesteps_so_far'], {}), "('TimestepsSoFar', timesteps_so_far)\n", (22336, 22372), False, 'from baselines import logger\n'), ((7380, 7403), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (7394, 7403), False, 'import os\n'), ((7417, 7437), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (7428, 7437), False, 'import os\n'), ((8034, 8057), 'shutil.copy2', 'shutil.copy2', (['src', 'dest'], {}), '(src, dest)\n', (8046, 8057), False, 'import shutil\n'), ((10349, 10373), 'tensorflow.minimum', 'tf.minimum', (['surr1', 'surr2'], {}), '(surr1, surr2)\n', (10359, 10373), True, 'import tensorflow as tf, numpy as np\n'), ((11475, 11519), 'tensorflow.minimum', 'tf.minimum', (['surr1_pol_ov_op', 'surr2_pol_ov_op'], {}), '(surr1_pol_ov_op, surr2_pol_ov_op)\n', (11485, 11519), True, 'import tensorflow as tf, numpy as np\n'), ((11614, 11636), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['entropy'], {}), '(entropy)\n', (11627, 11636), True, 'import tensorflow as tf, numpy as np\n'), ((13857, 13872), 'baselines.common.tf_util.get_session', 'U.get_session', ([], {}), '()\n', (13870, 13872), True, 'import baselines.common.tf_util as U\n'), ((17457, 17475), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (17464, 17475), True, 'import tensorflow as tf, numpy as np\n'), ((20752, 20779), 'baselines.logger.log', 'logger.log', (['"""Optimizing..."""'], {}), "('Optimizing...')\n", (20762, 20779), False, 'from baselines import logger\n'), ((22004, 22022), 'numpy.mean', 'np.mean', (['lenbuffer'], {}), '(lenbuffer)\n', (22011, 22022), True, 'import tensorflow as tf, numpy as np\n'), ((22067, 22085), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (22074, 22085), True, 'import tensorflow as tf, numpy as np\n'), ((22451, 22476), 'mpi4py.MPI.COMM_WORLD.Get_rank', 'MPI.COMM_WORLD.Get_rank', ([], {}), '()\n', (22474, 22476), False, 'from mpi4py import MPI\n'), ((22493, 22514), 'baselines.logger.dump_tabular', 'logger.dump_tabular', ([], {}), '()\n', (22512, 22514), False, 'from baselines import logger\n'), ((3522, 3533), 'numpy.copy', 'np.copy', (['ac'], {}), '(ac)\n', (3529, 3533), True, 'import tensorflow as tf, numpy as np\n'), ((7703, 7757), 'os.path.join', 'os.path.join', (['dirname_rel', '"""baselines/baselines/ppo1/"""'], {}), "(dirname_rel, 'baselines/baselines/ppo1/')\n", (7715, 7757), False, 'import os\n'), ((7949, 7966), 'os.makedirs', 'os.makedirs', (['dest'], {}), '(dest)\n', (7960, 7966), False, 'import os\n'), ((11125, 11145), 'tensorflow.transpose', 'tf.transpose', (['log_pi'], {}), '(log_pi)\n', (11137, 11145), True, 'import tensorflow as tf, numpy as np\n'), ((11159, 11183), 'tensorflow.transpose', 'tf.transpose', (['old_log_pi'], {}), '(old_log_pi)\n', (11171, 11183), True, 'import tensorflow as tf, numpy as np\n'), ((11959, 11991), 'baselines.common.tf_util.flatgrad', 'U.flatgrad', (['total_loss', 'var_list'], {}), '(total_loss, var_list)\n', (11969, 11991), True, 'import baselines.common.tf_util as U\n'), ((12210, 12231), 'tensorflow.assign', 'tf.assign', (['oldv', 'newv'], {}), '(oldv, newv)\n', (12219, 12231), True, 'import tensorflow as tf, numpy as np\n'), ((15719, 15745), 'numpy.mean', 'np.mean', (["seg['opt_dur'][i]"], {}), "(seg['opt_dur'][i])\n", (15726, 15745), True, 'import tensorflow as tf, numpy as np\n'), ((15890, 15916), 'numpy.mean', 'np.mean', (["seg['logstds'][i]"], {}), "(seg['logstds'][i])\n", (15897, 15916), True, 'import tensorflow as tf, numpy as np\n'), ((15978, 15992), 'numpy.exp', 'np.exp', (['logstd'], {}), '(logstd)\n', (15984, 15992), True, 'import tensorflow as tf, numpy as np\n'), ((16083, 16108), 'numpy.array', 'np.array', (["seg['optpol_p']"], {}), "(seg['optpol_p'])\n", (16091, 16108), True, 'import tensorflow as tf, numpy as np\n'), ((16165, 16188), 'numpy.array', 'np.array', (["seg['term_p']"], {}), "(seg['term_p'])\n", (16173, 16188), True, 'import tensorflow as tf, numpy as np\n'), ((16239, 16265), 'numpy.array', 'np.array', (["seg['value_val']"], {}), "(seg['value_val'])\n", (16247, 16265), True, 'import tensorflow as tf, numpy as np\n'), ((17271, 17286), 'baselines.common.tf_util.get_session', 'U.get_session', ([], {}), '()\n', (17284, 17286), True, 'import baselines.common.tf_util as U\n'), ((17395, 17413), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (17402, 17413), True, 'import tensorflow as tf, numpy as np\n'), ((17739, 17754), 'baselines.common.tf_util.get_session', 'U.get_session', ([], {}), '()\n', (17752, 17754), True, 'import baselines.common.tf_util as U\n'), ((18143, 18164), 'numpy.where', 'np.where', (['(opts == opt)'], {}), '(opts == opt)\n', (18151, 18164), True, 'import tensorflow as tf, numpy as np\n'), ((22418, 22429), 'time.time', 'time.time', ([], {}), '()\n', (22427, 22429), False, 'import time\n'), ((22716, 22734), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (22723, 22734), True, 'import tensorflow as tf, numpy as np\n'), ((23027, 23045), 'numpy.mean', 'np.mean', (['t_advs[i]'], {}), '(t_advs[i])\n', (23034, 23045), True, 'import tensorflow as tf, numpy as np\n'), ((19013, 19056), 'numpy.concatenate', 'np.concatenate', (["(oldmap['ob'], ob[indices])"], {}), "((oldmap['ob'], ob[indices]))\n", (19027, 19056), True, 'import tensorflow as tf, numpy as np\n'), ((19085, 19128), 'numpy.concatenate', 'np.concatenate', (["(oldmap['ac'], ac[indices])"], {}), "((oldmap['ac'], ac[indices]))\n", (19099, 19128), True, 'import tensorflow as tf, numpy as np\n'), ((19160, 19209), 'numpy.concatenate', 'np.concatenate', (["(oldmap['atarg'], atarg[indices])"], {}), "((oldmap['atarg'], atarg[indices]))\n", (19174, 19209), True, 'import tensorflow as tf, numpy as np\n'), ((19241, 19293), 'numpy.concatenate', 'np.concatenate', (["(oldmap['vtarg'], tdlamret[indices])"], {}), "((oldmap['vtarg'], tdlamret[indices]))\n", (19255, 19293), True, 'import tensorflow as tf, numpy as np\n'), ((21247, 21266), 'numpy.zeros_like', 'np.zeros_like', (['tadv'], {}), '(tadv)\n', (21260, 21266), True, 'import tensorflow as tf, numpy as np\n'), ((17557, 17575), 'numpy.mean', 'np.mean', (['rewbuffer'], {}), '(rewbuffer)\n', (17564, 17575), True, 'import tensorflow as tf, numpy as np\n'), ((19726, 19769), 'numpy.concatenate', 'np.concatenate', (["(oldmap['ob'], ob[indices])"], {}), "((oldmap['ob'], ob[indices]))\n", (19740, 19769), True, 'import tensorflow as tf, numpy as np\n'), ((19798, 19841), 'numpy.concatenate', 'np.concatenate', (["(oldmap['ac'], ac[indices])"], {}), "((oldmap['ac'], ac[indices]))\n", (19812, 19841), True, 'import tensorflow as tf, numpy as np\n'), ((19873, 19922), 'numpy.concatenate', 'np.concatenate', (["(oldmap['atarg'], atarg[indices])"], {}), "((oldmap['atarg'], atarg[indices]))\n", (19887, 19922), True, 'import tensorflow as tf, numpy as np\n'), ((19954, 20006), 'numpy.concatenate', 'np.concatenate', (["(oldmap['vtarg'], tdlamret[indices])"], {}), "((oldmap['vtarg'], tdlamret[indices]))\n", (19968, 20006), True, 'import tensorflow as tf, numpy as np\n'), ((22921, 22944), 'numpy.array', 'np.array', (["seg['term_p']"], {}), "(seg['term_p'])\n", (22929, 22944), True, 'import tensorflow as tf, numpy as np\n'), ((15088, 15099), 'time.time', 'time.time', ([], {}), '()\n', (15097, 15099), False, 'import time\n')]
import time from unittest.case import SkipTest from ddtrace.context import Context from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY from ddtrace.span import Span from ddtrace.ext import errors def test_ids(): s = Span(tracer=None, name='span.test') assert s.trace_id assert s.span_id assert not s.parent_id s2 = Span(tracer=None, name='t', trace_id=1, span_id=2, parent_id=1) assert s2.trace_id == 1 assert s2.span_id == 2 assert s2.parent_id == 1 def test_tags(): s = Span(tracer=None, name='test.span') s.set_tag('a', 'a') s.set_tag('b', 1) s.set_tag('c', '1') d = s.to_dict() expected = { 'a': 'a', 'b': '1', 'c': '1', } assert d['meta'] == expected def test_set_valid_metrics(): s = Span(tracer=None, name='test.span') s.set_metric('a', 0) s.set_metric('b', -12) s.set_metric('c', 12.134) s.set_metric('d', 1231543543265475686787869123) s.set_metric('e', '12.34') d = s.to_dict() expected = { 'a': 0, 'b': -12, 'c': 12.134, 'd': 1231543543265475686787869123, 'e': 12.34, } assert d['metrics'] == expected def test_set_invalid_metric(): s = Span(tracer=None, name='test.span') invalid_metrics = [ None, {}, [], s, 'quarante-douze', float('nan'), float('inf'), 1j ] for i, m in enumerate(invalid_metrics): k = str(i) s.set_metric(k, m) assert s.get_metric(k) is None def test_set_numpy_metric(): try: import numpy as np except ImportError: raise SkipTest('numpy not installed') s = Span(tracer=None, name='test.span') s.set_metric('a', np.int64(1)) assert s.get_metric('a') == 1 assert type(s.get_metric('a')) == float def test_tags_not_string(): # ensure we can cast as strings class Foo(object): def __repr__(self): 1 / 0 s = Span(tracer=None, name='test.span') s.set_tag('a', Foo()) def test_finish(): # ensure finish will record a span dt = DummyTracer() ctx = Context() s = Span(dt, 'test.span', context=ctx) ctx.add_span(s) assert s.duration is None sleep = 0.05 with s as s1: assert s is s1 time.sleep(sleep) assert s.duration >= sleep, '%s < %s' % (s.duration, sleep) assert 1 == dt.spans_recorded def test_finish_no_tracer(): # ensure finish works with no tracer without raising exceptions s = Span(tracer=None, name='test.span') s.finish() def test_finish_called_multiple_times(): # we should only record a span the first time finish is called on it dt = DummyTracer() ctx = Context() s = Span(dt, 'bar', context=ctx) ctx.add_span(s) s.finish() s.finish() assert dt.spans_recorded == 1 def test_finish_set_span_duration(): # If set the duration on a span, the span should be recorded with this # duration s = Span(tracer=None, name='test.span') s.duration = 1337.0 s.finish() assert s.duration == 1337.0 def test_traceback_with_error(): s = Span(None, 'test.span') try: 1 / 0 except ZeroDivisionError: s.set_traceback() else: assert 0, 'should have failed' assert s.error assert 'by zero' in s.get_tag(errors.ERROR_MSG) assert 'ZeroDivisionError' in s.get_tag(errors.ERROR_TYPE) def test_traceback_without_error(): s = Span(None, 'test.span') s.set_traceback() assert not s.error assert not s.get_tag(errors.ERROR_MSG) assert not s.get_tag(errors.ERROR_TYPE) assert 'in test_traceback_without_error' in s.get_tag(errors.ERROR_STACK) def test_ctx_mgr(): dt = DummyTracer() s = Span(dt, 'bar') assert not s.duration assert not s.error e = Exception('boo') try: with s: time.sleep(0.01) raise e except Exception as out: assert out == e assert s.duration > 0, s.duration assert s.error assert s.get_tag(errors.ERROR_MSG) == 'boo' assert 'Exception' in s.get_tag(errors.ERROR_TYPE) assert s.get_tag(errors.ERROR_STACK) else: assert 0, 'should have failed' def test_span_to_dict(): s = Span(tracer=None, name='test.span', service='s', resource='r') s.span_type = 'foo' s.set_tag('a', '1') s.set_meta('b', '2') s.finish() d = s.to_dict() assert d assert d['span_id'] == s.span_id assert d['trace_id'] == s.trace_id assert d['parent_id'] == s.parent_id assert d['meta'] == {'a': '1', 'b': '2'} assert d['type'] == 'foo' assert d['error'] == 0 assert type(d['error']) == int def test_span_to_dict_sub(): parent = Span(tracer=None, name='test.span', service='s', resource='r') s = Span(tracer=None, name='test.span', service='s', resource='r') s._parent = parent s.span_type = 'foo' s.set_tag('a', '1') s.set_meta('b', '2') s.finish() d = s.to_dict() assert d assert d['span_id'] == s.span_id assert d['trace_id'] == s.trace_id assert d['parent_id'] == s.parent_id assert d['meta'] == {'a': '1', 'b': '2'} assert d['type'] == 'foo' assert d['error'] == 0 assert type(d['error']) == int def test_span_boolean_err(): s = Span(tracer=None, name='foo.bar', service='s', resource='r') s.error = True s.finish() d = s.to_dict() assert d assert d['error'] == 1 assert type(d['error']) == int def test_numeric_tags_none(): s = Span(tracer=None, name='test.span') s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, None) d = s.to_dict() assert d assert 'metrics' not in d def test_numeric_tags_true(): s = Span(tracer=None, name='test.span') s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, True) d = s.to_dict() assert d expected = { ANALYTICS_SAMPLE_RATE_KEY: 1.0 } assert d['metrics'] == expected def test_numeric_tags_value(): s = Span(tracer=None, name='test.span') s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, 0.5) d = s.to_dict() assert d expected = { ANALYTICS_SAMPLE_RATE_KEY: 0.5 } assert d['metrics'] == expected def test_numeric_tags_bad_value(): s = Span(tracer=None, name='test.span') s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, 'Hello') d = s.to_dict() assert d assert 'metrics' not in d class DummyTracer(object): def __init__(self): self.debug_logging = False self.last_span = None self.spans_recorded = 0 def record(self, span): self.last_span = span self.spans_recorded += 1
[ "ddtrace.span.Span", "numpy.int64", "unittest.case.SkipTest", "time.sleep", "ddtrace.context.Context" ]
[((228, 263), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""span.test"""'}), "(tracer=None, name='span.test')\n", (232, 263), False, 'from ddtrace.span import Span\n'), ((344, 407), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""t"""', 'trace_id': '(1)', 'span_id': '(2)', 'parent_id': '(1)'}), "(tracer=None, name='t', trace_id=1, span_id=2, parent_id=1)\n", (348, 407), False, 'from ddtrace.span import Span\n'), ((519, 554), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (523, 554), False, 'from ddtrace.span import Span\n'), ((795, 830), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (799, 830), False, 'from ddtrace.span import Span\n'), ((1234, 1269), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (1238, 1269), False, 'from ddtrace.span import Span\n'), ((1706, 1741), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (1710, 1741), False, 'from ddtrace.span import Span\n'), ((1999, 2034), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (2003, 2034), False, 'from ddtrace.span import Span\n'), ((2154, 2163), 'ddtrace.context.Context', 'Context', ([], {}), '()\n', (2161, 2163), False, 'from ddtrace.context import Context\n'), ((2172, 2206), 'ddtrace.span.Span', 'Span', (['dt', '"""test.span"""'], {'context': 'ctx'}), "(dt, 'test.span', context=ctx)\n", (2176, 2206), False, 'from ddtrace.span import Span\n'), ((2547, 2582), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (2551, 2582), False, 'from ddtrace.span import Span\n'), ((2747, 2756), 'ddtrace.context.Context', 'Context', ([], {}), '()\n', (2754, 2756), False, 'from ddtrace.context import Context\n'), ((2765, 2793), 'ddtrace.span.Span', 'Span', (['dt', '"""bar"""'], {'context': 'ctx'}), "(dt, 'bar', context=ctx)\n", (2769, 2793), False, 'from ddtrace.span import Span\n'), ((3015, 3050), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (3019, 3050), False, 'from ddtrace.span import Span\n'), ((3165, 3188), 'ddtrace.span.Span', 'Span', (['None', '"""test.span"""'], {}), "(None, 'test.span')\n", (3169, 3188), False, 'from ddtrace.span import Span\n'), ((3498, 3521), 'ddtrace.span.Span', 'Span', (['None', '"""test.span"""'], {}), "(None, 'test.span')\n", (3502, 3521), False, 'from ddtrace.span import Span\n'), ((3785, 3800), 'ddtrace.span.Span', 'Span', (['dt', '"""bar"""'], {}), "(dt, 'bar')\n", (3789, 3800), False, 'from ddtrace.span import Span\n'), ((4309, 4371), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""', 'service': '"""s"""', 'resource': '"""r"""'}), "(tracer=None, name='test.span', service='s', resource='r')\n", (4313, 4371), False, 'from ddtrace.span import Span\n'), ((4792, 4854), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""', 'service': '"""s"""', 'resource': '"""r"""'}), "(tracer=None, name='test.span', service='s', resource='r')\n", (4796, 4854), False, 'from ddtrace.span import Span\n'), ((4863, 4925), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""', 'service': '"""s"""', 'resource': '"""r"""'}), "(tracer=None, name='test.span', service='s', resource='r')\n", (4867, 4925), False, 'from ddtrace.span import Span\n'), ((5364, 5424), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""foo.bar"""', 'service': '"""s"""', 'resource': '"""r"""'}), "(tracer=None, name='foo.bar', service='s', resource='r')\n", (5368, 5424), False, 'from ddtrace.span import Span\n'), ((5595, 5630), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (5599, 5630), False, 'from ddtrace.span import Span\n'), ((5781, 5816), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (5785, 5816), False, 'from ddtrace.span import Span\n'), ((6036, 6071), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (6040, 6071), False, 'from ddtrace.span import Span\n'), ((6294, 6329), 'ddtrace.span.Span', 'Span', ([], {'tracer': 'None', 'name': '"""test.span"""'}), "(tracer=None, name='test.span')\n", (6298, 6329), False, 'from ddtrace.span import Span\n'), ((1764, 1775), 'numpy.int64', 'np.int64', (['(1)'], {}), '(1)\n', (1772, 1775), True, 'import numpy as np\n'), ((2324, 2341), 'time.sleep', 'time.sleep', (['sleep'], {}), '(sleep)\n', (2334, 2341), False, 'import time\n'), ((1666, 1697), 'unittest.case.SkipTest', 'SkipTest', (['"""numpy not installed"""'], {}), "('numpy not installed')\n", (1674, 1697), False, 'from unittest.case import SkipTest\n'), ((3913, 3929), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (3923, 3929), False, 'import time\n')]
from gzip import ( compress, GzipFile ) import numpy as np from .record import Record UNK = '<unk>' PAD = '<pad>' class Vocab(Record): __attributes__ = ['words', 'counts'] def __init__(self, words, counts): self.words = words self.counts = counts self.word_ids = { word: id for id, word in enumerate(self.words) } self.unk_id = self.word_ids.get(UNK) self.pad_id = self.word_ids.get(PAD) def __getitem__(self, word): return self.word_ids[word] def __contains__(self, word): return word in self.word_ids def get(self, word, default=None): if word in self: return self[word] return default def count(self, word): return self.counts[self.word_ids[word]] def top(self, count=None): return sorted( self.words, key=self.count, reverse=True )[:count] def sampled(self, words): words = list(words) counts = [ self.counts[self.word_ids[_]] for _ in words ] return Vocab(words, counts) def __repr__(self): return '{name}(words=[...], counts=[...])'.format( name=self.__class__.__name__ ) def _repr_pretty_(self, printer, cycle): printer.text(repr(self)) @classmethod def from_glove(cls, words, counts): # for some reason glove vocab may have words with broken # unicode words = [_.decode('utf8', errors='ignore') for _ in words] # emb has unk in the end for word in (UNK, PAD): words.append(word) counts.append(0) return cls(words, counts) @property def as_glove(self): for word, count in zip(self.words, self.counts): if word in (UNK, PAD): continue word = word.encode('utf8') yield word, count @property def as_bytes(self): meta = [len(self.counts)] meta = np.array(meta).astype(np.uint32).tobytes() words = '\n'.join(self.words) words = words.encode('utf8') counts = np.array(self.counts, dtype=np.uint32).tobytes() return compress(meta + counts + words) @classmethod def from_file(cls, file): file = GzipFile(mode='rb', fileobj=file) buffer = file.read(4) size, = np.frombuffer(buffer, np.uint32) buffer = file.read(4 * size) counts = np.frombuffer(buffer, np.uint32).tolist() text = file.read().decode('utf8') words = text.splitlines() return cls(words, counts)
[ "gzip.GzipFile", "numpy.array", "numpy.frombuffer", "gzip.compress" ]
[((2259, 2290), 'gzip.compress', 'compress', (['(meta + counts + words)'], {}), '(meta + counts + words)\n', (2267, 2290), False, 'from gzip import compress, GzipFile\n'), ((2354, 2387), 'gzip.GzipFile', 'GzipFile', ([], {'mode': '"""rb"""', 'fileobj': 'file'}), "(mode='rb', fileobj=file)\n", (2362, 2387), False, 'from gzip import compress, GzipFile\n'), ((2435, 2467), 'numpy.frombuffer', 'np.frombuffer', (['buffer', 'np.uint32'], {}), '(buffer, np.uint32)\n', (2448, 2467), True, 'import numpy as np\n'), ((2195, 2233), 'numpy.array', 'np.array', (['self.counts'], {'dtype': 'np.uint32'}), '(self.counts, dtype=np.uint32)\n', (2203, 2233), True, 'import numpy as np\n'), ((2523, 2555), 'numpy.frombuffer', 'np.frombuffer', (['buffer', 'np.uint32'], {}), '(buffer, np.uint32)\n', (2536, 2555), True, 'import numpy as np\n'), ((2058, 2072), 'numpy.array', 'np.array', (['meta'], {}), '(meta)\n', (2066, 2072), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- from EXOSIMS.Prototypes.OpticalSystem import OpticalSystem import astropy.units as u import numpy as np import scipy.stats as st import scipy.optimize as opt class Nemati(OpticalSystem): """Nemati Optical System class This class contains all variables and methods necessary to perform Optical System Module calculations in exoplanet mission simulation using the model from Nemati 2014. Args: \*\*specs: user specified values """ def __init__(self, **specs): OpticalSystem.__init__(self, **specs) def calc_intTime(self, TL, sInds, fZ, fEZ, dMag, WA, mode): """Finds integration times of target systems for a specific observing mode (imaging or characterization), based on Nemati 2014 (SPIE). Args: TL (TargetList module): TargetList class object sInds (integer ndarray): Integer indices of the stars of interest fZ (astropy Quantity array): Surface brightness of local zodiacal light in units of 1/arcsec2 fEZ (astropy Quantity array): Surface brightness of exo-zodiacal light in units of 1/arcsec2 dMag (float ndarray): Differences in magnitude between planets and their host star WA (astropy Quantity array): Working angles of the planets of interest in units of arcsec mode (dict): Selected observing mode Returns: intTime (astropy Quantity array): Integration times in units of day """ # electron counts C_p, C_b, C_sp = self.Cp_Cb_Csp(TL, sInds, fZ, fEZ, dMag, WA, mode) # get SNR threshold SNR = mode['SNR'] # calculate integration time based on Nemati 2014 with np.errstate(divide='ignore', invalid='ignore'): intTime = np.true_divide(SNR**2*C_b, (C_p**2 - (SNR*C_sp)**2)) # infinite and NAN are set to zero intTime[np.isinf(intTime) | np.isnan(intTime)] = 0.*u.d # negative values are set to zero intTime[intTime < 0] = 0.*u.d return intTime.to('day') def calc_dMag_per_intTime(self, intTimes, TL, sInds, fZ, fEZ, WA, mode, C_b=None, C_sp=None): """Finds achievable dMag for one integration time per star in the input list at one working angle. Args: intTimes (astropy Quantity array): Integration times TL (TargetList module): TargetList class object sInds (integer ndarray): Integer indices of the stars of interest fZ (astropy Quantity array): Surface brightness of local zodiacal light for each star in sInds in units of 1/arcsec2 fEZ (astropy Quantity array): Surface brightness of exo-zodiacal light for each star in sInds in units of 1/arcsec2 WA (astropy Quantity array): Working angle for each star in sInds in units of arcsec mode (dict): Selected observing mode C_b (astropy Quantity array): Background noise electron count rate in units of 1/s (optional) C_sp (astropy Quantity array): Residual speckle spatial structure (systematic error) in units of 1/s (optional) Returns: dMag (ndarray): Achievable dMag for given integration time and working angle """ # cast sInds, WA, fZ, fEZ, and intTimes to arrays sInds = np.array(sInds, ndmin=1, copy=False) WA = np.array(WA.value, ndmin=1)*WA.unit fZ = np.array(fZ.value, ndmin=1)*fZ.unit fEZ = np.array(fEZ.value, ndmin=1)*fEZ.unit intTimes = np.array(intTimes.value, ndmin=1)*intTimes.unit assert len(intTimes) == len(sInds), "intTimes and sInds must be same length" assert len(fEZ) == len(sInds), "fEZ must be an array of length len(sInds)" assert len(fZ) == len(sInds), "fZ must be an array of length len(sInds)" assert len(WA) == len(sInds), "WA must be an array of length len(sInds)" # get scienceInstrument and starlightSuppressionSystem inst = mode['inst'] syst = mode['syst'] # get mode wavelength lam = mode['lam'] # get mode bandwidth (including any IFS spectral resolving power) deltaLam = lam/inst['Rs'] if 'spec' in inst['name'].lower() else mode['deltaLam'] # get star magnitude mV = TL.starMag(sInds, lam) # get signal to noise ratio SNR = mode['SNR'] # spectral flux density = F0 * A * Dlam * QE * T (attenuation due to optics) attenuation = inst['optics']*syst['optics'] C_F0 = self.F0(lam)*self.pupilArea*deltaLam*inst['QE'](lam)*attenuation # get core_thruput core_thruput = syst['core_thruput'](lam, WA) # calculate planet delta magnitude dMagLim = np.zeros(len(sInds)) + 25 if (C_b is None) or (C_sp is None): _, C_b, C_sp = self.Cp_Cb_Csp(TL, sInds, fZ, fEZ, dMagLim, WA, mode) dMag = -2.5*np.log10((SNR*np.sqrt(C_b/intTimes + C_sp**2)/(C_F0*10.0**(-0.4*mV)*core_thruput*inst['PCeff'])).decompose().value) return dMag def ddMag_dt(self, intTimes, TL, sInds, fZ, fEZ, WA, mode, C_b=None, C_sp=None): """Finds derivative of achievable dMag with respect to integration time Args: intTimes (astropy Quantity array): Integration times TL (TargetList module): TargetList class object sInds (integer ndarray): Integer indices of the stars of interest fZ (astropy Quantity array): Surface brightness of local zodiacal light for each star in sInds in units of 1/arcsec2 fEZ (astropy Quantity array): Surface brightness of exo-zodiacal light for each star in sInds in units of 1/arcsec2 WA (astropy Quantity array): Working angle for each star in sInds in units of arcsec mode (dict): Selected observing mode C_b (astropy Quantity array): Background noise electron count rate in units of 1/s (optional) C_sp (astropy Quantity array): Residual speckle spatial structure (systematic error) in units of 1/s (optional) Returns: ddMagdt (ndarray): Derivative of achievable dMag with respect to integration time """ # cast sInds, WA, fZ, fEZ, and intTimes to arrays sInds = np.array(sInds, ndmin=1, copy=False) WA = np.array(WA.value, ndmin=1)*WA.unit fZ = np.array(fZ.value, ndmin=1)*fZ.unit fEZ = np.array(fEZ.value, ndmin=1)*fEZ.unit intTimes = np.array(intTimes.value, ndmin=1)*intTimes.unit assert len(intTimes) == len(sInds), "intTimes and sInds must be same length" assert len(fEZ) == len(sInds), "fEZ must be an array of length len(sInds)" assert len(fZ) == len(sInds), "fZ must be an array of length len(sInds)" assert len(WA) == len(sInds), "WA must be an array of length len(sInds)" dMagLim = np.zeros(len(sInds)) + 25 if (C_b is None) or (C_sp is None): _, C_b, C_sp = self.Cp_Cb_Csp(TL, sInds, fZ, fEZ, dMagLim, WA, mode) ddMagdt = 2.5/(2.0*np.log(10.0))*(C_b/(C_b*intTimes + (C_sp*intTimes)**2)).to('1/s').value return ddMagdt/u.s
[ "numpy.sqrt", "numpy.log", "EXOSIMS.Prototypes.OpticalSystem.OpticalSystem.__init__", "numpy.array", "numpy.errstate", "numpy.isnan", "numpy.true_divide", "numpy.isinf" ]
[((590, 627), 'EXOSIMS.Prototypes.OpticalSystem.OpticalSystem.__init__', 'OpticalSystem.__init__', (['self'], {}), '(self, **specs)\n', (612, 627), False, 'from EXOSIMS.Prototypes.OpticalSystem import OpticalSystem\n'), ((3905, 3941), 'numpy.array', 'np.array', (['sInds'], {'ndmin': '(1)', 'copy': '(False)'}), '(sInds, ndmin=1, copy=False)\n', (3913, 3941), True, 'import numpy as np\n'), ((7218, 7254), 'numpy.array', 'np.array', (['sInds'], {'ndmin': '(1)', 'copy': '(False)'}), '(sInds, ndmin=1, copy=False)\n', (7226, 7254), True, 'import numpy as np\n'), ((1997, 2043), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (2008, 2043), True, 'import numpy as np\n'), ((2068, 2128), 'numpy.true_divide', 'np.true_divide', (['(SNR ** 2 * C_b)', '(C_p ** 2 - (SNR * C_sp) ** 2)'], {}), '(SNR ** 2 * C_b, C_p ** 2 - (SNR * C_sp) ** 2)\n', (2082, 2128), True, 'import numpy as np\n'), ((3956, 3983), 'numpy.array', 'np.array', (['WA.value'], {'ndmin': '(1)'}), '(WA.value, ndmin=1)\n', (3964, 3983), True, 'import numpy as np\n'), ((4006, 4033), 'numpy.array', 'np.array', (['fZ.value'], {'ndmin': '(1)'}), '(fZ.value, ndmin=1)\n', (4014, 4033), True, 'import numpy as np\n'), ((4057, 4085), 'numpy.array', 'np.array', (['fEZ.value'], {'ndmin': '(1)'}), '(fEZ.value, ndmin=1)\n', (4065, 4085), True, 'import numpy as np\n'), ((4115, 4148), 'numpy.array', 'np.array', (['intTimes.value'], {'ndmin': '(1)'}), '(intTimes.value, ndmin=1)\n', (4123, 4148), True, 'import numpy as np\n'), ((7269, 7296), 'numpy.array', 'np.array', (['WA.value'], {'ndmin': '(1)'}), '(WA.value, ndmin=1)\n', (7277, 7296), True, 'import numpy as np\n'), ((7319, 7346), 'numpy.array', 'np.array', (['fZ.value'], {'ndmin': '(1)'}), '(fZ.value, ndmin=1)\n', (7327, 7346), True, 'import numpy as np\n'), ((7370, 7398), 'numpy.array', 'np.array', (['fEZ.value'], {'ndmin': '(1)'}), '(fEZ.value, ndmin=1)\n', (7378, 7398), True, 'import numpy as np\n'), ((7428, 7461), 'numpy.array', 'np.array', (['intTimes.value'], {'ndmin': '(1)'}), '(intTimes.value, ndmin=1)\n', (7436, 7461), True, 'import numpy as np\n'), ((2182, 2199), 'numpy.isinf', 'np.isinf', (['intTime'], {}), '(intTime)\n', (2190, 2199), True, 'import numpy as np\n'), ((2202, 2219), 'numpy.isnan', 'np.isnan', (['intTime'], {}), '(intTime)\n', (2210, 2219), True, 'import numpy as np\n'), ((8020, 8032), 'numpy.log', 'np.log', (['(10.0)'], {}), '(10.0)\n', (8026, 8032), True, 'import numpy as np\n'), ((5589, 5624), 'numpy.sqrt', 'np.sqrt', (['(C_b / intTimes + C_sp ** 2)'], {}), '(C_b / intTimes + C_sp ** 2)\n', (5596, 5624), True, 'import numpy as np\n')]
#!/usr/bin/env python import numpy as np from olympus.surfaces import AbstractSurface class AckleyPath(AbstractSurface): def __init__(self, param_dim=2, noise=None): """Ackley path function. Args: param_dim (int): Number of input dimensions. Default is 2. noise (Noise): Noise object that injects noise into the evaluations of the surface. Default is None. """ AbstractSurface.__init__(**locals()) @property def minima(self): # minimum at the centre params = [0.5] * self.param_dim value = self._run(params) return [{'params': params, 'value': value}] @property def maxima(self): return None def _run(self, params): params = np.array(params) params = 64 * np.array(params) - 32 # rescale onto [-32, 32] a = 20. b = 0.2 c = 2 * np.pi n = float(len(params)) params = np.array(params) result = - a * np.exp(- b * np.sqrt(np.sum(params ** 2) / n)) - np.exp(np.sum(np.cos(c * params)) / n) + a + np.exp(1.) if self.noise is None: return result else: return self.noise(result)
[ "numpy.exp", "numpy.array", "numpy.sum", "numpy.cos" ]
[((761, 777), 'numpy.array', 'np.array', (['params'], {}), '(params)\n', (769, 777), True, 'import numpy as np\n'), ((950, 966), 'numpy.array', 'np.array', (['params'], {}), '(params)\n', (958, 966), True, 'import numpy as np\n'), ((1084, 1095), 'numpy.exp', 'np.exp', (['(1.0)'], {}), '(1.0)\n', (1090, 1095), True, 'import numpy as np\n'), ((800, 816), 'numpy.array', 'np.array', (['params'], {}), '(params)\n', (808, 816), True, 'import numpy as np\n'), ((1053, 1071), 'numpy.cos', 'np.cos', (['(c * params)'], {}), '(c * params)\n', (1059, 1071), True, 'import numpy as np\n'), ((1011, 1030), 'numpy.sum', 'np.sum', (['(params ** 2)'], {}), '(params ** 2)\n', (1017, 1030), True, 'import numpy as np\n')]
import random import numpy as np import cv2 from utils.transforms.transforms import CustomTransform class RandomFlip(CustomTransform): def __init__(self, prob_x=0, prob_y=0): """ Arguments: ---------- prob_x: range [0, 1], probability to use horizontal flip, setting to 0 means disabling flip prob_y: range [0, 1], probability to use vertical flip """ self.prob_x = prob_x self.prob_y = prob_y def __call__(self, sample): img = sample.get('img').copy() segLabel = sample.get('segLabel', None) if segLabel is not None: segLabel = segLabel.copy() flip_x = np.random.choice([False, True], p=(1 - self.prob_x, self.prob_x)) flip_y = np.random.choice([False, True], p=(1 - self.prob_y, self.prob_y)) if flip_x: img = np.ascontiguousarray(np.flip(img, axis=1)) if segLabel is not None: segLabel = np.ascontiguousarray(np.flip(segLabel, axis=1)) if flip_y: img = np.ascontiguousarray(np.flip(img, axis=0)) if segLabel is not None: segLabel = np.ascontiguousarray(np.flip(segLabel, axis=0)) _sample = sample.copy() _sample['img'] = img _sample['segLabel'] = segLabel return _sample class Darkness(CustomTransform): def __init__(self, coeff): assert coeff >= 1., "Darkness coefficient must be greater than 1" self.coeff = coeff def __call__(self, sample): img = sample.get('img') coeff = np.random.uniform(1., self.coeff) img = (img.astype('float32') / coeff).astype('uint8') _sample = sample.copy() _sample['img'] = img return _sample
[ "numpy.random.choice", "numpy.flip", "numpy.random.uniform" ]
[((675, 740), 'numpy.random.choice', 'np.random.choice', (['[False, True]'], {'p': '(1 - self.prob_x, self.prob_x)'}), '([False, True], p=(1 - self.prob_x, self.prob_x))\n', (691, 740), True, 'import numpy as np\n'), ((758, 823), 'numpy.random.choice', 'np.random.choice', (['[False, True]'], {'p': '(1 - self.prob_y, self.prob_y)'}), '([False, True], p=(1 - self.prob_y, self.prob_y))\n', (774, 823), True, 'import numpy as np\n'), ((1581, 1615), 'numpy.random.uniform', 'np.random.uniform', (['(1.0)', 'self.coeff'], {}), '(1.0, self.coeff)\n', (1598, 1615), True, 'import numpy as np\n'), ((882, 902), 'numpy.flip', 'np.flip', (['img'], {'axis': '(1)'}), '(img, axis=1)\n', (889, 902), True, 'import numpy as np\n'), ((1075, 1095), 'numpy.flip', 'np.flip', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (1082, 1095), True, 'import numpy as np\n'), ((989, 1014), 'numpy.flip', 'np.flip', (['segLabel'], {'axis': '(1)'}), '(segLabel, axis=1)\n', (996, 1014), True, 'import numpy as np\n'), ((1182, 1207), 'numpy.flip', 'np.flip', (['segLabel'], {'axis': '(0)'}), '(segLabel, axis=0)\n', (1189, 1207), True, 'import numpy as np\n')]
'''Utility functions and classes for handling image datasets.''' import cPickle import cv2 import os.path as osp import numpy as np import tensorflow as tf from config_tfvgg import cfg FLAGS = tf.app.flags.FLAGS def get_facebox_dims(img_shape,face_bbox,target_size,crop_size,spec,crop_ind): face_bbox = np.zeros_like(face_bbox) center = np.floor(np.array([face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]]) / 2) dims = np.array([face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]]) * scale face_bbox[0] = max(0, (center[0] - dims[0] / 2).astype(np.int32)) face_bbox[2] = min(img_shape[1], (center[0] + dims[0] / 2).astype(np.int32)) face_bbox[1] = max(0, (center[1] - dims[1] / 2).astype(np.int32)) face_bbox[3] = min(img_shape[0], (center[1] + dims[1] / 2).astype(np.int32)) (scale, isotropic, crop, mean) = (spec.scale_size, spec.isotropic, spec.crop_size) img_shape = np.array((face_bbox[3]-face_bbox[1]+1,face_bbox[2]-face_bbox[0]+1)) min_length = np.min(img_shape) new_shape = np.ceil((target_size * 1.0 / min_length) * img_shape) offset = ((new_shape - crop) / 2).astype(np.int32) return new_shape,offset def process_image_reg(img_path,spec, flip=False, crop_ind=0, face_bbox=None,face_box_scale=1): '''Crops, scales, and normalizes the given image. scale : The image wil be first scaled to this size. If isotropic is true, the smaller side is rescaled to this, preserving the aspect ratio. crop : After scaling, depending on crop_ind a crop of the image is given. crope_ind: 0 center, 1 SW, 2 SE, 3 NE, 4 NW crop flip: Whether to flip the image mean : Subtracted from the image ''' (scale, isotropic, crop, mean) = (spec.scale_size, spec.isotropic, spec.crop_size, spec.mean) img = cv2.imread(img_path) if face_bbox is not None: face_bbox = np.array(face_bbox) center =np.floor(np.array([face_bbox[2]+face_bbox[0],face_bbox[3]+face_bbox[1]])/2) dims =np.array([face_bbox[2]-face_bbox[0],face_bbox[3]-face_bbox[1]]) * face_box_scale face_bbox[0] = max(0,(center[0] - dims[0] / 2).astype(np.int32)) face_bbox[2] = min(img.shape[1],(center[0] + dims[0] / 2).astype(np.int32)) face_bbox[1] = max(0,(center[1] - dims[1] / 2).astype(np.int32)) face_bbox[3] = min(img.shape[0],(center[1] + dims[1] / 2).astype(np.int32)) img = img[face_bbox[1]:face_bbox[3],face_bbox[0]:face_bbox[2],:] # Rescale if flip: img = img[:,::-1,:] if isotropic: img_shape = np.array(img.shape[:2]) min_length = np.min(img_shape) new_shape = np.ceil((scale *1.0/ min_length) * img_shape) else: new_shape = np.array([scale, scale]) img = cv2.resize(img, tuple(new_shape.astype(np.int32).tolist()[::-1])) offset = [0,0] if crop_ind == 1: offset[0] = new_shape[0]-crop offset = new_shape-crop elif crop_ind == 2: offset = new_shape-crop elif crop_ind == 3: offset[1] = new_shape[1]-crop elif crop_ind == 4: offset = [0,0] else: offset = ((new_shape - crop) / 2).astype(np.int32) img = img[offset[0]:offset[0]+crop,offset[1]:offset[1]+crop,:] # Mean subtraction return img.astype(np.float) - mean def process_image(img, scale, isotropic, crop, mean, flip=False, crop_ind=0, face_bbox=None): '''Crops, scales, and normalizes the given image. scale : The image wil be first scaled to this size. If isotropic is true, the smaller side is rescaled to this, preserving the aspect ratio. crop : After scaling, depending on crop_ind a crop of the image is given. crope_ind: 0 center, 1 SW, 2 SE, 3 NE, 4 NW crop flip: Whether to flip the image mean : Subtracted from the image ''' if face_bbox is not None: img = tf.slice(img, begin=tf.pack([face_bbox[0], face_bbox[1], 0]), size=tf.pack([face_bbox[2]-face_bbox[0], face_bbox[3]-face_bbox[1], -1])) # Rescale if flip: img = tf.reverse(img,[False,True,False]) if isotropic: img_shape = tf.to_float(tf.shape(img)[:2]) min_length = tf.minimum(img_shape[0], img_shape[1]) new_shape = tf.to_int32((scale / min_length) * img_shape) else: new_shape = tf.pack([scale, scale]) img = tf.image.resize_images(img, new_shape) offset = [0,0] if crop_ind == 1: offset[0] = new_shape[0]-crop offset = new_shape-crop elif crop_ind == 2: offset = new_shape-crop elif crop_ind == 3: offset[1] = new_shape[1]-crop elif crop_ind == 4: offset = [0,0] else: offset = (new_shape - crop) / 2 img = tf.slice(img, begin=tf.pack([offset[0], offset[1], 0]), size=tf.pack([crop, crop, -1])) # Mean subtraction return tf.to_float(img) - mean class ImageProducer(object): ''' Loads and processes batches of images in parallel. ''' def __init__(self, image_paths, data_spec, num_concurrent=4, batch_size=None, labels=None): # The data specifications describe how to process the image self.data_spec = data_spec # A list of full image paths self.image_paths = image_paths # An optional list of labels corresponding to each image path self.labels = labels # A boolean flag per image indicating whether its a JPEG or PNG self.extension_mask = self.create_extension_mask(self.image_paths) # Create the loading and processing operations self.setup(batch_size=batch_size, num_concurrent=num_concurrent) def start(self, session, coordinator, num_concurrent=4): '''Start the processing worker threads.''' # Queue all paths session.run(self.enqueue_paths_op) # Close the path queue session.run(self.close_path_queue_op) # Start the queue runner and return the created threads return self.queue_runner.create_threads(session, coord=coordinator, start=True) def get(self, session): ''' Get a single batch of images along with their indices. If a set of labels were provided, the corresponding labels are returned instead of the indices. ''' (indices, images) = session.run(self.dequeue_op) if self.labels is not None: labels = [self.labels[idx] for idx in indices] return (labels, images) return (indices, images) def batches(self, session): '''Yield a batch until no more images are left.''' for _ in xrange(self.num_batches): yield self.get(session=session) def load_image(self, image_path, is_jpeg): # Read the file file_data = tf.read_file(image_path) # Decode the image data img = tf.cond( is_jpeg, lambda: tf.image.decode_jpeg(file_data, channels=self.data_spec.channels), lambda: tf.image.decode_png(file_data, channels=self.data_spec.channels)) if self.data_spec.expects_bgr: # Convert from RGB channel ordering to BGR # This matches, for instance, how OpenCV orders the channels. img = tf.reverse(img, [False, False, True]) return img def process(self,crop_flip): # Dequeue a single image path idx, is_jpeg, image_path = self.path_bbox_queue.dequeue() # Load the image # Process the image img_list = [] idx_list = [] for (c,f) in crop_flip: img = self.load_image(image_path, is_jpeg) processed_img = process_image(img=img, scale=self.data_spec.scale_size, isotropic=self.data_spec.isotropic, crop=self.data_spec.crop_size, mean=self.data_spec.mean, flip=f, crop_ind=c) img_list.append(processed_img) idx_list.append(idx) # Return the processed image, along with its index processed_idx_list = tf.pack(idx_list) processed_img_list = tf.pack(img_list) return (processed_idx_list, processed_img_list) @staticmethod def create_extension_mask(paths): def is_jpeg(path): extension = osp.splitext(path)[-1].lower() if extension in ('.jpg', '.jpeg'): return True if extension != '.png': raise ValueError('Unsupported image format: {}'.format(extension)) return False return [is_jpeg(p) for p in paths] def __len__(self): return len(self.image_paths) def setup(self, batch_size, num_concurrent): pass class VGGFaceProducer(ImageProducer): def __init__(self, image_paths, data_spec ,num_concurrent=4,bbox_fp=None,labels=None): round_rect = lambda x: [int(p) for p in x] try: v = self.face_bboxes except AttributeError: self.face_bboxes = None if bbox_fp is not None: face_bboxes=cPickle.load(open(bbox_fp,'r')) self.face_bboxes = [round_rect(face_bboxes[p][0]) for p in image_paths] # Initialize base super(VGGFaceProducer, self).__init__(image_paths=image_paths, data_spec=data_spec,num_concurrent=num_concurrent,labels=labels) def setup(self, batch_size, num_concurrent): # Validate the batch size num_images = len(self.image_paths) batch_size = min(num_images, batch_size or self.data_spec.batch_size) if num_images % batch_size != 0: raise ValueError( 'The total number of images ({}) must be divisible by the batch size ({}).'.format( num_images, batch_size)) self.num_batches = num_images / batch_size # Create a queue that will contain image paths (and their indices and extension indicator) if self.face_bboxes is None: self.path_bbox_queue = tf.FIFOQueue(capacity=num_images, dtypes=[tf.int32, tf.bool, tf.string], name='path_queue') indices = tf.range(num_images) self.enqueue_paths_op = self.path_bbox_queue.enqueue_many([indices, self.extension_mask, self.image_paths]) else: self.path_bbox_queue = tf.FIFOQueue(capacity=num_images, dtypes=[tf.int32, tf.bool, tf.string, tf.int32], name='path_queue') indices = tf.range(num_images) self.enqueue_paths_op = self.path_bbox_queue.enqueue_many([indices, self.extension_mask, self.image_paths,self.face_bboxes]) # Close the path queue (no more additions) self.close_path_queue_op = self.path_bbox_queue.close() # Create an operation that dequeues a single path and returns a processed image crop_flip = [[0,False]] if cfg.CROP: for i in range(1,5): crop_flip.append([i,False]) if cfg.FLIP: for i in range(len(crop_flip)): crop_flip.append((crop_flip[i][0],True)) (processed_idx_list,processed_img_list) = self.process(crop_flip) # Create a queue that will contain the processed images (and their indices) image_shape = (self.data_spec.crop_size, self.data_spec.crop_size, self.data_spec.channels) processed_queue = tf.FIFOQueue(capacity=int(np.ceil(len(crop_flip)*num_images / float(num_concurrent))), dtypes=[tf.int32, tf.float32], shapes=[(), image_shape], name='processed_queue') # Enqueue the processed image and path enqueue_processed_op = processed_queue.enqueue_many([processed_idx_list,processed_img_list]) # Create a dequeue op that fetches a batch of processed images off the queue [self.ind_deq,self.img_deq] = processed_queue.dequeue_many(batch_size) self.dequeue_op = [self.ind_deq,self.img_deq] # Create a queue runner to perform the processing operations in parallel num_concurrent = min(num_concurrent, num_images) self.queue_runner = tf.train.QueueRunner(processed_queue, [enqueue_processed_op] * num_concurrent) self.num_imgs = len(crop_flip)*num_images self.num_feats_per_image = len(crop_flip) def process(self,crop_flip): # Dequeue a single image path if self.face_bboxes is None: idx, is_jpeg, image_path = self.path_bbox_queue.dequeue() face_bbox = None else: idx, is_jpeg, image_path, face_bbox = self.path_bbox_queue.dequeue() # Load the image # Process the image img_list = [] idx_list = [] for (c,f) in crop_flip: img = self.load_image(image_path, is_jpeg) processed_img = process_image(img=img, scale=self.data_spec.scale_size, isotropic=self.data_spec.isotropic, crop=self.data_spec.crop_size, mean=self.data_spec.mean, flip=f, crop_ind=c, face_bbox=face_bbox) img_list.append(processed_img) idx_list.append(idx) # Return the processed image, along with its index processed_idx_list = tf.pack(idx_list) processed_img_list = tf.pack(img_list) return (processed_idx_list, processed_img_list) class LFWProducer(VGGFaceProducer): def __init__(self, val_path, data_path, data_spec,bbox_fp=None,num_concurrent=4,labels=None): round_rect = lambda x: [int(p) for p in x] image_paths = [osp.join(data_path, p) for p in val_path] self.face_bboxes=None if bbox_fp is not None: face_bboxes=cPickle.load(open(bbox_fp,'r')) self.face_bboxes = [round_rect(face_bboxes[p][0]) for p in val_path] super(LFWProducer, self).__init__(image_paths=image_paths, data_spec=data_spec,num_concurrent=num_concurrent,labels=labels)
[ "tensorflow.image.resize_images", "tensorflow.shape", "tensorflow.read_file", "numpy.array", "tensorflow.FIFOQueue", "numpy.min", "numpy.ceil", "tensorflow.reverse", "os.path.splitext", "tensorflow.to_int32", "tensorflow.range", "cv2.imread", "tensorflow.minimum", "tensorflow.image.decode_png", "tensorflow.to_float", "os.path.join", "tensorflow.pack", "tensorflow.train.QueueRunner", "numpy.zeros_like", "tensorflow.image.decode_jpeg" ]
[((309, 333), 'numpy.zeros_like', 'np.zeros_like', (['face_bbox'], {}), '(face_bbox)\n', (322, 333), True, 'import numpy as np\n'), ((925, 1001), 'numpy.array', 'np.array', (['(face_bbox[3] - face_bbox[1] + 1, face_bbox[2] - face_bbox[0] + 1)'], {}), '((face_bbox[3] - face_bbox[1] + 1, face_bbox[2] - face_bbox[0] + 1))\n', (933, 1001), True, 'import numpy as np\n'), ((1010, 1027), 'numpy.min', 'np.min', (['img_shape'], {}), '(img_shape)\n', (1016, 1027), True, 'import numpy as np\n'), ((1044, 1095), 'numpy.ceil', 'np.ceil', (['(target_size * 1.0 / min_length * img_shape)'], {}), '(target_size * 1.0 / min_length * img_shape)\n', (1051, 1095), True, 'import numpy as np\n'), ((1826, 1846), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (1836, 1846), False, 'import cv2\n'), ((4373, 4411), 'tensorflow.image.resize_images', 'tf.image.resize_images', (['img', 'new_shape'], {}), '(img, new_shape)\n', (4395, 4411), True, 'import tensorflow as tf\n'), ((441, 509), 'numpy.array', 'np.array', (['[face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]]'], {}), '([face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]])\n', (449, 509), True, 'import numpy as np\n'), ((1898, 1917), 'numpy.array', 'np.array', (['face_bbox'], {}), '(face_bbox)\n', (1906, 1917), True, 'import numpy as np\n'), ((2588, 2611), 'numpy.array', 'np.array', (['img.shape[:2]'], {}), '(img.shape[:2])\n', (2596, 2611), True, 'import numpy as np\n'), ((2633, 2650), 'numpy.min', 'np.min', (['img_shape'], {}), '(img_shape)\n', (2639, 2650), True, 'import numpy as np\n'), ((2671, 2716), 'numpy.ceil', 'np.ceil', (['(scale * 1.0 / min_length * img_shape)'], {}), '(scale * 1.0 / min_length * img_shape)\n', (2678, 2716), True, 'import numpy as np\n'), ((2747, 2771), 'numpy.array', 'np.array', (['[scale, scale]'], {}), '([scale, scale])\n', (2755, 2771), True, 'import numpy as np\n'), ((4078, 4115), 'tensorflow.reverse', 'tf.reverse', (['img', '[False, True, False]'], {}), '(img, [False, True, False])\n', (4088, 4115), True, 'import tensorflow as tf\n'), ((4204, 4242), 'tensorflow.minimum', 'tf.minimum', (['img_shape[0]', 'img_shape[1]'], {}), '(img_shape[0], img_shape[1])\n', (4214, 4242), True, 'import tensorflow as tf\n'), ((4263, 4306), 'tensorflow.to_int32', 'tf.to_int32', (['(scale / min_length * img_shape)'], {}), '(scale / min_length * img_shape)\n', (4274, 4306), True, 'import tensorflow as tf\n'), ((4339, 4362), 'tensorflow.pack', 'tf.pack', (['[scale, scale]'], {}), '([scale, scale])\n', (4346, 4362), True, 'import tensorflow as tf\n'), ((4871, 4887), 'tensorflow.to_float', 'tf.to_float', (['img'], {}), '(img)\n', (4882, 4887), True, 'import tensorflow as tf\n'), ((6770, 6794), 'tensorflow.read_file', 'tf.read_file', (['image_path'], {}), '(image_path)\n', (6782, 6794), True, 'import tensorflow as tf\n'), ((8224, 8241), 'tensorflow.pack', 'tf.pack', (['idx_list'], {}), '(idx_list)\n', (8231, 8241), True, 'import tensorflow as tf\n'), ((8271, 8288), 'tensorflow.pack', 'tf.pack', (['img_list'], {}), '(img_list)\n', (8278, 8288), True, 'import tensorflow as tf\n'), ((12703, 12781), 'tensorflow.train.QueueRunner', 'tf.train.QueueRunner', (['processed_queue', '([enqueue_processed_op] * num_concurrent)'], {}), '(processed_queue, [enqueue_processed_op] * num_concurrent)\n', (12723, 12781), True, 'import tensorflow as tf\n'), ((14098, 14115), 'tensorflow.pack', 'tf.pack', (['idx_list'], {}), '(idx_list)\n', (14105, 14115), True, 'import tensorflow as tf\n'), ((14145, 14162), 'tensorflow.pack', 'tf.pack', (['img_list'], {}), '(img_list)\n', (14152, 14162), True, 'import tensorflow as tf\n'), ((356, 424), 'numpy.array', 'np.array', (['[face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]]'], {}), '([face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]])\n', (364, 424), True, 'import numpy as np\n'), ((2024, 2092), 'numpy.array', 'np.array', (['[face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]]'], {}), '([face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1]])\n', (2032, 2092), True, 'import numpy as np\n'), ((4769, 4803), 'tensorflow.pack', 'tf.pack', (['[offset[0], offset[1], 0]'], {}), '([offset[0], offset[1], 0])\n', (4776, 4803), True, 'import tensorflow as tf\n'), ((4810, 4835), 'tensorflow.pack', 'tf.pack', (['[crop, crop, -1]'], {}), '([crop, crop, -1])\n', (4817, 4835), True, 'import tensorflow as tf\n'), ((7230, 7267), 'tensorflow.reverse', 'tf.reverse', (['img', '[False, False, True]'], {}), '(img, [False, False, True])\n', (7240, 7267), True, 'import tensorflow as tf\n'), ((10206, 10301), 'tensorflow.FIFOQueue', 'tf.FIFOQueue', ([], {'capacity': 'num_images', 'dtypes': '[tf.int32, tf.bool, tf.string]', 'name': '"""path_queue"""'}), "(capacity=num_images, dtypes=[tf.int32, tf.bool, tf.string],\n name='path_queue')\n", (10218, 10301), True, 'import tensorflow as tf\n'), ((10408, 10428), 'tensorflow.range', 'tf.range', (['num_images'], {}), '(num_images)\n', (10416, 10428), True, 'import tensorflow as tf\n'), ((10665, 10771), 'tensorflow.FIFOQueue', 'tf.FIFOQueue', ([], {'capacity': 'num_images', 'dtypes': '[tf.int32, tf.bool, tf.string, tf.int32]', 'name': '"""path_queue"""'}), "(capacity=num_images, dtypes=[tf.int32, tf.bool, tf.string, tf.\n int32], name='path_queue')\n", (10677, 10771), True, 'import tensorflow as tf\n'), ((10885, 10905), 'tensorflow.range', 'tf.range', (['num_images'], {}), '(num_images)\n', (10893, 10905), True, 'import tensorflow as tf\n'), ((14428, 14450), 'os.path.join', 'osp.join', (['data_path', 'p'], {}), '(data_path, p)\n', (14436, 14450), True, 'import os.path as osp\n'), ((1943, 2011), 'numpy.array', 'np.array', (['[face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]]'], {}), '([face_bbox[2] + face_bbox[0], face_bbox[3] + face_bbox[1]])\n', (1951, 2011), True, 'import numpy as np\n'), ((3920, 3960), 'tensorflow.pack', 'tf.pack', (['[face_bbox[0], face_bbox[1], 0]'], {}), '([face_bbox[0], face_bbox[1], 0])\n', (3927, 3960), True, 'import tensorflow as tf\n'), ((3967, 4038), 'tensorflow.pack', 'tf.pack', (['[face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1], -1]'], {}), '([face_bbox[2] - face_bbox[0], face_bbox[3] - face_bbox[1], -1])\n', (3974, 4038), True, 'import tensorflow as tf\n'), ((4164, 4177), 'tensorflow.shape', 'tf.shape', (['img'], {}), '(img)\n', (4172, 4177), True, 'import tensorflow as tf\n'), ((6891, 6956), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['file_data'], {'channels': 'self.data_spec.channels'}), '(file_data, channels=self.data_spec.channels)\n', (6911, 6956), True, 'import tensorflow as tf\n'), ((6978, 7042), 'tensorflow.image.decode_png', 'tf.image.decode_png', (['file_data'], {'channels': 'self.data_spec.channels'}), '(file_data, channels=self.data_spec.channels)\n', (6997, 7042), True, 'import tensorflow as tf\n'), ((8454, 8472), 'os.path.splitext', 'osp.splitext', (['path'], {}), '(path)\n', (8466, 8472), True, 'import os.path as osp\n')]
import spartan from spartan import core, expr, util, blob_ctx import numpy as np from .qr import qr def svd(A, k=None): """ Stochastic SVD. Parameters ---------- A : spartan matrix Array to compute the SVD on, of shape (M, N) k : int, optional Number of singular values and vectors to compute. The operations include matrix multiplication and QR decomposition. We parallelize both of them. Returns -------- U : Spartan array of shape (M, k) S : numpy array of shape (k,) V : numpy array of shape (k, k) """ if k is None: k = A.shape[1] Omega = expr.randn(A.shape[1], k) Y = expr.dot(A, Omega) Q, R = qr(Y) B = expr.dot(expr.transpose(Q), A) BTB = expr.dot(B, expr.transpose(B)).optimized().glom() S, U_ = np.linalg.eig(BTB) S = np.sqrt(S) # Sort by eigen values from large to small si = np.argsort(S)[::-1] S = S[si] U_ = U_[:, si] U = expr.dot(Q, U_).optimized().evaluate() V = np.dot(np.dot(expr.transpose(B).optimized().glom(), U_), np.diag(np.ones(S.shape[0]) / S)) return U, S, V.T
[ "spartan.expr.randn", "spartan.expr.dot", "numpy.sqrt", "numpy.linalg.eig", "numpy.ones", "spartan.expr.transpose", "numpy.argsort" ]
[((594, 619), 'spartan.expr.randn', 'expr.randn', (['A.shape[1]', 'k'], {}), '(A.shape[1], k)\n', (604, 619), False, 'from spartan import core, expr, util, blob_ctx\n'), ((627, 645), 'spartan.expr.dot', 'expr.dot', (['A', 'Omega'], {}), '(A, Omega)\n', (635, 645), False, 'from spartan import core, expr, util, blob_ctx\n'), ((769, 787), 'numpy.linalg.eig', 'np.linalg.eig', (['BTB'], {}), '(BTB)\n', (782, 787), True, 'import numpy as np\n'), ((794, 804), 'numpy.sqrt', 'np.sqrt', (['S'], {}), '(S)\n', (801, 804), True, 'import numpy as np\n'), ((678, 695), 'spartan.expr.transpose', 'expr.transpose', (['Q'], {}), '(Q)\n', (692, 695), False, 'from spartan import core, expr, util, blob_ctx\n'), ((858, 871), 'numpy.argsort', 'np.argsort', (['S'], {}), '(S)\n', (868, 871), True, 'import numpy as np\n'), ((1024, 1043), 'numpy.ones', 'np.ones', (['S.shape[0]'], {}), '(S.shape[0])\n', (1031, 1043), True, 'import numpy as np\n'), ((914, 929), 'spartan.expr.dot', 'expr.dot', (['Q', 'U_'], {}), '(Q, U_)\n', (922, 929), False, 'from spartan import core, expr, util, blob_ctx\n'), ((720, 737), 'spartan.expr.transpose', 'expr.transpose', (['B'], {}), '(B)\n', (734, 737), False, 'from spartan import core, expr, util, blob_ctx\n'), ((973, 990), 'spartan.expr.transpose', 'expr.transpose', (['B'], {}), '(B)\n', (987, 990), False, 'from spartan import core, expr, util, blob_ctx\n')]
from collections import namedtuple import tensorflow as tf import numpy as np from rl.agents.a2c.agent import A2CAgent TestArgType = namedtuple('ArgType', ['name']) arg_type = TestArgType('arg') A = np.array class A2CAgentTest(tf.test.TestCase): def test_compute_policy_log_probs(self): from rl.agents.a2c.agent import compute_policy_log_probs available_actions = A([[1, 0, 1], [1, 0, 0], [1, 1, 1]], dtype=np.float32) fn_pi = A([[0.2, 0.0, 0.8], [1.0, 0.0, 0.0], [0.2, 0.7, 0.1]], dtype=np.float32) fn_ids = A([2, 0, 1], dtype=np.int32) arg_pi = {arg_type: A([[0.8, 0.2], [0.0, 1.0], [0.5, 0.5]], dtype=np.float32)} arg_ids = {arg_type: A([0, 1, -1], dtype=np.int32)} log_probs = compute_policy_log_probs( available_actions, (fn_pi, arg_pi), (fn_ids, arg_ids) ) expected_log_probs = np.log([0.8, 1.0, 0.7]) + A([np.log(0.8), np.log(1.0), 0]) with self.test_session() as sess: log_probs_out = sess.run(log_probs) self.assertAllClose(log_probs_out, expected_log_probs) def test_compute_policy_entropy(self): from rl.agents.a2c.agent import compute_policy_entropy available_actions = A([[1, 0, 1], [1, 0, 0], [1, 1, 1]], dtype=np.float32) fn_pi = A([[0.2, 0.0, 0.8], [1.0, 0.0, 0.0], [0.2, 0.7, 0.1]], dtype=np.float32) fn_ids = A([2, 0, 1], dtype=np.int32) arg_pi = {arg_type: A([[0.8, 0.2], [0.0, 1.0], [0.5, 0.5]], dtype=np.float32)} arg_ids = {arg_type: A([0, 1, -1], dtype=np.int32)} entropy = compute_policy_entropy( available_actions, (fn_pi, arg_pi), (fn_ids, arg_ids) ) expected_entropy = (0.50040245 + 0.80181855) / 3.0 + (0.50040245) / 2 with self.test_session() as sess: entropy_out = sess.run(entropy) self.assertAllClose(entropy_out, expected_entropy) if __name__ == '__main__': tf.test.main()
[ "collections.namedtuple", "rl.agents.a2c.agent.compute_policy_entropy", "numpy.log", "tensorflow.test.main", "rl.agents.a2c.agent.compute_policy_log_probs" ]
[((137, 168), 'collections.namedtuple', 'namedtuple', (['"""ArgType"""', "['name']"], {}), "('ArgType', ['name'])\n", (147, 168), False, 'from collections import namedtuple\n'), ((2115, 2129), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (2127, 2129), True, 'import tensorflow as tf\n'), ((862, 941), 'rl.agents.a2c.agent.compute_policy_log_probs', 'compute_policy_log_probs', (['available_actions', '(fn_pi, arg_pi)', '(fn_ids, arg_ids)'], {}), '(available_actions, (fn_pi, arg_pi), (fn_ids, arg_ids))\n', (886, 941), False, 'from rl.agents.a2c.agent import compute_policy_log_probs\n'), ((1785, 1862), 'rl.agents.a2c.agent.compute_policy_entropy', 'compute_policy_entropy', (['available_actions', '(fn_pi, arg_pi)', '(fn_ids, arg_ids)'], {}), '(available_actions, (fn_pi, arg_pi), (fn_ids, arg_ids))\n', (1807, 1862), False, 'from rl.agents.a2c.agent import compute_policy_entropy\n'), ((980, 1003), 'numpy.log', 'np.log', (['[0.8, 1.0, 0.7]'], {}), '([0.8, 1.0, 0.7])\n', (986, 1003), True, 'import numpy as np\n'), ((1009, 1020), 'numpy.log', 'np.log', (['(0.8)'], {}), '(0.8)\n', (1015, 1020), True, 'import numpy as np\n'), ((1022, 1033), 'numpy.log', 'np.log', (['(1.0)'], {}), '(1.0)\n', (1028, 1033), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import pandas as pd import numpy as np def rescale(data, to=[0, 1]): """Rescale data. Rescale a numeric variable to a new range. Parameters ---------- data : list, array or Series Raw data. to : list New range of values of the data after rescaling. Returns ---------- list, array or Series The rescaled values. Examples ---------- >>> import neurokit2 as nk >>> >>> nk.rescale(data=[3, 1, 2, 4, 6], to=[0, 1]) """ # Return appropriate type if isinstance(data, list): data = list(_rescale(np.array(data), to=to)) else: data = _rescale(data, to=to) return data def _rescale(data, to=[0, 1]): y = (to[1] - to[0]) / (np.nanmax(data) - np.nanmin(data)) * (data - np.nanmin(data)) + to[0] return y
[ "numpy.nanmin", "numpy.array", "numpy.nanmax" ]
[((623, 637), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (631, 637), True, 'import numpy as np\n'), ((821, 836), 'numpy.nanmin', 'np.nanmin', (['data'], {}), '(data)\n', (830, 836), True, 'import numpy as np\n'), ((776, 791), 'numpy.nanmax', 'np.nanmax', (['data'], {}), '(data)\n', (785, 791), True, 'import numpy as np\n'), ((794, 809), 'numpy.nanmin', 'np.nanmin', (['data'], {}), '(data)\n', (803, 809), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding: utf-8 # In[1]: #Libraries import cv2 import numpy as np import pyautogui import keyboard # In[2]: #Color to detect BGR l = [17, 15, 100] #lower u = [80, 76, 220] #upper # In[3]: #region coordinates k_left, k_top, k_right, k_bottom = 640, 30, 440, 130 h_left, h_top, h_right, h_bottom = 440, 130, 240, 330 s_left, s_top, s_right, s_bottom = 840, 130, 640, 330 f_left, f_top, f_right, f_bottom = 640, 330, 440, 430 # In[4]: #Key Pressed current_key_pressed = set() # In[5]: #Accelerate def up(): #print("W") pyautogui.keyDown('up') current_key_pressed.add('w') # In[6]: #Steering Right def right(): #print("D") pyautogui.keyDown('right') current_key_pressed.add('d') # In[7]: #Steering Left def left(): #print("A") pyautogui.keyDown('left') current_key_pressed.add('a') # In[8]: #Brakes def down(): #print("S") pyautogui.keyDown('down') current_key_pressed.add('s') # In[9]: #Find contours def findContours(image): img = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) threshold = cv2.threshold(img, 15, 255, cv2.THRESH_BINARY)[1] (_, cnts, _) = cv2.findContours(threshold.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) return len(cnts) # In[10]: #Main function if __name__=='__main__': aWeight=0.5 cam=cv2.VideoCapture(0) cam.set(3,1280) cam.set(4,720) cam.set(cv2.CAP_PROP_FPS,60) while True: buttonPressed = False buttonPressed_leftright = False status, frame = cam.read() clone = frame.copy() clone = cv2.flip(clone,1) clone = cv2.resize(clone,(1280,720)) reg_up = clone[k_top:k_bottom, k_right:k_left] reg_left = clone[h_top:h_bottom, h_right:h_left] reg_right = clone[s_top:s_bottom, s_right:s_left] reg_down = clone[f_top:f_bottom, f_right:f_left] reg_up = cv2.GaussianBlur(reg_up, (7,7), 0) reg_right = cv2.GaussianBlur(reg_right, (7,7), 0) reg_left = cv2.GaussianBlur(reg_left, (7,7), 0) reg_down = cv2.GaussianBlur(reg_down, (7,7), 0) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, l, u) mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) l = np.array(lower, dtype="uint8") u = np.array(upper, dtype="uint8") mask_up = cv2.inRange(reg_up, l, u) mask_right = cv2.inRange(reg_right, l, u) mask_left = cv2.inRange(reg_left, l, u) mask_down = cv2.inRange(reg_down, l, u) out_up = cv2.bitwise_and(reg_up, reg_up, mask=mask_up) out_right = cv2.bitwise_and(reg_right, reg_right, mask=mask_right) out_left = cv2.bitwise_and(reg_left, reg_left, mask=mask_left) out_down = cv2.bitwise_and(reg_down, reg_down, mask=mask_down) cnts_up = findContours(out_up) cnts_right = findContours(out_right) cnts_left = findContours(out_left) cnts_down = findContours(out_down) if (cnts_up > 0): up() buttonPressed = True elif (cnts_right > 0): right() buttonPressed = True buttonPressed_leftright = True elif (cnts_left > 0): left() buttonPressed = True buttonPressed_leftright = True elif (cnts_down > 0): down() buttonPressed = True image_up = cv2.rectangle(clone, (k_left, k_top), (k_right, k_bottom), (255,0,255,0.5), 2) image_left = cv2.rectangle(clone, (h_left, h_top), (h_right, h_bottom), (255,0,0,0.5), 2) image_right = cv2.rectangle(clone, (s_left, s_top), (s_right, s_bottom), (0,0,255,0.5), 2) image_down = cv2.rectangle(clone, (f_left, f_top), (f_right, f_bottom), (0,255,255,0.5), 2) cv2.putText(image_up, "W", (k_left-170,k_top+110), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2) cv2.putText(image_left, "A", (h_left-170,h_top+200), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2) cv2.putText(image_right, "D", (s_left-170,s_top+200), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2) cv2.putText(image_down, "S", (f_left-170,f_top+110), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2) cv2.namedWindow("video",cv2.WINDOW_AUTOSIZE) cv2.imshow("video", clone) if not buttonPressed and len(current_key_pressed) != 0: for key in current_key_pressed: pyautogui.keyUp(key) current_key_pressed = set() if not buttonPressed_leftright and (('a' in current_key_pressed) or ('d' in current_key_pressed)): if 'a' in current_key_pressed: pyautogui.keyUp('left') current_key_pressed.remove('a') elif 'd' in current_key_pressed: pyautogui.keyUp('right') current_key_pressed.remove('d') if cv2.waitKey(1) & 0Xff == ord('q'): break cam.release() cv2.destroyAllWindows()
[ "cv2.rectangle", "cv2.imshow", "numpy.array", "cv2.destroyAllWindows", "cv2.threshold", "cv2.erode", "cv2.waitKey", "pyautogui.keyDown", "cv2.putText", "cv2.cvtColor", "cv2.resize", "cv2.GaussianBlur", "cv2.namedWindow", "cv2.flip", "cv2.inRange", "cv2.bitwise_and", "cv2.VideoCapture", "pyautogui.keyUp", "cv2.dilate" ]
[((566, 589), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""up"""'], {}), "('up')\n", (583, 589), False, 'import pyautogui\n'), ((685, 711), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""right"""'], {}), "('right')\n", (702, 711), False, 'import pyautogui\n'), ((805, 830), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""left"""'], {}), "('left')\n", (822, 830), False, 'import pyautogui\n'), ((917, 942), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""down"""'], {}), "('down')\n", (934, 942), False, 'import pyautogui\n'), ((1039, 1078), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (1051, 1078), False, 'import cv2\n'), ((1340, 1359), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1356, 1359), False, 'import cv2\n'), ((5079, 5102), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5100, 5102), False, 'import cv2\n'), ((1094, 1140), 'cv2.threshold', 'cv2.threshold', (['img', '(15)', '(255)', 'cv2.THRESH_BINARY'], {}), '(img, 15, 255, cv2.THRESH_BINARY)\n', (1107, 1140), False, 'import cv2\n'), ((1610, 1628), 'cv2.flip', 'cv2.flip', (['clone', '(1)'], {}), '(clone, 1)\n', (1618, 1628), False, 'import cv2\n'), ((1644, 1674), 'cv2.resize', 'cv2.resize', (['clone', '(1280, 720)'], {}), '(clone, (1280, 720))\n', (1654, 1674), False, 'import cv2\n'), ((1919, 1954), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['reg_up', '(7, 7)', '(0)'], {}), '(reg_up, (7, 7), 0)\n', (1935, 1954), False, 'import cv2\n'), ((1974, 2012), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['reg_right', '(7, 7)', '(0)'], {}), '(reg_right, (7, 7), 0)\n', (1990, 2012), False, 'import cv2\n'), ((2031, 2068), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['reg_left', '(7, 7)', '(0)'], {}), '(reg_left, (7, 7), 0)\n', (2047, 2068), False, 'import cv2\n'), ((2087, 2124), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['reg_down', '(7, 7)', '(0)'], {}), '(reg_down, (7, 7), 0)\n', (2103, 2124), False, 'import cv2\n'), ((2147, 2185), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HSV'], {}), '(frame, cv2.COLOR_BGR2HSV)\n', (2159, 2185), False, 'import cv2\n'), ((2210, 2232), 'cv2.inRange', 'cv2.inRange', (['hsv', 'l', 'u'], {}), '(hsv, l, u)\n', (2221, 2232), False, 'import cv2\n'), ((2248, 2283), 'cv2.erode', 'cv2.erode', (['mask', 'None'], {'iterations': '(2)'}), '(mask, None, iterations=2)\n', (2257, 2283), False, 'import cv2\n'), ((2299, 2335), 'cv2.dilate', 'cv2.dilate', (['mask', 'None'], {'iterations': '(2)'}), '(mask, None, iterations=2)\n', (2309, 2335), False, 'import cv2\n'), ((2349, 2379), 'numpy.array', 'np.array', (['lower'], {'dtype': '"""uint8"""'}), "(lower, dtype='uint8')\n", (2357, 2379), True, 'import numpy as np\n'), ((2392, 2422), 'numpy.array', 'np.array', (['upper'], {'dtype': '"""uint8"""'}), "(upper, dtype='uint8')\n", (2400, 2422), True, 'import numpy as np\n'), ((2442, 2467), 'cv2.inRange', 'cv2.inRange', (['reg_up', 'l', 'u'], {}), '(reg_up, l, u)\n', (2453, 2467), False, 'import cv2\n'), ((2489, 2517), 'cv2.inRange', 'cv2.inRange', (['reg_right', 'l', 'u'], {}), '(reg_right, l, u)\n', (2500, 2517), False, 'import cv2\n'), ((2538, 2565), 'cv2.inRange', 'cv2.inRange', (['reg_left', 'l', 'u'], {}), '(reg_left, l, u)\n', (2549, 2565), False, 'import cv2\n'), ((2586, 2613), 'cv2.inRange', 'cv2.inRange', (['reg_down', 'l', 'u'], {}), '(reg_down, l, u)\n', (2597, 2613), False, 'import cv2\n'), ((2632, 2677), 'cv2.bitwise_and', 'cv2.bitwise_and', (['reg_up', 'reg_up'], {'mask': 'mask_up'}), '(reg_up, reg_up, mask=mask_up)\n', (2647, 2677), False, 'import cv2\n'), ((2698, 2752), 'cv2.bitwise_and', 'cv2.bitwise_and', (['reg_right', 'reg_right'], {'mask': 'mask_right'}), '(reg_right, reg_right, mask=mask_right)\n', (2713, 2752), False, 'import cv2\n'), ((2772, 2823), 'cv2.bitwise_and', 'cv2.bitwise_and', (['reg_left', 'reg_left'], {'mask': 'mask_left'}), '(reg_left, reg_left, mask=mask_left)\n', (2787, 2823), False, 'import cv2\n'), ((2843, 2894), 'cv2.bitwise_and', 'cv2.bitwise_and', (['reg_down', 'reg_down'], {'mask': 'mask_down'}), '(reg_down, reg_down, mask=mask_down)\n', (2858, 2894), False, 'import cv2\n'), ((3514, 3600), 'cv2.rectangle', 'cv2.rectangle', (['clone', '(k_left, k_top)', '(k_right, k_bottom)', '(255, 0, 255, 0.5)', '(2)'], {}), '(clone, (k_left, k_top), (k_right, k_bottom), (255, 0, 255, \n 0.5), 2)\n', (3527, 3600), False, 'import cv2\n'), ((3614, 3693), 'cv2.rectangle', 'cv2.rectangle', (['clone', '(h_left, h_top)', '(h_right, h_bottom)', '(255, 0, 0, 0.5)', '(2)'], {}), '(clone, (h_left, h_top), (h_right, h_bottom), (255, 0, 0, 0.5), 2)\n', (3627, 3693), False, 'import cv2\n'), ((3713, 3792), 'cv2.rectangle', 'cv2.rectangle', (['clone', '(s_left, s_top)', '(s_right, s_bottom)', '(0, 0, 255, 0.5)', '(2)'], {}), '(clone, (s_left, s_top), (s_right, s_bottom), (0, 0, 255, 0.5), 2)\n', (3726, 3792), False, 'import cv2\n'), ((3811, 3897), 'cv2.rectangle', 'cv2.rectangle', (['clone', '(f_left, f_top)', '(f_right, f_bottom)', '(0, 255, 255, 0.5)', '(2)'], {}), '(clone, (f_left, f_top), (f_right, f_bottom), (0, 255, 255, \n 0.5), 2)\n', (3824, 3897), False, 'import cv2\n'), ((3905, 4014), 'cv2.putText', 'cv2.putText', (['image_up', '"""W"""', '(k_left - 170, k_top + 110)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.9)', '(36, 255, 12)', '(2)'], {}), "(image_up, 'W', (k_left - 170, k_top + 110), cv2.\n FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)\n", (3916, 4014), False, 'import cv2\n'), ((4011, 4122), 'cv2.putText', 'cv2.putText', (['image_left', '"""A"""', '(h_left - 170, h_top + 200)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.9)', '(36, 255, 12)', '(2)'], {}), "(image_left, 'A', (h_left - 170, h_top + 200), cv2.\n FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)\n", (4022, 4122), False, 'import cv2\n'), ((4119, 4231), 'cv2.putText', 'cv2.putText', (['image_right', '"""D"""', '(s_left - 170, s_top + 200)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.9)', '(36, 255, 12)', '(2)'], {}), "(image_right, 'D', (s_left - 170, s_top + 200), cv2.\n FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)\n", (4130, 4231), False, 'import cv2\n'), ((4228, 4339), 'cv2.putText', 'cv2.putText', (['image_down', '"""S"""', '(f_left - 170, f_top + 110)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.9)', '(36, 255, 12)', '(2)'], {}), "(image_down, 'S', (f_left - 170, f_top + 110), cv2.\n FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)\n", (4239, 4339), False, 'import cv2\n'), ((4337, 4382), 'cv2.namedWindow', 'cv2.namedWindow', (['"""video"""', 'cv2.WINDOW_AUTOSIZE'], {}), "('video', cv2.WINDOW_AUTOSIZE)\n", (4352, 4382), False, 'import cv2\n'), ((4390, 4416), 'cv2.imshow', 'cv2.imshow', (['"""video"""', 'clone'], {}), "('video', clone)\n", (4400, 4416), False, 'import cv2\n'), ((4542, 4562), 'pyautogui.keyUp', 'pyautogui.keyUp', (['key'], {}), '(key)\n', (4557, 4562), False, 'import pyautogui\n'), ((4783, 4806), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""left"""'], {}), "('left')\n", (4798, 4806), False, 'import pyautogui\n'), ((5003, 5017), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5014, 5017), False, 'import cv2\n'), ((4918, 4942), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""right"""'], {}), "('right')\n", (4933, 4942), False, 'import pyautogui\n')]
# Copyright 2018 The TensorFlow Probability 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 the JointDistributionAutoBatched.""" import collections import os # Dependency imports from absl.testing import parameterized import numpy as np import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import test_util tfb = tfp.bijectors tfd = tfp.distributions JAX_MODE = False Root = tfd.JointDistributionCoroutineAutoBatched.Root @test_util.test_all_tf_execution_regimes class JointDistributionAutoBatchedTest(test_util.TestCase): @parameterized.named_parameters( {'testcase_name': 'coroutine', 'jd_class': tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched}, {'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}) def test_batch_and_event_shape_with_plate(self, jd_class): models = {} def coroutine_model(): g = yield tfd.LogNormal(0., 1.) df = yield tfd.Exponential(1.) loc = yield tfd.Sample(tfd.Normal(0, g), 20) yield tfd.StudentT(tf.expand_dims(df, -1), loc, 1) models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_model models[tfd.JointDistributionSequentialAutoBatched] = [ tfd.LogNormal(0., 1.), tfd.Exponential(1.), lambda _, g: tfd.Sample(tfd.Normal(0, g), 20), lambda loc, df: tfd.StudentT(tf.expand_dims(df, -1), loc, 1) ] models[tfd.JointDistributionNamedAutoBatched] = collections.OrderedDict(( ('g', tfd.LogNormal(0., 1.)), ('df', tfd.Exponential(1.)), ('loc', lambda g: tfd.Sample(tfd.Normal(0, g), 20)), ('x', lambda loc, df: tfd.StudentT(tf.expand_dims(df, -1), loc, 1)))) joint = jd_class(models[jd_class], validate_args=True) # Properties `event_shape` and `batch_shape` should be defined # even before any sampling calls have occurred. self.assertAllEqual(joint._model_flatten(joint.event_shape), [[], [], [20], [20]]) self.assertAllEqual(joint.batch_shape, []) is_scalar = joint._model_flatten(joint.is_scalar_event()) self.assertAllEqual(is_scalar[0], True) self.assertAllEqual(is_scalar[1], True) self.assertAllEqual(is_scalar[2], False) self.assertAllEqual(is_scalar[3], False) event_shape = joint._model_flatten(joint.event_shape_tensor()) self.assertAllEqual(event_shape[0], []) self.assertAllEqual(event_shape[1], []) self.assertAllEqual(event_shape[2], [20]) self.assertAllEqual(event_shape[3], [20]) self.assertEqual(joint.is_scalar_batch(), True) batch_shape = joint.batch_shape_tensor() self.assertAllEqual(batch_shape, []) @parameterized.named_parameters( *(dict( # pylint: disable=g-complex-comprehension testcase_name=jd_type + '_' + sampler_type, jd_class=getattr(tfd, 'JointDistribution' + jd_type + 'AutoBatched'), sampler_type=sampler_type) for jd_type in ('Coroutine', 'Sequential', 'Named') for sampler_type in ('stateful', 'stateless'))) def test_model_with_nontrivial_batch_shape(self, jd_class, sampler_type): models = {} def coroutine_model(): g = yield tfd.LogNormal(0., [1., 2.]) df = yield tfd.Exponential([1., 2.]) loc = yield tfd.Sample(tfd.Normal(0, g), 20) yield tfd.StudentT(tf.expand_dims(df, -1), loc, 1) models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_model models[tfd.JointDistributionSequentialAutoBatched] = [ tfd.LogNormal(0., [1., 2.]), tfd.Exponential([1., 2.]), lambda _, g: tfd.Sample(tfd.Normal(0, g), 20), lambda loc, df: tfd.StudentT(tf.expand_dims(df, -1), loc, 1) ] models[tfd.JointDistributionNamedAutoBatched] = collections.OrderedDict(( ('g', tfd.LogNormal(0., [1., 2.])), ('df', tfd.Exponential([1., 2.])), ('loc', lambda g: tfd.Sample(tfd.Normal(0, g), 20)), ('x', lambda loc, df: tfd.StudentT(tf.expand_dims(df, -1), loc, 1)))) joint = jd_class(models[jd_class], batch_ndims=1, validate_args=True) self.assertAllEqual(joint._model_flatten(joint.event_shape), [[], [], [20], [20]]) self.assertAllEqual(joint.batch_shape, [2]) is_scalar = joint._model_flatten(joint.is_scalar_event()) self.assertAllEqual(is_scalar[0], True) self.assertAllEqual(is_scalar[1], True) self.assertAllEqual(is_scalar[2], False) self.assertAllEqual(is_scalar[3], False) self.assertAllEqual(joint.is_scalar_batch(), False) batch_shape = self.evaluate(joint.batch_shape_tensor()) self.assertAllEqual(batch_shape, [2]) x = joint.sample([5], seed=test_util.test_seed(sampler_type=sampler_type)) lp = self.evaluate(joint.log_prob(x)) self.assertAllEqual(lp.shape, [5, 2]) def test_model_with_dynamic_batch_ndims(self): if tf.executing_eagerly(): self.skipTest('Dynamic shape.') def coroutine_model(): g = yield tfd.LogNormal(0., [1., 2.]) df = yield tfd.Exponential([1., 2.]) loc = yield tfd.Sample(tfd.Normal(0, g), 20) yield tfd.StudentT(tf.expand_dims(df, -1), loc, 1) joint = tfd.JointDistributionCoroutineAutoBatched( coroutine_model, batch_ndims=tf1.placeholder_with_default(1, shape=[]), validate_args=True) batch_shape_tensor = self.evaluate(joint.batch_shape_tensor()) self.assertAllEqual(batch_shape_tensor, [2]) event_shape_tensor = self.evaluate(joint.event_shape_tensor()) self.assertAllEqual(event_shape_tensor[0], []) self.assertAllEqual(event_shape_tensor[1], []) self.assertAllEqual(event_shape_tensor[2], [20]) self.assertAllEqual(event_shape_tensor[3], [20]) self.assertAllEqual(joint.batch_shape, tf.TensorShape(None)) self.assertAllEqual(joint._model_flatten(joint.event_shape), [tf.TensorShape(None)] * 4) x = joint.sample([5], seed=test_util.test_seed(sampler_type='stateless')) lp = self.evaluate(joint.log_prob(x)) self.assertAllEqual(lp.shape, [5, 2]) @parameterized.named_parameters( {'testcase_name': 'coroutine', 'base_jd_class': tfd.JointDistributionCoroutine, 'jda_class': tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential', 'base_jd_class': tfd.JointDistributionSequential, 'jda_class': tfd.JointDistributionSequentialAutoBatched}, {'testcase_name': 'named', 'base_jd_class': tfd.JointDistributionNamed, 'jda_class': tfd.JointDistributionNamedAutoBatched}) def test_broadcast_ragged_batch_shape(self, base_jd_class, jda_class): base_jd_models = {} # Writing a JDC with ragged batch shape will broadcast the first # distribution over the second. # (though note, this model breaks `log_prob` with nontrivial sample shape). def coroutine(): x = yield Root(tfd.Normal(0., scale=1.)) yield tfd.Normal(x[..., tf.newaxis], [1., 2., 3., 4., 5.]) base_jd_models[tfd.JointDistributionCoroutine] = coroutine base_jd_models[tfd.JointDistributionSequential] = [ tfd.Normal(0., scale=1.), lambda x: tfd.Normal(x[..., tf.newaxis], [1., 2., 3., 4., 5.]) ] base_jd_models[tfd.JointDistributionNamed] = { 'x': tfd.Normal(0., scale=1.), 'y': lambda x: tfd.Normal(x[..., tf.newaxis], [1., 2., 3., 4., 5.]) } # But we can get equivalent behavior in a JDCA by expanding dims so that # the batch dimensions line up. jd_auto_models = {} def coroutine_auto(): x = yield tfd.Normal(0., scale=[1.]) yield tfd.Normal(x, [1., 2., 3., 4., 5.]) jd_auto_models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_auto jd_auto_models[tfd.JointDistributionSequentialAutoBatched] = [ tfd.Normal(0., scale=[1.]), lambda x: tfd.Normal(x, [1., 2., 3., 4., 5.]) ] jd_auto_models[tfd.JointDistributionNamedAutoBatched] = ( collections.OrderedDict(( ('x', tfd.Normal(0., scale=[1.])), ('y', lambda x: tfd.Normal(x, [1., 2., 3., 4., 5.]))))) # Writing a JD with ragged batch shape will broadcast the first # distribution over the second. # (though note, this model breaks `log_prob` with nontrivial sample shape). jd_broadcasting = base_jd_class(base_jd_models[base_jd_class]) # This model's broadcasting behavior is a footgun (it can break inference # routines and cause silently incorrect optimization); it should be # disallowed by `validate_args`. with self.assertRaisesRegexp( Exception, ('Component batch shapes are inconsistent|' 'Broadcasting probably indicates an error in model specification')): jda_invalid = jda_class(jd_auto_models[jda_class], batch_ndims=1, validate_args=True) _ = self.evaluate(jda_invalid.log_prob( jda_invalid.sample(seed=test_util.test_seed()))) # But, if the user wants to run with no guardrails, one can eke out # performance wins when evaluating a shared value over multiple models. jda_broadcasting = jda_class(jd_auto_models[jda_class], batch_ndims=1) self.assertAllEqual( jda_broadcasting._model_flatten(jda_broadcasting.event_shape), [[], []]) self.assertAllEqual(jda_broadcasting.batch_shape, [5]) joint_sample = jda_broadcasting.sample(seed=test_util.test_seed()) x_sample, y_sample = self.evaluate( list(joint_sample.values()) if hasattr(joint_sample, 'values') else joint_sample) # The model samples only a single value for x, shared across the batch. self.assertAllEqual(x_sample.shape, [1]) self.assertAllEqual(y_sample.shape, [5]) lp_jd_broadcast = self.evaluate(jd_broadcasting.log_prob( jd_broadcasting._model_unflatten([x_sample[..., 0], y_sample]))) lp_jda_broadcast = self.evaluate(jda_broadcasting.log_prob( jda_broadcasting._model_unflatten([x_sample, y_sample]))) self.assertAllEqual(lp_jda_broadcast.shape, [5]) self.assertAllEqual(lp_jd_broadcast, lp_jda_broadcast) # Try drawing multiple samples and computing log-prob. joint_sample = self.evaluate(jda_broadcasting.sample( [2, 3], seed=test_util.test_seed())) lp_jda_broadcast = self.evaluate(jda_broadcasting.log_prob(joint_sample)) self.assertAllEqual(lp_jda_broadcast.shape, [2, 3, 5]) @parameterized.named_parameters( {'testcase_name': 'coroutine', 'jd_class': tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched}, {'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}) def test_log_prob_and_prob_with_plate(self, jd_class): models = {} def coroutine_model(): a = yield tfd.Bernoulli(probs=0.5, dtype=tf.float32) b = yield tfd.Sample(tfd.Bernoulli(probs=0.25 + 0.5*a, dtype=tf.float32), 2) yield tfd.Normal(loc=a, scale=1. + b) models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_model models[tfd.JointDistributionSequentialAutoBatched] = [ tfd.Bernoulli(probs=0.5, dtype=tf.float32), lambda a: tfd.Sample(tfd.Bernoulli( # pylint: disable=g-long-lambda probs=0.25 + 0.5*a, dtype=tf.float32), 2), lambda b, a: tfd.Normal(loc=a, scale=1. + b) ] models[tfd.JointDistributionNamedAutoBatched] = collections.OrderedDict(( ('a', tfd.Bernoulli(probs=0.5, dtype=tf.float32)), ('b', lambda a: tfd.Sample(tfd.Bernoulli( # pylint: disable=g-long-lambda probs=0.25 + 0.5*a, dtype=tf.float32), 2)), ('c', lambda b, a: tfd.Normal(loc=a, scale=1. + b)))) joint = jd_class(models[jd_class], validate_args=True) z = self.evaluate(joint.sample(seed=test_util.test_seed())) a, b, c = z.values() if hasattr(z, 'values') else z log_prob = self.evaluate(joint.log_prob(z)) prob = self.evaluate(joint.prob(z)) expected_log_prob = self.evaluate( np.log(0.5) + tf.reduce_sum(tf.math.log(b * (0.25 + 0.5 * a) + (1 - b) * (0.75 - 0.5 * a))) + tf.reduce_sum(-0.5 * ((c - a) / (1. + b))**2 - 0.5 * np.log(2. * np.pi) - tf.math.log((1. + b)))) self.assertAllClose(log_prob, expected_log_prob) self.assertAllClose(prob, np.exp(expected_log_prob)) @parameterized.named_parameters( {'testcase_name': 'coroutine', 'jd_class': tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched}, {'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}) def test_log_prob_multiple_samples(self, jd_class): models = {} def coroutine_model(): a = yield tfd.Bernoulli(probs=0.5, dtype=tf.float32) b = yield tfd.Bernoulli(probs=0.25 + 0.5*a, dtype=tf.float32) yield tfd.Normal(loc=a, scale=1. + b) models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_model models[tfd.JointDistributionSequentialAutoBatched] = [ tfd.Bernoulli(probs=0.5, dtype=tf.float32), lambda a: tfd.Bernoulli(probs=0.25 + 0.5*a, dtype=tf.float32), lambda b, a: tfd.Normal(loc=a, scale=1. + b) ] models[tfd.JointDistributionNamedAutoBatched] = collections.OrderedDict(( ('a', tfd.Bernoulli(probs=0.5, dtype=tf.float32)), ('b', lambda a: tfd.Bernoulli(probs=0.25 + 0.5*a, dtype=tf.float32)), ('c', lambda b, a: tfd.Normal(loc=a, scale=1. + b)))) joint = jd_class(models[jd_class], validate_args=True) z = joint.sample(4, seed=test_util.test_seed()) log_prob = joint.log_prob(z) a, b, c = z.values() if hasattr(z, 'values') else z # pylint: disable=unbalanced-tuple-unpacking expected_log_prob = ( np.log(0.5) + tf.math.log(b * (0.25 + 0.5 * a) + (1 - b) * (0.75 -0.5 * a)) + -0.5 * ((c - a) / (1. + b)) ** 2 - 0.5 * np.log(2. * np.pi) - tf.math.log((1. + b))) self.assertAllClose(*self.evaluate([log_prob, expected_log_prob])) @parameterized.named_parameters( {'testcase_name': 'coroutine', 'jd_class': tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched}, {'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}) def test_sample_and_log_prob(self, jd_class): # Define a bijector to detect if/when `inverse` is called. inverted_values = [] class InverseTracingExp(tfb.Exp): def _inverse(self, y): inverted_values.append(y) return tf.math.log(y) models = {} def coroutine_model(): g = yield InverseTracingExp()(tfd.Normal(0., 1.), name='g') df = yield tfd.Exponential(1., name='df') loc = yield tfd.Sample(tfd.Normal(0, g), 20, name='loc') yield tfd.StudentT(df, loc, 1, name='x') models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_model models[tfd.JointDistributionSequentialAutoBatched] = [ InverseTracingExp()(tfd.Normal(0., 1.), name='g'), tfd.Exponential(1., name='df'), lambda _, g: tfd.Sample(tfd.Normal(0, g), 20, name='loc'), lambda loc, df: tfd.StudentT(df, loc, 1, name='x') ] models[tfd.JointDistributionNamedAutoBatched] = collections.OrderedDict(( ('g', InverseTracingExp()(tfd.Normal(0., 1.))), ('df', tfd.Exponential(1.)), ('loc', lambda g: tfd.Sample(tfd.Normal(0, g), 20)), ('x', lambda loc, df: tfd.StudentT(df, loc, 1)))) joint = jd_class(models[jd_class], validate_args=True) seed = test_util.test_seed(sampler_type='stateless') for sample_shape in ([], [5]): inverted_values.clear() x1, lp1 = self.evaluate( joint.experimental_sample_and_log_prob( sample_shape, seed=seed, df=2.7)) # Check that kwargs are supported. x2 = self.evaluate( joint.sample(sample_shape, seed=seed, df=2.7)) self.assertAllCloseNested(x1, x2) self.assertLen(inverted_values, 0) lp2 = joint.log_prob(x1) self.assertLen(inverted_values, 1) self.assertAllClose(lp1, lp2) @test_util.jax_disable_test_missing_functionality('b/157594634') def test_sample_distributions(self): def coroutine_model(): g = yield tfd.Normal(0., 1., name='g') df = yield tfd.Exponential(1., name='df') loc = yield tfd.Normal(tf.zeros([20]), g, name='loc') yield tfd.StudentT(df, loc, 1, name='x') joint = tfd.JointDistributionCoroutineAutoBatched(coroutine_model) ds, xs = joint.sample_distributions([4, 3], seed=test_util.test_seed()) for d, x in zip(ds, xs): self.assertGreaterEqual(len(d.batch_shape), 2) lp = d.log_prob(x) self.assertAllEqual(lp.shape[:2], [4, 3]) @test_util.jax_disable_test_missing_functionality('b/201586404') def test_sample_distributions_not_composite_tensor_raises_error(self): def coroutine_model(): yield tfd.TransformedDistribution(tfd.Normal(0., 1.), tfb.Exp(), name='td') joint = tfd.JointDistributionCoroutineAutoBatched(coroutine_model) # Sampling with trivial sample shape avoids the vmap codepath. ds, _ = joint.sample_distributions([], seed=test_util.test_seed()) self.assertIsInstance(ds[0], tfd.TransformedDistribution) with self.assertRaisesRegex( TypeError, r'Some component distribution\(s\) cannot be returned'): joint.sample_distributions([4, 3], seed=test_util.test_seed()) def test_sample_with_batch_value(self): @tfd.JointDistributionCoroutineAutoBatched def dist(): a = yield tfd.Sample(tfd.Normal(0, 1.), 2) b = yield tfd.Sample(tfd.Normal(0, 1.), 3) # The following line fails if not autovectorized. yield tfd.Normal(a[tf.newaxis, ...] * b[..., tf.newaxis], 1.) x = self.evaluate(dist.sample(123, seed=test_util.test_seed())) x2 = self.evaluate(dist.sample(value=x, seed=test_util.test_seed())) self.assertAllCloseNested(x, x2) # Also test a dict-type value (JDNamed). dist = tfd.JointDistributionNamedAutoBatched({ 'a': tfd.Sample(tfd.Normal(0, 1.), 2), 'b': tfd.Sample(tfd.Normal(0, 1.), 3), 'c': lambda a, b: tfd.Normal( # pylint: disable=g-long-lambda a[tf.newaxis, ...] * b[..., tf.newaxis], 1.)}) x = self.evaluate(dist.sample(123, seed=test_util.test_seed())) x2 = self.evaluate(dist.sample(value=x, seed=test_util.test_seed())) self.assertAllCloseNested(x, x2) def test_sample_with_value_as_kwarg(self): @tfd.JointDistributionCoroutineAutoBatched def dist(): a = yield tfd.Sample(tfd.Normal(0, 1.), 2, name='a') b = yield tfd.Sample(tfd.Normal(0, 1.), 3, name='b') # The following line fails if not autovectorized. yield tfd.Normal(a[tf.newaxis, ...] * b[..., tf.newaxis], 1., name='c') x = self.evaluate(dist.sample(4, seed=test_util.test_seed())) x2 = self.evaluate(dist.sample(seed=test_util.test_seed(), a=x.a)) self.assertAllClose(x.a, x2.a) self.assertAllEqual(x2.b.shape, [4, 3]) self.assertAllEqual(x2.c.shape, [4, 3, 2]) @parameterized.named_parameters( dict(testcase_name='stateful', sampler_type='stateful'), dict(testcase_name='stateless', sampler_type='stateless')) def test_sample_with_partially_specified_value(self, sampler_type): num_features = 5 def dist(): scale_variance = yield tfd.InverseGamma(0.5, 0.5) scale_noncentered = yield tfd.Sample(tfd.HalfNormal(1.), num_features) scale = scale_noncentered * scale_variance[..., None]**0.5 weights_noncentered = yield tfd.Sample(tfd.Normal(0., 1.), num_features) yield tfd.Deterministic(weights_noncentered * scale) joint = tfd.JointDistributionCoroutineAutoBatched(dist, validate_args=True) value_partial_batch_dim = 4 value_ = (3., None, None, np.ones([value_partial_batch_dim, num_features])) value = [None if v is None else tf.cast(v, tf.float32) for v in value_] # The sample should keep the specified values. xs = self.evaluate( joint.sample( value=value, seed=test_util.test_seed(sampler_type=sampler_type))) self.assertAllEqual(xs[0], tf.fill([value_partial_batch_dim], value[0])) self.assertAllEqual(xs[1].shape, [value_partial_batch_dim, num_features]) self.assertAllEqual(xs[2].shape, [value_partial_batch_dim, num_features]) self.assertAllEqual(xs[3], value[3]) # With sample shape. sample_shape = [6, 2] samples = joint.sample(sample_shape, value=value, seed=test_util.test_seed(sampler_type=sampler_type)) xs = self.evaluate(samples) expect_shp = sample_shape + [value_partial_batch_dim, num_features] self.assertAllEqual( xs[0], tf.fill(sample_shape + [value_partial_batch_dim], value[0])) self.assertAllEqual(xs[1].shape, expect_shp) self.assertAllEqual(xs[2].shape, expect_shp) self.assertAllEqual(xs[3], value[3] * tf.ones(expect_shp)) sample_shape_dynamic = tf1.placeholder_with_default( sample_shape, shape=None) samples = joint.sample(sample_shape_dynamic, value=value, seed=test_util.test_seed(sampler_type=sampler_type)) xs = self.evaluate(samples) self.assertAllEqual( xs[0], tf.fill(sample_shape + [value_partial_batch_dim], value[0])) self.assertAllEqual(xs[1].shape, expect_shp) self.assertAllEqual(xs[2].shape, expect_shp) self.assertAllEqual(xs[3], value[3] * tf.ones(expect_shp)) @parameterized.named_parameters( dict(testcase_name='stateful', sampler_type='stateful'), dict(testcase_name='stateless', sampler_type='stateless')) def test_sample_with_prefix_of_values(self, sampler_type): num_rows = 4 num_columns = 5 def dist(): a = yield tfd.Sample(tfd.Normal(0., 1.), num_rows, name='a') b = yield tfd.Sample(tfd.Normal(0., 1.), num_columns, name='b') yield tfd.Normal(a[..., None] * b[None, ...], 1., name='c') tuple_joint = tfd.JointDistributionCoroutineAutoBatched( dist, validate_args=True) namedtuple_joint = tfd.JointDistributionCoroutineAutoBatched( dist, sample_dtype=collections.namedtuple( 'ModelSpec', ['a', 'b', 'c'])( a=tf.float32, b=tf.float32, c=tf.float32), validate_args=True) value_partial_batch_dim = 3 v0 = 3. * np.ones([value_partial_batch_dim, num_rows]).astype(np.float32) # Tuple (or namedtuple) value contains only the first variable. tuple_value = (v0,) namedtuple_value = collections.namedtuple('ValueSpec', ['a'])(a=v0) for joint in (tuple_joint, namedtuple_joint): for value in (tuple_value, namedtuple_value): xs = self.evaluate( joint.sample(value=value, seed=test_util.test_seed(sampler_type=sampler_type))) self.assertAllEqual(xs[0], v0) self.assertAllEqual(xs[1].shape, [value_partial_batch_dim, num_columns]) self.assertAllEqual(xs[2].shape, [value_partial_batch_dim, num_rows, num_columns]) def test_unit_sample_shape_avoids_vectorization(self): xs = [] # Collect (possibly symbolic) Tensors sampled inside the model. @tfd.JointDistributionCoroutineAutoBatched def dist(): x = yield tfd.Normal(0., 1., name='x') xs.append(x) # Try sampling with a variety of unit sample shapes. self.assertEqual( [1], dist.sample( 1, seed=test_util.test_seed(sampler_type='seedless')).x.shape) self.assertEqual( [1], dist.sample([1], seed=test_util.test_seed(sampler_type='seedless')).x.shape) self.assertEqual( [1, 1], dist.sample([1, 1], seed=test_util.test_seed(sampler_type='seedless')).x.shape) # Check that the model only ever saw the trivial sample shape. for x in xs: self.assertEqual(x.shape, []) def test_unit_sample_shape(self): @tfd.JointDistributionCoroutineAutoBatched def dist(): x = yield tfd.Normal(loc=tf.zeros([3]), scale=1., name='x') yield tfd.Bernoulli(logits=tf.einsum('n->', x), name='y') for sample_shape in [(), 1, [1], [1, 1], [2]]: self.assertAllEqual( dist.log_prob( dist.sample(sample_shape, seed=test_util.test_seed())).shape, np.reshape(sample_shape, [-1])) def test_sample_dtype_structures_output(self): num_features = 4 def dist(): scale_variance = yield Root(tfd.InverseGamma(0.5, 0.5)) scale_noncentered = yield Root( tfd.Sample(tfd.HalfNormal(1.), num_features)) scale = scale_noncentered * scale_variance[..., None]**0.5 weights_noncentered = yield Root( tfd.Sample(tfd.Normal(0., 1.), num_features)) yield tfd.Deterministic(weights_noncentered * scale) # Currently sample_dtype is only used for `tf.nest.pack_structure_as`. In # the future we may use it for error checking and/or casting. sample_dtype = collections.namedtuple('Model', [ 'scale_variance', 'scale_noncentered', 'weights_noncentered', 'weights', ])(*([None]*4)) joint = tfd.JointDistributionCoroutineAutoBatched( dist, sample_dtype=sample_dtype, validate_args=True) self.assertAllEqual(sorted(sample_dtype._fields), sorted(joint.sample( seed=test_util.test_seed())._fields)) ds, xs = joint.sample_distributions(seed=test_util.test_seed()) tf.nest.assert_same_structure(sample_dtype, ds) tf.nest.assert_same_structure(sample_dtype, xs) self.assertEqual([3, 4], joint.log_prob(joint.sample( [3, 4], seed=test_util.test_seed())).shape) def test_repr_with_custom_sample_dtype(self): sd = collections.namedtuple('Model', ['s', 'w'])(None, None) def dist(): s = yield tfd.Sample(tfd.InverseGamma(2, 2), 100) yield tfd.Normal(0, s) m = tfd.JointDistributionCoroutineAutoBatched(dist, sample_dtype=sd) self.assertEqual( ('<tfp.distributions.JointDistributionCoroutineAutoBatched' ' \'JointDistributionCoroutineAutoBatched\'' ' batch_shape=[]' ' event_shape=Model(s=[100], w=[100])' ' dtype=Model(s=float32, w=float32)>'), repr(m)) @parameterized.named_parameters( {'testcase_name': 'coroutine', 'jd_class': tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched}, {'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}) @test_util.jax_disable_variable_test def test_latent_dirichlet_allocation(self, jd_class): # pylint: disable=g-doc-args """Tests Latent Dirichlet Allocation joint model. The LDA generative process can be written as: ```none N[i] ~ Poisson(xi) theta[i] ~ Dirichlet(alpha) Z[i] ~ Multinomial(N[i], theta[i]) for k in 1...K: X[i,k] ~ Multinomial(Z[i, k], beta[j]) ``` Typically `xi` is specified and `alpha`, `beta` are fit using type-II maximum likelihood estimators. Reference: http://www.jmlr.org/papers/volume3/blei03a/blei03a.pdf """ seed = test_util.test_seed_stream() # Hyperparameters. num_topics = 3 num_words = 10 avg_doc_length = 5 u = tfd.Uniform(low=-1., high=1.) alpha = tfp.util.TransformedVariable( u.sample([num_topics], seed=seed()), tfb.Softplus(), name='alpha') beta = tf.Variable(u.sample([num_topics, num_words], seed=seed()), name='beta') # Note near 1:1 with mathematical specification. The main distinction is the # use of Independent--this lets us easily aggregate multinomials across # topics (and in any "shape" of documents). def lda_coroutine_model(): n = yield Root(tfd.Poisson(rate=avg_doc_length)) theta = yield Root(tfd.Dirichlet(concentration=alpha)) z = yield tfd.Multinomial(total_count=n, probs=theta) yield tfd.Multinomial(total_count=z, logits=beta) if jd_class is tfd.JointDistributionCoroutineAutoBatched: model = lda_coroutine_model elif jd_class is tfd.JointDistributionSequentialAutoBatched: model = [ tfd.Poisson(rate=avg_doc_length), # n tfd.Dirichlet(concentration=alpha), # theta lambda theta, n: tfd.Multinomial(total_count=n, probs=theta), # z lambda z: tfd.Multinomial(total_count=z, logits=beta) ] elif jd_class is tfd.JointDistributionNamedAutoBatched: model = collections.OrderedDict(( ('n', tfd.Poisson(rate=avg_doc_length)), ('theta', tfd.Dirichlet(concentration=alpha)), ('z', lambda theta, n: tfd.Multinomial(total_count=n, probs=theta)), ('X', lambda z: tfd.Multinomial(total_count=z, logits=beta)))) # TODO(b/159842104): Enable autovectorization for Multinomial sampling. lda = jd_class(model, validate_args=True, use_vectorized_map=False) # Now, let's sample some "documents" and compute the log-prob of each. docs_shape = [2, 4] # That is, 8 docs in the shape of [2, 4]. sample = lda.sample(docs_shape, seed=seed()) log_probs = lda.log_prob(sample) self.assertEqual(docs_shape, log_probs.shape) # Verify we correctly track trainable variables. self.assertLen(lda.trainable_variables, 2) self.assertIs(alpha.pretransformed_input, lda.trainable_variables[0]) self.assertIs(beta, lda.trainable_variables[1]) # Ensure we can compute gradients. with tf.GradientTape() as tape: # Note: The samples are not taped, hence implicitly "stop_gradient." negloglik = -lda.log_prob(sample) grads = tape.gradient(negloglik, lda.trainable_variables) self.assertLen(grads, 2) self.assertAllEqual((alpha.pretransformed_input.shape, beta.shape), (grads[0].shape, grads[1].shape)) self.assertAllNotNone(grads) @parameterized.named_parameters( {'testcase_name': 'coroutine', 'jd_class': tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched}, {'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}) def test_default_event_space_bijector(self, jd_class): models = {} def coroutine_model(): high = yield tfd.LogNormal(0., [1.]) yield tfd.Uniform(low=[[-1., -2.]], high=high[..., tf.newaxis]) yield tfd.Deterministic([[0., 1., 2.]]) models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_model models[tfd.JointDistributionSequentialAutoBatched] = [ tfd.LogNormal(0., [1.]), lambda high: tfd.Uniform(low=[[-1., -2.]], high=high[..., tf.newaxis]), tfd.Deterministic([[0., 1., 2.]]) ] models[tfd.JointDistributionNamedAutoBatched] = collections.OrderedDict(( ('high', tfd.LogNormal(0., [1.])), ('x', lambda high: tfd.Uniform(low=[[-1., -2.]], # pylint: disable=g-long-lambda high=high[..., tf.newaxis])), ('y', tfd.Deterministic([[0., 1., 2.]])))) joint = jd_class(models[jd_class], batch_ndims=1, validate_args=True) self.assertAllEqual(joint.batch_shape, [1]) self.assertAllEqualNested(tf.nest.flatten(joint.event_shape), [[], [2], [3]]) joint_bijector = joint.experimental_default_event_space_bijector() y = self.evaluate(joint.sample([2, 3], seed=test_util.test_seed())) x = joint_bijector.inverse(y) self.assertAllCloseNested(y, joint_bijector.forward(x)) fldj = joint_bijector.forward_log_det_jacobian( x, event_ndims=tf.nest.pack_sequence_as(joint.dtype, [0, 1, 2])) ildj = joint_bijector.inverse_log_det_jacobian( y, event_ndims=tf.nest.pack_sequence_as(joint.dtype, [0, 1, 1])) self.assertAllEqual(fldj.shape, joint.log_prob(y).shape) self.assertAllClose(fldj, -ildj) # Passing inputs *without* batch shape should return sane outputs. y = self.evaluate(joint.sample([], seed=test_util.test_seed())) # Strip the sample to represent just a single event. unbatched_y = tf.nest.map_structure(lambda t: t[0, ...], y) self.assertAllEqualNested(tf.nest.map_structure(tf.shape, unbatched_y), joint.event_shape_tensor()) ildj = joint_bijector.inverse_log_det_jacobian( unbatched_y, event_ndims=tf.nest.pack_sequence_as(joint.dtype, [0, 1, 1])) self.assertAllEqual(ildj.shape, joint.log_prob(unbatched_y).shape) @parameterized.named_parameters( {'testcase_name': 'coroutine', 'jd_class': tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched}, {'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}) def test_default_event_space_bijector_constant_jacobian(self, jd_class): models = {} def coroutine_model(): yield tfd.Normal(0., [1., 2.], name='x') models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_model models[tfd.JointDistributionSequentialAutoBatched] = [ tfd.Normal(0., [1., 2.], name='x') ] models[tfd.JointDistributionNamedAutoBatched] = { 'x': tfd.Normal(0., [1., 2.], name='x')} joint = jd_class(models[jd_class], batch_ndims=1, validate_args=True) self.assertAllEqual(joint.batch_shape, [2]) joint_bijector = joint.experimental_default_event_space_bijector() y = self.evaluate(joint.sample([3], seed=test_util.test_seed())) x = joint_bijector.inverse(y) self.assertAllCloseNested(y, joint_bijector.forward(x)) fldj = joint_bijector.forward_log_det_jacobian(x) ildj = joint_bijector.inverse_log_det_jacobian(y) self.assertAllEqual(fldj.shape, joint.log_prob(y).shape) self.assertAllClose(fldj, -ildj) def test_nested_joint_distributions(self): batch_shape = [2, 3] def inner_fn(): xy = yield tfd.JointDistributionNamedAutoBatched( {'x': tfd.Normal(loc=tf.zeros(batch_shape), scale=tf.ones(batch_shape), name='x'), 'y': lambda x: tfd.Poisson(log_rate=x, name='y')}, batch_ndims=2, name='xy') _ = yield tfd.Normal(loc=0., scale=xy['y'], name='z') joint = tfd.JointDistributionSequentialAutoBatched([ tfd.JointDistributionCoroutineAutoBatched(inner_fn, batch_ndims=1, name='a')]) z = joint.sample(seed=test_util.test_seed()) # Batch and event shape. self.assertAllEqual(joint.batch_shape, []) self.assertAllEqualNested( tf.nest.map_structure(lambda x: tf.TensorShape(x.shape), z), joint.event_shape) # Sample shape. z2 = self.evaluate( joint.sample(5, seed=test_util.test_seed())) lp2 = joint.log_prob(z2) self.assertAllEqual(lp2.shape, [5]) z3 = joint.sample(value=z2, seed=test_util.test_seed()) self.assertAllCloseNested(z2, z3) @parameterized.named_parameters(*[ dict(testcase_name='_{}{}'.format(jd_class.__name__, # pylint: disable=g-complex-comprehension '_jit' if jit else ''), jd_class=jd_class, jit=jit) for jd_class in (tfd.JointDistributionCoroutineAutoBatched, tfd.JointDistributionSequentialAutoBatched, tfd.JointDistributionNamedAutoBatched) for jit in (False, True) ]) def test_kahan_precision(self, jd_class, jit): maybe_jit = lambda f: f if jit: self.skip_if_no_xla() if not JAX_MODE and not tf.test.is_gpu_available(): self.skipTest('b/179303849') maybe_jit = tf.function(jit_compile=True) def make_models(dtype): models = {} def mk_20k_poisson(log_rate): return tfd.Poisson(log_rate=tf.broadcast_to(log_rate[..., tf.newaxis], log_rate.shape + (20_000,))) def coroutine_model(): log_rate = yield tfd.Normal(0., dtype(.2), name='log_rate') yield mk_20k_poisson(log_rate).copy(name='x') models[tfd.JointDistributionCoroutineAutoBatched] = coroutine_model models[tfd.JointDistributionSequentialAutoBatched] = [ tfd.Normal(0., dtype(.2)), mk_20k_poisson ] models[tfd.JointDistributionNamedAutoBatched] = collections.OrderedDict(( ('log_rate', tfd.Normal(0., dtype(.2))), ('x', mk_20k_poisson))) return models joint = jd_class(make_models(np.float32)[jd_class], validate_args=True, experimental_use_kahan_sum=True) joint64 = jd_class(make_models(np.float64)[jd_class], validate_args=True) stream = test_util.test_seed_stream() nsamp = 7 xs = self.evaluate( joint.sample(log_rate=tf.zeros([nsamp]), seed=stream())) if isinstance(xs, dict): xs['log_rate'] = tfd.Normal(0, .2).sample(nsamp, seed=stream()) else: xs = (tfd.Normal(0, .2).sample(nsamp, seed=stream()), xs[1]) xs64 = tf.nest.map_structure(lambda x: tf.cast(x, tf.float64), xs) lp = maybe_jit(joint.copy(validate_args=not jit).log_prob)(xs) lp64 = joint64.log_prob(xs64) lp, lp64 = self.evaluate((tf.cast(lp, tf.float64), lp64)) # Without Kahan, example max-abs-diff: ~0.06 self.assertAllClose(lp64, lp, rtol=0., atol=.01) def test_kahan_broadcasting_check(self): def model(): _ = yield tfd.Normal(0., 1.) # Batch shape () _ = yield tfd.Normal([0., 1., 2.], 1.) # Batch shape [3] dist = tfd.JointDistributionCoroutineAutoBatched( model, validate_args=True, experimental_use_kahan_sum=True, batch_ndims=1) sample = self.evaluate(dist.sample(seed=test_util.test_seed( sampler_type='stateless'))) with self.assertRaises(ValueError): self.evaluate(dist.log_prob(sample)) if __name__ == '__main__': # TODO(b/173158845): XLA:CPU reassociates away the Kahan correction term. os.environ['XLA_FLAGS'] = '--xla_cpu_enable_fast_math=false' test_util.main()
[ "tensorflow.compat.v2.nest.map_structure", "numpy.log", "tensorflow.compat.v2.einsum", "tensorflow_probability.python.internal.test_util.jax_disable_test_missing_functionality", "tensorflow.compat.v2.cast", "tensorflow.compat.v2.nest.pack_sequence_as", "tensorflow.compat.v2.nest.assert_same_structure", "numpy.reshape", "tensorflow.compat.v2.executing_eagerly", "tensorflow.compat.v2.function", "tensorflow.compat.v2.math.log", "tensorflow.compat.v2.expand_dims", "tensorflow.compat.v2.TensorShape", "numpy.exp", "tensorflow.compat.v2.ones", "tensorflow.compat.v2.nest.flatten", "tensorflow.compat.v1.placeholder_with_default", "collections.namedtuple", "numpy.ones", "tensorflow.compat.v2.zeros", "tensorflow_probability.python.internal.test_util.main", "tensorflow.compat.v2.fill", "tensorflow.compat.v2.broadcast_to", "absl.testing.parameterized.named_parameters", "tensorflow_probability.python.internal.test_util.test_seed_stream", "tensorflow_probability.python.internal.test_util.test_seed", "tensorflow.compat.v2.GradientTape", "tensorflow.compat.v2.test.is_gpu_available" ]
[((1233, 1535), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': 'coroutine', 'jd_class': tfd.\n JointDistributionCoroutineAutoBatched}", "{'testcase_name': 'sequential', 'jd_class': tfd.\n JointDistributionSequentialAutoBatched}", "{'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}"], {}), "({'testcase_name': 'coroutine', 'jd_class':\n tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name':\n 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched},\n {'testcase_name': 'named', 'jd_class': tfd.\n JointDistributionNamedAutoBatched})\n", (1263, 1535), False, 'from absl.testing import parameterized\n'), ((6819, 7278), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': 'coroutine', 'base_jd_class': tfd.\n JointDistributionCoroutine, 'jda_class': tfd.\n JointDistributionCoroutineAutoBatched}", "{'testcase_name': 'sequential', 'base_jd_class': tfd.\n JointDistributionSequential, 'jda_class': tfd.\n JointDistributionSequentialAutoBatched}", "{'testcase_name': 'named', 'base_jd_class': tfd.JointDistributionNamed,\n 'jda_class': tfd.JointDistributionNamedAutoBatched}"], {}), "({'testcase_name': 'coroutine',\n 'base_jd_class': tfd.JointDistributionCoroutine, 'jda_class': tfd.\n JointDistributionCoroutineAutoBatched}, {'testcase_name': 'sequential',\n 'base_jd_class': tfd.JointDistributionSequential, 'jda_class': tfd.\n JointDistributionSequentialAutoBatched}, {'testcase_name': 'named',\n 'base_jd_class': tfd.JointDistributionNamed, 'jda_class': tfd.\n JointDistributionNamedAutoBatched})\n", (6849, 7278), False, 'from absl.testing import parameterized\n'), ((11146, 11448), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': 'coroutine', 'jd_class': tfd.\n JointDistributionCoroutineAutoBatched}", "{'testcase_name': 'sequential', 'jd_class': tfd.\n JointDistributionSequentialAutoBatched}", "{'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}"], {}), "({'testcase_name': 'coroutine', 'jd_class':\n tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name':\n 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched},\n {'testcase_name': 'named', 'jd_class': tfd.\n JointDistributionNamedAutoBatched})\n", (11176, 11448), False, 'from absl.testing import parameterized\n'), ((13230, 13532), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': 'coroutine', 'jd_class': tfd.\n JointDistributionCoroutineAutoBatched}", "{'testcase_name': 'sequential', 'jd_class': tfd.\n JointDistributionSequentialAutoBatched}", "{'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}"], {}), "({'testcase_name': 'coroutine', 'jd_class':\n tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name':\n 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched},\n {'testcase_name': 'named', 'jd_class': tfd.\n JointDistributionNamedAutoBatched})\n", (13260, 13532), False, 'from absl.testing import parameterized\n'), ((15023, 15325), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': 'coroutine', 'jd_class': tfd.\n JointDistributionCoroutineAutoBatched}", "{'testcase_name': 'sequential', 'jd_class': tfd.\n JointDistributionSequentialAutoBatched}", "{'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}"], {}), "({'testcase_name': 'coroutine', 'jd_class':\n tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name':\n 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched},\n {'testcase_name': 'named', 'jd_class': tfd.\n JointDistributionNamedAutoBatched})\n", (15053, 15325), False, 'from absl.testing import parameterized\n'), ((17195, 17258), 'tensorflow_probability.python.internal.test_util.jax_disable_test_missing_functionality', 'test_util.jax_disable_test_missing_functionality', (['"""b/157594634"""'], {}), "('b/157594634')\n", (17243, 17258), False, 'from tensorflow_probability.python.internal import test_util\n'), ((17832, 17895), 'tensorflow_probability.python.internal.test_util.jax_disable_test_missing_functionality', 'test_util.jax_disable_test_missing_functionality', (['"""b/201586404"""'], {}), "('b/201586404')\n", (17880, 17895), False, 'from tensorflow_probability.python.internal import test_util\n'), ((27580, 27882), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': 'coroutine', 'jd_class': tfd.\n JointDistributionCoroutineAutoBatched}", "{'testcase_name': 'sequential', 'jd_class': tfd.\n JointDistributionSequentialAutoBatched}", "{'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}"], {}), "({'testcase_name': 'coroutine', 'jd_class':\n tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name':\n 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched},\n {'testcase_name': 'named', 'jd_class': tfd.\n JointDistributionNamedAutoBatched})\n", (27610, 27882), False, 'from absl.testing import parameterized\n'), ((31272, 31574), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': 'coroutine', 'jd_class': tfd.\n JointDistributionCoroutineAutoBatched}", "{'testcase_name': 'sequential', 'jd_class': tfd.\n JointDistributionSequentialAutoBatched}", "{'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}"], {}), "({'testcase_name': 'coroutine', 'jd_class':\n tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name':\n 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched},\n {'testcase_name': 'named', 'jd_class': tfd.\n JointDistributionNamedAutoBatched})\n", (31302, 31574), False, 'from absl.testing import parameterized\n'), ((33918, 34220), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["{'testcase_name': 'coroutine', 'jd_class': tfd.\n JointDistributionCoroutineAutoBatched}", "{'testcase_name': 'sequential', 'jd_class': tfd.\n JointDistributionSequentialAutoBatched}", "{'testcase_name': 'named', 'jd_class': tfd.JointDistributionNamedAutoBatched}"], {}), "({'testcase_name': 'coroutine', 'jd_class':\n tfd.JointDistributionCoroutineAutoBatched}, {'testcase_name':\n 'sequential', 'jd_class': tfd.JointDistributionSequentialAutoBatched},\n {'testcase_name': 'named', 'jd_class': tfd.\n JointDistributionNamedAutoBatched})\n", (33948, 34220), False, 'from absl.testing import parameterized\n'), ((39530, 39546), 'tensorflow_probability.python.internal.test_util.main', 'test_util.main', ([], {}), '()\n', (39544, 39546), False, 'from tensorflow_probability.python.internal import test_util\n'), ((5620, 5642), 'tensorflow.compat.v2.executing_eagerly', 'tf.executing_eagerly', ([], {}), '()\n', (5640, 5642), True, 'import tensorflow.compat.v2 as tf\n'), ((16614, 16659), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': '"""stateless"""'}), "(sampler_type='stateless')\n", (16633, 16659), False, 'from tensorflow_probability.python.internal import test_util\n'), ((22191, 22245), 'tensorflow.compat.v1.placeholder_with_default', 'tf1.placeholder_with_default', (['sample_shape'], {'shape': 'None'}), '(sample_shape, shape=None)\n', (22219, 22245), True, 'import tensorflow.compat.v1 as tf1\n'), ((26791, 26838), 'tensorflow.compat.v2.nest.assert_same_structure', 'tf.nest.assert_same_structure', (['sample_dtype', 'ds'], {}), '(sample_dtype, ds)\n', (26820, 26838), True, 'import tensorflow.compat.v2 as tf\n'), ((26843, 26890), 'tensorflow.compat.v2.nest.assert_same_structure', 'tf.nest.assert_same_structure', (['sample_dtype', 'xs'], {}), '(sample_dtype, xs)\n', (26872, 26890), True, 'import tensorflow.compat.v2 as tf\n'), ((28516, 28544), 'tensorflow_probability.python.internal.test_util.test_seed_stream', 'test_util.test_seed_stream', ([], {}), '()\n', (28542, 28544), False, 'from tensorflow_probability.python.internal import test_util\n'), ((33520, 33565), 'tensorflow.compat.v2.nest.map_structure', 'tf.nest.map_structure', (['(lambda t: t[0, ...])', 'y'], {}), '(lambda t: t[0, ...], y)\n', (33541, 33565), True, 'import tensorflow.compat.v2 as tf\n'), ((38209, 38237), 'tensorflow_probability.python.internal.test_util.test_seed_stream', 'test_util.test_seed_stream', ([], {}), '()\n', (38235, 38237), False, 'from tensorflow_probability.python.internal import test_util\n'), ((6513, 6533), 'tensorflow.compat.v2.TensorShape', 'tf.TensorShape', (['None'], {}), '(None)\n', (6527, 6533), True, 'import tensorflow.compat.v2 as tf\n'), ((13199, 13224), 'numpy.exp', 'np.exp', (['expected_log_prob'], {}), '(expected_log_prob)\n', (13205, 13224), True, 'import numpy as np\n'), ((14924, 14944), 'tensorflow.compat.v2.math.log', 'tf.math.log', (['(1.0 + b)'], {}), '(1.0 + b)\n', (14935, 14944), True, 'import tensorflow.compat.v2 as tf\n'), ((21034, 21082), 'numpy.ones', 'np.ones', (['[value_partial_batch_dim, num_features]'], {}), '([value_partial_batch_dim, num_features])\n', (21041, 21082), True, 'import numpy as np\n'), ((21368, 21412), 'tensorflow.compat.v2.fill', 'tf.fill', (['[value_partial_batch_dim]', 'value[0]'], {}), '([value_partial_batch_dim], value[0])\n', (21375, 21412), True, 'import tensorflow.compat.v2 as tf\n'), ((21941, 22000), 'tensorflow.compat.v2.fill', 'tf.fill', (['(sample_shape + [value_partial_batch_dim])', 'value[0]'], {}), '(sample_shape + [value_partial_batch_dim], value[0])\n', (21948, 22000), True, 'import tensorflow.compat.v2 as tf\n'), ((22469, 22528), 'tensorflow.compat.v2.fill', 'tf.fill', (['(sample_shape + [value_partial_batch_dim])', 'value[0]'], {}), '(sample_shape + [value_partial_batch_dim], value[0])\n', (22476, 22528), True, 'import tensorflow.compat.v2 as tf\n'), ((23750, 23792), 'collections.namedtuple', 'collections.namedtuple', (['"""ValueSpec"""', "['a']"], {}), "('ValueSpec', ['a'])\n", (23772, 23792), False, 'import collections\n'), ((26279, 26389), 'collections.namedtuple', 'collections.namedtuple', (['"""Model"""', "['scale_variance', 'scale_noncentered', 'weights_noncentered', 'weights']"], {}), "('Model', ['scale_variance', 'scale_noncentered',\n 'weights_noncentered', 'weights'])\n", (26301, 26389), False, 'import collections\n'), ((27059, 27102), 'collections.namedtuple', 'collections.namedtuple', (['"""Model"""', "['s', 'w']"], {}), "('Model', ['s', 'w'])\n", (27081, 27102), False, 'import collections\n'), ((30871, 30888), 'tensorflow.compat.v2.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (30886, 30888), True, 'import tensorflow.compat.v2 as tf\n'), ((32636, 32670), 'tensorflow.compat.v2.nest.flatten', 'tf.nest.flatten', (['joint.event_shape'], {}), '(joint.event_shape)\n', (32651, 32670), True, 'import tensorflow.compat.v2 as tf\n'), ((33596, 33640), 'tensorflow.compat.v2.nest.map_structure', 'tf.nest.map_structure', (['tf.shape', 'unbatched_y'], {}), '(tf.shape, unbatched_y)\n', (33617, 33640), True, 'import tensorflow.compat.v2 as tf\n'), ((37191, 37220), 'tensorflow.compat.v2.function', 'tf.function', ([], {'jit_compile': '(True)'}), '(jit_compile=True)\n', (37202, 37220), True, 'import tensorflow.compat.v2 as tf\n'), ((5431, 5477), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': 'sampler_type'}), '(sampler_type=sampler_type)\n', (5450, 5477), False, 'from tensorflow_probability.python.internal import test_util\n'), ((6006, 6047), 'tensorflow.compat.v1.placeholder_with_default', 'tf1.placeholder_with_default', (['(1)'], {'shape': '[]'}), '(1, shape=[])\n', (6034, 6047), True, 'import tensorflow.compat.v1 as tf1\n'), ((6684, 6729), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': '"""stateless"""'}), "(sampler_type='stateless')\n", (6703, 6729), False, 'from tensorflow_probability.python.internal import test_util\n'), ((10137, 10158), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (10156, 10158), False, 'from tensorflow_probability.python.internal import test_util\n'), ((14537, 14558), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (14556, 14558), False, 'from tensorflow_probability.python.internal import test_util\n'), ((15604, 15618), 'tensorflow.compat.v2.math.log', 'tf.math.log', (['y'], {}), '(y)\n', (15615, 15618), True, 'import tensorflow.compat.v2 as tf\n'), ((17650, 17671), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (17669, 17671), False, 'from tensorflow_probability.python.internal import test_util\n'), ((18345, 18366), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (18364, 18366), False, 'from tensorflow_probability.python.internal import test_util\n'), ((21120, 21142), 'tensorflow.compat.v2.cast', 'tf.cast', (['v', 'tf.float32'], {}), '(v, tf.float32)\n', (21127, 21142), True, 'import tensorflow.compat.v2 as tf\n'), ((21749, 21795), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': 'sampler_type'}), '(sampler_type=sampler_type)\n', (21768, 21795), False, 'from tensorflow_probability.python.internal import test_util\n'), ((22142, 22161), 'tensorflow.compat.v2.ones', 'tf.ones', (['expect_shp'], {}), '(expect_shp)\n', (22149, 22161), True, 'import tensorflow.compat.v2 as tf\n'), ((22349, 22395), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': 'sampler_type'}), '(sampler_type=sampler_type)\n', (22368, 22395), False, 'from tensorflow_probability.python.internal import test_util\n'), ((22670, 22689), 'tensorflow.compat.v2.ones', 'tf.ones', (['expect_shp'], {}), '(expect_shp)\n', (22677, 22689), True, 'import tensorflow.compat.v2 as tf\n'), ((25618, 25648), 'numpy.reshape', 'np.reshape', (['sample_shape', '[-1]'], {}), '(sample_shape, [-1])\n', (25628, 25648), True, 'import numpy as np\n'), ((26764, 26785), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (26783, 26785), False, 'from tensorflow_probability.python.internal import test_util\n'), ((33032, 33080), 'tensorflow.compat.v2.nest.pack_sequence_as', 'tf.nest.pack_sequence_as', (['joint.dtype', '[0, 1, 2]'], {}), '(joint.dtype, [0, 1, 2])\n', (33056, 33080), True, 'import tensorflow.compat.v2 as tf\n'), ((33157, 33205), 'tensorflow.compat.v2.nest.pack_sequence_as', 'tf.nest.pack_sequence_as', (['joint.dtype', '[0, 1, 1]'], {}), '(joint.dtype, [0, 1, 1])\n', (33181, 33205), True, 'import tensorflow.compat.v2 as tf\n'), ((33793, 33841), 'tensorflow.compat.v2.nest.pack_sequence_as', 'tf.nest.pack_sequence_as', (['joint.dtype', '[0, 1, 1]'], {}), '(joint.dtype, [0, 1, 1])\n', (33817, 33841), True, 'import tensorflow.compat.v2 as tf\n'), ((35994, 36015), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (36013, 36015), False, 'from tensorflow_probability.python.internal import test_util\n'), ((36426, 36447), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (36445, 36447), False, 'from tensorflow_probability.python.internal import test_util\n'), ((38560, 38582), 'tensorflow.compat.v2.cast', 'tf.cast', (['x', 'tf.float64'], {}), '(x, tf.float64)\n', (38567, 38582), True, 'import tensorflow.compat.v2 as tf\n'), ((38719, 38742), 'tensorflow.compat.v2.cast', 'tf.cast', (['lp', 'tf.float64'], {}), '(lp, tf.float64)\n', (38726, 38742), True, 'import tensorflow.compat.v2 as tf\n'), ((1816, 1838), 'tensorflow.compat.v2.expand_dims', 'tf.expand_dims', (['df', '(-1)'], {}), '(df, -1)\n', (1830, 1838), True, 'import tensorflow.compat.v2 as tf\n'), ((2132, 2154), 'tensorflow.compat.v2.expand_dims', 'tf.expand_dims', (['df', '(-1)'], {}), '(df, -1)\n', (2146, 2154), True, 'import tensorflow.compat.v2 as tf\n'), ((4092, 4114), 'tensorflow.compat.v2.expand_dims', 'tf.expand_dims', (['df', '(-1)'], {}), '(df, -1)\n', (4106, 4114), True, 'import tensorflow.compat.v2 as tf\n'), ((4420, 4442), 'tensorflow.compat.v2.expand_dims', 'tf.expand_dims', (['df', '(-1)'], {}), '(df, -1)\n', (4434, 4442), True, 'import tensorflow.compat.v2 as tf\n'), ((5873, 5895), 'tensorflow.compat.v2.expand_dims', 'tf.expand_dims', (['df', '(-1)'], {}), '(df, -1)\n', (5887, 5895), True, 'import tensorflow.compat.v2 as tf\n'), ((6625, 6645), 'tensorflow.compat.v2.TensorShape', 'tf.TensorShape', (['None'], {}), '(None)\n', (6639, 6645), True, 'import tensorflow.compat.v2 as tf\n'), ((10981, 11002), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (11000, 11002), False, 'from tensorflow_probability.python.internal import test_util\n'), ((12613, 12634), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (12632, 12634), False, 'from tensorflow_probability.python.internal import test_util\n'), ((12830, 12841), 'numpy.log', 'np.log', (['(0.5)'], {}), '(0.5)\n', (12836, 12841), True, 'import numpy as np\n'), ((14895, 14914), 'numpy.log', 'np.log', (['(2.0 * np.pi)'], {}), '(2.0 * np.pi)\n', (14901, 14914), True, 'import numpy as np\n'), ((17447, 17461), 'tensorflow.compat.v2.zeros', 'tf.zeros', (['[20]'], {}), '([20])\n', (17455, 17461), True, 'import tensorflow.compat.v2 as tf\n'), ((18586, 18607), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (18605, 18607), False, 'from tensorflow_probability.python.internal import test_util\n'), ((18981, 19002), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (19000, 19002), False, 'from tensorflow_probability.python.internal import test_util\n'), ((19054, 19075), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (19073, 19075), False, 'from tensorflow_probability.python.internal import test_util\n'), ((19480, 19501), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (19499, 19501), False, 'from tensorflow_probability.python.internal import test_util\n'), ((19553, 19574), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (19572, 19574), False, 'from tensorflow_probability.python.internal import test_util\n'), ((20018, 20039), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (20037, 20039), False, 'from tensorflow_probability.python.internal import test_util\n'), ((20082, 20103), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (20101, 20103), False, 'from tensorflow_probability.python.internal import test_util\n'), ((21288, 21334), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': 'sampler_type'}), '(sampler_type=sampler_type)\n', (21307, 21334), False, 'from tensorflow_probability.python.internal import test_util\n'), ((23369, 23421), 'collections.namedtuple', 'collections.namedtuple', (['"""ModelSpec"""', "['a', 'b', 'c']"], {}), "('ModelSpec', ['a', 'b', 'c'])\n", (23391, 23421), False, 'import collections\n'), ((23570, 23614), 'numpy.ones', 'np.ones', (['[value_partial_batch_dim, num_rows]'], {}), '([value_partial_batch_dim, num_rows])\n', (23577, 23614), True, 'import numpy as np\n'), ((32838, 32859), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (32857, 32859), False, 'from tensorflow_probability.python.internal import test_util\n'), ((33421, 33442), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (33440, 33442), False, 'from tensorflow_probability.python.internal import test_util\n'), ((34935, 34956), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (34954, 34956), False, 'from tensorflow_probability.python.internal import test_util\n'), ((36165, 36188), 'tensorflow.compat.v2.TensorShape', 'tf.TensorShape', (['x.shape'], {}), '(x.shape)\n', (36179, 36188), True, 'import tensorflow.compat.v2 as tf\n'), ((36295, 36316), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (36314, 36316), False, 'from tensorflow_probability.python.internal import test_util\n'), ((37108, 37134), 'tensorflow.compat.v2.test.is_gpu_available', 'tf.test.is_gpu_available', ([], {}), '()\n', (37132, 37134), True, 'import tensorflow.compat.v2 as tf\n'), ((38306, 38323), 'tensorflow.compat.v2.zeros', 'tf.zeros', (['[nsamp]'], {}), '([nsamp])\n', (38314, 38323), True, 'import tensorflow.compat.v2 as tf\n'), ((39220, 39265), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': '"""stateless"""'}), "(sampler_type='stateless')\n", (39239, 39265), False, 'from tensorflow_probability.python.internal import test_util\n'), ((12866, 12928), 'tensorflow.compat.v2.math.log', 'tf.math.log', (['(b * (0.25 + 0.5 * a) + (1 - b) * (0.75 - 0.5 * a))'], {}), '(b * (0.25 + 0.5 * a) + (1 - b) * (0.75 - 0.5 * a))\n', (12877, 12928), True, 'import tensorflow.compat.v2 as tf\n'), ((13092, 13112), 'tensorflow.compat.v2.math.log', 'tf.math.log', (['(1.0 + b)'], {}), '(1.0 + b)\n', (13103, 13112), True, 'import tensorflow.compat.v2 as tf\n'), ((14732, 14743), 'numpy.log', 'np.log', (['(0.5)'], {}), '(0.5)\n', (14738, 14743), True, 'import numpy as np\n'), ((14754, 14816), 'tensorflow.compat.v2.math.log', 'tf.math.log', (['(b * (0.25 + 0.5 * a) + (1 - b) * (0.75 - 0.5 * a))'], {}), '(b * (0.25 + 0.5 * a) + (1 - b) * (0.75 - 0.5 * a))\n', (14765, 14816), True, 'import tensorflow.compat.v2 as tf\n'), ((25303, 25316), 'tensorflow.compat.v2.zeros', 'tf.zeros', (['[3]'], {}), '([3])\n', (25311, 25316), True, 'import tensorflow.compat.v2 as tf\n'), ((25371, 25390), 'tensorflow.compat.v2.einsum', 'tf.einsum', (['"""n->"""', 'x'], {}), "('n->', x)\n", (25380, 25390), True, 'import tensorflow.compat.v2 as tf\n'), ((37340, 37409), 'tensorflow.compat.v2.broadcast_to', 'tf.broadcast_to', (['log_rate[..., tf.newaxis]', '(log_rate.shape + (20000,))'], {}), '(log_rate[..., tf.newaxis], log_rate.shape + (20000,))\n', (37355, 37409), True, 'import tensorflow.compat.v2 as tf\n'), ((2428, 2450), 'tensorflow.compat.v2.expand_dims', 'tf.expand_dims', (['df', '(-1)'], {}), '(df, -1)\n', (2442, 2450), True, 'import tensorflow.compat.v2 as tf\n'), ((4728, 4750), 'tensorflow.compat.v2.expand_dims', 'tf.expand_dims', (['df', '(-1)'], {}), '(df, -1)\n', (4742, 4750), True, 'import tensorflow.compat.v2 as tf\n'), ((9665, 9686), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (9684, 9686), False, 'from tensorflow_probability.python.internal import test_util\n'), ((23998, 24044), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': 'sampler_type'}), '(sampler_type=sampler_type)\n', (24017, 24044), False, 'from tensorflow_probability.python.internal import test_util\n'), ((24710, 24754), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': '"""seedless"""'}), "(sampler_type='seedless')\n", (24729, 24754), False, 'from tensorflow_probability.python.internal import test_util\n'), ((24850, 24894), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': '"""seedless"""'}), "(sampler_type='seedless')\n", (24869, 24894), False, 'from tensorflow_probability.python.internal import test_util\n'), ((24996, 25040), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {'sampler_type': '"""seedless"""'}), "(sampler_type='seedless')\n", (25015, 25040), False, 'from tensorflow_probability.python.internal import test_util\n'), ((26686, 26707), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (26705, 26707), False, 'from tensorflow_probability.python.internal import test_util\n'), ((26970, 26991), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (26989, 26991), False, 'from tensorflow_probability.python.internal import test_util\n'), ((13049, 13068), 'numpy.log', 'np.log', (['(2.0 * np.pi)'], {}), '(2.0 * np.pi)\n', (13055, 13068), True, 'import numpy as np\n'), ((25577, 25598), 'tensorflow_probability.python.internal.test_util.test_seed', 'test_util.test_seed', ([], {}), '()\n', (25596, 25598), False, 'from tensorflow_probability.python.internal import test_util\n'), ((35439, 35460), 'tensorflow.compat.v2.zeros', 'tf.zeros', (['batch_shape'], {}), '(batch_shape)\n', (35447, 35460), True, 'import tensorflow.compat.v2 as tf\n'), ((35495, 35515), 'tensorflow.compat.v2.ones', 'tf.ones', (['batch_shape'], {}), '(batch_shape)\n', (35502, 35515), True, 'import tensorflow.compat.v2 as tf\n')]
import numpy as np from sklearn.decomposition import PCA import pandas as pd import matplotlib.pyplot as plt import random import seaborn as sns from sklearn.cluster import KMeans from sklearn.metrics import confusion_matrix from sklearn.metrics.cluster import adjusted_rand_score from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split import pandas.util.testing as tm from keras.datasets import mnist import tensorflow_datasets as tfds import tensorflow as tf from google.colab import files import sys import itertools as it #@title ElasticNetSubspaceClustering import warnings import progressbar import spams import time from scipy import sparse from sklearn import cluster from sklearn.base import BaseEstimator, ClusterMixin from sklearn.decomposition import sparse_encode from sklearn.linear_model import orthogonal_mp from sklearn.neighbors import kneighbors_graph from sklearn.preprocessing import normalize from sklearn.utils import check_random_state, check_array, check_symmetric class SelfRepresentation(BaseEstimator, ClusterMixin): def __init__(self, n_clusters=8, affinity='symmetrize', random_state=None, n_init=20, n_jobs=1): self.n_clusters = n_clusters self.affinity = affinity self.random_state = random_state self.n_init = n_init self.n_jobs = n_jobs def fit(self, X, y=None): X = check_array(X, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64) time_base = time.time() self._self_representation(X) self.timer_self_representation_ = time.time() - time_base self._representation_to_affinity() self._spectral_clustering() self.timer_time_ = time.time() - time_base return self def fit_self_representation(self, X, y=None): X = check_array(X, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64) time_base = time.time() self._self_representation(X) self.timer_self_representation_ = time.time() - time_base return self def _representation_to_affinity(self): normalized_representation_matrix_ = normalize(self.representation_matrix_, 'l2') if self.affinity == 'symmetrize': self.affinity_matrix_ = 0.5 * (np.absolute(normalized_representation_matrix_) + np.absolute(normalized_representation_matrix_.T)) elif self.affinity == 'nearest_neighbors': neighbors_graph = kneighbors_graph(normalized_representation_matrix_, 3, mode='connectivity', include_self=False) self.affinity_matrix_ = 0.5 * (neighbors_graph + neighbors_graph.T) def _spectral_clustering(self): affinity_matrix_ = check_symmetric(self.affinity_matrix_) random_state = check_random_state(self.random_state) laplacian = sparse.csgraph.laplacian(affinity_matrix_, normed=True) _, vec = sparse.linalg.eigsh(sparse.identity(laplacian.shape[0]) - laplacian, k=self.n_clusters, sigma=None, which='LA') embedding = normalize(vec) _, self.labels_, _ = cluster.k_means(embedding, self.n_clusters, random_state=random_state, n_init=self.n_init) def active_support_elastic_net(X, y, alpha, tau=1.0, algorithm='spams', support_init='knn', support_size=100, maxiter=40): n_samples = X.shape[0] if n_samples <= support_size: # skip active support search for small scale data supp = np.arange(n_samples, dtype=int) # this results in the following iteration to converge in 1 iteration else: if support_init == 'L2': L2sol = np.linalg.solve(np.identity(y.shape[1]) * alpha + np.dot(X.T, X), y.T) c0 = np.dot(X, L2sol)[:, 0] supp = np.argpartition(-np.abs(c0), support_size)[0:support_size] elif support_init == 'knn': supp = np.argpartition(-np.abs(np.dot(y, X.T)[0]), support_size)[0:support_size] curr_obj = float("inf") for _ in range(maxiter): Xs = X[supp, :] if algorithm == 'spams': cs = spams.lasso(np.asfortranarray(y.T), D=np.asfortranarray(Xs.T), lambda1=tau*alpha, lambda2=(1.0-tau)*alpha) cs = np.asarray(cs.todense()).T else: cs = sparse_encode(y, Xs, algorithm=algorithm, alpha=alpha) delta = (y - np.dot(cs, Xs)) / alpha obj = tau * np.sum(np.abs(cs[0])) + (1.0 - tau)/2.0 * np.sum(np.power(cs[0], 2.0)) + alpha/2.0 * np.sum(np.power(delta, 2.0)) if curr_obj - obj < 1.0e-10 * curr_obj: break curr_obj = obj coherence = np.abs(np.dot(delta, X.T))[0] coherence[supp] = 0 addedsupp = np.nonzero(coherence > tau + 1.0e-10)[0] if addedsupp.size == 0: # converged break # Find the set of nonzero entries of cs. activesupp = supp[np.abs(cs[0]) > 1.0e-10] if activesupp.size > 0.8 * support_size: # this suggests that support_size is too small and needs to be increased support_size = min([round(max([activesupp.size, support_size]) * 1.1), n_samples]) if addedsupp.size + activesupp.size > support_size: ord = np.argpartition(-coherence[addedsupp], support_size - activesupp.size)[0:support_size - activesupp.size] addedsupp = addedsupp[ord] supp = np.concatenate([activesupp, addedsupp]) c = np.zeros(n_samples) c[supp] = cs return c def elastic_net_subspace_clustering(X, gamma=50.0, gamma_nz=True, tau=1.0, algorithm='lasso_lars', active_support=True, active_support_params=None, n_nonzero=50): if algorithm in ('lasso_lars', 'lasso_cd') and tau < 1.0 - 1.0e-10: warnings.warn('algorithm {} cannot handle tau smaller than 1. Using tau = 1'.format(algorithm)) tau = 1.0 if active_support == True and active_support_params == None: active_support_params = {} n_samples = X.shape[0] rows = np.zeros(n_samples * n_nonzero) cols = np.zeros(n_samples * n_nonzero) vals = np.zeros(n_samples * n_nonzero) curr_pos = 0 for i in progressbar.progressbar(range(n_samples)): y = X[i, :].copy().reshape(1, -1) X[i, :] = 0 if algorithm in ('lasso_lars', 'lasso_cd', 'spams'): if gamma_nz == True: coh = np.delete(np.absolute(np.dot(X, y.T)), i) alpha0 = np.amax(coh) / tau # value for which the solution is zero alpha = alpha0 / gamma else: alpha = 1.0 / gamma if active_support == True: c = active_support_elastic_net(X, y, alpha, tau, algorithm, **active_support_params) else: if algorithm == 'spams': c = spams.lasso(np.asfortranarray(y.T), D=np.asfortranarray(X.T), lambda1=tau * alpha, lambda2=(1.0-tau) * alpha) c = np.asarray(c.todense()).T[0] else: c = sparse_encode(y, X, algorithm=algorithm, alpha=alpha)[0] else: warnings.warn("algorithm {} not found".format(algorithm)) index = np.flatnonzero(c) if index.size > n_nonzero: # warnings.warn("The number of nonzero entries in sparse subspace clustering exceeds n_nonzero") index = index[np.argsort(-np.absolute(c[index]))[0:n_nonzero]] rows[curr_pos:curr_pos + len(index)] = i cols[curr_pos:curr_pos + len(index)] = index vals[curr_pos:curr_pos + len(index)] = c[index] curr_pos += len(index) X[i, :] = y # affinity = sparse.csr_matrix((vals, (rows, cols)), shape=(n_samples, n_samples)) + sparse.csr_matrix((vals, (cols, rows)), shape=(n_samples, n_samples)) return sparse.csr_matrix((vals, (rows, cols)), shape=(n_samples, n_samples)) class ElasticNetSubspaceClustering(SelfRepresentation): def __init__(self, n_clusters=8, affinity='symmetrize', random_state=None, n_init=20, n_jobs=1, gamma=50.0, gamma_nz=True, tau=1.0, algorithm='lasso_lars', active_support=True, active_support_params=None, n_nonzero=50): self.gamma = gamma self.gamma_nz = gamma_nz self.tau = tau self.algorithm = algorithm self.active_support = active_support self.active_support_params = active_support_params self.n_nonzero = n_nonzero SelfRepresentation.__init__(self, n_clusters, affinity, random_state, n_init, n_jobs) def _self_representation(self, X): self.representation_matrix_ = elastic_net_subspace_clustering(X, self.gamma, self.gamma_nz, self.tau, self.algorithm, self.active_support, self.active_support_params, self.n_nonzero) def sparse_subspace_clustering_orthogonal_matching_pursuit(X, n_nonzero=10, thr=1.0e-6): n_samples = X.shape[0] rows = np.zeros(n_samples * n_nonzero, dtype = int) cols = np.zeros(n_samples * n_nonzero, dtype = int) vals = np.zeros(n_samples * n_nonzero) curr_pos = 0 for i in progressbar.progressbar(range(n_samples)): # for i in range(n_samples): residual = X[i, :].copy() # initialize residual supp = np.empty(shape=(0), dtype = int) # initialize support residual_norm_thr = np.linalg.norm(X[i, :]) * thr for t in range(n_nonzero): # for each iteration of OMP # compute coherence between residuals and X coherence = abs( np.matmul(residual, X.T) ) coherence[i] = 0.0 # update support supp = np.append(supp, np.argmax(coherence)) # compute coefficients c = np.linalg.lstsq( X[supp, :].T, X[i, :].T, rcond=None)[0] # compute residual residual = X[i, :] - np.matmul(c.T, X[supp, :]) # check termination if np.sum(residual **2) < residual_norm_thr: break rows[curr_pos:curr_pos + len(supp)] = i cols[curr_pos:curr_pos + len(supp)] = supp vals[curr_pos:curr_pos + len(supp)] = c curr_pos += len(supp) # affinity = sparse.csr_matrix((vals, (rows, cols)), shape=(n_samples, n_samples)) + sparse.csr_matrix((vals, (cols, rows)), shape=(n_samples, n_samples)) return sparse.csr_matrix((vals, (rows, cols)), shape=(n_samples, n_samples)) class SparseSubspaceClusteringOMP(SelfRepresentation): def __init__(self, n_clusters=8, affinity='symmetrize', random_state=None, n_init=10, n_jobs=1, n_nonzero=10, thr=1.0e-6): self.n_nonzero = n_nonzero self.thr = thr SelfRepresentation.__init__(self, n_clusters, affinity, random_state, n_init, n_jobs) def _self_representation(self, X): self.representation_matrix_ = sparse_subspace_clustering_orthogonal_matching_pursuit(X, self.n_nonzero, self.thr) def least_squares_subspace_clustering(X, gamma=10.0, exclude_self=False): n_samples, n_features = X.shape if exclude_self == False: if n_samples < n_features: gram = np.matmul(X, X.T) return np.linalg.solve(gram + np.eye(n_sample) / gamma, gram).T else: tmp = np.linalg.solve(np.matmul(X.T, X) + np.eye(n_features) / gamma, X.T) return np.matmul(X, tmp).T else: if n_samples < n_features: D = np.linalg.solve(np.matmul(X, X.T) + np.eye(n_sample) / gamma, np.eye(n_sample)) # see Theorem 6 in https://arxiv.org/pdf/1404.6736.pdf else: tmp = np.linalg.solve(np.matmul(X.T, X) + np.eye(n_features) / gamma, X.T) D = eye(n_samples) - np.matmul(X, tmp) D = D / D.diagonal()[None,:] np.fill_diagonal(D, 0.0) return -1.0 * D.T class LeastSquaresSubspaceClustering(SelfRepresentation): def __init__(self, n_clusters=8, affinity='symmetrize', random_state=None, n_init=None, n_jobs=1, gamma=10.0, exclude_self=False): self.gamma = gamma self.exclude_self = exclude_self SelfRepresentation.__init__(self, n_clusters, affinity, random_state, n_init, n_jobs) def _self_representation(self, X): self.representation_matrix_ = least_squares_subspace_clustering(X, self.gamma, self.exclude_self) if 'google.colab' in sys.modules: uploaded = files.upload() #subtract the mean from every class def preprocess_substract_mean(X, y): labels = np.unique(y) X_processed= X.copy() for l in labels: mean = np.average(X_processed[y == l], 0) X_processed[y == l] = X_processed[y == l]- mean return X_processed def q_a(X,y): #Run PCA on the dataset and plot the projection on the first 2 principal components, with each class marked in a different color/symbol X_train_processed = preprocess_substract_mean(X, y) pca = PCA(2) # project from 64 to 2 dimensions projected = pca.fit_transform(X_train_processed) #print(X_train_processed) #print(projected.shape) plt.scatter(projected[:, 0], projected[:, 1], c=y_train, edgecolor='none', alpha=0.5, cmap=plt.cm.get_cmap('tab10', 10)) plt.xlabel('component 1') plt.ylabel('component 2') # plt.colorbar(); plt.show() q_a(X_train,y_train) def angle_calucalte(p1, p2): p1_u = p1 / np.linalg.norm(p1) p2_u = p2 / np.linalg.norm(p2) return (np.arccos(np.clip(np.dot(p1_u, p2_u), -1.0, 1.0))) def q_b(X,y): # Sample at least 5000 pairs of points from the same class and 5000 pairs of points from different classes, labels = np.unique(y) n=5000 cos_theta_in_all = np.empty( shape=(0, 0) ) cos_theta_out_all = np.empty( shape=(0, 0) ) num_labels = len(labels) rand_indx1 = random.choices(range(len(X)), k=int(n)) rand_indx2 = list(pd.Series(rand_indx1).apply(lambda x: random.choices(Y.index[Y ==Y[x]]))) rand_indx2 = [j[0] for j in rand_indx2] rand_indx3 = list(pd.Series(rand_indx1).apply(lambda x: random.choices(Y.index[Y !=Y[x]]))) rand_indx3 = [j[0] for j in rand_indx3] points_in_1 = X_train.iloc[rand_indx1,:] points_in_2 = X_train.iloc[rand_indx2,:] points_out_1 = X_train.iloc[rand_indx3,:] #compute the angle between every pair of points theta_in_all = [angle_calucalte(points_in_1.iloc[i,:],points_in_2.iloc[i,:]) for i in range(len(points_in_1))] theta_out_all = [angle_calucalte(points_in_1.iloc[i,:],points_out_1.iloc[i,:]) for i in range(len(points_in_1))] # Plot the distribution of between-cluster angles and within cluster angles. sns.distplot(theta_in_all,hist=True) sns.distplot(theta_out_all,hist=True) plt.legend(labels=['theta in', 'theta out']) plt.show() q_b(X_train,y_train) l=5 pca = PCA() pca.fit_transform(X_train) #print(pca.explained_variance_ratio_.round(3)) np.cumsum(pca.explained_variance_ratio_).round(3) def q_c(X,y): # Perform PCA for each class separately, and plot for each class the proportion of variance explained vs the number of components ordered from the first PC until the last. # What number of components would you take for further analysis? labels = np.unique(y) #fig1, ax1 = plt.subplots() fig2, ax2 = plt.subplots() for l in labels: pca = PCA() pca.fit_transform(X[y==l]) exp_var_ratio = pca.explained_variance_ratio_ #ax1.plot(exp_var_ratio,label=f'class {l}') ax2.plot(np.cumsum(pca.explained_variance_ratio_),label=f'class {l}') #ax1.set_title("Explained Variance per class") ax2.set_title("Cumulated Explained Variance per class") #ax1.legend() ax2.legend() #fig1.show() fig2.show() # Repeat but now with PCA for the entire dataset #fig3, ax3 = plt.subplots() fig4, ax4 = plt.subplots() pca = PCA() projected = pca.fit_transform(X) exp_var_ratio = pca.explained_variance_ratio_ #x3.plot(exp_var_ratio) ax4.plot(np.cumsum(exp_var_ratio)) #ax3.set_title("Explained Variance Global") ax4.set_title("Cumulated Explained Variance Global") #fig3.show() fig4.show() q_c(X_train,Y_train) #What number of components would you take for further analysis? pca = PCA(0.9) pca.fit_transform(X_train) print(f"The number of components necessary to explain 90% of the data is : {pca.n_components_}") def performance_measure2(k,cluster1,cluster2): data = {'cluster1': cluster1,'cluster2': cluster2} clusters = pd.DataFrame(data, index=range(len(cluster1))) all_per = list(it.permutations(range(k))) accuracy_rate_all_per = np.zeros(len(all_per)) for l, per in enumerate(all_per) : c = [i for i in range(k)] dic = dict(zip(c,per)) clusters['premut_cluster'] = clusters['cluster2'].transform(lambda x: dic[x] if x in dic else None) m = clusters.groupby(['cluster1','premut_cluster']).size().unstack(fill_value=0) accuracy_rate_all_per[l]=np.trace(m) cost_cluster = (accuracy_rate_all_per.max())/len(cluster1) return (cost_cluster) def performance_measure3(cluster1,cluster2): data = {'cluster1': cluster1,'cluster2': cluster2} clusters = pd.DataFrame(data, index=range(len(cluster1))) m = -1*np.array(clusters.groupby(['cluster1','cluster2']).size().unstack(fill_value=0)) indx, per = linear_sum_assignment(m) cost_cluster = -m[indx,per].sum()/len(clusters) return (cost_cluster) num_components = 85 pca =PCA(num_components) pca_X =pca.fit_transform(X_train) kmeans_after_PCA = KMeans(n_clusters=10).fit(pca_X) kmeans_after_PCA.labels_ a,b def q_d(X,y): #Run the following algorithms on your dataset: #For each algorithm, compute and report the clustering accuracy from eq. (6). Explain your results. labels = np.unique(y) K=10 #i. K-means with K = 10 kmeans = KMeans(n_clusters=K).fit(X) kmeans_acc = performance_measure2(K,Y_train,kmeans.labels_) #ii. PCA with the number of components chosen based on (c.), followed by K-means with K = 10 on the projection to the top components. num_components = PCA(0.9).n_components_ pca =PCA(num_components) pca_X =pca.fit_transform(X) kmeans_after_PCA = KMeans(n_clusters=K).fit(pca_X) kmeans_after_PCA.labels_ kmeans_pca_acc = performance_measure2(K,Y_train,kmeans_after_PCA.labels_) #iii. A subspace clustering algorithm of your choice (ENsc), where you can set the number of clusters to the correct one, 10. model_ensc = ElasticNetSubspaceClustering(n_clusters=K, algorithm='spams', gamma=500) ensc_acc = performance_measure2(K,Y_train,model_ensc.fit(X).lables_) print(f'kmeans acc is: {kmeans_acc} , pca followed by kmeans acc is : {kmeans_pca_acc}, ensc acc is {ensc_acc}') q_d(X_train,y_train) def main(): #X_train, y_train = load_mnist('data/fashion', kind='train') #X_test, y_test = load_mnist('data/fashion', kind='t10k') train_data = pd.read_csv('fashion-mnist_train.csv') X_train = train_data.drop('label', axis=1) y_train = train_data['label'] #X_train =X_train.astype(np.uint) #y_train =y_train.astype(np.uint) #X_test = X_test.astype(np.uint) #y_test = y_test.astype(np.uint) q_a(X_train, y_train) q_b(X_train, y_train) q_c(X_train, y_train) q_d(X_train, y_train) if __name__ == '__main__': main()
[ "numpy.trace", "pandas.read_csv", "matplotlib.pyplot.ylabel", "sklearn.neighbors.kneighbors_graph", "random.choices", "numpy.linalg.norm", "sklearn.decomposition.sparse_encode", "numpy.arange", "sklearn.cluster.k_means", "seaborn.distplot", "sklearn.decomposition.PCA", "matplotlib.pyplot.xlabel", "numpy.flatnonzero", "numpy.dot", "numpy.empty", "numpy.matmul", "numpy.concatenate", "numpy.linalg.lstsq", "scipy.sparse.csr_matrix", "numpy.identity", "numpy.abs", "numpy.eye", "sklearn.utils.check_random_state", "numpy.average", "numpy.argmax", "numpy.fill_diagonal", "numpy.asfortranarray", "numpy.nonzero", "matplotlib.pyplot.cm.get_cmap", "scipy.sparse.identity", "time.time", "matplotlib.pyplot.legend", "matplotlib.pyplot.show", "sklearn.cluster.KMeans", "sklearn.utils.check_symmetric", "pandas.Series", "numpy.unique", "numpy.argpartition", "scipy.sparse.csgraph.laplacian", "numpy.power", "numpy.absolute", "google.colab.files.upload", "numpy.sum", "numpy.zeros", "sklearn.utils.check_array", "numpy.cumsum", "sklearn.preprocessing.normalize", "numpy.amax", "matplotlib.pyplot.subplots" ]
[((15196, 15201), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (15199, 15201), False, 'from sklearn.decomposition import PCA\n'), ((16649, 16657), 'sklearn.decomposition.PCA', 'PCA', (['(0.9)'], {}), '(0.9)\n', (16652, 16657), False, 'from sklearn.decomposition import PCA\n'), ((17838, 17857), 'sklearn.decomposition.PCA', 'PCA', (['num_components'], {}), '(num_components)\n', (17841, 17857), False, 'from sklearn.decomposition import PCA\n'), ((5622, 5641), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (5630, 5641), True, 'import numpy as np\n'), ((6214, 6245), 'numpy.zeros', 'np.zeros', (['(n_samples * n_nonzero)'], {}), '(n_samples * n_nonzero)\n', (6222, 6245), True, 'import numpy as np\n'), ((6257, 6288), 'numpy.zeros', 'np.zeros', (['(n_samples * n_nonzero)'], {}), '(n_samples * n_nonzero)\n', (6265, 6288), True, 'import numpy as np\n'), ((6300, 6331), 'numpy.zeros', 'np.zeros', (['(n_samples * n_nonzero)'], {}), '(n_samples * n_nonzero)\n', (6308, 6331), True, 'import numpy as np\n'), ((8066, 8135), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['(vals, (rows, cols))'], {'shape': '(n_samples, n_samples)'}), '((vals, (rows, cols)), shape=(n_samples, n_samples))\n', (8083, 8135), False, 'from scipy import sparse\n'), ((9356, 9398), 'numpy.zeros', 'np.zeros', (['(n_samples * n_nonzero)'], {'dtype': 'int'}), '(n_samples * n_nonzero, dtype=int)\n', (9364, 9398), True, 'import numpy as np\n'), ((9412, 9454), 'numpy.zeros', 'np.zeros', (['(n_samples * n_nonzero)'], {'dtype': 'int'}), '(n_samples * n_nonzero, dtype=int)\n', (9420, 9454), True, 'import numpy as np\n'), ((9468, 9499), 'numpy.zeros', 'np.zeros', (['(n_samples * n_nonzero)'], {}), '(n_samples * n_nonzero)\n', (9476, 9499), True, 'import numpy as np\n'), ((10749, 10818), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['(vals, (rows, cols))'], {'shape': '(n_samples, n_samples)'}), '((vals, (rows, cols)), shape=(n_samples, n_samples))\n', (10766, 10818), False, 'from scipy import sparse\n'), ((12777, 12791), 'google.colab.files.upload', 'files.upload', ([], {}), '()\n', (12789, 12791), False, 'from google.colab import files\n'), ((12879, 12891), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (12888, 12891), True, 'import numpy as np\n'), ((13286, 13292), 'sklearn.decomposition.PCA', 'PCA', (['(2)'], {}), '(2)\n', (13289, 13292), False, 'from sklearn.decomposition import PCA\n'), ((13600, 13625), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""component 1"""'], {}), "('component 1')\n", (13610, 13625), True, 'import matplotlib.pyplot as plt\n'), ((13630, 13655), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""component 2"""'], {}), "('component 2')\n", (13640, 13655), True, 'import matplotlib.pyplot as plt\n'), ((13682, 13692), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13690, 13692), True, 'import matplotlib.pyplot as plt\n'), ((14023, 14035), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (14032, 14035), True, 'import numpy as np\n'), ((14070, 14092), 'numpy.empty', 'np.empty', ([], {'shape': '(0, 0)'}), '(shape=(0, 0))\n', (14078, 14092), True, 'import numpy as np\n'), ((14119, 14141), 'numpy.empty', 'np.empty', ([], {'shape': '(0, 0)'}), '(shape=(0, 0))\n', (14127, 14141), True, 'import numpy as np\n'), ((15016, 15053), 'seaborn.distplot', 'sns.distplot', (['theta_in_all'], {'hist': '(True)'}), '(theta_in_all, hist=True)\n', (15028, 15053), True, 'import seaborn as sns\n'), ((15057, 15095), 'seaborn.distplot', 'sns.distplot', (['theta_out_all'], {'hist': '(True)'}), '(theta_out_all, hist=True)\n', (15069, 15095), True, 'import seaborn as sns\n'), ((15099, 15143), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'labels': "['theta in', 'theta out']"}), "(labels=['theta in', 'theta out'])\n", (15109, 15143), True, 'import matplotlib.pyplot as plt\n'), ((15148, 15158), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15156, 15158), True, 'import matplotlib.pyplot as plt\n'), ((15606, 15618), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (15615, 15618), True, 'import numpy as np\n'), ((15667, 15681), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (15679, 15681), True, 'import matplotlib.pyplot as plt\n'), ((16224, 16238), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (16236, 16238), True, 'import matplotlib.pyplot as plt\n'), ((16249, 16254), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (16252, 16254), False, 'from sklearn.decomposition import PCA\n'), ((18164, 18176), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (18173, 18176), True, 'import numpy as np\n'), ((18522, 18541), 'sklearn.decomposition.PCA', 'PCA', (['num_components'], {}), '(num_components)\n', (18525, 18541), False, 'from sklearn.decomposition import PCA\n'), ((19330, 19368), 'pandas.read_csv', 'pd.read_csv', (['"""fashion-mnist_train.csv"""'], {}), "('fashion-mnist_train.csv')\n", (19341, 19368), True, 'import pandas as pd\n'), ((1406, 1475), 'sklearn.utils.check_array', 'check_array', (['X'], {'accept_sparse': "['csr', 'csc', 'coo']", 'dtype': 'np.float64'}), "(X, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64)\n", (1417, 1475), False, 'from sklearn.utils import check_random_state, check_array, check_symmetric\n'), ((1496, 1507), 'time.time', 'time.time', ([], {}), '()\n', (1505, 1507), False, 'import time\n'), ((1844, 1913), 'sklearn.utils.check_array', 'check_array', (['X'], {'accept_sparse': "['csr', 'csc', 'coo']", 'dtype': 'np.float64'}), "(X, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64)\n", (1855, 1913), False, 'from sklearn.utils import check_random_state, check_array, check_symmetric\n'), ((1934, 1945), 'time.time', 'time.time', ([], {}), '()\n', (1943, 1945), False, 'import time\n'), ((2175, 2219), 'sklearn.preprocessing.normalize', 'normalize', (['self.representation_matrix_', '"""l2"""'], {}), "(self.representation_matrix_, 'l2')\n", (2184, 2219), False, 'from sklearn.preprocessing import normalize\n'), ((2767, 2805), 'sklearn.utils.check_symmetric', 'check_symmetric', (['self.affinity_matrix_'], {}), '(self.affinity_matrix_)\n', (2782, 2805), False, 'from sklearn.utils import check_random_state, check_array, check_symmetric\n'), ((2829, 2866), 'sklearn.utils.check_random_state', 'check_random_state', (['self.random_state'], {}), '(self.random_state)\n', (2847, 2866), False, 'from sklearn.utils import check_random_state, check_array, check_symmetric\n'), ((2896, 2951), 'scipy.sparse.csgraph.laplacian', 'sparse.csgraph.laplacian', (['affinity_matrix_'], {'normed': '(True)'}), '(affinity_matrix_, normed=True)\n', (2920, 2951), False, 'from scipy import sparse\n'), ((3139, 3153), 'sklearn.preprocessing.normalize', 'normalize', (['vec'], {}), '(vec)\n', (3148, 3153), False, 'from sklearn.preprocessing import normalize\n'), ((3183, 3277), 'sklearn.cluster.k_means', 'cluster.k_means', (['embedding', 'self.n_clusters'], {'random_state': 'random_state', 'n_init': 'self.n_init'}), '(embedding, self.n_clusters, random_state=random_state,\n n_init=self.n_init)\n', (3198, 3277), False, 'from sklearn import cluster\n'), ((3605, 3636), 'numpy.arange', 'np.arange', (['n_samples'], {'dtype': 'int'}), '(n_samples, dtype=int)\n', (3614, 3636), True, 'import numpy as np\n'), ((5569, 5608), 'numpy.concatenate', 'np.concatenate', (['[activesupp, addedsupp]'], {}), '([activesupp, addedsupp])\n', (5583, 5608), True, 'import numpy as np\n'), ((7447, 7464), 'numpy.flatnonzero', 'np.flatnonzero', (['c'], {}), '(c)\n', (7461, 7464), True, 'import numpy as np\n'), ((9679, 9707), 'numpy.empty', 'np.empty', ([], {'shape': '(0)', 'dtype': 'int'}), '(shape=0, dtype=int)\n', (9687, 9707), True, 'import numpy as np\n'), ((12166, 12190), 'numpy.fill_diagonal', 'np.fill_diagonal', (['D', '(0.0)'], {}), '(D, 0.0)\n', (12182, 12190), True, 'import numpy as np\n'), ((12954, 12988), 'numpy.average', 'np.average', (['X_processed[y == l]', '(0)'], {}), '(X_processed[y == l], 0)\n', (12964, 12988), True, 'import numpy as np\n'), ((13765, 13783), 'numpy.linalg.norm', 'np.linalg.norm', (['p1'], {}), '(p1)\n', (13779, 13783), True, 'import numpy as np\n'), ((13800, 13818), 'numpy.linalg.norm', 'np.linalg.norm', (['p2'], {}), '(p2)\n', (13814, 13818), True, 'import numpy as np\n'), ((15278, 15318), 'numpy.cumsum', 'np.cumsum', (['pca.explained_variance_ratio_'], {}), '(pca.explained_variance_ratio_)\n', (15287, 15318), True, 'import numpy as np\n'), ((15717, 15722), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (15720, 15722), False, 'from sklearn.decomposition import PCA\n'), ((16385, 16409), 'numpy.cumsum', 'np.cumsum', (['exp_var_ratio'], {}), '(exp_var_ratio)\n', (16394, 16409), True, 'import numpy as np\n'), ((17350, 17361), 'numpy.trace', 'np.trace', (['m'], {}), '(m)\n', (17358, 17361), True, 'import numpy as np\n'), ((17911, 17932), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(10)'}), '(n_clusters=10)\n', (17917, 17932), False, 'from sklearn.cluster import KMeans\n'), ((18490, 18498), 'sklearn.decomposition.PCA', 'PCA', (['(0.9)'], {}), '(0.9)\n', (18493, 18498), False, 'from sklearn.decomposition import PCA\n'), ((1596, 1607), 'time.time', 'time.time', ([], {}), '()\n', (1605, 1607), False, 'import time\n'), ((1735, 1746), 'time.time', 'time.time', ([], {}), '()\n', (1744, 1746), False, 'import time\n'), ((2034, 2045), 'time.time', 'time.time', ([], {}), '()\n', (2043, 2045), False, 'import time\n'), ((4436, 4490), 'sklearn.decomposition.sparse_encode', 'sparse_encode', (['y', 'Xs'], {'algorithm': 'algorithm', 'alpha': 'alpha'}), '(y, Xs, algorithm=algorithm, alpha=alpha)\n', (4449, 4490), False, 'from sklearn.decomposition import sparse_encode\n'), ((4871, 4906), 'numpy.nonzero', 'np.nonzero', (['(coherence > tau + 1e-10)'], {}), '(coherence > tau + 1e-10)\n', (4881, 4906), True, 'import numpy as np\n'), ((9762, 9785), 'numpy.linalg.norm', 'np.linalg.norm', (['X[i, :]'], {}), '(X[i, :])\n', (9776, 9785), True, 'import numpy as np\n'), ((11525, 11542), 'numpy.matmul', 'np.matmul', (['X', 'X.T'], {}), '(X, X.T)\n', (11534, 11542), True, 'import numpy as np\n'), ((13566, 13594), 'matplotlib.pyplot.cm.get_cmap', 'plt.cm.get_cmap', (['"""tab10"""', '(10)'], {}), "('tab10', 10)\n", (13581, 13594), True, 'import matplotlib.pyplot as plt\n'), ((13849, 13867), 'numpy.dot', 'np.dot', (['p1_u', 'p2_u'], {}), '(p1_u, p2_u)\n', (13855, 13867), True, 'import numpy as np\n'), ((15882, 15922), 'numpy.cumsum', 'np.cumsum', (['pca.explained_variance_ratio_'], {}), '(pca.explained_variance_ratio_)\n', (15891, 15922), True, 'import numpy as np\n'), ((18228, 18248), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'K'}), '(n_clusters=K)\n', (18234, 18248), False, 'from sklearn.cluster import KMeans\n'), ((18597, 18617), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'K'}), '(n_clusters=K)\n', (18603, 18617), False, 'from sklearn.cluster import KMeans\n'), ((2485, 2584), 'sklearn.neighbors.kneighbors_graph', 'kneighbors_graph', (['normalized_representation_matrix_', '(3)'], {'mode': '"""connectivity"""', 'include_self': '(False)'}), "(normalized_representation_matrix_, 3, mode='connectivity',\n include_self=False)\n", (2501, 2584), False, 'from sklearn.neighbors import kneighbors_graph\n'), ((2989, 3024), 'scipy.sparse.identity', 'sparse.identity', (['laplacian.shape[0]'], {}), '(laplacian.shape[0])\n', (3004, 3024), False, 'from scipy import sparse\n'), ((3862, 3878), 'numpy.dot', 'np.dot', (['X', 'L2sol'], {}), '(X, L2sol)\n', (3868, 3878), True, 'import numpy as np\n'), ((4236, 4258), 'numpy.asfortranarray', 'np.asfortranarray', (['y.T'], {}), '(y.T)\n', (4253, 4258), True, 'import numpy as np\n'), ((4519, 4533), 'numpy.dot', 'np.dot', (['cs', 'Xs'], {}), '(cs, Xs)\n', (4525, 4533), True, 'import numpy as np\n'), ((4800, 4818), 'numpy.dot', 'np.dot', (['delta', 'X.T'], {}), '(delta, X.T)\n', (4806, 4818), True, 'import numpy as np\n'), ((5060, 5073), 'numpy.abs', 'np.abs', (['cs[0]'], {}), '(cs[0])\n', (5066, 5073), True, 'import numpy as np\n'), ((5401, 5471), 'numpy.argpartition', 'np.argpartition', (['(-coherence[addedsupp])', '(support_size - activesupp.size)'], {}), '(-coherence[addedsupp], support_size - activesupp.size)\n', (5416, 5471), True, 'import numpy as np\n'), ((9948, 9972), 'numpy.matmul', 'np.matmul', (['residual', 'X.T'], {}), '(residual, X.T)\n', (9957, 9972), True, 'import numpy as np\n'), ((10070, 10090), 'numpy.argmax', 'np.argmax', (['coherence'], {}), '(coherence)\n', (10079, 10090), True, 'import numpy as np\n'), ((10143, 10195), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['X[supp, :].T', 'X[i, :].T'], {'rcond': 'None'}), '(X[supp, :].T, X[i, :].T, rcond=None)\n', (10158, 10195), True, 'import numpy as np\n'), ((10264, 10290), 'numpy.matmul', 'np.matmul', (['c.T', 'X[supp, :]'], {}), '(c.T, X[supp, :])\n', (10273, 10290), True, 'import numpy as np\n'), ((10338, 10359), 'numpy.sum', 'np.sum', (['(residual ** 2)'], {}), '(residual ** 2)\n', (10344, 10359), True, 'import numpy as np\n'), ((11739, 11756), 'numpy.matmul', 'np.matmul', (['X', 'tmp'], {}), '(X, tmp)\n', (11748, 11756), True, 'import numpy as np\n'), ((11882, 11898), 'numpy.eye', 'np.eye', (['n_sample'], {}), '(n_sample)\n', (11888, 11898), True, 'import numpy as np\n'), ((12103, 12120), 'numpy.matmul', 'np.matmul', (['X', 'tmp'], {}), '(X, tmp)\n', (12112, 12120), True, 'import numpy as np\n'), ((14252, 14273), 'pandas.Series', 'pd.Series', (['rand_indx1'], {}), '(rand_indx1)\n', (14261, 14273), True, 'import pandas as pd\n'), ((14290, 14324), 'random.choices', 'random.choices', (['Y.index[Y == Y[x]]'], {}), '(Y.index[Y == Y[x]])\n', (14304, 14324), False, 'import random\n'), ((14392, 14413), 'pandas.Series', 'pd.Series', (['rand_indx1'], {}), '(rand_indx1)\n', (14401, 14413), True, 'import pandas as pd\n'), ((14430, 14464), 'random.choices', 'random.choices', (['Y.index[Y != Y[x]]'], {}), '(Y.index[Y != Y[x]])\n', (14444, 14464), False, 'import random\n'), ((2305, 2351), 'numpy.absolute', 'np.absolute', (['normalized_representation_matrix_'], {}), '(normalized_representation_matrix_)\n', (2316, 2351), True, 'import numpy as np\n'), ((2354, 2402), 'numpy.absolute', 'np.absolute', (['normalized_representation_matrix_.T'], {}), '(normalized_representation_matrix_.T)\n', (2365, 2402), True, 'import numpy as np\n'), ((3824, 3838), 'numpy.dot', 'np.dot', (['X.T', 'X'], {}), '(X.T, X)\n', (3830, 3838), True, 'import numpy as np\n'), ((4262, 4285), 'numpy.asfortranarray', 'np.asfortranarray', (['Xs.T'], {}), '(Xs.T)\n', (4279, 4285), True, 'import numpy as np\n'), ((4658, 4678), 'numpy.power', 'np.power', (['delta', '(2.0)'], {}), '(delta, 2.0)\n', (4666, 4678), True, 'import numpy as np\n'), ((6661, 6673), 'numpy.amax', 'np.amax', (['coh'], {}), '(coh)\n', (6668, 6673), True, 'import numpy as np\n'), ((11667, 11684), 'numpy.matmul', 'np.matmul', (['X.T', 'X'], {}), '(X.T, X)\n', (11676, 11684), True, 'import numpy as np\n'), ((11836, 11853), 'numpy.matmul', 'np.matmul', (['X', 'X.T'], {}), '(X, X.T)\n', (11845, 11853), True, 'import numpy as np\n'), ((12017, 12034), 'numpy.matmul', 'np.matmul', (['X.T', 'X'], {}), '(X.T, X)\n', (12026, 12034), True, 'import numpy as np\n'), ((3790, 3813), 'numpy.identity', 'np.identity', (['y.shape[1]'], {}), '(y.shape[1])\n', (3801, 3813), True, 'import numpy as np\n'), ((3921, 3931), 'numpy.abs', 'np.abs', (['c0'], {}), '(c0)\n', (3927, 3931), True, 'import numpy as np\n'), ((4573, 4586), 'numpy.abs', 'np.abs', (['cs[0]'], {}), '(cs[0])\n', (4579, 4586), True, 'import numpy as np\n'), ((4615, 4635), 'numpy.power', 'np.power', (['cs[0]', '(2.0)'], {}), '(cs[0], 2.0)\n', (4623, 4635), True, 'import numpy as np\n'), ((6616, 6630), 'numpy.dot', 'np.dot', (['X', 'y.T'], {}), '(X, y.T)\n', (6622, 6630), True, 'import numpy as np\n'), ((7049, 7071), 'numpy.asfortranarray', 'np.asfortranarray', (['y.T'], {}), '(y.T)\n', (7066, 7071), True, 'import numpy as np\n'), ((7283, 7336), 'sklearn.decomposition.sparse_encode', 'sparse_encode', (['y', 'X'], {'algorithm': 'algorithm', 'alpha': 'alpha'}), '(y, X, algorithm=algorithm, alpha=alpha)\n', (7296, 7336), False, 'from sklearn.decomposition import sparse_encode\n'), ((11687, 11705), 'numpy.eye', 'np.eye', (['n_features'], {}), '(n_features)\n', (11693, 11705), True, 'import numpy as np\n'), ((11856, 11872), 'numpy.eye', 'np.eye', (['n_sample'], {}), '(n_sample)\n', (11862, 11872), True, 'import numpy as np\n'), ((12037, 12055), 'numpy.eye', 'np.eye', (['n_features'], {}), '(n_features)\n', (12043, 12055), True, 'import numpy as np\n'), ((7075, 7097), 'numpy.asfortranarray', 'np.asfortranarray', (['X.T'], {}), '(X.T)\n', (7092, 7097), True, 'import numpy as np\n'), ((7642, 7663), 'numpy.absolute', 'np.absolute', (['c[index]'], {}), '(c[index])\n', (7653, 7663), True, 'import numpy as np\n'), ((11585, 11601), 'numpy.eye', 'np.eye', (['n_sample'], {}), '(n_sample)\n', (11591, 11601), True, 'import numpy as np\n'), ((4042, 4056), 'numpy.dot', 'np.dot', (['y', 'X.T'], {}), '(y, X.T)\n', (4048, 4056), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # class file uppergeodesic.py # started as a script to visualize what happens to hyperbolic plane # if different isometries act on it import geodesic as gd import numpy as np import numpy.linalg as lina import matplotlib.pyplot as plt # upper half space as the basic model class UpperGeodesic(gd.Geodesic): """UpperGeodesic line in upper half space takes endpoints on boundary as arguments stores x and y data as points in x and y string "inf" is point at infinity, i.e. y=inf """ xmin = 0 xmax = 0 ymin = 0 # just for consistency, shouldn't change ymax = 0 inf = "inf" def __init__(self, a, b, color="b", label=''): """initialize UpperGeodesic by endpoints a, b - x values of the endpoints or "inf" if infinity res is resolution """ super().__init__(a, b, color, label) # adjust the boundaries of hyperbolic space if self.start != UpperGeodesic.inf: if self.start < UpperGeodesic.xmin: UpperGeodesic.xmin = self.start if self.end > UpperGeodesic.xmax: UpperGeodesic.xmax = self.end UpperGeodesic.ymax = (UpperGeodesic.xmax - UpperGeodesic.xmin)/2 @classmethod def vertical(cls, real): return cls(cls.inf, real) @classmethod def from_midpoint_and_radius(cls, m, r): """ m is only the real part of the circle thing """ return cls(m-r, m+r) def sort_se(self): """sort start and end""" if self.end == self.inf: # just want to assume that the first value is inf if any self.end = self.start self.start = self.inf if self.start != self.inf and self.end < self.start: # swap a and self.end such that a < self.end c = self.start self.start = self.end self.end = c def get_data(self): if self.start == UpperGeodesic.inf: # vertical line xs = [self.end, self.end] ys = [self.ymin, self.ymax] else: # calculate semicircle t = np.linspace(0, np.pi, self.res) r = (self.end - self.start)/2 xs = r*(1 + np.cos(t)) + self.start ys = r*np.sin(t) return(xs, ys) ## the next two functions create new geodesics from existing ones def new_geod(self, a, b, c, d): """return new geodesic by received by moebius trafo apply the matrix | a b | | c d | on the geodesic self and return the resulting geodesic """ start = self.apply_moebius(a, b, c, d, self.start) end = self.apply_moebius(a, b, c, d, self.end) return(UpperGeodesic(start, end)) def new_from_matrix(self, M): return self.new_geod(M[0,0], M[0,1], M[1,0], M[1,1]) ## apply transformations to ONE geodesic def apply_matrix(self, M): self.start = self.apply_moebius(M[0,0], M[0,1], M[1, 0], M[1,1], self.start) self.end = self.apply_moebius(M[0,0], M[0,1], M[1, 0], M[1,1], self.end) self.sort_se() def translate_one_geod(self, dx): if self.start != UpperGeodesic.inf: self.start += dx if self.end != UpperGeodesic.inf: self.end += dx def translate_one_at_zero(self, dx): """inverts at unit sphere, translates and inverts again""" a = self.inversion_on_unit_circle(self.start) b = self.inversion_on_unit_circle(self.end) if a != UpperGeodesic.inf: a += dx if b != UpperGeodesic.inf: b += dx self.start = self.inversion_on_unit_circle(a) self.end = self.inversion_on_unit_circle(b) self.sort_se() def rotate_one_geod(self, phi): """rotates the geodesic on upper half space conjugate to a rotation around origin in the disc model """ if self.start == UpperGeodesic.inf: alpha = -np.pi/2 else: alpha = self.from_upper_to_disc(self.start) beta = self.from_upper_to_disc(self.end) alpha += phi beta += phi self.start = self.from_disc_to_upper(alpha) self.end = self.from_disc_to_upper(beta) self.sort_se() def hyperbolic_translate_one(self, dmult=1.001): """translates one geodesic along UpperGeodesic(-1,1)""" diag = (dmult + 1.0/dmult)/2.0 off = (1.0/dmult - dmult)/2.0 matrix = np.matrix([[diag, off], [off, diag]]) self.apply_matrix(matrix) # tesselate hyperbolic space @classmethod def tesselate(self, depth=10): """Tesselates according to SL(2,Z)""" g0 = UpperGeodesic(-1,1, "r") g1 = UpperGeodesic(-0.5,self.inf, "r") g2 = UpperGeodesic(0.5,self.inf, "r") first = [g0,g1,g2] for k in range(1, depth): for g in first: g.new_geod(1, k, 0, 1) g.new_geod(1, -k, 0, 1) kmax = len(UpperGeodesic.all_geods) for geod in UpperGeodesic.all_geods[:kmax]: temp = [geod.new_geod(0, -1, 1, 0)] for k in range(1, 2*depth): temp.append(geod.new_geod(1, 0, k, 1)) temp.append(geod.new_geod(1, 0, -k, 1)) for k in range(1, depth//2): for t in temp: t.new_geod(1, k, 0, 1) t.new_geod(1, -k, 0, 1) UpperGeodesic.xmin= -3 UpperGeodesic.xmax= 3 UpperGeodesic.ymax= 3 ## plot commands @classmethod def set_plot_limits(cls): highest = max(abs(i) for i in [cls.ymin, cls.ymax, cls.xmax, cls.xmin]) cls.ax.axis([-highest, highest, 0, highest]) @classmethod def plot_all(cls): if UpperGeodesic.ymax <= UpperGeodesic.ymin: UpperGeodesic.ymax = UpperGeodesic.ymin + 1 # else nothing to plot super().plot_all()
[ "numpy.sin", "numpy.matrix", "numpy.linspace", "numpy.cos" ]
[((4613, 4650), 'numpy.matrix', 'np.matrix', (['[[diag, off], [off, diag]]'], {}), '([[diag, off], [off, diag]])\n', (4622, 4650), True, 'import numpy as np\n'), ((2161, 2192), 'numpy.linspace', 'np.linspace', (['(0)', 'np.pi', 'self.res'], {}), '(0, np.pi, self.res)\n', (2172, 2192), True, 'import numpy as np\n'), ((2302, 2311), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (2308, 2311), True, 'import numpy as np\n'), ((2259, 2268), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (2265, 2268), True, 'import numpy as np\n')]
""" Created on Thu Sept 24 2020- @author: <NAME> GitHub username: esgomezm """ import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.keras.losses import binary_crossentropy import numpy as np from tensorflow.keras import losses # -------------------------------- # ## Unet with tf 2.0.0 # https://www.kaggle.com/advaitsave/tensorflow-2-nuclei-segmentation-unet # ## binary weighted loss example # https://www.kaggle.com/lyakaap/weighing-boundary-pixels-loss-script-by-keras2 # https://stackoverflow.com/questions/48555820/keras-binary-segmentation-add-weight-to-loss-function/48577360 # https://stackoverflow.com/questions/55213599/u-net-with-pixel-wise-weighted-cross-entropy-input-dimension-errors # https://lars76.github.io/neural-networks/object-detection/losses-for-segmentation/ # https://stackoverflow.com/questions/46858016/keras-custom-loss-function-to-pass-arguments-other-than-y-true-and-y-pred # -------------------------------- # weight: weighted tensor(same s☺hape as mask image) def weighted_bce(y_true, y_pred, weight): # avoiding overflow epsilon = 1e-7 y_pred = K.clip(y_pred, epsilon, 1. - epsilon) logit_y_pred = K.log(y_pred / (1. - y_pred)) # https://www.tensorflow.org/api_docs/python/tf/nn/weighted_cross_entropy_with_logits loss = (1. - y_true) * logit_y_pred + (1. + (weight - 1.) * y_true) * \ (K.log(1. + K.exp(-K.abs(logit_y_pred))) + K.maximum(-logit_y_pred, 0.)) return K.sum(loss) / K.sum(weight) def weighted_dice(y_true, y_pred, weight): smooth = 1. w, m1, m2 = weight * weight, y_true, y_pred intersection = (m1 * m2) score = (2. * K.sum(w * intersection) + smooth) / (K.sum(w * m1) + K.sum(w * m2) + smooth) loss = 1. - K.sum(score) return loss def weighted_bce_dice_loss(y_true, y_pred): y_true = K.cast(y_true, 'float32') y_pred = K.cast(y_pred, 'float32') # if we want to get same size of output, kernel size must be odd number averaged_mask = K.pool2d( y_true, pool_size=(11, 11), strides=(1, 1), padding='same', pool_mode='avg') border = K.cast(K.greater(averaged_mask, 0.005), 'float32') * K.cast(K.less(averaged_mask, 0.995), 'float32') weight = K.ones_like(averaged_mask) w0 = K.sum(weight) weight += border * 2 w1 = K.sum(weight) weight *= (w0 / w1) loss = weighted_bce(y_true, y_pred, weight) + weighted_dice(y_true, y_pred, weight) return loss def bce_loss(X): # y_true, y_pred, weight = X y_true, y_pred = X loss = binary_crossentropy(y_true, y_pred) loss = tf.expand_dims(loss, 3) # loss = multiply([loss, weight]) return loss def identity_loss(y_true, y_pred): # return K.mean(y_pred, axis=-1) return y_pred def jaccard_multiple_output(y_true, y_pred, from_logits = True): """Define Jaccard index for multiple labels. Args: y_true (tensor): ground truth masks. y_pred (tensor): predicted masks. Return: jac (tensor): Jaccard index value """ if from_logits: # run activation to evaluate the jaccard index y_pred_ = tf.sigmoid(y_pred) y_pred_ = y_pred_ > 0.5 y_pred_ = tf.cast(y_pred_, dtype=tf.int8) y_true_ = tf.cast(y_true, dtype=tf.int8) TP = tf.math.count_nonzero(y_pred_ * y_true_) FP = tf.math.count_nonzero(y_pred_ * (1 - y_true_)) FN = tf.math.count_nonzero((1 - y_pred_) * y_true_) jac = tf.cond(tf.greater((TP + FP + FN), 0), lambda: TP / (TP + FP + FN), lambda: tf.cast(0.000, dtype='float64')) return jac def jaccard_sparse(y_true, y_pred, skip_background=True): """Define Jaccard index (multi-class). Args: y_true (tensor): ground truth masks. y_pred (tensor): predicted masks. skip_background (bool, optional): skip background label. Return: jac (tensor): Jaccard index value """ # number of classes (last dimension of predictions) num_classes = tf.shape(y_pred)[-1] # one_hot representation of predicted segmentation y_pred_ = tf.cast(y_pred, dtype=tf.int32) y_pred_ = tf.one_hot(tf.math.argmax(y_pred_, axis=-1), num_classes, axis=-1) # one_hot representation of ground truth segmentation y_true_ = tf.cast(y_true[...,0], dtype=tf.int32) y_true_ = tf.one_hot(y_true_, num_classes, axis=-1) if skip_background: y_pred_ = y_pred_[...,1:] y_true_ = y_true_[...,1:] TP = tf.math.count_nonzero(y_pred_ * y_true_) FP = tf.math.count_nonzero(y_pred_ * (y_true_ - 1)) FN = tf.math.count_nonzero((y_pred_ - 1) * y_true_) jac = tf.cond(tf.greater((TP + FP + FN), 0), lambda: TP / (TP + FP + FN), lambda: tf.cast(0.000, dtype='float64')) return jac def jaccard_cce(y_true, y_pred, skip_background=True): """Define Jaccard index for multiple labels. Args: y_true (tensor): ground truth masks. y_pred (tensor): predicted masks. skip_background (bool, optional): skip 0-label from calculation Return: jac (tensor): Jaccard index value """ # We read the number of classes from the last dimension of the true labels num_classes = tf.shape(y_true)[-1] # one_hot representation of predicted segmentation after argmax y_pred_ = tf.cast(y_pred, dtype=tf.float32) y_pred_ = tf.one_hot(tf.math.argmax(y_pred_, axis=-1), num_classes, axis=-1) # y_true is already one-hot encoded y_true_ = tf.cast(y_true, dtype=tf.float32) # skip background pixels from the Jaccard index calculation if skip_background: y_true_ = y_true_[...,1:] y_pred_ = y_pred_[...,1:] TP = tf.math.count_nonzero(y_pred_ * y_true_) FP = tf.math.count_nonzero(y_pred_ * (y_true_ - 1)) FN = tf.math.count_nonzero((y_pred_ - 1) * y_true_) jac = tf.cond(tf.greater((TP + FP + FN), 0), lambda: TP / (TP + FP + FN), lambda: tf.cast(0.000, dtype='float64')) return jac ## Code taken from DeepSTORM at ZeroCostDL4Mic. Please cite when using it # Define a matlab like gaussian 2D filter def matlab_style_gauss2D(shape=(7,7),sigma=1): """ 2D gaussian filter - should give the same result as: MATLAB's fspecial('gaussian',[shape],[sigma]) """ m,n = [(ss-1.)/2. for ss in shape] y,x = np.ogrid[-m:m+1,-n:n+1] h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) ) h.astype(dtype=K.floatx()) h[ h < np.finfo(h.dtype).eps*h.max() ] = 0 sumh = h.sum() if sumh != 0: h /= sumh h = h*2.0 h = h.astype('float32') return h # Expand the filter dimensions ## We changed the kernel size from 7 to 10. # psf_heatmap = matlab_style_gauss2D(shape=(14, 14), sigma=2) # gfilter = tf.reshape(psf_heatmap, [14, 14, 1, 1]) # Combined MSE + L1 loss def L1L2loss(input_shape, gfilter, strides=(1, 1)): """ Args: input_shape: (512,512,1) Returns: """ def bump_mse(heatmap_true, spikes_pred): # generate the heatmap corresponding to the predicted spikes if len(strides) == 2: heatmap_pred = K.conv2d(spikes_pred, gfilter, strides=strides, padding='same') elif len(strides) == 3: heatmap_pred = K.conv3d(spikes_pred, gfilter, strides=strides, padding='same') # heatmaps MSE loss_heatmaps = losses.mean_squared_error(heatmap_true,heatmap_pred) # l1 on the predicted spikes loss_spikes = losses.mean_absolute_error(spikes_pred,tf.zeros(input_shape)) return loss_heatmaps + loss_spikes return bump_mse
[ "tensorflow.keras.backend.log", "tensorflow.shape", "tensorflow.keras.backend.floatx", "tensorflow.keras.backend.greater", "tensorflow.keras.backend.ones_like", "tensorflow.keras.losses.binary_crossentropy", "tensorflow.cast", "tensorflow.keras.backend.conv2d", "tensorflow.keras.backend.conv3d", "tensorflow.keras.backend.maximum", "numpy.exp", "tensorflow.math.count_nonzero", "tensorflow.keras.backend.cast", "tensorflow.greater", "tensorflow.zeros", "tensorflow.one_hot", "tensorflow.math.argmax", "tensorflow.sigmoid", "tensorflow.keras.backend.less", "tensorflow.keras.losses.mean_squared_error", "tensorflow.expand_dims", "numpy.finfo", "tensorflow.keras.backend.sum", "tensorflow.keras.backend.pool2d", "tensorflow.keras.backend.clip", "tensorflow.keras.backend.abs" ]
[((1129, 1167), 'tensorflow.keras.backend.clip', 'K.clip', (['y_pred', 'epsilon', '(1.0 - epsilon)'], {}), '(y_pred, epsilon, 1.0 - epsilon)\n', (1135, 1167), True, 'from tensorflow.keras import backend as K\n'), ((1186, 1216), 'tensorflow.keras.backend.log', 'K.log', (['(y_pred / (1.0 - y_pred))'], {}), '(y_pred / (1.0 - y_pred))\n', (1191, 1216), True, 'from tensorflow.keras import backend as K\n'), ((1843, 1868), 'tensorflow.keras.backend.cast', 'K.cast', (['y_true', '"""float32"""'], {}), "(y_true, 'float32')\n", (1849, 1868), True, 'from tensorflow.keras import backend as K\n'), ((1882, 1907), 'tensorflow.keras.backend.cast', 'K.cast', (['y_pred', '"""float32"""'], {}), "(y_pred, 'float32')\n", (1888, 1907), True, 'from tensorflow.keras import backend as K\n'), ((2004, 2093), 'tensorflow.keras.backend.pool2d', 'K.pool2d', (['y_true'], {'pool_size': '(11, 11)', 'strides': '(1, 1)', 'padding': '"""same"""', 'pool_mode': '"""avg"""'}), "(y_true, pool_size=(11, 11), strides=(1, 1), padding='same',\n pool_mode='avg')\n", (2012, 2093), True, 'from tensorflow.keras import backend as K\n'), ((2226, 2252), 'tensorflow.keras.backend.ones_like', 'K.ones_like', (['averaged_mask'], {}), '(averaged_mask)\n', (2237, 2252), True, 'from tensorflow.keras import backend as K\n'), ((2262, 2275), 'tensorflow.keras.backend.sum', 'K.sum', (['weight'], {}), '(weight)\n', (2267, 2275), True, 'from tensorflow.keras import backend as K\n'), ((2310, 2323), 'tensorflow.keras.backend.sum', 'K.sum', (['weight'], {}), '(weight)\n', (2315, 2323), True, 'from tensorflow.keras import backend as K\n'), ((2538, 2573), 'tensorflow.keras.losses.binary_crossentropy', 'binary_crossentropy', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (2557, 2573), False, 'from tensorflow.keras.losses import binary_crossentropy\n'), ((2585, 2608), 'tensorflow.expand_dims', 'tf.expand_dims', (['loss', '(3)'], {}), '(loss, 3)\n', (2599, 2608), True, 'import tensorflow as tf\n'), ((3206, 3237), 'tensorflow.cast', 'tf.cast', (['y_pred_'], {'dtype': 'tf.int8'}), '(y_pred_, dtype=tf.int8)\n', (3213, 3237), True, 'import tensorflow as tf\n'), ((3252, 3282), 'tensorflow.cast', 'tf.cast', (['y_true'], {'dtype': 'tf.int8'}), '(y_true, dtype=tf.int8)\n', (3259, 3282), True, 'import tensorflow as tf\n'), ((3293, 3333), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['(y_pred_ * y_true_)'], {}), '(y_pred_ * y_true_)\n', (3314, 3333), True, 'import tensorflow as tf\n'), ((3343, 3389), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['(y_pred_ * (1 - y_true_))'], {}), '(y_pred_ * (1 - y_true_))\n', (3364, 3389), True, 'import tensorflow as tf\n'), ((3399, 3445), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['((1 - y_pred_) * y_true_)'], {}), '((1 - y_pred_) * y_true_)\n', (3420, 3445), True, 'import tensorflow as tf\n'), ((4117, 4148), 'tensorflow.cast', 'tf.cast', (['y_pred'], {'dtype': 'tf.int32'}), '(y_pred, dtype=tf.int32)\n', (4124, 4148), True, 'import tensorflow as tf\n'), ((4312, 4351), 'tensorflow.cast', 'tf.cast', (['y_true[..., 0]'], {'dtype': 'tf.int32'}), '(y_true[..., 0], dtype=tf.int32)\n', (4319, 4351), True, 'import tensorflow as tf\n'), ((4365, 4406), 'tensorflow.one_hot', 'tf.one_hot', (['y_true_', 'num_classes'], {'axis': '(-1)'}), '(y_true_, num_classes, axis=-1)\n', (4375, 4406), True, 'import tensorflow as tf\n'), ((4514, 4554), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['(y_pred_ * y_true_)'], {}), '(y_pred_ * y_true_)\n', (4535, 4554), True, 'import tensorflow as tf\n'), ((4564, 4610), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['(y_pred_ * (y_true_ - 1))'], {}), '(y_pred_ * (y_true_ - 1))\n', (4585, 4610), True, 'import tensorflow as tf\n'), ((4620, 4666), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['((y_pred_ - 1) * y_true_)'], {}), '((y_pred_ - 1) * y_true_)\n', (4641, 4666), True, 'import tensorflow as tf\n'), ((5380, 5413), 'tensorflow.cast', 'tf.cast', (['y_pred'], {'dtype': 'tf.float32'}), '(y_pred, dtype=tf.float32)\n', (5387, 5413), True, 'import tensorflow as tf\n'), ((5554, 5587), 'tensorflow.cast', 'tf.cast', (['y_true'], {'dtype': 'tf.float32'}), '(y_true, dtype=tf.float32)\n', (5561, 5587), True, 'import tensorflow as tf\n'), ((5750, 5790), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['(y_pred_ * y_true_)'], {}), '(y_pred_ * y_true_)\n', (5771, 5790), True, 'import tensorflow as tf\n'), ((5800, 5846), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['(y_pred_ * (y_true_ - 1))'], {}), '(y_pred_ * (y_true_ - 1))\n', (5821, 5846), True, 'import tensorflow as tf\n'), ((5856, 5902), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['((y_pred_ - 1) * y_true_)'], {}), '((y_pred_ - 1) * y_true_)\n', (5877, 5902), True, 'import tensorflow as tf\n'), ((6426, 6474), 'numpy.exp', 'np.exp', (['(-(x * x + y * y) / (2.0 * sigma * sigma))'], {}), '(-(x * x + y * y) / (2.0 * sigma * sigma))\n', (6432, 6474), True, 'import numpy as np\n'), ((1478, 1489), 'tensorflow.keras.backend.sum', 'K.sum', (['loss'], {}), '(loss)\n', (1483, 1489), True, 'from tensorflow.keras import backend as K\n'), ((1492, 1505), 'tensorflow.keras.backend.sum', 'K.sum', (['weight'], {}), '(weight)\n', (1497, 1505), True, 'from tensorflow.keras import backend as K\n'), ((1755, 1767), 'tensorflow.keras.backend.sum', 'K.sum', (['score'], {}), '(score)\n', (1760, 1767), True, 'from tensorflow.keras import backend as K\n'), ((3145, 3163), 'tensorflow.sigmoid', 'tf.sigmoid', (['y_pred'], {}), '(y_pred)\n', (3155, 3163), True, 'import tensorflow as tf\n'), ((3465, 3492), 'tensorflow.greater', 'tf.greater', (['(TP + FP + FN)', '(0)'], {}), '(TP + FP + FN, 0)\n', (3475, 3492), True, 'import tensorflow as tf\n'), ((4022, 4038), 'tensorflow.shape', 'tf.shape', (['y_pred'], {}), '(y_pred)\n', (4030, 4038), True, 'import tensorflow as tf\n'), ((4174, 4206), 'tensorflow.math.argmax', 'tf.math.argmax', (['y_pred_'], {'axis': '(-1)'}), '(y_pred_, axis=-1)\n', (4188, 4206), True, 'import tensorflow as tf\n'), ((4686, 4713), 'tensorflow.greater', 'tf.greater', (['(TP + FP + FN)', '(0)'], {}), '(TP + FP + FN, 0)\n', (4696, 4713), True, 'import tensorflow as tf\n'), ((5277, 5293), 'tensorflow.shape', 'tf.shape', (['y_true'], {}), '(y_true)\n', (5285, 5293), True, 'import tensorflow as tf\n'), ((5439, 5471), 'tensorflow.math.argmax', 'tf.math.argmax', (['y_pred_'], {'axis': '(-1)'}), '(y_pred_, axis=-1)\n', (5453, 5471), True, 'import tensorflow as tf\n'), ((5922, 5949), 'tensorflow.greater', 'tf.greater', (['(TP + FP + FN)', '(0)'], {}), '(TP + FP + FN, 0)\n', (5932, 5949), True, 'import tensorflow as tf\n'), ((7406, 7459), 'tensorflow.keras.losses.mean_squared_error', 'losses.mean_squared_error', (['heatmap_true', 'heatmap_pred'], {}), '(heatmap_true, heatmap_pred)\n', (7431, 7459), False, 'from tensorflow.keras import losses\n'), ((2119, 2150), 'tensorflow.keras.backend.greater', 'K.greater', (['averaged_mask', '(0.005)'], {}), '(averaged_mask, 0.005)\n', (2128, 2150), True, 'from tensorflow.keras import backend as K\n'), ((2172, 2200), 'tensorflow.keras.backend.less', 'K.less', (['averaged_mask', '(0.995)'], {}), '(averaged_mask, 0.995)\n', (2178, 2200), True, 'from tensorflow.keras import backend as K\n'), ((3551, 3580), 'tensorflow.cast', 'tf.cast', (['(0.0)'], {'dtype': '"""float64"""'}), "(0.0, dtype='float64')\n", (3558, 3580), True, 'import tensorflow as tf\n'), ((4772, 4801), 'tensorflow.cast', 'tf.cast', (['(0.0)'], {'dtype': '"""float64"""'}), "(0.0, dtype='float64')\n", (4779, 4801), True, 'import tensorflow as tf\n'), ((6008, 6037), 'tensorflow.cast', 'tf.cast', (['(0.0)'], {'dtype': '"""float64"""'}), "(0.0, dtype='float64')\n", (6015, 6037), True, 'import tensorflow as tf\n'), ((6487, 6497), 'tensorflow.keras.backend.floatx', 'K.floatx', ([], {}), '()\n', (6495, 6497), True, 'from tensorflow.keras import backend as K\n'), ((7170, 7233), 'tensorflow.keras.backend.conv2d', 'K.conv2d', (['spikes_pred', 'gfilter'], {'strides': 'strides', 'padding': '"""same"""'}), "(spikes_pred, gfilter, strides=strides, padding='same')\n", (7178, 7233), True, 'from tensorflow.keras import backend as K\n'), ((7558, 7579), 'tensorflow.zeros', 'tf.zeros', (['input_shape'], {}), '(input_shape)\n', (7566, 7579), True, 'import tensorflow as tf\n'), ((1437, 1466), 'tensorflow.keras.backend.maximum', 'K.maximum', (['(-logit_y_pred)', '(0.0)'], {}), '(-logit_y_pred, 0.0)\n', (1446, 1466), True, 'from tensorflow.keras import backend as K\n'), ((1662, 1685), 'tensorflow.keras.backend.sum', 'K.sum', (['(w * intersection)'], {}), '(w * intersection)\n', (1667, 1685), True, 'from tensorflow.keras import backend as K\n'), ((1699, 1712), 'tensorflow.keras.backend.sum', 'K.sum', (['(w * m1)'], {}), '(w * m1)\n', (1704, 1712), True, 'from tensorflow.keras import backend as K\n'), ((1715, 1728), 'tensorflow.keras.backend.sum', 'K.sum', (['(w * m2)'], {}), '(w * m2)\n', (1720, 1728), True, 'from tensorflow.keras import backend as K\n'), ((7294, 7357), 'tensorflow.keras.backend.conv3d', 'K.conv3d', (['spikes_pred', 'gfilter'], {'strides': 'strides', 'padding': '"""same"""'}), "(spikes_pred, gfilter, strides=strides, padding='same')\n", (7302, 7357), True, 'from tensorflow.keras import backend as K\n'), ((6510, 6527), 'numpy.finfo', 'np.finfo', (['h.dtype'], {}), '(h.dtype)\n', (6518, 6527), True, 'import numpy as np\n'), ((1413, 1432), 'tensorflow.keras.backend.abs', 'K.abs', (['logit_y_pred'], {}), '(logit_y_pred)\n', (1418, 1432), True, 'from tensorflow.keras import backend as K\n')]
import json import bz2 import gzip import _pickle as cPickle import gym import numpy as np import quaternion import skimage.morphology import habitat from envs.utils.fmm_planner import FMMPlanner from constants import coco_categories import envs.utils.pose as pu class ObjectGoal_Env(habitat.RLEnv): """The Object Goal Navigation environment class. The class is responsible for loading the dataset, generating episodes, and computing evaluation metrics. """ def __init__(self, args, rank, config_env, dataset): self.args = args self.rank = rank super().__init__(config_env, dataset) # Loading dataset info file self.split = config_env.DATASET.SPLIT self.episodes_dir = config_env.DATASET.EPISODES_DIR.format( split=self.split) if args.custom_eps: with open("{}/train_episode_data.json".format(args.custom_eps), 'r') as f: episodes_all = json.load(f) self.episodes_all = {} for ep in episodes_all: if ep["scene"] in self.episodes_all: self.episodes_all[ep["scene"]].append(ep) else: self.episodes_all[ep["scene"]] = [ep] dataset_info_file = self.episodes_dir + \ "{split}_info.pbz2".format(split=self.split) with bz2.BZ2File(dataset_info_file, 'rb') as f: self.dataset_info = cPickle.load(f) # Specifying action and observation space self.action_space = gym.spaces.Discrete(3) self.observation_space = gym.spaces.Box(0, 255, (3, args.frame_height, args.frame_width), dtype='uint8') # Initializations self.episode_no = 0 # Scene info self.last_scene_path = None self.scene_path = None self.scene_name = None # Episode Dataset info self.eps_data = None self.eps_data_idx = None self.gen_ep_idx = 1 self.gt_planner = None self.object_boundary = None self.goal_idx = None self.goal_name = None self.map_obj_origin = None self.starting_loc = None self.starting_distance = None if args.eval and args.shuffle: self.shuffled_indices = np.arange(args.num_eval_episodes) np.random.shuffle(self.shuffled_indices) # Episode tracking info self.curr_distance = None self.prev_distance = None self.timestep = None self.stopped = None self.path_length = None self.last_sim_location = None self.trajectory_states = [] self.info = {} self.info['distance_to_goal'] = None self.info['spl'] = None self.info['success'] = None def load_new_episode(self): """The function loads a fixed episode from the episode dataset. This function is used for evaluating a trained model on the val split. """ args = self.args self.scene_path = self.habitat_env.sim.config.SCENE scene_name = self.scene_path.split("/")[-1].split(".")[0] if self.scene_path != self.last_scene_path: if not args.testset: episodes_file = self.episodes_dir + \ "content/{}_episodes.json.gz".format(scene_name) print("Loading episodes from: {}".format(episodes_file)) with gzip.open(episodes_file, 'r') as f: self.eps_data = json.loads( f.read().decode('utf-8'))["episodes"] else: episodes_file = self.episodes_dir + \ "content/{}_test_episodes.json".format(scene_name) print("Loading episodes from: {}".format(episodes_file)) with open(episodes_file, 'r') as f: self.eps_data = json.load(f) self.eps_data_idx = 0 self.last_scene_path = self.scene_path # Load episode info if self.args.shuffle: episode = self.eps_data[self.shuffled_indices[self.eps_data_idx]] else: episode = self.eps_data[self.eps_data_idx] self.info["episode_data"] = episode self.eps_data_idx += 1 self.eps_data_idx = self.eps_data_idx % len(self.eps_data) pos = episode["start_position"] rot = quaternion.from_float_array(episode["start_rotation"]) goal_name = episode["object_category"] goal_idx = episode["object_id"] floor_idx = episode["floor_id"] # Load scene info scene_info = self.dataset_info[scene_name] sem_map = scene_info[floor_idx]['sem_map'] map_obj_origin = scene_info[floor_idx]['origin'] # Setup ground truth planner object_boundary = args.success_dist map_resolution = args.map_resolution selem = skimage.morphology.disk(2) traversible = skimage.morphology.binary_dilation( sem_map[0], selem) != True traversible = 1 - traversible planner = FMMPlanner(traversible) selem = skimage.morphology.disk( int(object_boundary * 100. / map_resolution)) goal_map = skimage.morphology.binary_dilation( sem_map[goal_idx + 1], selem) != True goal_map = 1 - goal_map planner.set_multi_goal(goal_map) # Get starting loc in GT map coordinates x = -pos[2] y = -pos[0] min_x, min_y = map_obj_origin / 100.0 map_loc = int((-y - min_y) * 20.), int((-x - min_x) * 20.) self.gt_planner = planner self.starting_loc = map_loc self.object_boundary = object_boundary self.goal_idx = goal_idx self.goal_name = goal_name self.map_obj_origin = map_obj_origin self.starting_distance = self.gt_planner.fmm_dist[self.starting_loc]\ / 20.0 + self.object_boundary self.info["episode_data"]["shortest_dist"] = self.starting_distance self.prev_distance = self.starting_distance self._env.sim.set_agent_state(pos, rot) self.info["sim_pos"] = pos self.info["sim_rot"] = rot self.info["scene"] = scene_name self.info["floor_idx"] = floor_idx # The following two should match approximately #print(self.starting_loc) #print(self.sim_continuous_to_sim_map(self.get_sim_location())) self.info['gt_pos'] = self.sim_continuous_to_sim_map(self.get_sim_location()) obs = self._env.sim.get_observations_at(pos, rot) return obs def load_incomplete_episode(self): args = self.args self.scene_path = self.habitat_env.sim.config.SCENE scene_name = self.scene_path.split("/")[-1].split(".")[0] if self.scene_path != self.last_scene_path: print("Loading episodes from: {}".format(scene_name)) self.eps_data_idx = 0 self.last_scene_path = self.scene_path episode = self.episodes_all[scene_name][self.eps_data_idx] self.info["episode_data"] = episode self.eps_data_idx += 1 self.eps_data_idx = self.eps_data_idx % len(self.episodes_all[scene_name]) pos = episode["sim_pos"] rot = quaternion.from_rotation_vector(episode["sim_rot"]) goal_name = episode["goal_name"] goal_idx = episode["goal_cat_id"] floor_idx = episode["floor_idx"] # Load scene info scene_info = self.dataset_info[scene_name] sem_map = scene_info[floor_idx]['sem_map'] map_obj_origin = scene_info[floor_idx]['origin'] # Setup ground truth planner object_boundary = args.success_dist map_resolution = args.map_resolution selem = skimage.morphology.disk(2) traversible = skimage.morphology.binary_dilation( sem_map[0], selem) != True traversible = 1 - traversible planner = FMMPlanner(traversible) selem = skimage.morphology.disk( int(object_boundary * 100. / map_resolution)) goal_map = skimage.morphology.binary_dilation( sem_map[goal_idx + 1], selem) != True goal_map = 1 - goal_map planner.set_multi_goal(goal_map) # Get starting loc in GT map coordinates x = -pos[2] y = -pos[0] min_x, min_y = map_obj_origin / 100.0 map_loc = int((-y - min_y) * 20.), int((-x - min_x) * 20.) self.gt_planner = planner self.starting_loc = map_loc self.object_boundary = object_boundary self.goal_idx = goal_idx self.goal_name = goal_name self.map_obj_origin = map_obj_origin self.starting_distance = self.gt_planner.fmm_dist[self.starting_loc]\ / 20.0 + self.object_boundary self.info["episode_data"]["shortest_dist"] = self.starting_distance self.prev_distance = self.starting_distance self._env.sim.set_agent_state(pos, rot) self.info["sim_pos"] = pos self.info["sim_rot"] = rot # The following two should match approximately #print(self.starting_loc) #print(self.sim_continuous_to_sim_map(self.get_sim_location())) self.info['gt_pos'] = self.sim_continuous_to_sim_map(self.get_sim_location()) obs = self._env.sim.get_observations_at(pos, rot) return obs def generate_new_episode(self): """The function generates a random valid episode. This function is used for training a model on the train split. """ args = self.args self.scene_path = self.habitat_env.sim.config.SCENE scene_name = self.scene_path.split("/")[-1].split(".")[0] scene_info = self.dataset_info[scene_name] map_resolution = args.map_resolution floor_idx = np.random.randint(len(scene_info.keys())) floor_height = scene_info[floor_idx]['floor_height'] sem_map = scene_info[floor_idx]['sem_map'] map_obj_origin = scene_info[floor_idx]['origin'] cat_counts = sem_map.sum(2).sum(1) possible_cats = list(np.arange(6)) for i in range(6): if cat_counts[i + 1] == 0: possible_cats.remove(i) object_boundary = args.success_dist loc_found = False while not loc_found: if len(possible_cats) == 0: print("No valid objects for {}".format(floor_height)) eps = eps - 1 continue goal_idx = np.random.choice(possible_cats) for key, value in coco_categories.items(): if value == goal_idx: goal_name = key selem = skimage.morphology.disk(2) traversible = skimage.morphology.binary_dilation( sem_map[0], selem) != True traversible = 1 - traversible planner = FMMPlanner(traversible) selem = skimage.morphology.disk( int(object_boundary * 100. / map_resolution)) goal_map = skimage.morphology.binary_dilation( sem_map[goal_idx + 1], selem) != True goal_map = 1 - goal_map planner.set_multi_goal(goal_map) m1 = sem_map[0] > 0 m2 = planner.fmm_dist > (args.min_d - object_boundary) * 20.0 m3 = planner.fmm_dist < (args.max_d - object_boundary) * 20.0 possible_starting_locs = np.logical_and(m1, m2) possible_starting_locs = np.logical_and( possible_starting_locs, m3) * 1. if possible_starting_locs.sum() != 0: loc_found = True else: print("Invalid object: {} / {} / {}".format( scene_name, floor_height, goal_name)) possible_cats.remove(goal_idx) scene_info[floor_idx]["sem_map"][goal_idx + 1, :, :] = 0. self.dataset_info[scene_name][floor_idx][ "sem_map"][goal_idx + 1, :, :] = 0. loc_found = False while not loc_found: pos = self._env.sim.sample_navigable_point() x = -pos[2] y = -pos[0] min_x, min_y = map_obj_origin / 100.0 map_loc = int((-y - min_y) * 20.), int((-x - min_x) * 20.) if abs(pos[1] - floor_height) < args.floor_thr / 100.0 and \ possible_starting_locs[map_loc[0], map_loc[1]] == 1: loc_found = True agent_state = self._env.sim.get_agent_state(0) rotation = agent_state.rotation rvec = quaternion.as_rotation_vector(rotation) rvec[1] = np.random.rand() * 2 * np.pi rot = quaternion.from_rotation_vector(rvec) self.gt_planner = planner self.starting_loc = map_loc self.object_boundary = object_boundary self.goal_idx = goal_idx self.goal_name = goal_name self.map_obj_origin = map_obj_origin self.starting_distance = self.gt_planner.fmm_dist[self.starting_loc] \ / 20.0 + self.object_boundary self.prev_distance = self.starting_distance self._env.sim.set_agent_state(pos, rot) self.info["sim_pos"] = pos self.info["sim_rot"] = quaternion.as_float_array(rot) self.info["episode_id"] = self.gen_ep_idx self.gen_ep_idx += 1 self.info["scene"] = scene_name self.info["floor_idx"] = floor_idx self.info["goal_name"] = goal_name # The following two should match approximately # print(starting_loc) # print(self.sim_continuous_to_sim_map(self.get_sim_location())) self.info['gt_pos'] = self.sim_continuous_to_sim_map(self.get_sim_location()) obs = self._env.sim.get_observations_at(pos, rot) return obs def sim_map_to_sim_continuous(self, coords): """Converts ground-truth 2D Map coordinates to absolute Habitat simulator position and rotation. """ agent_state = self._env.sim.get_agent_state(0) y, x = coords min_x, min_y = self.map_obj_origin / 100.0 cont_x = x / 20. + min_x cont_y = y / 20. + min_y agent_state.position[0] = cont_y agent_state.position[2] = cont_x rotation = agent_state.rotation rvec = quaternion.as_rotation_vector(rotation) if self.args.train_single_eps: rvec[1] = 0.0 else: rvec[1] = np.random.rand() * 2 * np.pi rot = quaternion.from_rotation_vector(rvec) return agent_state.position, rot def sim_continuous_to_sim_map(self, sim_loc): """Converts absolute Habitat simulator pose to ground-truth 2D Map coordinates. """ x, y, o = sim_loc min_x, min_y = self.map_obj_origin / 100.0 x, y = int((-x - min_x) * 20.), int((-y - min_y) * 20.) o = np.rad2deg(o) + 180.0 return y, x, o def reset(self): """Resets the environment to a new episode. Returns: obs (ndarray): RGBD observations (4 x H x W) info (dict): contains timestep, pose, goal category and evaluation metric info """ args = self.args new_scene = self.episode_no % args.num_train_episodes == 0 self.episode_no += 1 # Initializations self.timestep = 0 self.stopped = False self.path_length = 1e-5 self.trajectory_states = [] if new_scene: obs = super().reset() self.scene_name = self.habitat_env.sim.config.SCENE print("Changing scene: {}/{}".format(self.rank, self.scene_name)) self.scene_path = self.habitat_env.sim.config.SCENE if args.gen_episode: obs = self.generate_new_episode() elif args.custom_eps: obs = self.load_incomplete_episode() elif self.split == "val": obs = self.load_new_episode() else: obs = self.generate_new_episode() rgb = obs['rgb'].astype(np.uint8) depth = obs['depth'] state = np.concatenate((rgb, depth), axis=2).transpose(2, 0, 1) self.last_sim_location = self.get_sim_location() # Set info self.info['time'] = self.timestep self.info['sensor_pose'] = [0., 0., 0.] self.info['goal_cat_id'] = self.goal_idx self.info['goal_name'] = self.goal_name return state, self.info def step(self, action): """Function to take an action in the environment. Args: action (dict): dict with following keys: 'action' (int): 0: stop, 1: forward, 2: left, 3: right Returns: obs (ndarray): RGBD observations (4 x H x W) reward (float): amount of reward returned after previous action done (bool): whether the episode has ended info (dict): contains timestep, pose, goal category and evaluation metric info """ action = action["action"] if action == 0: self.stopped = True # Not sending stop to simulator, resetting manually action = 3 obs, rew, done, _ = super().step(action) # Get pose change dx, dy, do = self.get_pose_change() self.info['sensor_pose'] = [dx, dy, do] self.path_length += pu.get_l2_distance(0, dx, 0, dy) spl, success, dist = 0., 0., 0. if done: spl, success, dist = self.get_metrics() self.info['distance_to_goal'] = dist self.info['spl'] = spl self.info['success'] = success rgb = obs['rgb'].astype(np.uint8) depth = obs['depth'] state = np.concatenate((rgb, depth), axis=2).transpose(2, 0, 1) self.timestep += 1 self.info['time'] = self.timestep return state, rew, done, self.info def get_reward_range(self): """This function is not used, Habitat-RLEnv requires this function""" return (0., 1.0) def get_reward(self, observations): curr_loc = self.sim_continuous_to_sim_map(self.get_sim_location()) self.curr_distance = self.gt_planner.fmm_dist[curr_loc[0], curr_loc[1]] / 20.0 reward = (self.prev_distance - self.curr_distance) * \ self.args.reward_coeff self.prev_distance = self.curr_distance return reward def get_metrics(self): """This function computes evaluation metrics for the Object Goal task Returns: spl (float): Success weighted by Path Length (See https://arxiv.org/pdf/1807.06757.pdf) success (int): 0: Failure, 1: Successful dist (float): Distance to Success (DTS), distance of the agent from the success threshold boundary in meters. (See https://arxiv.org/pdf/2007.00643.pdf) """ curr_loc = self.sim_continuous_to_sim_map(self.get_sim_location()) dist = self.gt_planner.fmm_dist[curr_loc[0], curr_loc[1]] / 20.0 if dist == 0.0: success = 1 else: success = 0 spl = min(success * self.starting_distance / self.path_length, 1) return spl, success, dist def get_done(self, observations): if self.info['time'] >= self.args.max_episode_length - 1: done = True elif self.stopped: done = True else: done = False return done def get_info(self, observations): """This function is not used, Habitat-RLEnv requires this function""" info = {} return info def get_spaces(self): """Returns observation and action spaces for the ObjectGoal task.""" return self.observation_space, self.action_space def get_sim_location(self): """Returns x, y, o pose of the agent in the Habitat simulator.""" agent_state = super().habitat_env.sim.get_agent_state(0) x = -agent_state.position[2] y = -agent_state.position[0] axis = quaternion.as_euler_angles(agent_state.rotation)[0] if (axis % (2 * np.pi)) < 0.1 or (axis % (2 * np.pi)) > 2 * np.pi - 0.1: o = quaternion.as_euler_angles(agent_state.rotation)[1] else: o = 2 * np.pi - quaternion.as_euler_angles(agent_state.rotation)[1] if o > np.pi: o -= 2 * np.pi return x, y, o def get_pose_change(self): """Returns dx, dy, do pose change of the agent relative to the last timestep.""" curr_sim_pose = self.get_sim_location() dx, dy, do = pu.get_rel_pose_change( curr_sim_pose, self.last_sim_location) self.last_sim_location = curr_sim_pose return dx, dy, do
[ "quaternion.as_rotation_vector", "quaternion.as_float_array", "envs.utils.fmm_planner.FMMPlanner", "numpy.random.rand", "gzip.open", "envs.utils.pose.get_l2_distance", "numpy.arange", "_pickle.load", "bz2.BZ2File", "numpy.concatenate", "constants.coco_categories.items", "numpy.rad2deg", "quaternion.from_float_array", "numpy.random.choice", "gym.spaces.Discrete", "quaternion.from_rotation_vector", "numpy.logical_and", "quaternion.as_euler_angles", "gym.spaces.Box", "json.load", "envs.utils.pose.get_rel_pose_change", "numpy.random.shuffle" ]
[((1554, 1576), 'gym.spaces.Discrete', 'gym.spaces.Discrete', (['(3)'], {}), '(3)\n', (1573, 1576), False, 'import gym\n'), ((1611, 1690), 'gym.spaces.Box', 'gym.spaces.Box', (['(0)', '(255)', '(3, args.frame_height, args.frame_width)'], {'dtype': '"""uint8"""'}), "(0, 255, (3, args.frame_height, args.frame_width), dtype='uint8')\n", (1625, 1690), False, 'import gym\n'), ((4531, 4585), 'quaternion.from_float_array', 'quaternion.from_float_array', (["episode['start_rotation']"], {}), "(episode['start_rotation'])\n", (4558, 4585), False, 'import quaternion\n'), ((5223, 5246), 'envs.utils.fmm_planner.FMMPlanner', 'FMMPlanner', (['traversible'], {}), '(traversible)\n', (5233, 5246), False, 'from envs.utils.fmm_planner import FMMPlanner\n'), ((7404, 7455), 'quaternion.from_rotation_vector', 'quaternion.from_rotation_vector', (["episode['sim_rot']"], {}), "(episode['sim_rot'])\n", (7435, 7455), False, 'import quaternion\n'), ((8090, 8113), 'envs.utils.fmm_planner.FMMPlanner', 'FMMPlanner', (['traversible'], {}), '(traversible)\n', (8100, 8113), False, 'from envs.utils.fmm_planner import FMMPlanner\n'), ((12741, 12780), 'quaternion.as_rotation_vector', 'quaternion.as_rotation_vector', (['rotation'], {}), '(rotation)\n', (12770, 12780), False, 'import quaternion\n'), ((12842, 12879), 'quaternion.from_rotation_vector', 'quaternion.from_rotation_vector', (['rvec'], {}), '(rvec)\n', (12873, 12879), False, 'import quaternion\n'), ((13400, 13430), 'quaternion.as_float_array', 'quaternion.as_float_array', (['rot'], {}), '(rot)\n', (13425, 13430), False, 'import quaternion\n'), ((14469, 14508), 'quaternion.as_rotation_vector', 'quaternion.as_rotation_vector', (['rotation'], {}), '(rotation)\n', (14498, 14508), False, 'import quaternion\n'), ((14654, 14691), 'quaternion.from_rotation_vector', 'quaternion.from_rotation_vector', (['rvec'], {}), '(rvec)\n', (14685, 14691), False, 'import quaternion\n'), ((17587, 17619), 'envs.utils.pose.get_l2_distance', 'pu.get_l2_distance', (['(0)', 'dx', '(0)', 'dy'], {}), '(0, dx, 0, dy)\n', (17605, 17619), True, 'import envs.utils.pose as pu\n'), ((20971, 21032), 'envs.utils.pose.get_rel_pose_change', 'pu.get_rel_pose_change', (['curr_sim_pose', 'self.last_sim_location'], {}), '(curr_sim_pose, self.last_sim_location)\n', (20993, 21032), True, 'import envs.utils.pose as pu\n'), ((1384, 1420), 'bz2.BZ2File', 'bz2.BZ2File', (['dataset_info_file', '"""rb"""'], {}), "(dataset_info_file, 'rb')\n", (1395, 1420), False, 'import bz2\n'), ((1459, 1474), '_pickle.load', 'cPickle.load', (['f'], {}), '(f)\n', (1471, 1474), True, 'import _pickle as cPickle\n'), ((2440, 2473), 'numpy.arange', 'np.arange', (['args.num_eval_episodes'], {}), '(args.num_eval_episodes)\n', (2449, 2473), True, 'import numpy as np\n'), ((2486, 2526), 'numpy.random.shuffle', 'np.random.shuffle', (['self.shuffled_indices'], {}), '(self.shuffled_indices)\n', (2503, 2526), True, 'import numpy as np\n'), ((10252, 10264), 'numpy.arange', 'np.arange', (['(6)'], {}), '(6)\n', (10261, 10264), True, 'import numpy as np\n'), ((10663, 10694), 'numpy.random.choice', 'np.random.choice', (['possible_cats'], {}), '(possible_cats)\n', (10679, 10694), True, 'import numpy as np\n'), ((10726, 10749), 'constants.coco_categories.items', 'coco_categories.items', ([], {}), '()\n', (10747, 10749), False, 'from constants import coco_categories\n'), ((11043, 11066), 'envs.utils.fmm_planner.FMMPlanner', 'FMMPlanner', (['traversible'], {}), '(traversible)\n', (11053, 11066), False, 'from envs.utils.fmm_planner import FMMPlanner\n'), ((11589, 11611), 'numpy.logical_and', 'np.logical_and', (['m1', 'm2'], {}), '(m1, m2)\n', (11603, 11611), True, 'import numpy as np\n'), ((15047, 15060), 'numpy.rad2deg', 'np.rad2deg', (['o'], {}), '(o)\n', (15057, 15060), True, 'import numpy as np\n'), ((20364, 20412), 'quaternion.as_euler_angles', 'quaternion.as_euler_angles', (['agent_state.rotation'], {}), '(agent_state.rotation)\n', (20390, 20412), False, 'import quaternion\n'), ((960, 972), 'json.load', 'json.load', (['f'], {}), '(f)\n', (969, 972), False, 'import json\n'), ((11649, 11691), 'numpy.logical_and', 'np.logical_and', (['possible_starting_locs', 'm3'], {}), '(possible_starting_locs, m3)\n', (11663, 11691), True, 'import numpy as np\n'), ((12799, 12815), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (12813, 12815), True, 'import numpy as np\n'), ((16280, 16316), 'numpy.concatenate', 'np.concatenate', (['(rgb, depth)'], {'axis': '(2)'}), '((rgb, depth), axis=2)\n', (16294, 16316), True, 'import numpy as np\n'), ((17945, 17981), 'numpy.concatenate', 'np.concatenate', (['(rgb, depth)'], {'axis': '(2)'}), '((rgb, depth), axis=2)\n', (17959, 17981), True, 'import numpy as np\n'), ((20555, 20603), 'quaternion.as_euler_angles', 'quaternion.as_euler_angles', (['agent_state.rotation'], {}), '(agent_state.rotation)\n', (20581, 20603), False, 'import quaternion\n'), ((3579, 3608), 'gzip.open', 'gzip.open', (['episodes_file', '"""r"""'], {}), "(episodes_file, 'r')\n", (3588, 3608), False, 'import gzip\n'), ((4030, 4042), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4039, 4042), False, 'import json\n'), ((14611, 14627), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (14625, 14627), True, 'import numpy as np\n'), ((20649, 20697), 'quaternion.as_euler_angles', 'quaternion.as_euler_angles', (['agent_state.rotation'], {}), '(agent_state.rotation)\n', (20675, 20697), False, 'import quaternion\n')]
import math import re import matplotlib.pyplot as plt import numpy as np import pandas as pd from go_utils.cleanup import ( # isort: skip rename_latlon_cols, replace_column_prefix, round_cols, standardize_null_vals, ) from go_utils.plot import ( # isort: skip completeness_histogram, plot_freq_bar, plot_int_distribution, ) __doc__ = r""" ## Mosquito Specific Cleanup Procedures ### Converting Larvae Data to Integers Larvae Data is stored as a string in the raw GLOBE Observer dataset. To facillitate analysis, [this method](#larvae_to_num) converts this data to numerical data. It needs to account for 4 types of data: 1. Regular Data: Converts it to a number 2. Extraneously large data ($\geq 100$ as its hard to count more than that amount accurately): To maintain the information from that entry, the `LarvaeCountMagnitude` flag is used to indicate the real value 3. Ranges (e.g. "25-50"): Chooses the lower bound and set the `LarvaeCountIsRangeFlag` to true. 4. Null Values: Sets null values to $-9999$ It generates the following flags: - `LarvaeCountMagnitude`: The integer flag contains the order of magnitude (0-4) by which the larvae count exceeds the maximum Larvae Count of 100. This is calculated by $1 + \lfloor \log{\frac{num}{100}} \rfloor$. As a result: - `0`: Corresponds to a Larvae Count $\leq 100$ - `1`: Corresponds to a Larvae Count between $100$ and $999$ - `2`: Corresponds to a Larvae Count between $1000$ and $9999$ - `3`: Corresponds to a Larvae Count between $10,000$ and $99,999$ - `4`: Corresponds to a Larvae Count $\geq 100,000$ - `LarvaeCountIsRange`: Either a $1$ which indicates the entry was a range (e.g. 25-50) or $0$ which indicates the entry wasn't a range. Additionally, there were extremely large values that Python was unable to process (`1e+27`) and so there was an initial preprocessing step to set those numbers to 100000 (which corresponds to the maximum magnitude flag). """ def cleanup_column_prefix(df, inplace=False): """Method for shortening raw mosquito habitat mapper column names. Parameters ---------- df : pd.DataFrame The DataFrame containing raw mosquito habitat mapper data. inplace : bool, default=False Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place. Returns ------- pd.DataFrame or None A DataFrame with the cleaned up column prefixes. If `inplace=True` it returns None. """ return replace_column_prefix(df, "mosquitohabitatmapper", "mhm", inplace=inplace) def _entry_to_num(entry): try: if entry == "more than 100": return 101, 1, 1 if pd.isna(entry): return -9999, 0, 0 elif float(entry) > 100: return 101, min(math.floor(math.log10(float(entry) / 100)) + 1, 4), 0 return float(entry), 0, 0 except ValueError: return float(re.sub(r"-.*", "", entry)), 0, 1 def larvae_to_num( mhm_df, larvae_count_col="mhm_LarvaeCount", magnitude="mhm_LarvaeCountMagnitude", range_flag="mhm_LarvaeCountIsRangeFlag", inplace=False, ): """Converts the Larvae Count of the Mosquito Habitat Mapper Dataset from being stored as a string to integers. See [here](#converting-larvae-data-to-integers) for more information. Parameters ---------- mhm_df : pd.DataFrame A DataFrame of Mosquito Habitat Mapper data that needs the larvae counts to be set to numbers larvae_count_col : str, default="mhm_LarvaeCount" The name of the column storing the larvae count. **Note**: The columns will be output in the format: `prefix_ColumnName` where `prefix` is all the characters that preceed the words `LarvaeCount` in the specified name. magnitude: str, default="mhm_LarvaeCountMagnitude" The name of the column which will store the generated LarvaeCountMagnitude output range_flag : str, default="mhm_LarvaeCountIsRangeFlag" The name of the column which will store the generated LarvaeCountIsRange flag inplace : bool, default=False Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place. Returns ------- pd.DataFrame A DataFrame with the larvae count as integers. If `inplace=True` it returns None. """ if not inplace: mhm_df = mhm_df.copy() # Preprocessing step to remove extremely erroneous values for i in mhm_df.index: count = mhm_df[larvae_count_col][i] if not pd.isna(count) and type(count) is str and "e+" in count: mhm_df.at[i, larvae_count_col] = "100000" larvae_conversion = np.vectorize(_entry_to_num) ( mhm_df[larvae_count_col], mhm_df[magnitude], mhm_df[range_flag], ) = larvae_conversion(mhm_df[larvae_count_col].to_numpy()) if not inplace: return mhm_df def has_genus_flag(df, genus_col="mhm_Genus", bit_col="mhm_HasGenus", inplace=False): """ Creates a bit flag: `mhm_HasGenus` where 1 denotes a recorded Genus and 0 denotes the contrary. Parameters ---------- df : pd.DataFrame A mosquito habitat mapper DataFrame genus_col : str, default="mhm_Genus" The name of the column in the mosquito habitat mapper DataFrame that contains the genus records. bit_col : str, default="mhm_HasGenus" The name of the column which will store the generated HasGenus flag inplace : bool, default=False Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place. Returns ------- pd.DataFrame A DataFrame with the HasGenus flag. If `inplace=True` it returns None. """ if not inplace: df = df.copy() df[bit_col] = (~pd.isna(df[genus_col].to_numpy())).astype(int) if not inplace: return df def infectious_genus_flag( df, genus_col="mhm_Genus", bit_col="mhm_IsGenusOfInterest", inplace=False ): """ Creates a bit flag: `mhm_IsGenusOfInterest` where 1 denotes a Genus of a infectious mosquito and 0 denotes the contrary. Parameters ---------- df : pd.DataFrame A mosquito habitat mapper DataFrame genus_col : str, default="mhm_Genus" The name of the column in the mosquito habitat mapper DataFrame that contains the genus records. bit_col : str, default="mhm_HasGenus" The name of the column which will store the generated IsGenusOfInterest flag inplace : bool, default=False Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place. Returns ------- pd.DataFrame A DataFrame with the IsGenusOfInterest flag. If `inplace=True` it returns None. """ if not inplace: df = df.copy() infectious_genus_flag = np.vectorize( lambda genus: genus in ["Aedes", "Anopheles", "Culex"] ) df[bit_col] = infectious_genus_flag(df[genus_col].to_numpy()).astype(int) if not inplace: return df def is_container_flag( df, watersource_col="mhm_WaterSourceType", bit_col="mhm_IsWaterSourceContainer", inplace=False, ): """ Creates a bit flag: `mhm_IsWaterSourceContainer` where 1 denotes if a watersource is a container (e.g. ovitrap, pots, tires, etc.) and 0 denotes the contrary. Parameters ---------- df : pd.DataFrame A mosquito habitat mapper DataFrame watersource_col : str, default="mhm_WaterSourceType" The name of the column in the mosquito habitat mapper DataFrame that contains the watersource type records. bit_col : str, default="mhm_IsWaterSourceContainer" The name of the column which will store the generated IsWaterSourceContainer flag inplace : bool, default=False Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place. Returns ------- pd.DataFrame A DataFrame with the IsContainer flag. If `inplace=True` it returns None. """ if not inplace: df = df.copy() mark_containers = np.vectorize(lambda container: "container" in container) df[bit_col] = mark_containers(df[watersource_col].to_numpy()).astype(int) if not inplace: return df def has_watersource_flag( df, watersource_col="mhm_WaterSource", bit_col="mhm_HasWaterSource", inplace=False ): """ Creates a bit flag: `mhm_HasWaterSource` where 1 denotes if there is a watersource and 0 denotes the contrary. Parameters ---------- df : pd.DataFrame A mosquito habitat mapper DataFrame watersource_col : str, default="mhm_WaterSource" The name of the column in the mosquito habitat mapper DataFrame that contains the watersource records. bit_col : str, default="mhm_IsWaterSourceContainer" The name of the column which will store the generated HasWaterSource flag inplace : bool, default=False Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place. Returns ------- pd.DataFrame A DataFrame with the HasWaterSource flag. If `inplace=True` it returns None. """ if not inplace: df = df.copy() has_watersource = np.vectorize(lambda watersource: int(not pd.isna(watersource))) df[bit_col] = has_watersource(df[watersource_col].to_numpy()) if not inplace: return df def photo_bit_flags( df, watersource_photos="mhm_WaterSourcePhotoUrls", larvae_photos="mhm_LarvaFullBodyPhotoUrls", abdomen_photos="mhm_AbdomenCloseupPhotoUrls", photo_count="mhm_PhotoCount", rejected_count="mhm_RejectedCount", pending_count="mhm_PendingCount", photo_bit_binary="mhm_PhotoBitBinary", photo_bit_decimal="mhm_PhotoBitDecimal", inplace=False, ): """ Creates the following flags: - `PhotoCount`: The number of valid photos per record. - `RejectedCount`: The number of photos that were rejected per record. - `PendingCount`: The number of photos that are pending approval per record. - `PhotoBitBinary`: A string that represents the presence of a photo in the order of watersource, larvae, and abdomen. For example, if the entry is `110`, that indicates that there is a water source photo and a larvae photo, but no abdomen photo. - `PhotoBitDecimal`: The numerical representation of the mhm_PhotoBitBinary string. Parameters ---------- df : pd.DataFrame A mosquito habitat mapper DataFrame watersource_photos : str, default="mhm_WaterSourcePhotoUrls" The name of the column in the mosquito habitat mapper DataFrame that contains the watersource photo url records. larvae_photos : str, default="mhm_LarvaFullBodyPhotoUrls" The name of the column in the mosquito habitat mapper DataFrame that contains the larvae photo url records. abdomen_photos : str, default="mhm_AbdomenCloseupPhotoUrls" The name of the column in the mosquito habitat mapper DataFrame that contains the abdomen photo url records. photo_count : str, default="mhm_PhotoCount" The name of the column that will store the PhotoCount flag. rejected_count : str, default="mhm_RejectedCount" The name of the column that will store the RejectedCount flag. pending_count : str, default="mhm_PendingCount" The name of the column that will store the PendingCount flag. photo_bit_binary : str, default="mhm_PhotoBitBinary" The name of the column that will store the PhotoBitBinary flag. photo_bit_decimal : str, default="mhm_PhotoBitDecimal" The name of the column that will store the PhotoBitDecimal flag. inplace : bool, default=False Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place. Returns ------- pd.DataFrame A DataFrame with the photo flags. If `inplace=True` it returns None. """ def pic_data(*args): pic_count = 0 rejected_count = 0 pending_count = 0 valid_photo_bit_mask = "" # bit_power = len(args) - 1 # For url string -- if we see ANY http, add 1 # also count all valid photos, rejected photos, # If there are NO http then add 0, to empty photo field for url_string in args: if not pd.isna(url_string): if "http" not in url_string: valid_photo_bit_mask += "0" else: valid_photo_bit_mask += "1" pic_count += url_string.count("http") pending_count += url_string.count("pending") rejected_count += url_string.count("rejected") else: valid_photo_bit_mask += "0" return ( pic_count, rejected_count, pending_count, valid_photo_bit_mask, int(valid_photo_bit_mask, 2), ) if not inplace: df = df.copy() get_photo_data = np.vectorize(pic_data) ( df[photo_count], df[rejected_count], df[pending_count], df[photo_bit_binary], df[photo_bit_decimal], ) = get_photo_data( df[watersource_photos].to_numpy(), df[larvae_photos].to_numpy(), df[abdomen_photos].to_numpy(), ) if not inplace: return df def completion_score_flag( df, photo_bit_binary="mhm_PhotoBitBinary", has_genus="mhm_HasGenus", sub_completeness="mhm_SubCompletenessScore", completeness="mhm_CumulativeCompletenessScore", inplace=False, ): """ Adds the following completness score flags: - `SubCompletenessScore`: The percentage of the watersource photos, larvae photos, abdomen photos, and genus columns that are filled out. - `CumulativeCompletenessScore`: The percentage of non null values out of all the columns. Parameters ---------- df : pd.DataFrame A mosquito habitat mapper DataFrame with the [`PhotoBitDecimal`](#photo_bit_flags) and [`HasGenus`](#has_genus_flags) flags. photo_bit_binary: str, default="mhm_PhotoBitBinary" The name of the column in the mosquito habitat mapper DataFrame that contains the PhotoBitBinary flag. sub_completeness : str, default="mhm_HasGenus" The name of the column in the mosquito habitat mapper DataFrame that will contain the generated SubCompletenessScore flag. completeness : str, default="mhm_SubCompletenessScore" The name of the column in the mosquito habitat mapper DataFrame that will contain the generated CumulativeCompletenessScore flag. inplace : bool, default=False Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place. Returns ------- pd.DataFrame A DataFrame with completion score flags. If `inplace=True` it returns None. """ def sum_bit_mask(bit_mask="0"): total = 0.0 for char in bit_mask: total += int(char) return total if not inplace: df = df.copy() scores = {} scores["sub_score"] = [] # Cummulative Completion Score scores["cumulative_score"] = round(df.count(axis=1) / len(df.columns), 2) # Sub-Score for index in df.index: bit_mask = df[photo_bit_binary][index] sub_score = df[has_genus][index] + sum_bit_mask(bit_mask=bit_mask) sub_score /= 4.0 scores["sub_score"].append(sub_score) df[sub_completeness], df[completeness] = ( scores["sub_score"], scores["cumulative_score"], ) if not inplace: return df def apply_cleanup(mhm_df): """Applies a full cleanup procedure to the mosquito habitat mapper data. Only returns a copy. It follows the following steps: - Removes Homogenous Columns - Renames Latitude and Longitudes - Cleans the Column Naming - Converts Larvae Count to Numbers - Rounds Columns - Standardizes Null Values Parameters ---------- mhm_df : pd.DataFrame A DataFrame containing **raw** Mosquito Habitat Mapper Data from the API. Returns ------- pd.DataFrame A DataFrame containing the cleaned up Mosquito Habitat Mapper Data """ mhm_df = mhm_df.copy() rename_latlon_cols(mhm_df, inplace=True) cleanup_column_prefix(mhm_df, inplace=True) larvae_to_num(mhm_df, inplace=True) round_cols(mhm_df, inplace=True) standardize_null_vals(mhm_df, inplace=True) return mhm_df def add_flags(mhm_df): """Adds the following flags to the Mosquito Habitat Mapper Data: - Has Genus - Is Infectious Genus/Genus of Interest - Is Container - Has WaterSource - Photo Bit Flags - Completion Score Flag This returns a copy of the original DataFrame with the flags added onto it. Parameters ---------- mhm_df : pd.DataFrame A DataFrame containing cleaned up Mosquito Habitat Mapper Data ideally from the method. Returns ------- pd.DataFrame A DataFrame containing the flagged Mosquito Habitat Mapper Data """ mhm_df = mhm_df.copy() has_genus_flag(mhm_df, inplace=True) infectious_genus_flag(mhm_df, inplace=True) is_container_flag(mhm_df, inplace=True) has_watersource_flag(mhm_df, inplace=True) photo_bit_flags(mhm_df, inplace=True) completion_score_flag(mhm_df, inplace=True) return mhm_df def plot_valid_entries(df, bit_col, entry_type): """ Plots the number of entries with photos and the number of entries without photos Parameters ---------- df : pd.DataFrame The DataFrame containing Mosquito Habitat Mapper Data with the PhotoBitDecimal Flag. """ plt.figure() num_valid = len(df[df[bit_col] > 0]) plt.title(f"Entries with {entry_type} vs No {entry_type}") plt.ylabel("Number of Entries") plt.bar(entry_type, num_valid, color="#e34a33") plt.bar(f"No {entry_type}", len(df) - num_valid, color="#fdcc8a") def photo_subjects(mhm_df): """ Plots the amount of photos for each photo area (Larvae, Abdomen, Watersource) Parameters ---------- mhm_df : pd.DataFrame The DataFrame containing Mosquito Habitat Mapper Data with the PhotoBitDecimal Flag. """ total_dict = {"Larvae Photos": 0, "Abdomen Photos": 0, "Watersource Photos": 0} for number in mhm_df["mhm_PhotoBitDecimal"]: total_dict["Watersource Photos"] += number & 4 total_dict["Larvae Photos"] += number & 2 total_dict["Abdomen Photos"] += number & 1 for key in total_dict.keys(): if total_dict[key] != 0: total_dict[key] = math.log10(total_dict[key]) else: total_dict[key] = 0 plt.figure(figsize=(10, 5)) plt.title("Mosquito Habitat Mapper - Photo Subject Frequencies (Log Scale)") plt.xlabel("Photo Type") plt.ylabel("Frequency (Log Scale)") plt.bar(total_dict.keys(), total_dict.values(), color="lightblue") def diagnostic_plots(mhm_df): """ Generates (but doesn't display) diagnostic plots to gain insight into the current data. Plots: - Larvae Count Distribution (where a negative entry denotes null data) - Photo Subject Distribution - Number of valid photos vs no photos - Completeness Score Distribution - Subcompleteness Score Distribution Parameters ---------- mhm_df : pd.DataFrame The DataFrame containing Flagged and Cleaned Mosquito Habitat Mapper Data. """ plot_int_distribution(mhm_df, "mhm_LarvaeCount", "Larvae Count") photo_subjects(mhm_df) plot_freq_bar(mhm_df, "Mosquito Habitat Mapper", "mhm_Genus", "Genus Types") plot_valid_entries(mhm_df, "mhm_HasGenus", "Genus Classifications") plot_valid_entries(mhm_df, "mhm_PhotoBitDecimal", "Valid Photos") completeness_histogram( mhm_df, "Mosquito Habitat Mapper", "mhm_CumulativeCompletenessScore", "Cumulative Completeness", ) completeness_histogram( mhm_df, "Mosquito Habitat Mapper", "mhm_SubCompletenessScore", "Sub Completeness", ) def qa_filter( mhm_df, has_genus=False, min_larvae_count=-9999, has_photos=False, is_container=False, ): """ Can filter a cleaned and flagged mosquito habitat mapper DataFrame based on the following criteria: - `Has Genus`: If the entry has an identified genus - `Min Larvae Count` : Minimum larvae count needed for an entry - `Has Photos` : If the entry contains valid photo entries - `Is Container` : If the entry's watersource was a container Returns a copy of the DataFrame Parameters ---------- has_genus : bool, default=False If True, only entries with an identified genus will be returned. min_larvae_count : int, default=-9999 Only entries with a larvae count greater than or equal to this parameter will be included. has_photos : bool, default=False If True, only entries with recorded photos will be returned is_container : bool, default=False If True, only entries with containers will be returned Returns ------- pd.DataFrame A DataFrame of the applied filters. """ mhm_df = mhm_df[mhm_df["mhm_LarvaeCount"] >= min_larvae_count] if has_genus: mhm_df = mhm_df[mhm_df["mhm_HasGenus"] == 1] if has_photos: mhm_df = mhm_df[mhm_df["mhm_PhotoBitDecimal"] > 0] if is_container: mhm_df = mhm_df[mhm_df["mhm_IsWaterSourceContainer"] == 1] return mhm_df
[ "go_utils.plot.completeness_histogram", "go_utils.plot.plot_int_distribution", "matplotlib.pyplot.ylabel", "go_utils.cleanup.round_cols", "matplotlib.pyplot.xlabel", "go_utils.cleanup.rename_latlon_cols", "matplotlib.pyplot.figure", "matplotlib.pyplot.bar", "re.sub", "go_utils.cleanup.standardize_null_vals", "pandas.isna", "matplotlib.pyplot.title", "math.log10", "go_utils.cleanup.replace_column_prefix", "numpy.vectorize", "go_utils.plot.plot_freq_bar" ]
[((2550, 2624), 'go_utils.cleanup.replace_column_prefix', 'replace_column_prefix', (['df', '"""mosquitohabitatmapper"""', '"""mhm"""'], {'inplace': 'inplace'}), "(df, 'mosquitohabitatmapper', 'mhm', inplace=inplace)\n", (2571, 2624), False, 'from go_utils.cleanup import rename_latlon_cols, replace_column_prefix, round_cols, standardize_null_vals\n'), ((4754, 4781), 'numpy.vectorize', 'np.vectorize', (['_entry_to_num'], {}), '(_entry_to_num)\n', (4766, 4781), True, 'import numpy as np\n'), ((6970, 7038), 'numpy.vectorize', 'np.vectorize', (["(lambda genus: genus in ['Aedes', 'Anopheles', 'Culex'])"], {}), "(lambda genus: genus in ['Aedes', 'Anopheles', 'Culex'])\n", (6982, 7038), True, 'import numpy as np\n'), ((8261, 8317), 'numpy.vectorize', 'np.vectorize', (["(lambda container: 'container' in container)"], {}), "(lambda container: 'container' in container)\n", (8273, 8317), True, 'import numpy as np\n'), ((13235, 13257), 'numpy.vectorize', 'np.vectorize', (['pic_data'], {}), '(pic_data)\n', (13247, 13257), True, 'import numpy as np\n'), ((16539, 16579), 'go_utils.cleanup.rename_latlon_cols', 'rename_latlon_cols', (['mhm_df'], {'inplace': '(True)'}), '(mhm_df, inplace=True)\n', (16557, 16579), False, 'from go_utils.cleanup import rename_latlon_cols, replace_column_prefix, round_cols, standardize_null_vals\n'), ((16672, 16704), 'go_utils.cleanup.round_cols', 'round_cols', (['mhm_df'], {'inplace': '(True)'}), '(mhm_df, inplace=True)\n', (16682, 16704), False, 'from go_utils.cleanup import rename_latlon_cols, replace_column_prefix, round_cols, standardize_null_vals\n'), ((16709, 16752), 'go_utils.cleanup.standardize_null_vals', 'standardize_null_vals', (['mhm_df'], {'inplace': '(True)'}), '(mhm_df, inplace=True)\n', (16730, 16752), False, 'from go_utils.cleanup import rename_latlon_cols, replace_column_prefix, round_cols, standardize_null_vals\n'), ((17989, 18001), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (17999, 18001), True, 'import matplotlib.pyplot as plt\n'), ((18047, 18105), 'matplotlib.pyplot.title', 'plt.title', (['f"""Entries with {entry_type} vs No {entry_type}"""'], {}), "(f'Entries with {entry_type} vs No {entry_type}')\n", (18056, 18105), True, 'import matplotlib.pyplot as plt\n'), ((18110, 18141), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Entries"""'], {}), "('Number of Entries')\n", (18120, 18141), True, 'import matplotlib.pyplot as plt\n'), ((18146, 18193), 'matplotlib.pyplot.bar', 'plt.bar', (['entry_type', 'num_valid'], {'color': '"""#e34a33"""'}), "(entry_type, num_valid, color='#e34a33')\n", (18153, 18193), True, 'import matplotlib.pyplot as plt\n'), ((19009, 19036), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (19019, 19036), True, 'import matplotlib.pyplot as plt\n'), ((19041, 19117), 'matplotlib.pyplot.title', 'plt.title', (['"""Mosquito Habitat Mapper - Photo Subject Frequencies (Log Scale)"""'], {}), "('Mosquito Habitat Mapper - Photo Subject Frequencies (Log Scale)')\n", (19050, 19117), True, 'import matplotlib.pyplot as plt\n'), ((19122, 19146), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Photo Type"""'], {}), "('Photo Type')\n", (19132, 19146), True, 'import matplotlib.pyplot as plt\n'), ((19151, 19186), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frequency (Log Scale)"""'], {}), "('Frequency (Log Scale)')\n", (19161, 19186), True, 'import matplotlib.pyplot as plt\n'), ((19783, 19847), 'go_utils.plot.plot_int_distribution', 'plot_int_distribution', (['mhm_df', '"""mhm_LarvaeCount"""', '"""Larvae Count"""'], {}), "(mhm_df, 'mhm_LarvaeCount', 'Larvae Count')\n", (19804, 19847), False, 'from go_utils.plot import completeness_histogram, plot_freq_bar, plot_int_distribution\n'), ((19879, 19955), 'go_utils.plot.plot_freq_bar', 'plot_freq_bar', (['mhm_df', '"""Mosquito Habitat Mapper"""', '"""mhm_Genus"""', '"""Genus Types"""'], {}), "(mhm_df, 'Mosquito Habitat Mapper', 'mhm_Genus', 'Genus Types')\n", (19892, 19955), False, 'from go_utils.plot import completeness_histogram, plot_freq_bar, plot_int_distribution\n'), ((20102, 20225), 'go_utils.plot.completeness_histogram', 'completeness_histogram', (['mhm_df', '"""Mosquito Habitat Mapper"""', '"""mhm_CumulativeCompletenessScore"""', '"""Cumulative Completeness"""'], {}), "(mhm_df, 'Mosquito Habitat Mapper',\n 'mhm_CumulativeCompletenessScore', 'Cumulative Completeness')\n", (20124, 20225), False, 'from go_utils.plot import completeness_histogram, plot_freq_bar, plot_int_distribution\n'), ((20265, 20374), 'go_utils.plot.completeness_histogram', 'completeness_histogram', (['mhm_df', '"""Mosquito Habitat Mapper"""', '"""mhm_SubCompletenessScore"""', '"""Sub Completeness"""'], {}), "(mhm_df, 'Mosquito Habitat Mapper',\n 'mhm_SubCompletenessScore', 'Sub Completeness')\n", (20287, 20374), False, 'from go_utils.plot import completeness_histogram, plot_freq_bar, plot_int_distribution\n'), ((2739, 2753), 'pandas.isna', 'pd.isna', (['entry'], {}), '(entry)\n', (2746, 2753), True, 'import pandas as pd\n'), ((18931, 18958), 'math.log10', 'math.log10', (['total_dict[key]'], {}), '(total_dict[key])\n', (18941, 18958), False, 'import math\n'), ((4618, 4632), 'pandas.isna', 'pd.isna', (['count'], {}), '(count)\n', (4625, 4632), True, 'import pandas as pd\n'), ((12562, 12581), 'pandas.isna', 'pd.isna', (['url_string'], {}), '(url_string)\n', (12569, 12581), True, 'import pandas as pd\n'), ((2979, 3003), 're.sub', 're.sub', (['"""-.*"""', '""""""', 'entry'], {}), "('-.*', '', entry)\n", (2985, 3003), False, 'import re\n'), ((9482, 9502), 'pandas.isna', 'pd.isna', (['watersource'], {}), '(watersource)\n', (9489, 9502), True, 'import pandas as pd\n')]
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """FCIDump dumper.""" from typing import List, Optional from io import TextIOWrapper import itertools import numpy as np def dump(outpath: str, norb: int, nelec: int, hijs: List[float], hijkls: List[float], einact: float, ms2: int = 0, orbsym: Optional[List[int]] = None, isym: int = 1 ) -> None: # pylint: disable=wrong-spelling-in-docstring """Generates a FCIDump output. Args: outpath: Path to the output file. norb: The number of orbitals. nelec: The number of electrons. hijs: The pair of alpha and beta 1-electron integrals. The latter may be None. hijkls: The triplet of alpha/alpha, beta/alpha and beta/beta 2-electron integrals. The latter two may be None. einact: The inactive energy. ms2: 2*S, where S is the spin quantum number. orbsym: A list of spatial symmetries of the orbitals. isym: The spatial symmetry of the wave function. """ hij, hij_b = hijs hijkl, hijkl_ba, hijkl_bb = hijkls # assert that either all beta variables are None or all of them are not assert all([h is None for h in [hij_b, hijkl_ba, hijkl_bb]]) \ or all([h is not None for h in [hij_b, hijkl_ba, hijkl_bb]]) assert norb == hij.shape[0] == hijkl.shape[0] mos = range(norb) with open(outpath, 'w') as outfile: # print header outfile.write('&FCI NORB={:4d},NELEC={:4d},MS2={:4d}\n'.format(norb, nelec, ms2)) if orbsym is None: outfile.write(' ORBSYM=' + '1,'*norb + '\n') else: assert len(orbsym) == norb outfile.write(' ORBSYM=' + ','.join(orbsym) + '\n') outfile.write(' ISYM={:d},\n/&END\n'.format(isym)) # append 2e integrals _dump_2e_ints(hijkl, mos, outfile) if hijkl_ba is not None: _dump_2e_ints(hijkl_ba.transpose(), mos, outfile, beta=1) if hijkl_bb is not None: _dump_2e_ints(hijkl_bb, mos, outfile, beta=2) # append 1e integrals _dump_1e_ints(hij, mos, outfile) if hij_b is not None: _dump_1e_ints(hij_b, mos, outfile, beta=True) # TODO append MO energies (last three indices are 0) # append inactive energy _write_to_outfile(outfile, einact, (0, 0, 0, 0)) def _dump_1e_ints(hij: List[float], mos: List[int], outfile: TextIOWrapper, beta: bool = False) -> None: idx_offset = 1 if not beta else 1+len(mos) hij_elements = set() for i, j in itertools.product(mos, repeat=2): if i == j: _write_to_outfile(outfile, hij[i][j], (i+idx_offset, j+idx_offset, 0, 0)) continue if (j, i) in hij_elements and np.isclose(hij[i][j], hij[j][i]): continue _write_to_outfile(outfile, hij[i][j], (i+idx_offset, j+idx_offset, 0, 0)) hij_elements.add((i, j)) def _dump_2e_ints(hijkl: List[float], mos: List[int], outfile: TextIOWrapper, beta: int = 0) -> None: idx_offsets = [1, 1] for b in range(beta): idx_offsets[1-b] += len(mos) hijkl_elements = set() # pylint: disable=invalid-name for elem in itertools.product(mos, repeat=4): if np.isclose(hijkl[elem], 0.0, atol=1e-14): continue if len(set(elem)) == 1: _write_to_outfile(outfile, hijkl[elem], (*[e+idx_offsets[0] for e in elem[:2]], *[e+idx_offsets[1] for e in elem[2:]])) continue if beta != 1 and elem[::-1] in hijkl_elements and \ np.isclose(hijkl[elem], hijkl[elem[::-1]]): continue bra_perms = set(itertools.permutations(elem[:2])) ket_perms = set(itertools.permutations(elem[2:])) if beta == 1: permutations = itertools.product(bra_perms, ket_perms) else: permutations = itertools.chain( itertools.product(bra_perms, ket_perms), itertools.product(ket_perms, bra_perms) ) for perm in {e1 + e2 for e1, e2 in permutations}: if perm in hijkl_elements and np.isclose(hijkl[elem], hijkl[perm]): break else: _write_to_outfile(outfile, hijkl[elem], (*[e+idx_offsets[0] for e in elem[:2]], *[e+idx_offsets[1] for e in elem[2:]])) hijkl_elements.add(elem) def _write_to_outfile(outfile: str, value: float, indices: List[int]): outfile.write('{:23.16E}{:4d}{:4d}{:4d}{:4d}\n'.format(value, *indices))
[ "itertools.permutations", "itertools.product", "numpy.isclose" ]
[((3021, 3053), 'itertools.product', 'itertools.product', (['mos'], {'repeat': '(2)'}), '(mos, repeat=2)\n', (3038, 3053), False, 'import itertools\n'), ((3677, 3709), 'itertools.product', 'itertools.product', (['mos'], {'repeat': '(4)'}), '(mos, repeat=4)\n', (3694, 3709), False, 'import itertools\n'), ((3722, 3762), 'numpy.isclose', 'np.isclose', (['hijkl[elem]', '(0.0)'], {'atol': '(1e-14)'}), '(hijkl[elem], 0.0, atol=1e-14)\n', (3732, 3762), True, 'import numpy as np\n'), ((3219, 3251), 'numpy.isclose', 'np.isclose', (['hij[i][j]', 'hij[j][i]'], {}), '(hij[i][j], hij[j][i])\n', (3229, 3251), True, 'import numpy as np\n'), ((4099, 4141), 'numpy.isclose', 'np.isclose', (['hijkl[elem]', 'hijkl[elem[::-1]]'], {}), '(hijkl[elem], hijkl[elem[::-1]])\n', (4109, 4141), True, 'import numpy as np\n'), ((4188, 4220), 'itertools.permutations', 'itertools.permutations', (['elem[:2]'], {}), '(elem[:2])\n', (4210, 4220), False, 'import itertools\n'), ((4246, 4278), 'itertools.permutations', 'itertools.permutations', (['elem[2:]'], {}), '(elem[2:])\n', (4268, 4278), False, 'import itertools\n'), ((4329, 4368), 'itertools.product', 'itertools.product', (['bra_perms', 'ket_perms'], {}), '(bra_perms, ket_perms)\n', (4346, 4368), False, 'import itertools\n'), ((4443, 4482), 'itertools.product', 'itertools.product', (['bra_perms', 'ket_perms'], {}), '(bra_perms, ket_perms)\n', (4460, 4482), False, 'import itertools\n'), ((4500, 4539), 'itertools.product', 'itertools.product', (['ket_perms', 'bra_perms'], {}), '(ket_perms, bra_perms)\n', (4517, 4539), False, 'import itertools\n'), ((4654, 4690), 'numpy.isclose', 'np.isclose', (['hijkl[elem]', 'hijkl[perm]'], {}), '(hijkl[elem], hijkl[perm])\n', (4664, 4690), True, 'import numpy as np\n')]
from flask import Flask, flash, request, redirect, url_for, render_template from werkzeug.utils import secure_filename import os from keras.models import load_model from keras.applications.inception_resnet_v2 import InceptionResNetV2 import tensorflow as tf from skimage.io import imsave from skimage.transform import resize import numpy as np from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img from skimage.color import rgb2lab, lab2rgb, rgb2gray, gray2rgb from keras.applications.inception_resnet_v2 import preprocess_input from PIL import Image,ImageChops import logging global graph graph = tf.get_default_graph() app = Flask(__name__) app.secret_key = "hello" ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) model = load_model('trained-model.h5') UPLOAD_FOLDER = '/home/nubaf/Git-Projects/colorization/files' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER files = [f for f in os.listdir('.') if os.path.isfile(f)] checkInception = False for f in files: if f == "inception.h5": checkInception = True inception = load_model('inception.h5', compile=False) break if not checkInception: inception = InceptionResNetV2(weights='imagenet', include_top=True) inception.save('inception.h5') inception.graph = graph def create_inception_embedding(grayscaled_rgb): grayscaled_rgb_resized = [] for i in grayscaled_rgb: i = resize(i, (299, 299, 3), mode='constant') grayscaled_rgb_resized.append(i) grayscaled_rgb_resized = np.array(grayscaled_rgb_resized) grayscaled_rgb_resized = preprocess_input(grayscaled_rgb_resized) with graph.as_default(): embed = inception.predict(grayscaled_rgb_resized) return embed def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': try: url = request.form['url'] if 'examples' in url: color_file = process(url) return render_template('index.html', res='static/examples/girl.jpg') # check if the post request has the file part except: logging.exception('') if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) color_file = process(file.filename) return render_template('index.html', og=color_file[0], res=color_file[1]) return render_template('index.html') def process(img): if 'examples' in img: im = Image.open(img) name = img.split('.')[0].split('/')[-1] else: im = Image.open('files/' + img) name = img.split('.')[0] old_size = im.size # old_size[0] is in (width, height) format ratio = float(256)/max(old_size) new_size = tuple([int(x*ratio) for x in old_size]) im = im.resize(new_size, Image.ANTIALIAS) new_im = Image.new("RGB", (256, 256)) new_im.paste(im, ((256-new_size[0])//2,(256-new_size[1])//2)) new_im.save('static/processed_png/' + name + ".png","PNG") a = np.array(img_to_array(load_img('static/processed_png/' + name +'.png'))) a = a.reshape(1,256,256,3) #gray_me = gray2rgb(rgb2gray(1.0/255*a)) color_me_embed = create_inception_embedding(a) a = rgb2lab(1.0/255*a)[:,:,:,0] a = a.reshape(a.shape+(1,)) with graph.as_default(): output = model.predict([a, color_me_embed]) output = output * 128 for i in range(len(output)): cur = np.zeros((256, 256, 3)) cur[:,:,0] = a[i][:,:,0] cur[:,:,1:] = output[i] imsave(f'static/colored_img/{name}.png',(lab2rgb(cur))) trim(Image.open(f'static/processed_png/{name}.png')).save(f'static/processed_png/{name}.png') trim(Image.open(f'static/colored_img/{name}.png')).save(f'static/colored_img/{name}.png') return (f'static/processed_png/{name}.png',f'static/colored_img/{name}.png') def trim(im): bg = Image.new(im.mode, im.size, im.getpixel((0,0))) diff = ImageChops.difference(im, bg) diff = ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: return im.crop(bbox) if __name__ == "__main__": app.run(debug=True)
[ "flask.render_template", "flask.Flask", "PIL.Image.new", "logging.exception", "numpy.array", "werkzeug.utils.secure_filename", "os.listdir", "skimage.color.rgb2lab", "flask.flash", "keras.applications.inception_resnet_v2.preprocess_input", "skimage.color.lab2rgb", "keras.applications.inception_resnet_v2.InceptionResNetV2", "PIL.ImageChops.add", "tensorflow.get_default_graph", "PIL.ImageChops.difference", "os.path.isfile", "flask.redirect", "skimage.transform.resize", "keras.preprocessing.image.load_img", "PIL.Image.open", "keras.models.load_model", "os.path.join", "numpy.zeros" ]
[((642, 664), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (662, 664), True, 'import tensorflow as tf\n'), ((671, 686), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (676, 686), False, 'from flask import Flask, flash, request, redirect, url_for, render_template\n'), ((769, 799), 'keras.models.load_model', 'load_model', (['"""trained-model.h5"""'], {}), "('trained-model.h5')\n", (779, 799), False, 'from keras.models import load_model\n'), ((1176, 1231), 'keras.applications.inception_resnet_v2.InceptionResNetV2', 'InceptionResNetV2', ([], {'weights': '"""imagenet"""', 'include_top': '(True)'}), "(weights='imagenet', include_top=True)\n", (1193, 1231), False, 'from keras.applications.inception_resnet_v2 import InceptionResNetV2\n'), ((1526, 1558), 'numpy.array', 'np.array', (['grayscaled_rgb_resized'], {}), '(grayscaled_rgb_resized)\n', (1534, 1558), True, 'import numpy as np\n'), ((1588, 1628), 'keras.applications.inception_resnet_v2.preprocess_input', 'preprocess_input', (['grayscaled_rgb_resized'], {}), '(grayscaled_rgb_resized)\n', (1604, 1628), False, 'from keras.applications.inception_resnet_v2 import preprocess_input\n'), ((2969, 2998), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (2984, 2998), False, 'from flask import Flask, flash, request, redirect, url_for, render_template\n'), ((3422, 3450), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(256, 256)'], {}), "('RGB', (256, 256))\n", (3431, 3450), False, 'from PIL import Image, ImageChops\n'), ((4569, 4598), 'PIL.ImageChops.difference', 'ImageChops.difference', (['im', 'bg'], {}), '(im, bg)\n', (4590, 4598), False, 'from PIL import Image, ImageChops\n'), ((4610, 4647), 'PIL.ImageChops.add', 'ImageChops.add', (['diff', 'diff', '(2.0)', '(-100)'], {}), '(diff, diff, 2.0, -100)\n', (4624, 4647), False, 'from PIL import Image, ImageChops\n'), ((926, 941), 'os.listdir', 'os.listdir', (['"""."""'], {}), "('.')\n", (936, 941), False, 'import os\n'), ((945, 962), 'os.path.isfile', 'os.path.isfile', (['f'], {}), '(f)\n', (959, 962), False, 'import os\n'), ((1081, 1122), 'keras.models.load_model', 'load_model', (['"""inception.h5"""'], {'compile': '(False)'}), "('inception.h5', compile=False)\n", (1091, 1122), False, 'from keras.models import load_model\n'), ((1414, 1455), 'skimage.transform.resize', 'resize', (['i', '(299, 299, 3)'], {'mode': '"""constant"""'}), "(i, (299, 299, 3), mode='constant')\n", (1420, 1455), False, 'from skimage.transform import resize\n'), ((3057, 3072), 'PIL.Image.open', 'Image.open', (['img'], {}), '(img)\n', (3067, 3072), False, 'from PIL import Image, ImageChops\n'), ((3144, 3170), 'PIL.Image.open', 'Image.open', (["('files/' + img)"], {}), "('files/' + img)\n", (3154, 3170), False, 'from PIL import Image, ImageChops\n'), ((3796, 3818), 'skimage.color.rgb2lab', 'rgb2lab', (['(1.0 / 255 * a)'], {}), '(1.0 / 255 * a)\n', (3803, 3818), False, 'from skimage.color import rgb2lab, lab2rgb, rgb2gray, gray2rgb\n'), ((2332, 2353), 'flask.flash', 'flash', (['"""No file part"""'], {}), "('No file part')\n", (2337, 2353), False, 'from flask import Flask, flash, request, redirect, url_for, render_template\n'), ((2373, 2394), 'flask.redirect', 'redirect', (['request.url'], {}), '(request.url)\n', (2381, 2394), False, 'from flask import Flask, flash, request, redirect, url_for, render_template\n'), ((2577, 2602), 'flask.flash', 'flash', (['"""No selected file"""'], {}), "('No selected file')\n", (2582, 2602), False, 'from flask import Flask, flash, request, redirect, url_for, render_template\n'), ((2622, 2643), 'flask.redirect', 'redirect', (['request.url'], {}), '(request.url)\n', (2630, 2643), False, 'from flask import Flask, flash, request, redirect, url_for, render_template\n'), ((2716, 2746), 'werkzeug.utils.secure_filename', 'secure_filename', (['file.filename'], {}), '(file.filename)\n', (2731, 2746), False, 'from werkzeug.utils import secure_filename\n'), ((2889, 2955), 'flask.render_template', 'render_template', (['"""index.html"""'], {'og': 'color_file[0]', 'res': 'color_file[1]'}), "('index.html', og=color_file[0], res=color_file[1])\n", (2904, 2955), False, 'from flask import Flask, flash, request, redirect, url_for, render_template\n'), ((3610, 3659), 'keras.preprocessing.image.load_img', 'load_img', (["('static/processed_png/' + name + '.png')"], {}), "('static/processed_png/' + name + '.png')\n", (3618, 3659), False, 'from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\n'), ((4022, 4045), 'numpy.zeros', 'np.zeros', (['(256, 256, 3)'], {}), '((256, 256, 3))\n', (4030, 4045), True, 'import numpy as np\n'), ((2114, 2175), 'flask.render_template', 'render_template', (['"""index.html"""'], {'res': '"""static/examples/girl.jpg"""'}), "('index.html', res='static/examples/girl.jpg')\n", (2129, 2175), False, 'from flask import Flask, flash, request, redirect, url_for, render_template\n'), ((2258, 2279), 'logging.exception', 'logging.exception', (['""""""'], {}), "('')\n", (2275, 2279), False, 'import logging\n'), ((2769, 2820), 'os.path.join', 'os.path.join', (["app.config['UPLOAD_FOLDER']", 'filename'], {}), "(app.config['UPLOAD_FOLDER'], filename)\n", (2781, 2820), False, 'import os\n'), ((4172, 4184), 'skimage.color.lab2rgb', 'lab2rgb', (['cur'], {}), '(cur)\n', (4179, 4184), False, 'from skimage.color import rgb2lab, lab2rgb, rgb2gray, gray2rgb\n'), ((4204, 4250), 'PIL.Image.open', 'Image.open', (['f"""static/processed_png/{name}.png"""'], {}), "(f'static/processed_png/{name}.png')\n", (4214, 4250), False, 'from PIL import Image, ImageChops\n'), ((4310, 4354), 'PIL.Image.open', 'Image.open', (['f"""static/colored_img/{name}.png"""'], {}), "(f'static/colored_img/{name}.png')\n", (4320, 4354), False, 'from PIL import Image, ImageChops\n')]
from collections import ChainMap from collections.abc import Mapping, Iterable from itertools import groupby from operator import itemgetter import numpy as np from probability import RowKey from probability import TableColumns # from probability.core_1 import RowKey # from probability.core_1 import TableColumns def to_dict(groupby_index, value_index): def make_dict(sorted_items): # It groups the sorted item based on # the element as groupby_index # and then sum the values at value_index return { k: sum([item[value_index] for item in g2]) for k, g2 in groupby(sorted_items, key=itemgetter(groupby_index)) } return make_dict class Table(dict): def __init__(self, rows, names=None, _internal_=False, _children_names_=None): if _internal_: # rows are dictionary for internal calls key_values = rows try: self._row_sample_ = next(iter(rows)) except StopIteration: # Rows are empty super().__init__(key_values) self._row_sample_ = None self.names = names if _children_names_ is None: self.children_names = [] self.columns = TableColumns( names=names, children_names=[], table=self ) else: self.children_names = _children_names_ self.columns = TableColumns( names=names, children_names=_children_names_, table=self ) return else: if isinstance(rows, Mapping): key_values = [(RowKey(k), value) for k, value in rows.items()] elif isinstance(rows, Iterable): key_values = [(RowKey(k), value) for k, value in rows] else: raise ValueError("Table expect rows as Mapping/Iterable") self._row_sample_ = key_values[0][0] if names is None: names = [f"X{i+1}" for i, _ in enumerate(self._row_sample_)] if len(names) != len(self._row_sample_): raise ValueError("The length of column names and columns are not the same.") super().__init__(key_values) self.names = names value_sample = super().__getitem__(self._row_sample_) if isinstance(value_sample, Table): self.columns = TableColumns( names=names, children_names=value_sample.names, table=self ) self.children_names = value_sample.names else: if _children_names_ is None: self.children_names = [] self.columns = TableColumns(names=names, children_names=[], table=self) else: self.children_names = _children_names_ self.columns = TableColumns( names=names, children_names=_children_names_, table=self ) def __missing__(self, key): return None def __getitem__(self, args): """Override the dict by converting the comma separated arguments to RowKey """ # This is faster than isinstance # We are sure there is not any inheritance # to deal with if type(args) is RowKey: return super().__getitem__(args) if self.columns.size == 1: key = self.columns.to_key(args) else: key = self.columns.to_key(*args) return super().__getitem__(key) def _check_keys_consistencies_(self): # We suppose each column is positioned # in a fix place of the n-tuple. # Therefore, the levels of the column can be # found by iterating over each tuple's item # Convert each features line to tuple first_row_types = [type(item) for item in self._row_sample_] for row in self.keys(): # compair length if len(row) != self.columns.size: raise ValueError("The length of the 'factors' are not consistence.") # compair row's elements type comparisions = [ isinstance(element, type_1) for element, type_1 in zip(row, first_row_types) ] if not all(comparisions): raise ValueError("The types of the 'factors' are not consistence.") def to_2d_array(self): """Convert the distribution ( or the self._counter's key:value) to a 2D numpy array where the array rows are [[(RV_1, RV_2, ..., RV_n, count)],[... Returns: numpy ndarray: A 2D numpy array that the its last column is the counts. """ return np.array([k + (v,) for k, v in self.items()], dtype=np.object) def _product_(self, right): """Multiply two Tables. Args: right ([type]): [description] Raises: ValueError: [description] Returns: [type]: [description] """ if not isinstance(right, Table): raise ValueError("The 'right' argument must be a Table.") # Find common variables # reorder commons based on their order in left_common_indices commons = [ name for name in self.names if name in (set(self.names) & set(right.names)) ] # When there is no common variable, it is just a simple product if len(commons) == 0: names = np.r_[self.names, right.names] return ( { k1 + k2: v1 * v2 for k1, v1 in self.items() for k2, v2 in right.items() }, names, ) # In the case that there is one or more common variables, # the operation is similar to SQL inner join # So, create a lookup for the left table, by using the # common variables as key. left_common_indices = [ i for i, name in enumerate(self.names) if name in commons ] # the order in right must be the same as the left # so we reorder the indices base on its left order right_common_indices = [ i for name in commons for i, name2 in enumerate(right.names) if name == name2 ] right_complement_indices = [ i for i, name in enumerate(right.names) if name not in commons ] # Methods to split the keys def l_comm(key): return tuple([key[i] for i in left_common_indices]) def r_comm(key): return tuple([key[i] for i in right_common_indices]) def r_comp(key): return tuple([key[i] for i in right_complement_indices]) # left and right tables lookup # left : (key:value) == (common_key: (left_key, left_value)) left_lookup = {} for k, value in self.items(): comm = l_comm(k) if comm in left_lookup: left_lookup[comm] += [(k, value)] else: left_lookup[comm] = [(k, value)] # right : (key:value) == (common_key: (right_compliment_key, right_value)) right_lookup = {} for k, value in right.items(): comm = r_comm(k) if comm in right_lookup: right_lookup[comm] += [(r_comp(k), value)] else: right_lookup[comm] = [(r_comp(k), value)] # The inner join happens over keys of two dictionaries (left_lookup and # right_lookup). prodcut_dict = {} for comm, l_values in left_lookup.items(): if comm not in right_lookup: continue for left_key, left_value in l_values: for right_comp, right_value in right_lookup[comm]: # prodcut_dict values must be multiplied. # prodcut_dict keys are the combination: (left, right_compliment). prodcut_dict[left_key + right_comp] = left_value * right_value # names are the combination of [left_names, right_compelements_names] combined_names = np.r_[ self.names, [name for name in right.names if name not in commons], ] return (prodcut_dict, combined_names) def marginal(self, *args, normalise=True): """Marginal of (group by) the Table over a set of columns. P(X, Y, Z) -> P(X, Y) or P(X, Z) or P(Y, Z) Args: args (list): List of column names to marginalised. Raises: ValueError: Raises when one of the column names is not defined. Or raises when requested for all column names. Returns: Table: (rows, names). """ # check the validity of operation based on column names if len(args) == self.columns.size: raise ValueError("Cannot marginalize on all column names.") # split columns to indices and comp_indices columns_info = self.columns.split_columns(*args) # # Convert the key:values to 2D numpy array # the array rows are (row, value) arr = self.to_2d_array() # filter the compliment columns filtered_arr = np.c_[arr[:, columns_info.complimnet_indices], arr[:, -1]] # split the 2d array's rows to a tuple of # compliment columns (row[comp_indices]) # and count row[-1] arr_gen = ((RowKey(row[:-1]), row[-1]) for row in filtered_arr) # Before calling the groupby, we have to sort the generator # by the tuple of compliment columns (index zero in itemgetter) sorted_arr = sorted(arr_gen, key=itemgetter(0)) # since the values in each 'group' are # (compliment columns, value) # here we group by 'compliment columns' and apply # the sum on the value. Then the dictionary of # compliment columns:op_of_values # is an acceptable argument for Table grouped_arr = { k: sum([item[1] for item in g]) for k, g in groupby(sorted_arr, key=itemgetter(0)) } table = Table(grouped_arr, columns_info.complimnet_names, _internal_=True) if normalise: table.normalise() return table def condition_on(self, *args, normalise=True): """Creates the conditional based on the provided names of columns. P(X, Y) -> P(X | Y) or P(Y | X) Args: args (list): List of names of provided random variables. Raises: ValueError: If the provided RV names do not exist in the distribution. Returns: MultiTable """ if self.columns.size == 1: raise ValueError("This is a single column Table and cannot condition on.") if len(args) == self.columns.size: raise ValueError("Cannot condition on all columns.") # split columns to indices and comp_indices columns_info = self.columns.split_columns(*args) # Convert the key:value to 2D numpy array # the array rows are (rows, value) arr = self.to_2d_array() # divide the 2d array's rows to a tuple of columns, # (row[indices]), compliment columns (row[comp_indices]) # and values row[-1] arr_gen = ( ( RowKey(row[columns_info.indices]), RowKey(row[columns_info.complimnet_indices]), row[-1], ) for row in arr ) # Before calling the groupby, we have to sort the generator # by the tuple of columns (index zero in itemgetter) # And since later we will call the group by on group, # for each key we do the inner sort too (index one in itemgetter) sorted_arr = sorted(arr_gen, key=itemgetter(0, 1)) # This method convert a group to a dictionary def make_dict(group): # since the values in 'group' argument are # (columns, compliment columns, value) # here we group by 'compliment columns' and sum # the values. return { k: sum([item[2] for item in g2]) for k, g2 in groupby(group, key=itemgetter(1)) } # For each group (belongs a unique values), we create # a dictionary in a dictionary comprehension grouped_arr = { k: make_dict(g) for k, g in groupby(sorted_arr, key=itemgetter(0)) } # The above dictionary is dictionary of dictionaries # # the first set of names is for parent dictionary # and the second set is for children table = MultiTable( { key: Table(values, columns_info.complimnet_names, _internal_=True) for key, values in grouped_arr.items() }, columns_info.indices_names, ) if normalise: table.normalise() return table def reduce(self, **kwargs): """Reduce the Table by one or more columns. P(X, Y) -> P(X = x, Y) or P(X, Y = y) Args: kwargs (dict): A dictionary that its 'key' is the name of the column and its 'value' is the value that must be reduced by. Raises: ValueError: If the provided names do not exist in the Table. Returns: [Table]: A reduce Table. """ # split columns to indices and comp_indices columns = list(kwargs.keys()) if len(columns) == self.columns.size: raise ValueError("Cannot reduce on all column names.") columns_info = self.columns.split_columns(*columns) values = np.array([value for _, value in kwargs.items()], dtype=np.object) # # Convert the key:values to 2D numpy array # the array rows are (keys, value) arr_counter = self.to_2d_array() # filter the 2d array rows by provided values of the reduce # conditioned_arr is a boolean one, and filtering happens # in the second line conditioned_arr = np.all(arr_counter[:, columns_info.indices] == values, axis=1) sliced_arr = arr_counter[conditioned_arr, :] # filter the 2d array columns (the compliment columns) # plus the value column (which is the last column) sliced_arr = sliced_arr[:, columns_info.complimnet_indices + [-1]] # divide the 2d array's rows to a tuple of columns # and value # So, we make a generator that divide the rows to the tuple of # columns (tuple(row[:-1]) and value (row[-1]) arr_gen = ((RowKey(row[:-1]), row[-1]) for row in sliced_arr) # Before calling the groupby, we have to sort the generator # by the tuple of column (index zero in itemgetter) sorted_slice_arr = sorted(arr_gen, key=itemgetter(0)) # group by the filtered columns (compliment # columns) and sum the value per key # Note that the 'itemgetter' read the first index which # is the tuple of compliment columns return Table( { k: sum([item[1] for item in g]) for k, g in groupby(sorted_slice_arr, key=itemgetter(0)) }, columns_info.complimnet_names, _internal_=True, ) def get(self, *args, **kwargs): key = self.columns.to_key(*args, **kwargs) return super().__getitem__(key) def to_table(self, sort=False, value_title=""): arr = self.to_2d_array().astype("U") arr_len = np.apply_along_axis(lambda row: [len(item) for item in row], 0, arr) max_levels_len = np.max(arr_len[:, :-1], axis=0) max_freq_len = max(np.max(arr_len[:, -1]), len(value_title)) def padding(max_len): def str_padding(value): return "".join([" "] * (max_len - len(str(value)))) return str_padding r_padding = padding(max_freq_len) if sort: # sort by values items = reversed(sorted(self.items(), key=lambda item: item[1])) else: # sort by keys items = sorted(self.items()) rows = "" header = "" horizontal_line = "" for i, name in enumerate(self.names): header += f"|{name}{padding(max_levels_len[i])(name)}" horizontal_line += "|" + "".join(["-"] * max_levels_len[i]) header += "|" + "".join([" "] * max_freq_len) + "|" horizontal_line += "|" + "".join(["-"] * max_freq_len) + "|" for k, value in items: key_str = "" for i, k_part in enumerate(k): key_str += f"|{padding(max_levels_len[i])(k_part)}{k_part}" freq_padding = r_padding(value) rows += f"{key_str}|{value}{freq_padding}|\n" return f"{header}\n{horizontal_line}\n{rows}" def add(self, that): """Combines two FrequencyTable and return a new one. All the frequencies are sum together. This is not a mathematical sum. """ ############################################# # check the validity of operation based on column names if not isinstance(that, Table): raise ValueError("Table can only adds to Table.") if self.columns.size != that.columns.size: raise ValueError("Two adding Table do not have the same columns.") if len(self.children_names) != len(that.children_names): raise ValueError("Two adding Table do not have the same children columns.") for i, name in enumerate(self.names): if name != that.names[i]: raise ValueError( "Two adding Table do not have the same columns " "(order must be the same too)." ) for i, name in enumerate(self.children_names): if name != that.children_names[i]: raise ValueError( "Two adding Table do not have the same children columns " "(order must be the same too)." ) ############################################# # Algorithm # def add_internal(this, that, names): if that is not None: for key in that.keys(): if key in this: this[key] += that[key] else: this[key] = that[key] return Table(this, names=names, _internal_=True) ############################################ # MultiTable handeling if self.columns.is_multitable(): return Table( { k: add_internal(table.copy(), that[k], self.children_names) for k, table in self.items() }, self.names, _internal_=True, ) return add_internal(self.copy(), that, self.names) def total(self): if self.columns.is_multitable(): return {k: table.total() for k, table in self.items()} return sum(self.values()) def normalise(self): if self.columns.is_multitable(): for k, total in self.total().items(): if total == 0: continue table = self[k] for k2 in table: table[k2] /= total else: total = self.total() if total != 0: for k in self.keys(): self[k] /= total def __mul__(self, right): """Multiplies a table with this one. P(X, Y) * k -> P(X, Y) P(X) * P(Y, Z) -> P(X, Y, Z) Args: right ([type]): [description] Raises: ValueError: [description] Returns: [type]: [description] """ if not isinstance(right, Table): raise ValueError("The 'right' argument must be a 'Table'.") (rows, names) = self._product_(right) return Table(rows, names, _internal_=True) def __rmul__(self, left): """Multiplies a table with this one. k * P(X, Y) -> P(X, Y) P(X) * P(Y, Z) -> P(X, Y, Z) Args: right ([type]): [description] Raises: ValueError: [description] Returns: [type]: [description] """ if not isinstance(left, Table): raise ValueError("The 'right' argument must be a 'Table'.") (rows, names) = left._product_(self) return Table(rows, names, _internal_=True) def __add__(self, right): return self.add(right) def prod_right(table, key2, value2): # Product a table with kay and value if value2 is None: return {} return {key1 + key2: value1 * value2 for key1, value1 in table.items()} def prod_left(table, key2, value2): # Product a table with kay and value if value2 is None: return {} return {key2 + key1: value1 * value2 for key1, value1 in table.items()} def multi_table_to_table_product(left, right, all_ordered_names): """Multiply two tables. P(X, Y | Z) * P(Z) -> P(X, Y, Z) P(X, Y | Z, W) * P(Z) -> P(X, Y, Z | W) """ # Case P(X, Y | Z) * P(Z) -> P(X, Y, Z) if list(left.names) == list(right.names): return Table( ChainMap( *[ prod_right(table, key2=k, value2=right[k]) for k, table in left.items() ] ), left.columns.children_names + left.names, _internal_=True, ) # Case P(X, Y | Z, W) * P(Z) -> P(X, Y, Z | W) for name in right.names: if not left.columns: raise ValueError( f"Column name '{name}'in right table is not defined on " "conditioned columns of the left Table (name mismatched)." ) # e.g. P(X, Y | Z, W) * P(Z) : indices of [W] indices = [i for i, name in enumerate(left.names) if name not in right.names] # e.g. P(X, Y | Z, W) * P(Z) : indices of [Z] compliment_indices = [i for i in range(left.columns.size) if i not in indices] # e.g. P(X, Y | Z, W) * P(Z) : [W] reduced_names = [left.names[i] for i in indices] children_names = [ names for names in all_ordered_names if names not in reduced_names ] def reduced_key(key): # Method to split the keys return {left.names[i]: key[i] for i in indices} def compliment_key(key): # Method to make a split key return RowKey(*[key[i] for i in compliment_indices]) # Case: P(X, Y | Z, W) * P(Z) -> P(X, Y, Z | W) if right.columns.size == len(indices): return MultiTable( ChainMap( *[ prod_right(table, key2=k, value2=right[k]) for k, table in left.items() ] ), reduced_names, _children_names_=children_names, ) return MultiTable( { compliment_key(k): table * right.reduce(**reduced_key(k)) for k, table in left.items() }, reduced_names, _children_names_=children_names, ) def table_to_multi_table_product(left, right, all_ordered_names): """Multiply two tables. P(Z) * P(X, Y | Z) -> P(Z, X, Y) P(Z) * P(X, Y | Z, W) -> P(Z, X, Y | W) """ # Case P(Z) * P(X, Y | Z) -> P(Z, X, Y) if list(left.names) == list(right.names): return Table( ChainMap( *[ prod_left(table, key2=k, value2=left[k]) for k, table in right.items() ] ), right.names + right.columns.children_names, _internal_=True, ) # Case P(Z) * P(X, Y | Z, W) -> P(Z, X, Y | W) for name in left.names: if not right.columns: raise ValueError( f"Column name '{name}'in left table is not defined on " "conditioned columns of the right Table (name mismatched)." ) # e.g. P(Z) * P(X, Y | Z, W) : indices of [W] indices = [i for i, name in enumerate(right.names) if name not in left.names] # e.g. P(Z) * P(X, Y | Z, W) : indices of [Z] compliment_indices = [i for i in range(right.columns.size) if i not in indices] # e.g. P(Z) * P(X, Y | Z, W) : [W] reduced_names = [right.names[i] for i in indices] children_names = [ names for names in all_ordered_names if names not in reduced_names ] def reduced_key(key): # Method to split the keys return {right.names[i]: key[i] for i in indices} def compliment_key(key): # Method to make a split key return RowKey(*[key[i] for i in compliment_indices]) # Case: P(Z) * P(X, Y | Z, W) -> P(Z, X, Y | W) if left.columns.size == len(indices): return MultiTable( ChainMap( *[ prod_left(table, key2=k, value2=left[k]) for k, table in right.items() ] ), reduced_names, _children_names_=children_names, ) return MultiTable( { compliment_key(k): table * left.reduce(**reduced_key(k)) for k, table in right.items() }, reduced_names, _children_names_=children_names, ) def multi_table_to_multi_table_product(table_main, table_side, all_ordered_names): indices = [ i for i, name in enumerate(table_main.names) if name not in table_side.names ] compliment_indices = [i for i in range(table_main.columns.size) if i not in indices] reduced_names = [table_main.names[i] for i in compliment_indices] children_names = [ names for names in all_ordered_names if names not in reduced_names ] def reduced_key(key): # Method to split the keys return {table_main.names[i]: key[i] for i in indices} def compliment_key(key): # Method to split the keys return RowKey(*[key[i] for i in compliment_indices]) if len(table_side.columns.children_names) == len(indices): def prod2(key1, table1): table_side_table2 = table_side[key1] if table_side_table2 is None: return {} return { compliment_key(key1): table1 * table2 for key2, table2 in table_side_table2 } return MultiTable( ChainMap(*[prod2(key1, table1) for key1, table1 in table_main.items()]), reduced_names, _children_names_=children_names, ) return MultiTable( { compliment_key(key1): table1 * table2 for key1, table1 in table_main.items() for key2, table2 in table_side.reduce(**reduced_key(key1)) }, reduced_names, _children_names_=children_names, ) def multi_table_product(left, right): """Multiply two tables. P(X, Y | Z) * P(Z) -> P(X, Y , Z) P(X, Y | Z, W) * P(Z) -> P(X, Y , Z | W) P(X, Y | Z, U) * P(Z | U) -> P(X, Y , Z | U) P(X, Y | Z, U, W) * P(Z | U, W) -> P(X, Y , Z | U, W) in the case of two conditionals, the longer one defines the order of variables e.g. P(X, Y | Z, U, W) * P(Z | W, U) -> P(X, Y , Z | U, W) P(Z | W, U) * P(X, Y | Z, U, W) -> P(X, Y , Z | U, W) Args: left ([type]): [description] right ([type]): [description] Raises: ValueError: [description] Returns: [type]: [description] """ # Cases: # P(X, Y | Z) * P(Z) -> P(X, Y, Z) # P(X, Y | Z, W) * P(Z) -> P(X, Y, Z | W) if not isinstance(right, MultiTable): if sorted(right.names) != sorted(left.names): raise ValueError("The right names is" " not equal to conditionals of left.") all_ordered_names = left.columns.children_names + right.columns.names return multi_table_to_table_product(left, right, all_ordered_names) # Cases: # P(Z) * P(X, Y | Z) -> P(Z, X, Y) # P(Z) * P(X, Y | Z, W) -> P(Z, X, Y | W) if not isinstance(left, MultiTable): if sorted(right.names) != sorted(left.names): raise ValueError("The left names is" " not equal to conditionals of right.") all_ordered_names = left.names + right.columns.children_names return table_to_multi_table_product(left, right, all_ordered_names) # Cases: # P(X, Y | Z, U) * P(Z | U) -> P(X, Y, Z | U) # P(X, Y | Z, U, W) * P(Z | U, W) -> P(X, Y, Z | U, W) # P(X, Y, Z| U, W) * P(U | W) -> P(X, Y, Z, U | W # P(X, Y, Z| U, V, W) * P(U, V | W) -> P(X, Y, Z, U, V | W) def in_the_other(first, second): for name in first: if name not in second: return False return True common_conditions = [name for name in left.names if name in right.names] right_compliment_conditions = [ name for name in right.names if name not in common_conditions ] left_compliment_conditions = [ name for name in left.names if name not in common_conditions ] # To check the crossed cases # e.g. P(X | Y) * P(Y | X) # after removing common names on conditionals, # one of them must remains conditionless # e.g. # 1) P(X, Y | Z, U) * P(Z | U) # removes commons: P(X, Y | Z) * P(Z) # 2) P(Z | U, W) * P(X, Y | Z, U, W) # removes commons: P(Z) * P(X, Y | Z) # 3) P(X | Y) * P(Y | X) # remove commons fails if len(right_compliment_conditions) == 0: if not in_the_other(right.columns.children_names, left.names): raise ValueError( "Columns in right is not defined in conditional names of left." ) all_ordered_names = left.columns.children_names + right.columns.children_names return multi_table_to_multi_table_product(left, right, all_ordered_names) elif len(left_compliment_conditions) == 0: if not in_the_other(left.columns.children_names, right.names): raise ValueError( "Columns in left is not defined in conditional names of right." ) all_ordered_names = left.columns.children_names + right.columns.children_names return multi_table_to_multi_table_product(right, left, all_ordered_names) else: raise ValueError("Columns and conditional names mismatch.") class MultiTable(Table): def __init__(self, rows, names=None, _children_names_=None): super().__init__( rows, names, _internal_=True, _children_names_=_children_names_ ) def marginal(self, *args, normalise=True): """[summary] P(X, Y | Z) -> P(X | Z) or P(Y | Z) Args: normalise (bool, optional): [description]. Defaults to True. Raises: ValueError: [description] Returns: MultiTable: [description] """ for name in args: if name in self.names: raise ValueError(f"Cannot marginalize on conditioned columns:'{name}'.") table = Table( { k: table.marginal(*args, normalise=normalise) for k, table in self.items() }, self.names, _internal_=True, ) if normalise: table.normalise() return table def condition_on(self, *args, normalise=True): """Creates the conditional based on the provided names of columns. P(X, Y | Z) -> P(X | Y, Z) or P(Y | X, Z) Args: args (list): List of names of provided random variables. Raises: ValueError: If the provided RV names do not exist in the distribution. Returns: (row, names) """ for name in args: if name in self.names: raise ValueError(f"Cannot condition on conditioned columns:'{name}'.") conditioned_children = ( (k, table.condition_on(*args, normalise=normalise)) for k, table in self.items() ) return MultiTable( { key2 + key1: table for key1, key2_table in conditioned_children for key2, table in key2_table.items() }, # It results in: P(X, Y | Z) -> P(X | Y, Z) # inversing the order turns it P(X, Y | Z) -> P(X | Z, Y) # Maybe more controls is needed here list(args) + self.names, ) def reduce(self, **kwargs): """Reduce the Table by one or more columns. P(X, Y | Z) -> P(X = x, Y | Z) or P(X, Y = y | Z) Args: kwargs (dict): A dictionary that its 'key' is the name of the column and its 'value' is the value that must be reduced by. Raises: ValueError: If the provided names do not exist in the Table. Returns: [Table]: A reduce Table. """ return MultiTable( {k: table.reduce(**kwargs) for k, table in self.items()}, self.names, ) def __mul__(self, right): if not isinstance(right, Table): raise ValueError("The 'right' argument must be a 'Table'.") return multi_table_product(self, right) def __rmul__(self, left): if not isinstance(left, Table): raise ValueError("The 'left' argument must be a 'Table'.") return multi_table_product(left, self)
[ "probability.RowKey", "numpy.max", "operator.itemgetter", "numpy.all", "probability.TableColumns" ]
[((14467, 14529), 'numpy.all', 'np.all', (['(arr_counter[:, columns_info.indices] == values)'], {'axis': '(1)'}), '(arr_counter[:, columns_info.indices] == values, axis=1)\n', (14473, 14529), True, 'import numpy as np\n'), ((16044, 16075), 'numpy.max', 'np.max', (['arr_len[:, :-1]'], {'axis': '(0)'}), '(arr_len[:, :-1], axis=0)\n', (16050, 16075), True, 'import numpy as np\n'), ((23022, 23067), 'probability.RowKey', 'RowKey', (['*[key[i] for i in compliment_indices]'], {}), '(*[key[i] for i in compliment_indices])\n', (23028, 23067), False, 'from probability import RowKey\n'), ((25228, 25273), 'probability.RowKey', 'RowKey', (['*[key[i] for i in compliment_indices]'], {}), '(*[key[i] for i in compliment_indices])\n', (25234, 25273), False, 'from probability import RowKey\n'), ((26548, 26593), 'probability.RowKey', 'RowKey', (['*[key[i] for i in compliment_indices]'], {}), '(*[key[i] for i in compliment_indices])\n', (26554, 26593), False, 'from probability import RowKey\n'), ((2490, 2562), 'probability.TableColumns', 'TableColumns', ([], {'names': 'names', 'children_names': 'value_sample.names', 'table': 'self'}), '(names=names, children_names=value_sample.names, table=self)\n', (2502, 2562), False, 'from probability import TableColumns\n'), ((16104, 16126), 'numpy.max', 'np.max', (['arr_len[:, -1]'], {}), '(arr_len[:, -1])\n', (16110, 16126), True, 'import numpy as np\n'), ((2773, 2829), 'probability.TableColumns', 'TableColumns', ([], {'names': 'names', 'children_names': '[]', 'table': 'self'}), '(names=names, children_names=[], table=self)\n', (2785, 2829), False, 'from probability import TableColumns\n'), ((2934, 3004), 'probability.TableColumns', 'TableColumns', ([], {'names': 'names', 'children_names': '_children_names_', 'table': 'self'}), '(names=names, children_names=_children_names_, table=self)\n', (2946, 3004), False, 'from probability import TableColumns\n'), ((9663, 9679), 'probability.RowKey', 'RowKey', (['row[:-1]'], {}), '(row[:-1])\n', (9669, 9679), False, 'from probability import RowKey\n'), ((9896, 9909), 'operator.itemgetter', 'itemgetter', (['(0)'], {}), '(0)\n', (9906, 9909), False, 'from operator import itemgetter\n'), ((11646, 11679), 'probability.RowKey', 'RowKey', (['row[columns_info.indices]'], {}), '(row[columns_info.indices])\n', (11652, 11679), False, 'from probability import RowKey\n'), ((11697, 11741), 'probability.RowKey', 'RowKey', (['row[columns_info.complimnet_indices]'], {}), '(row[columns_info.complimnet_indices])\n', (11703, 11741), False, 'from probability import RowKey\n'), ((12125, 12141), 'operator.itemgetter', 'itemgetter', (['(0)', '(1)'], {}), '(0, 1)\n', (12135, 12141), False, 'from operator import itemgetter\n'), ((15005, 15021), 'probability.RowKey', 'RowKey', (['row[:-1]'], {}), '(row[:-1])\n', (15011, 15021), False, 'from probability import RowKey\n'), ((15230, 15243), 'operator.itemgetter', 'itemgetter', (['(0)'], {}), '(0)\n', (15240, 15243), False, 'from operator import itemgetter\n'), ((647, 672), 'operator.itemgetter', 'itemgetter', (['groupby_index'], {}), '(groupby_index)\n', (657, 672), False, 'from operator import itemgetter\n'), ((1300, 1356), 'probability.TableColumns', 'TableColumns', ([], {'names': 'names', 'children_names': '[]', 'table': 'self'}), '(names=names, children_names=[], table=self)\n', (1312, 1356), False, 'from probability import TableColumns\n'), ((1519, 1589), 'probability.TableColumns', 'TableColumns', ([], {'names': 'names', 'children_names': '_children_names_', 'table': 'self'}), '(names=names, children_names=_children_names_, table=self)\n', (1531, 1589), False, 'from probability import TableColumns\n'), ((1746, 1755), 'probability.RowKey', 'RowKey', (['k'], {}), '(k)\n', (1752, 1755), False, 'from probability import RowKey\n'), ((10313, 10326), 'operator.itemgetter', 'itemgetter', (['(0)'], {}), '(0)\n', (10323, 10326), False, 'from operator import itemgetter\n'), ((12771, 12784), 'operator.itemgetter', 'itemgetter', (['(0)'], {}), '(0)\n', (12781, 12784), False, 'from operator import itemgetter\n'), ((1870, 1879), 'probability.RowKey', 'RowKey', (['k'], {}), '(k)\n', (1876, 1879), False, 'from probability import RowKey\n'), ((12538, 12551), 'operator.itemgetter', 'itemgetter', (['(1)'], {}), '(1)\n', (12548, 12551), False, 'from operator import itemgetter\n'), ((15593, 15606), 'operator.itemgetter', 'itemgetter', (['(0)'], {}), '(0)\n', (15603, 15606), False, 'from operator import itemgetter\n')]
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy from functools import partial import numpy as np import scipy from addict import Dict from ....algorithms.quantization import utils as eu from ....engines.ac_engine import ACEngine from ....graph.model_utils import get_nodes_by_type from ....graph.node_utils import get_all_node_outputs from ....graph.utils import find_operation_matches from ....samplers.creator import create_sampler SPECIAL_METRICS = ['cmc', 'reid_map', 'pairwise_accuracy_subsets', 'pairwise_accuracy', 'normalized_embedding_accuracy', 'face_recognition_tafa_pair_metric', 'localization_recall', 'coco_orig_keypoints_precision', 'coco_orig_segm_precision', 'coco_orig_keypoints_precision'] METRICS_CONFIGS = {'sigmoid_recom_loss': {'metrics': 'log_loss', 'postprocessing': 'sigmoid_normalize_recommendation'}, 'coco_precision': {'metrics': 'coco_precision'}, 'coco_segm_precision': {'metrics': 'coco_segm_precision'}} METRIC2PROXY_METRIC = { 'hit_ratio': { 'persample': 'sigmoid_recom_loss', 'ranking': 'sigmoid_recom_loss' }, 'ndcg': { 'persample': 'sigmoid_recom_loss', 'ranking': 'sigmoid_recom_loss' }, 'coco_orig_precision': { 'persample': 'coco_precision' }, 'coco_orig_keypoints_precision': { 'persample': 'coco_precision' }, 'coco_orig_segm_precision': { 'persample': 'coco_segm_precision' } } def create_metric_config(engine, algo_config: Dict, force_logit_comparison=False, logit_distance_type='cosine') -> Dict: def create_metric_params(metric_name): engine_metrics_attributes = engine.get_metrics_attributes() if metric_name not in engine_metrics_attributes: RuntimeError('Couldn\'t create metric parameters. ' 'Metric {} not registered in the engine.'.format(metric_name)) params = Dict() params.name = metric_name params.type = engine_metrics_attributes[metric_name]['type'] params.is_special = (params.type in SPECIAL_METRICS) or force_logit_comparison if engine_metrics_attributes[metric_name]['direction'] == 'higher-better': params.comparator = (lambda a: a) elif engine_metrics_attributes[metric_name]['direction'] == 'higher-worse': params.comparator = (lambda a: -a) else: raise ValueError('Unexpected {} metric direction value.'.format(metric_name)) params.sort_fn = partial(sort_by_logit_distance, distance=logit_distance_type) \ if params.is_special else partial(sort_by_metric_difference, comp_fn=params.comparator) return params def metric_to_proxy_map(metrics): """Determines which metrics need proxy metrics and creates metrics to proxy metrics map. :param metrics: optimizable metrics names :returns a dictionary of metrics to proxy metrics mapping {metric_name: 'persample': proxy_name, 'ranking': proxy_name} a list of proxy metrics names to register """ def update_proxy_list(proxy_metric_name): """Updates a list of proxy metrics names to register. :return a proxy metric name in accordance with the engine naming """ proxy_config = METRICS_CONFIGS.get(proxy_metric_name, {}) metric_config = proxy_config.get('metrics') postprocessing_config = proxy_config.get('postprocessing') if metric_config or postprocessing_config: to_register.add(proxy_metric_name) return metric_name_from_config(metric_config) match_names_config = Dict({metric_name: {} for metric_name in metrics}) to_register = set() for metric_name, metric_type in metrics: if metric_type in METRIC2PROXY_METRIC: persample_metric_name = METRIC2PROXY_METRIC[metric_type].get('persample') persample_proxy_metric_name = update_proxy_list(persample_metric_name) if persample_proxy_metric_name: match_names_config[metric_name].persample = persample_proxy_metric_name ranking_metric_name = METRIC2PROXY_METRIC[metric_type].get('ranking') ranking_proxy_metric_name = update_proxy_list(ranking_metric_name) if ranking_proxy_metric_name: match_names_config[metric_name].ranking = ranking_proxy_metric_name return match_names_config, list(to_register) metrics_attributes = engine.get_metrics_attributes() # configure which metrics to optimize if algo_config.metrics: metrics_names = [] for metric in algo_config.metrics: metric_type = metric.type if metric.type else metric.name metrics_names.append((metric.name, metric_type)) else: metrics_names = [(metric_name, metric_attr.get('type', metric_name)) for metric_name, metric_attr in metrics_attributes.items()] # register proxy metrics metrics_to_proxy_map, metrics_to_register = metric_to_proxy_map(metrics_names) register_metrics(engine, metrics_to_register) metrics_config = Dict() for metric, _ in metrics_names: persample_name = metrics_to_proxy_map[metric].get('persample', metric) ranking_name = metrics_to_proxy_map[metric].get('ranking', metric) metrics_config[metric].persample = create_metric_params(persample_name) metrics_config[metric].ranking = create_metric_params(ranking_name) metrics_config[metric].update(create_metric_params(metric)) return metrics_config def metric_name_from_config(metric_config): if isinstance(metric_config, str): return metric_config if isinstance(metric_config, dict): return metric_config.get('name', metric_config['type']) return None def register_metrics(engine, metrics_names: list): """Registers metrics and postprocessing in the engine. :param engine: an engine in which metrics will be registered :param metrics_names: a list of metrics names """ registered_metrics = engine.get_metrics_attributes() for metric in metrics_names: if metric not in METRICS_CONFIGS: raise ValueError('Cannot register metric. Unsupported name {}.'.format(metric)) proxy_config = METRICS_CONFIGS.get(metric, {}) if 'metrics' in proxy_config: metric_config = proxy_config['metrics'] if metric_name_from_config(metric_config) not in registered_metrics: register_metric(engine, metric_config) if 'postprocessing' in proxy_config: postprocessing_config = proxy_config['postprocessing'] register_postprocessing(engine, postprocessing_config) def sort_by_logit_distance(u, v, reverse=False, distance='cosine'): if len(u) != len(v): raise RuntimeError('Cannot compare samples. ' 'Lists of per-sample metric results should be the same length.') kd_distance = lambda u, v: scipy.stats.entropy(scipy.special.softmax(u), scipy.special.softmax(v)) mse_distance = lambda u, v: np.mean((u - v) ** 2) distance_function = { 'cosine': scipy.spatial.distance.cosine, 'kd': kd_distance, 'mse': mse_distance, } distance_between_samples = np.array([distance_function[distance](ui.flatten(), vi.flatten()) for ui, vi in zip(u, v)]) sorted_arr = np.argsort(distance_between_samples) if reverse: sorted_arr = np.flip(sorted_arr) return sorted_arr def sort_by_metric_difference(u, v, comp_fn=lambda a: a, reverse=False): if len(u) != len(v): raise RuntimeError('Cannot compare samples. ' 'Lists of per-sample metric results should be the same length.') u = np.asarray(u) v = np.asarray(v) sorted_arr = np.argsort(comp_fn(u - v)) if reverse: sorted_arr = np.flip(sorted_arr) return sorted_arr def register_metric(engine, metric_config): if isinstance(engine, ACEngine): engine.add_metric(metric_config) else: raise NotImplementedError('{} engine cannot register new metrics.' .format(type(engine).__name__)) def register_postprocessing(engine, postprocessing_config): if isinstance(engine, ACEngine): engine.add_postprocessing(postprocessing_config) else: raise NotImplementedError('{} engine cannot register new postprocessing.' .format(type(engine).__name__)) def is_preset_performance(config: Dict): if config.weights.mode == 'symmetric' and config.activations.mode == 'symmetric': return True if config.weights.mode == 'asymmetric' or config.activations.mode == 'asymmetric': return False if config.preset == 'performance': return True return False def get_mixed_preset_config(config: Dict): config = deepcopy(config) config.update(preset='mixed') if config.activations.mode: config.activations.mode = 'asymmetric' if config.weights.mode: config.weights.mode = 'symmetric' return config def get_num_of_quantized_ops(model, quantizable_operations): quantized_ops = set() nodes_to_see = [] for fq_node in get_nodes_by_type(model, ['FakeQuantize']): nodes_to_see.extend(get_all_node_outputs(fq_node)) while nodes_to_see: child = nodes_to_see.pop() if find_operation_matches(quantizable_operations, child): quantized_ops.add(child) continue nodes_to_see.extend(get_all_node_outputs(child)) return len(quantized_ops) def evaluate_model( model, engine, dataset_size, subset_indices=None, print_progress=True, metrics_config=None, per_sample_subset_indices=None, output_node_name=None, stats_layout=None, ): """Evaluates the model and processes metrics values :param model: model to evaluate :param subset_indices: image indices to evaluate on. If None evaluate on whole dataset :param per_sample_subset_indices: image indices for which to return per-sample metrics. If None for all predicted images :param print_progress: Whether to print inference progress :returns a dictionary of predicted metrics {metric_name: value} a dictionary of per-sample metrics values {metric_name: [values]} """ engine.set_model(model) eu.select_evaluation_dataset(engine) if not subset_indices: subset_indices = range(dataset_size) index_sampler = create_sampler(engine, samples=subset_indices) (metrics_per_sample, metrics), raw_output = engine.predict(stats_layout=stats_layout, sampler=index_sampler, metric_per_sample=True, print_progress=print_progress) raw_output = process_raw_output(raw_output, output_node_name) metrics_per_sample = process_per_sample_metrics(metrics_per_sample, metrics_config, per_sample_subset_indices, raw_output=raw_output) metrics = dict((name, value) for name, value in metrics.items() if name in metrics_config) eu.reset_dataset_to_default(engine) return metrics, metrics_per_sample def process_raw_output(output, output_node_name): if not output: return [] return output[output_node_name]['output_logits'] def process_per_sample_metrics(metrics_per_sample, metrics_config, indices=None, raw_output=None): """Creates a dictionary of per-sample metrics values {metric_name: [values]} :param metrics_per_sample: list of per-sample metrics :param indices: indices of samples to be considered. All if None :param raw_output: raw output from the model :return processed dictionary """ metrics_to_keep = {config.persample.name: config.persample for config in metrics_config.values()} if not metrics_to_keep: return {} processed_metrics_per_sample = dict((name, []) for name in metrics_to_keep) for metric_name, metric_params in metrics_to_keep.items(): if metric_params.is_special: processed_metrics_per_sample[metric_name] = raw_output for value in metrics_per_sample: if value['metric_name'] in metrics_to_keep: if metrics_to_keep[value['metric_name']].is_special: continue if value['result'] is not None: result_value = np.nanmean(value['result']) else: result_value = None processed_metrics_per_sample[value['metric_name']].append(result_value) # check that all metrics have equal number of samples if not len({len(value) for value in processed_metrics_per_sample.values()}) == 1: raise RuntimeError('Inconsistent number of per-sample metric values') if indices: for name, values in processed_metrics_per_sample.items(): processed_metrics_per_sample[name] = [values[i] for i in indices] return processed_metrics_per_sample
[ "addict.Dict", "numpy.mean", "numpy.flip", "numpy.asarray", "numpy.argsort", "numpy.nanmean", "functools.partial", "copy.deepcopy", "scipy.special.softmax" ]
[((5558, 5564), 'addict.Dict', 'Dict', ([], {}), '()\n', (5562, 5564), False, 'from addict import Dict\n'), ((7929, 7965), 'numpy.argsort', 'np.argsort', (['distance_between_samples'], {}), '(distance_between_samples)\n', (7939, 7965), True, 'import numpy as np\n'), ((8299, 8312), 'numpy.asarray', 'np.asarray', (['u'], {}), '(u)\n', (8309, 8312), True, 'import numpy as np\n'), ((8321, 8334), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (8331, 8334), True, 'import numpy as np\n'), ((9438, 9454), 'copy.deepcopy', 'deepcopy', (['config'], {}), '(config)\n', (9446, 9454), False, 'from copy import deepcopy\n'), ((2174, 2180), 'addict.Dict', 'Dict', ([], {}), '()\n', (2178, 2180), False, 'from addict import Dict\n'), ((4016, 4066), 'addict.Dict', 'Dict', (['{metric_name: {} for metric_name in metrics}'], {}), '({metric_name: {} for metric_name in metrics})\n', (4020, 4066), False, 'from addict import Dict\n'), ((7587, 7608), 'numpy.mean', 'np.mean', (['((u - v) ** 2)'], {}), '((u - v) ** 2)\n', (7594, 7608), True, 'import numpy as np\n'), ((8003, 8022), 'numpy.flip', 'np.flip', (['sorted_arr'], {}), '(sorted_arr)\n', (8010, 8022), True, 'import numpy as np\n'), ((8416, 8435), 'numpy.flip', 'np.flip', (['sorted_arr'], {}), '(sorted_arr)\n', (8423, 8435), True, 'import numpy as np\n'), ((2763, 2824), 'functools.partial', 'partial', (['sort_by_logit_distance'], {'distance': 'logit_distance_type'}), '(sort_by_logit_distance, distance=logit_distance_type)\n', (2770, 2824), False, 'from functools import partial\n'), ((2865, 2926), 'functools.partial', 'partial', (['sort_by_metric_difference'], {'comp_fn': 'params.comparator'}), '(sort_by_metric_difference, comp_fn=params.comparator)\n', (2872, 2926), False, 'from functools import partial\n'), ((7452, 7476), 'scipy.special.softmax', 'scipy.special.softmax', (['u'], {}), '(u)\n', (7473, 7476), False, 'import scipy\n'), ((7529, 7553), 'scipy.special.softmax', 'scipy.special.softmax', (['v'], {}), '(v)\n', (7550, 7553), False, 'import scipy\n'), ((13422, 13449), 'numpy.nanmean', 'np.nanmean', (["value['result']"], {}), "(value['result'])\n", (13432, 13449), True, 'import numpy as np\n')]
from collections import defaultdict import time from joblib import Parallel, delayed from multiprocessing import cpu_count from math import ceil import torch from torch import nn import torch.multiprocessing as mp import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from torch.utils.data.distributed import DistributedSampler from nltk.corpus import stopwords from transformers import AdamW, get_linear_schedule_with_warmup # ================================================================================= #from transformers.models.camembert.tokenization_camembert import CamembertTokenizer from transformers import BertTokenizer # ================================================================================= import numpy as np import os import shutil import sys from tqdm import tqdm from LOTClass.bert.model import LOTClassModel import warnings warnings.filterwarnings("ignore") class LOTClassTrainer(object): def __init__(self, args): self.args = args self.verbose = args.verbose self.max_len = args.max_len self.dataset_dir = args.dataset_dir self.dist_port = args.dist_port self.num_cpus = min(10, cpu_count() - 1) if cpu_count() > 1 else 1 self.world_size = args.gpus self.train_batch_size = args.train_batch_size self.eval_batch_size = args.eval_batch_size self.accum_steps = args.accum_steps eff_batch_size = self.train_batch_size * self.world_size * self.accum_steps assert abs(eff_batch_size - 128) < 10, f"Make sure the effective training batch size is around 128, current: {eff_batch_size}" print(f"Effective training batch size: {eff_batch_size}") self.pretrained_lm = args.pretrained_lm self.tokenizer = BertTokenizer.from_pretrained(self.pretrained_lm, do_lower_case=True) #self.tokenizer = CamembertTokenizer.from_pretrained(self.pretrained_lm, force_download=True) self.vocab = self.tokenizer.get_vocab() self.vocab_size = len(self.vocab) self.mask_id = self.vocab[self.tokenizer.mask_token] self.inv_vocab = {k:v for v, k in self.vocab.items()} self.read_label_names(args.dataset_dir, args.label_names_file) self.num_class = len(self.label_name_dict) self.model = LOTClassModel.from_pretrained(self.pretrained_lm, output_attentions=False, output_hidden_states=False, num_labels=self.num_class) self.read_data(args.dataset_dir, args.train_file, args.test_file, args.test_label_file) self.with_test_label = True if args.test_label_file is not None else False self.temp_dir = f'tmp_{self.dist_port}' self.mcp_loss = nn.CrossEntropyLoss() self.st_loss = nn.KLDivLoss(reduction='batchmean') self.update_interval = args.update_interval self.early_stop = args.early_stop # set up distributed training def set_up_dist(self, rank): dist.init_process_group( backend='nccl', init_method=f'tcp://localhost:{self.dist_port}', world_size=self.world_size, rank=rank ) # create local model model = self.model.to(rank) model = DDP(model, device_ids=[rank], find_unused_parameters=True) return model # get document truncation statistics with the defined max length def corpus_trunc_stats(self, docs): doc_len = [] for doc in docs: input_ids = self.tokenizer.encode(doc, add_special_tokens=True) doc_len.append(len(input_ids)) print(f"Document max length: {np.max(doc_len)}, avg length: {np.mean(doc_len)}, std length: {np.std(doc_len)}") trunc_frac = np.sum(np.array(doc_len) > self.max_len) / len(doc_len) print(f"Truncated fraction of all documents: {trunc_frac}") # convert a list of strings to token ids def encode(self, docs): encoded_dict = self.tokenizer.batch_encode_plus(docs, add_special_tokens=True, max_length=self.max_len, padding='max_length', return_attention_mask=True, truncation=True, return_tensors='pt') input_ids = encoded_dict['input_ids'] if self.verbose: print(f"input_ids size (from encode): {input_ids.size()}") print(f"input_ids (from encode): {input_ids}") attention_masks = encoded_dict['attention_mask'] return input_ids, attention_masks # convert list of token ids to list of strings def decode(self, ids): strings = self.tokenizer.batch_decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False) return strings # convert dataset into tensors def create_dataset(self, dataset_dir, text_file, label_file, loader_name, find_label_name=False, label_name_loader_name=None): loader_file = os.path.join(dataset_dir, loader_name) if os.path.exists(loader_file): print(f"Loading encoded texts from {loader_file}") data = torch.load(loader_file) else: print(f"Reading texts from {os.path.join(dataset_dir, text_file)}") corpus = open(os.path.join(dataset_dir, text_file), encoding="utf-8") docs = [doc.strip() for doc in corpus.readlines()] print(f"Converting texts into tensors.") chunk_size = ceil(len(docs) / self.num_cpus) chunks = [docs[x:x+chunk_size] for x in range(0, len(docs), chunk_size)] results = Parallel(n_jobs=self.num_cpus)(delayed(self.encode)(docs=chunk) for chunk in chunks) input_ids = torch.cat([result[0] for result in results]) print(f"Concatenated input_ids size: {input_ids.size()}") attention_masks = torch.cat([result[1] for result in results]) print(f"Saving encoded texts into {loader_file}") if label_file is not None: print(f"Reading labels from {os.path.join(dataset_dir, label_file)}") truth = open(os.path.join(dataset_dir, label_file)) labels = [int(label.strip()) for label in truth.readlines()] labels = torch.tensor(labels) data = {"input_ids": input_ids, "attention_masks": attention_masks, "labels": labels} else: data = {"input_ids": input_ids, "attention_masks": attention_masks} torch.save(data, loader_file) if find_label_name: loader_file = os.path.join(dataset_dir, label_name_loader_name) if os.path.exists(loader_file): print(f"Loading texts with label names from {loader_file}") label_name_data = torch.load(loader_file) else: print(f"Reading texts from {os.path.join(dataset_dir, text_file)}") corpus = open(os.path.join(dataset_dir, text_file), encoding="utf-8") docs = [doc.strip() for doc in corpus.readlines()] print("Locating label names in the corpus.") chunk_size = ceil(len(docs) / self.num_cpus) chunks = [docs[x:x+chunk_size] for x in range(0, len(docs), chunk_size)] results = Parallel(n_jobs=self.num_cpus)(delayed(self.label_name_occurrence)(docs=chunk) for chunk in chunks) input_ids_with_label_name = torch.cat([result[0] for result in results]) attention_masks_with_label_name = torch.cat([result[1] for result in results]) label_name_idx = torch.cat([result[2] for result in results]) print(f"Concatenated input_ids_with_label_name size: {input_ids_with_label_name.size()}") assert len(input_ids_with_label_name) > 0, "No label names appear in corpus!" label_name_data = {"input_ids": input_ids_with_label_name, "attention_masks": attention_masks_with_label_name, "labels": label_name_idx} loader_file = os.path.join(dataset_dir, label_name_loader_name) print(f"Saving texts with label names into {loader_file}") torch.save(label_name_data, loader_file) return data, label_name_data else: return data # find label name indices and replace out-of-vocab label names with [MASK] def label_name_in_doc(self, doc): doc = self.tokenizer.tokenize(doc) if self.verbose: print(doc) label_idx = -1 * torch.ones(self.max_len, dtype=torch.long) new_doc = [] wordpcs = [] idx = 1 # index starts at 1 due to [CLS] token for i, wordpc in enumerate(doc): wordpcs.append(wordpc[2:] if wordpc.startswith("##") else wordpc) if self.verbose: print(wordpcs) if idx >= self.max_len - 1: # last index will be [SEP] token break if i == len(doc) - 1 or not doc[i+1].startswith("##"): word = ''.join(wordpcs) if word in self.label2class: label_idx[idx] = self.label2class[word] # replace label names that are not in tokenizer's vocabulary with the [MASK] token if word not in self.vocab: wordpcs = [self.tokenizer.mask_token] new_word = ''.join(wordpcs) if new_word != self.tokenizer.unk_token: idx += len(wordpcs) new_doc.append(new_word) wordpcs = [] if (label_idx >= 0).any(): return ' '.join(new_doc), label_idx else: return None # find label name occurrences in the corpus def label_name_occurrence(self, docs): text_with_label = [] label_name_idx = [] for doc in docs: result = self.label_name_in_doc(doc) if result is not None: text_with_label.append(result[0]) label_name_idx.append(result[1].unsqueeze(0)) if len(text_with_label) > 0: encoded_dict = self.tokenizer.batch_encode_plus(text_with_label, add_special_tokens=True, max_length=self.max_len, padding='max_length', return_attention_mask=True, truncation=True, return_tensors='pt') input_ids_with_label_name = encoded_dict['input_ids'] attention_masks_with_label_name = encoded_dict['attention_mask'] label_name_idx = torch.cat(label_name_idx, dim=0) else: input_ids_with_label_name = torch.ones(0, self.max_len, dtype=torch.long) attention_masks_with_label_name = torch.ones(0, self.max_len, dtype=torch.long) label_name_idx = torch.ones(0, self.max_len, dtype=torch.long) return input_ids_with_label_name, attention_masks_with_label_name, label_name_idx # read text corpus and labels from files def read_data(self, dataset_dir, train_file, test_file, test_label_file): self.train_data, self.label_name_data = self.create_dataset(dataset_dir, train_file, None, "train.pt", find_label_name=True, label_name_loader_name="label_name_data.pt") if test_file is not None: self.test_data = self.create_dataset(dataset_dir, test_file, test_label_file, "test.pt") # read label names from file def read_label_names(self, dataset_dir, label_name_file): label_name_file = open(os.path.join(dataset_dir, label_name_file)) label_names = label_name_file.readlines() self.label_name_dict = {i: [word.lower() for word in category_words.strip().split()] for i, category_words in enumerate(label_names)} print(f"Label names used for each class are: {self.label_name_dict}") self.label2class = {} self.all_label_name_ids = [self.mask_id] self.all_label_names = [self.tokenizer.mask_token] for class_idx in self.label_name_dict: for word in self.label_name_dict[class_idx]: assert word not in self.label2class, f"\"{word}\" used as the label name by multiple classes!" self.label2class[word] = class_idx if word in self.vocab: self.all_label_name_ids.append(self.vocab[word]) self.all_label_names.append(word) # create dataset loader def make_dataloader(self, rank, data_dict, batch_size): if self.verbose: print(f"data_dict['input_ids']: {data_dict['input_ids']}") if "labels" in data_dict: dataset = TensorDataset(data_dict["input_ids"], data_dict["attention_masks"], data_dict["labels"]) else: dataset = TensorDataset(data_dict["input_ids"], data_dict["attention_masks"]) sampler = DistributedSampler(dataset, num_replicas=self.world_size, rank=rank) dataset_loader = DataLoader(dataset, sampler=sampler, batch_size=batch_size, shuffle=False) return dataset_loader # filter out stop words and words in multiple categories def filter_keywords(self, category_vocab_size=100): all_words = defaultdict(list) sorted_dicts = {} for i, cat_dict in self.category_words_freq.items(): sorted_dict = {k:v for k, v in sorted(cat_dict.items(), key=lambda item: item[1], reverse=True)[:category_vocab_size]} sorted_dicts[i] = sorted_dict for word_id in sorted_dict: all_words[word_id].append(i) repeat_words = [] for word_id in all_words: if len(all_words[word_id]) > 1: repeat_words.append(word_id) self.category_vocab = {} for i, sorted_dict in sorted_dicts.items(): self.category_vocab[i] = np.array(list(sorted_dict.keys())) stopwords_vocab = stopwords.words('english') for i, word_list in self.category_vocab.items(): delete_idx = [] for j, word_id in enumerate(word_list): word = self.inv_vocab[word_id] if word in self.label_name_dict[i]: continue if not word.isalpha() or len(word) == 1 or word in stopwords_vocab or word_id in repeat_words: delete_idx.append(j) self.category_vocab[i] = np.delete(self.category_vocab[i], delete_idx) def print_predictions(self, word_list): if not self.verbose: return print(40*'=') print(self.decode(word_list)) print(40*'=') # construct category vocabulary (distributed function) def category_vocabulary_dist(self, rank, top_pred_num=50, loader_name="category_vocab.pt"): if self.world_size > 1: model = self.set_up_dist(rank) else: self.model.to(rank) model = self.model model.eval() label_name_dataset_loader = self.make_dataloader(rank, self.label_name_data, self.eval_batch_size) category_words_freq = {i: defaultdict(float) for i in range(self.num_class)} wrap_label_name_dataset_loader = tqdm(label_name_dataset_loader) if rank == 0 else label_name_dataset_loader try: for batch in wrap_label_name_dataset_loader: with torch.no_grad(): input_ids = batch[0].to(rank) input_mask = batch[1].to(rank) label_pos = batch[2].to(rank) match_idx = label_pos >= 0 if self.verbose: print(match_idx) for input_id in input_ids: self.print_predictions(input_id) for attention_mask in input_mask: print(attention_mask) predictions = model(input_ids, pred_mode="mlm", token_type_ids=None, attention_mask=input_mask) if self.verbose: print(predictions.size()) _, sorted_res = torch.topk(predictions[match_idx], top_pred_num, dim=-1) label_idx = label_pos[match_idx] for i, word_list in enumerate(sorted_res): self.print_predictions(word_list) for j, word_id in enumerate(word_list): category_words_freq[label_idx[i].item()][word_id.item()] += 1 if self.verbose: print(category_words_freq) save_file = os.path.join(self.temp_dir, f"{rank}_"+loader_name) torch.save(category_words_freq, save_file) except RuntimeError as err: self.cuda_mem_error(err, "eval", rank) # construct category vocabulary def category_vocabulary(self, top_pred_num=50, category_vocab_size=100, loader_name="category_vocab.pt"): loader_file = os.path.join(self.dataset_dir, loader_name) if os.path.exists(loader_file): print(f"Loading category vocabulary from {loader_file}") self.category_vocab = torch.load(loader_file) else: print("Contructing category vocabulary.") if not os.path.exists(self.temp_dir): os.makedirs(self.temp_dir) if self.verbose: print(f"Args: ({top_pred_num, loader_name}); World size: {self.world_size}") #mp.spawn(self.category_vocabulary_dist, nprocs=self.world_size, args=(top_pred_num, loader_name)) self.category_vocabulary_dist(0, top_pred_num, loader_name) gather_res = [] for f in os.listdir(self.temp_dir): if f[-3:] == '.pt': gather_res.append(torch.load(os.path.join(self.temp_dir, f))) assert len(gather_res) == self.world_size, "Number of saved files not equal to number of processes!" self.category_words_freq = {i: defaultdict(float) for i in range(self.num_class)} for i in range(self.num_class): for category_words_freq in gather_res: for word_id, freq in category_words_freq[i].items(): self.category_words_freq[i][word_id] += freq self.filter_keywords(category_vocab_size) torch.save(self.category_vocab, loader_file) if os.path.exists(self.temp_dir): shutil.rmtree(self.temp_dir) for i, category_vocab in self.category_vocab.items(): print(f"Class {i} category vocabulary: {[self.inv_vocab[w] for w in category_vocab]}\n") # prepare self supervision for masked category prediction (distributed function) def prepare_mcp_dist(self, rank, top_pred_num=50, match_threshold=20, loader_name="mcp_train.pt"): if self.world_size > 1: model = self.set_up_dist(rank) else: model = self.model model.eval() train_dataset_loader = self.make_dataloader(rank, self.train_data, self.eval_batch_size) all_input_ids = [] all_mask_label = [] all_input_mask = [] category_doc_num = defaultdict(int) wrap_train_dataset_loader = tqdm(train_dataset_loader) if rank == 0 else train_dataset_loader try: for batch in wrap_train_dataset_loader: with torch.no_grad(): input_ids = batch[0].to(rank) input_mask = batch[1].to(rank) predictions = model(input_ids, pred_mode="mlm", token_type_ids=None, attention_mask=input_mask) _, sorted_res = torch.topk(predictions, top_pred_num, dim=-1) for i, category_vocab in self.category_vocab.items(): match_idx = torch.zeros_like(sorted_res).bool() for word_id in category_vocab: match_idx = (sorted_res == word_id) | match_idx match_count = torch.sum(match_idx.int(), dim=-1) valid_idx = (match_count > match_threshold) & (input_mask > 0) valid_doc = torch.sum(valid_idx, dim=-1) > 0 if valid_doc.any(): mask_label = -1 * torch.ones_like(input_ids) mask_label[valid_idx] = i all_input_ids.append(input_ids[valid_doc].cpu()) all_mask_label.append(mask_label[valid_doc].cpu()) all_input_mask.append(input_mask[valid_doc].cpu()) category_doc_num[i] += valid_doc.int().sum().item() all_input_ids = torch.cat(all_input_ids, dim=0) all_mask_label = torch.cat(all_mask_label, dim=0) all_input_mask = torch.cat(all_input_mask, dim=0) save_dict = { "all_input_ids": all_input_ids, "all_mask_label": all_mask_label, "all_input_mask": all_input_mask, "category_doc_num": category_doc_num, } save_file = os.path.join(self.temp_dir, f"{rank}_"+loader_name) torch.save(save_dict, save_file) except RuntimeError as err: self.cuda_mem_error(err, "eval", rank) # prepare self supervision for masked category prediction def prepare_mcp(self, top_pred_num=50, match_threshold=20, loader_name="mcp_train.pt"): loader_file = os.path.join(self.dataset_dir, loader_name) if os.path.exists(loader_file): print(f"Loading masked category prediction data from {loader_file}") self.mcp_data = torch.load(loader_file) else: loader_file = os.path.join(self.dataset_dir, loader_name) print("Preparing self supervision for masked category prediction.") if not os.path.exists(self.temp_dir): os.makedirs(self.temp_dir) #mp.spawn(self.prepare_mcp_dist, nprocs=self.world_size, args=(top_pred_num, match_threshold, loader_name)) self.prepare_mcp_dist(0, top_pred_num, match_threshold, loader_name) gather_res = [] for f in os.listdir(self.temp_dir): if f[-3:] == '.pt': gather_res.append(torch.load(os.path.join(self.temp_dir, f))) assert len(gather_res) == self.world_size, "Number of saved files not equal to number of processes!" all_input_ids = torch.cat([res["all_input_ids"] for res in gather_res], dim=0) all_mask_label = torch.cat([res["all_mask_label"] for res in gather_res], dim=0) all_input_mask = torch.cat([res["all_input_mask"] for res in gather_res], dim=0) category_doc_num = {i: 0 for i in range(self.num_class)} for i in category_doc_num: for res in gather_res: if i in res["category_doc_num"]: category_doc_num[i] += res["category_doc_num"][i] print(f"Number of documents with category indicative terms found for each category is: {category_doc_num}") self.mcp_data = {"input_ids": all_input_ids, "attention_masks": all_input_mask, "labels": all_mask_label} torch.save(self.mcp_data, loader_file) if os.path.exists(self.temp_dir): shutil.rmtree(self.temp_dir) for i in category_doc_num: assert category_doc_num[i] > 10, f"Too few ({category_doc_num[i]}) documents with category indicative terms found for category {i}; " \ "try to add more unlabeled documents to the training corpus (recommend) or reduce `--match_threshold` (not recommend)" print(f"There are totally {len(self.mcp_data['input_ids'])} documents with category indicative terms.") # masked category prediction (distributed function) def mcp_dist(self, rank, epochs=5, loader_name="mcp_model.pt"): if self.world_size > 1: model = self.set_up_dist(rank) else: model = self.model mcp_dataset_loader = self.make_dataloader(rank, self.mcp_data, self.train_batch_size) total_steps = len(mcp_dataset_loader) * epochs / self.accum_steps optimizer = AdamW(filter(lambda p: p.requires_grad, model.parameters()), lr=2e-5, eps=1e-8) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0.1*total_steps, num_training_steps=total_steps) try: for i in range(epochs): model.train() total_train_loss = 0 if rank == 0: print(f"Epoch {i+1}:") wrap_mcp_dataset_loader = tqdm(mcp_dataset_loader) if rank == 0 else mcp_dataset_loader model.zero_grad() for j, batch in enumerate(wrap_mcp_dataset_loader): input_ids = batch[0].to(rank) input_mask = batch[1].to(rank) labels = batch[2].to(rank) mask_pos = labels >= 0 labels = labels[mask_pos] # mask out category indicative words input_ids[mask_pos] = self.mask_id logits = model(input_ids, pred_mode="classification", token_type_ids=None, attention_mask=input_mask) logits = logits[mask_pos] loss = self.mcp_loss(logits.view(-1, self.num_class), labels.view(-1)) / self.accum_steps total_train_loss += loss.item() loss.backward() if (j+1) % self.accum_steps == 0: # Clip the norm of the gradients to 1.0. nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() scheduler.step() model.zero_grad() avg_train_loss = torch.tensor([total_train_loss / len(mcp_dataset_loader) * self.accum_steps]).to(rank) gather_list = [torch.ones_like(avg_train_loss) for _ in range(self.world_size)] if self.world_size > 1: dist.all_gather(gather_list, avg_train_loss) avg_train_loss = torch.tensor(gather_list) if rank == 0: print(f"Average training loss: {avg_train_loss.mean().item()}") if rank == 0: loader_file = os.path.join(self.dataset_dir, loader_name) torch.save(self.model.state_dict(), loader_file) except RuntimeError as err: self.cuda_mem_error(err, "train", rank) # masked category prediction def mcp(self, top_pred_num=50, match_threshold=20, epochs=5, loader_name="mcp_model.pt"): loader_file = os.path.join(self.dataset_dir, loader_name) if os.path.exists(loader_file): print(f"\nLoading model trained via masked category prediction from {loader_file}") else: self.prepare_mcp(top_pred_num, match_threshold) print(f"\nTraining model via masked category prediction.") #mp.spawn(self.mcp_dist, nprocs=self.world_size, args=(epochs, loader_name)) self.mcp_dist(0, epochs, loader_name) self.model.load_state_dict(torch.load(loader_file)) # prepare self training data and target distribution def prepare_self_train_data(self, rank, model, idx): target_num = min(self.world_size * self.train_batch_size * self.update_interval * self.accum_steps, len(self.train_data["input_ids"])) if idx + target_num >= len(self.train_data["input_ids"]): select_idx = torch.cat((torch.arange(idx, len(self.train_data["input_ids"])), torch.arange(idx + target_num - len(self.train_data["input_ids"])))) else: select_idx = torch.arange(idx, idx + target_num) assert len(select_idx) == target_num idx = (idx + len(select_idx)) % len(self.train_data["input_ids"]) select_dataset = {"input_ids": self.train_data["input_ids"][select_idx], "attention_masks": self.train_data["attention_masks"][select_idx]} dataset_loader = self.make_dataloader(rank, select_dataset, self.eval_batch_size) input_ids, input_mask, preds = self.inference(model, dataset_loader, rank, return_type="data") gather_input_ids = [torch.ones_like(input_ids) for _ in range(self.world_size)] gather_input_mask = [torch.ones_like(input_mask) for _ in range(self.world_size)] gather_preds = [torch.ones_like(preds) for _ in range(self.world_size)] dist.all_gather(gather_input_ids, input_ids) dist.all_gather(gather_input_mask, input_mask) dist.all_gather(gather_preds, preds) input_ids = torch.cat(gather_input_ids, dim=0).cpu() input_mask = torch.cat(gather_input_mask, dim=0).cpu() all_preds = torch.cat(gather_preds, dim=0).cpu() weight = all_preds**2 / torch.sum(all_preds, dim=0) target_dist = (weight.t() / torch.sum(weight, dim=1)).t() all_target_pred = target_dist.argmax(dim=-1) agree = (all_preds.argmax(dim=-1) == all_target_pred).int().sum().item() / len(all_target_pred) self_train_dict = {"input_ids": input_ids, "attention_masks": input_mask, "labels": target_dist} return self_train_dict, idx, agree # train a model on batches of data with target labels def self_train_batches(self, rank, model, self_train_loader, optimizer, scheduler, test_dataset_loader): model.train() total_train_loss = 0 wrap_train_dataset_loader = tqdm(self_train_loader) if rank == 0 else self_train_loader model.zero_grad() try: for j, batch in enumerate(wrap_train_dataset_loader): input_ids = batch[0].to(rank) input_mask = batch[1].to(rank) target_dist = batch[2].to(rank) logits = model(input_ids, pred_mode="classification", token_type_ids=None, attention_mask=input_mask) logits = logits[:, 0, :] preds = nn.LogSoftmax(dim=-1)(logits) loss = self.st_loss(preds.view(-1, self.num_class), target_dist.view(-1, self.num_class)) / self.accum_steps total_train_loss += loss.item() loss.backward() if (j+1) % self.accum_steps == 0: # Clip the norm of the gradients to 1.0. nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() scheduler.step() model.zero_grad() if self.with_test_label: acc = self.inference(model, test_dataset_loader, rank, return_type="acc") gather_acc = [torch.ones_like(acc) for _ in range(self.world_size)] dist.all_gather(gather_acc, acc) acc = torch.tensor(gather_acc).mean().item() avg_train_loss = torch.tensor([total_train_loss / len(wrap_train_dataset_loader) * self.accum_steps]).to(rank) gather_list = [torch.ones_like(avg_train_loss) for _ in range(self.world_size)] dist.all_gather(gather_list, avg_train_loss) avg_train_loss = torch.tensor(gather_list) if rank == 0: print(f"lr: {optimizer.param_groups[0]['lr']:.4g}") print(f"Average training loss: {avg_train_loss.mean().item()}") if self.with_test_label: print(f"Test acc: {acc}") except RuntimeError as err: self.cuda_mem_error(err, "train", rank) # self training (distributed function) def self_train_dist(self, rank, epochs, loader_name="final_model.pt"): model = self.set_up_dist(rank) test_dataset_loader = self.make_dataloader(rank, self.test_data, self.eval_batch_size) if self.with_test_label else None total_steps = int(len(self.train_data["input_ids"]) * epochs / (self.world_size * self.train_batch_size * self.accum_steps)) optimizer = AdamW(filter(lambda p: p.requires_grad, model.parameters()), lr=1e-6, eps=1e-8) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0.1*total_steps, num_training_steps=total_steps) idx = 0 if self.early_stop: agree_count = 0 for i in tqdm(range(int(total_steps / self.update_interval))): self_train_dict, idx, agree = self.prepare_self_train_data(rank, model, idx) # early stop if current prediction agrees with target distribution for 3 consecutive updates if self.early_stop: if 1 - agree < 1e-3: agree_count += 1 else: agree_count = 0 if agree_count >= 3: break self_train_dataset_loader = self.make_dataloader(rank, self_train_dict, self.train_batch_size) self.self_train_batches(rank, model, self_train_dataset_loader, optimizer, scheduler, test_dataset_loader) if rank == 0: loader_file = os.path.join(self.dataset_dir, loader_name) print(f"Saving final model to {loader_file}") torch.save(model.module.state_dict(), loader_file) # self training def self_train(self, epochs, loader_name="final_model.pt"): loader_file = os.path.join(self.dataset_dir, loader_name) if os.path.exists(loader_file): print(f"\nFinal model {loader_file} found, skip self-training") else: rand_idx = torch.randperm(len(self.train_data["input_ids"])) self.train_data = {"input_ids": self.train_data["input_ids"][rand_idx], "attention_masks": self.train_data["attention_masks"][rand_idx]} print(f"\nStart self-training.") if self.world_size > 1: mp.spawn(self.self_train_dist, nprocs=self.world_size, args=(epochs, loader_name)) else: self.self_train_dist(0, epochs, loader_name) # use a model to do inference on a dataloader def inference(self, model, dataset_loader, rank, return_type): if return_type == "data": all_input_ids = [] all_input_mask = [] all_preds = [] elif return_type == "acc": pred_labels = [] truth_labels = [] elif return_type == "pred": pred_labels = [] model.eval() try: for batch in dataset_loader: with torch.no_grad(): input_ids = batch[0].to(rank) input_mask = batch[1].to(rank) logits = model(input_ids, pred_mode="classification", token_type_ids=None, attention_mask=input_mask) logits = logits[:, 0, :] if return_type == "data": all_input_ids.append(input_ids) all_input_mask.append(input_mask) all_preds.append(nn.Softmax(dim=-1)(logits)) elif return_type == "acc": labels = batch[2] pred_labels.append(torch.argmax(logits, dim=-1).cpu()) truth_labels.append(labels) elif return_type == "pred": pred_labels.append(torch.argmax(logits, dim=-1).cpu()) if return_type == "data": all_input_ids = torch.cat(all_input_ids, dim=0) all_input_mask = torch.cat(all_input_mask, dim=0) all_preds = torch.cat(all_preds, dim=0) return all_input_ids, all_input_mask, all_preds elif return_type == "acc": pred_labels = torch.cat(pred_labels, dim=0) truth_labels = torch.cat(truth_labels, dim=0) samples = len(truth_labels) acc = (pred_labels == truth_labels).float().sum() / samples return acc.to(rank) elif return_type == "pred": pred_labels = torch.cat(pred_labels, dim=0) return pred_labels except RuntimeError as err: self.cuda_mem_error(err, "eval", rank) # use trained model to make predictions on the test set def write_results(self, loader_name="final_model.pt", out_file="out.txt"): loader_file = os.path.join(self.dataset_dir, loader_name) assert os.path.exists(loader_file) print(f"\nLoading final model from {loader_file}") self.model.load_state_dict(torch.load(loader_file)) self.model.to(0) test_set = TensorDataset(self.test_data["input_ids"], self.test_data["attention_masks"]) test_dataset_loader = DataLoader(test_set, sampler=SequentialSampler(test_set), batch_size=self.eval_batch_size) pred_labels = self.inference(self.model, test_dataset_loader, 0, return_type="pred") out_file = os.path.join(self.dataset_dir, out_file) print(f"Writing prediction results to {out_file}") f_out = open(out_file, 'w') for label in pred_labels: f_out.write(str(label.item()) + '\n') # print error message based on CUDA memory error def cuda_mem_error(self, err, mode, rank): if rank == 0: print(err) if "CUDA out of memory" in str(err): if mode == "eval": print(f"Your GPUs can't hold the current batch size for evaluation, try to reduce `--eval_batch_size`, current: {self.eval_batch_size}") else: print(f"Your GPUs can't hold the current batch size for training, try to reduce `--train_batch_size`, current: {self.train_batch_size}") sys.exit(1)
[ "torch.nn.CrossEntropyLoss", "multiprocessing.cpu_count", "numpy.array", "torch.utils.data.distributed.DistributedSampler", "torch.sum", "sys.exit", "joblib.delayed", "torch.arange", "os.path.exists", "numpy.mean", "os.listdir", "nltk.corpus.stopwords.words", "numpy.delete", "numpy.max", "LOTClass.bert.model.LOTClassModel.from_pretrained", "torch.zeros_like", "torch.distributed.all_gather", "torch.nn.parallel.DistributedDataParallel", "torch.argmax", "torch.ones_like", "torch.topk", "torch.nn.KLDivLoss", "torch.utils.data.SequentialSampler", "torch.utils.data.TensorDataset", "shutil.rmtree", "torch.save", "numpy.std", "warnings.filterwarnings", "torch.cat", "os.makedirs", "torch.multiprocessing.spawn", "torch.nn.Softmax", "transformers.get_linear_schedule_with_warmup", "torch.load", "tqdm.tqdm", "transformers.BertTokenizer.from_pretrained", "os.path.join", "joblib.Parallel", "torch.tensor", "collections.defaultdict", "torch.nn.LogSoftmax", "torch.utils.data.DataLoader", "torch.no_grad", "torch.distributed.init_process_group", "torch.ones" ]
[((970, 1003), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (993, 1003), False, 'import warnings\n'), ((1868, 1937), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['self.pretrained_lm'], {'do_lower_case': '(True)'}), '(self.pretrained_lm, do_lower_case=True)\n', (1897, 1937), False, 'from transformers import BertTokenizer\n'), ((2396, 2529), 'LOTClass.bert.model.LOTClassModel.from_pretrained', 'LOTClassModel.from_pretrained', (['self.pretrained_lm'], {'output_attentions': '(False)', 'output_hidden_states': '(False)', 'num_labels': 'self.num_class'}), '(self.pretrained_lm, output_attentions=False,\n output_hidden_states=False, num_labels=self.num_class)\n', (2425, 2529), False, 'from LOTClass.bert.model import LOTClassModel\n'), ((2930, 2951), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (2949, 2951), False, 'from torch import nn\n'), ((2975, 3010), 'torch.nn.KLDivLoss', 'nn.KLDivLoss', ([], {'reduction': '"""batchmean"""'}), "(reduction='batchmean')\n", (2987, 3010), False, 'from torch import nn\n'), ((3181, 3313), 'torch.distributed.init_process_group', 'dist.init_process_group', ([], {'backend': '"""nccl"""', 'init_method': 'f"""tcp://localhost:{self.dist_port}"""', 'world_size': 'self.world_size', 'rank': 'rank'}), "(backend='nccl', init_method=\n f'tcp://localhost:{self.dist_port}', world_size=self.world_size, rank=rank)\n", (3204, 3313), True, 'import torch.distributed as dist\n'), ((3448, 3506), 'torch.nn.parallel.DistributedDataParallel', 'DDP', (['model'], {'device_ids': '[rank]', 'find_unused_parameters': '(True)'}), '(model, device_ids=[rank], find_unused_parameters=True)\n', (3451, 3506), True, 'from torch.nn.parallel import DistributedDataParallel as DDP\n'), ((5102, 5140), 'os.path.join', 'os.path.join', (['dataset_dir', 'loader_name'], {}), '(dataset_dir, loader_name)\n', (5114, 5140), False, 'import os\n'), ((5152, 5179), 'os.path.exists', 'os.path.exists', (['loader_file'], {}), '(loader_file)\n', (5166, 5179), False, 'import os\n'), ((13068, 13136), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['dataset'], {'num_replicas': 'self.world_size', 'rank': 'rank'}), '(dataset, num_replicas=self.world_size, rank=rank)\n', (13086, 13136), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((13162, 13236), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'sampler': 'sampler', 'batch_size': 'batch_size', 'shuffle': '(False)'}), '(dataset, sampler=sampler, batch_size=batch_size, shuffle=False)\n', (13172, 13236), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n'), ((13405, 13422), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (13416, 13422), False, 'from collections import defaultdict\n'), ((14100, 14126), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (14115, 14126), False, 'from nltk.corpus import stopwords\n'), ((17233, 17276), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'loader_name'], {}), '(self.dataset_dir, loader_name)\n', (17245, 17276), False, 'import os\n'), ((17288, 17315), 'os.path.exists', 'os.path.exists', (['loader_file'], {}), '(loader_file)\n', (17302, 17315), False, 'import os\n'), ((19454, 19470), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (19465, 19470), False, 'from collections import defaultdict\n'), ((21898, 21941), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'loader_name'], {}), '(self.dataset_dir, loader_name)\n', (21910, 21941), False, 'import os\n'), ((21953, 21980), 'os.path.exists', 'os.path.exists', (['loader_file'], {}), '(loader_file)\n', (21967, 21980), False, 'import os\n'), ((24789, 24903), 'transformers.get_linear_schedule_with_warmup', 'get_linear_schedule_with_warmup', (['optimizer'], {'num_warmup_steps': '(0.1 * total_steps)', 'num_training_steps': 'total_steps'}), '(optimizer, num_warmup_steps=0.1 *\n total_steps, num_training_steps=total_steps)\n', (24820, 24903), False, 'from transformers import AdamW, get_linear_schedule_with_warmup\n'), ((27329, 27372), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'loader_name'], {}), '(self.dataset_dir, loader_name)\n', (27341, 27372), False, 'import os\n'), ((27384, 27411), 'os.path.exists', 'os.path.exists', (['loader_file'], {}), '(loader_file)\n', (27398, 27411), False, 'import os\n'), ((29199, 29243), 'torch.distributed.all_gather', 'dist.all_gather', (['gather_input_ids', 'input_ids'], {}), '(gather_input_ids, input_ids)\n', (29214, 29243), True, 'import torch.distributed as dist\n'), ((29252, 29298), 'torch.distributed.all_gather', 'dist.all_gather', (['gather_input_mask', 'input_mask'], {}), '(gather_input_mask, input_mask)\n', (29267, 29298), True, 'import torch.distributed as dist\n'), ((29307, 29343), 'torch.distributed.all_gather', 'dist.all_gather', (['gather_preds', 'preds'], {}), '(gather_preds, preds)\n', (29322, 29343), True, 'import torch.distributed as dist\n'), ((32858, 32972), 'transformers.get_linear_schedule_with_warmup', 'get_linear_schedule_with_warmup', (['optimizer'], {'num_warmup_steps': '(0.1 * total_steps)', 'num_training_steps': 'total_steps'}), '(optimizer, num_warmup_steps=0.1 *\n total_steps, num_training_steps=total_steps)\n', (32889, 32972), False, 'from transformers import AdamW, get_linear_schedule_with_warmup\n'), ((34077, 34120), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'loader_name'], {}), '(self.dataset_dir, loader_name)\n', (34089, 34120), False, 'import os\n'), ((34132, 34159), 'os.path.exists', 'os.path.exists', (['loader_file'], {}), '(loader_file)\n', (34146, 34159), False, 'import os\n'), ((37219, 37262), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'loader_name'], {}), '(self.dataset_dir, loader_name)\n', (37231, 37262), False, 'import os\n'), ((37278, 37305), 'os.path.exists', 'os.path.exists', (['loader_file'], {}), '(loader_file)\n', (37292, 37305), False, 'import os\n'), ((37469, 37546), 'torch.utils.data.TensorDataset', 'TensorDataset', (["self.test_data['input_ids']", "self.test_data['attention_masks']"], {}), "(self.test_data['input_ids'], self.test_data['attention_masks'])\n", (37482, 37546), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n'), ((37780, 37820), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'out_file'], {}), '(self.dataset_dir, out_file)\n', (37792, 37820), False, 'import os\n'), ((38574, 38585), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (38582, 38585), False, 'import sys\n'), ((5263, 5286), 'torch.load', 'torch.load', (['loader_file'], {}), '(loader_file)\n', (5273, 5286), False, 'import torch\n'), ((5852, 5896), 'torch.cat', 'torch.cat', (['[result[0] for result in results]'], {}), '([result[0] for result in results])\n', (5861, 5896), False, 'import torch\n'), ((5997, 6041), 'torch.cat', 'torch.cat', (['[result[1] for result in results]'], {}), '([result[1] for result in results])\n', (6006, 6041), False, 'import torch\n'), ((6636, 6665), 'torch.save', 'torch.save', (['data', 'loader_file'], {}), '(data, loader_file)\n', (6646, 6665), False, 'import torch\n'), ((6720, 6769), 'os.path.join', 'os.path.join', (['dataset_dir', 'label_name_loader_name'], {}), '(dataset_dir, label_name_loader_name)\n', (6732, 6769), False, 'import os\n'), ((6785, 6812), 'os.path.exists', 'os.path.exists', (['loader_file'], {}), '(loader_file)\n', (6799, 6812), False, 'import os\n'), ((8684, 8726), 'torch.ones', 'torch.ones', (['self.max_len'], {'dtype': 'torch.long'}), '(self.max_len, dtype=torch.long)\n', (8694, 8726), False, 'import torch\n'), ((10713, 10745), 'torch.cat', 'torch.cat', (['label_name_idx'], {'dim': '(0)'}), '(label_name_idx, dim=0)\n', (10722, 10745), False, 'import torch\n'), ((10800, 10845), 'torch.ones', 'torch.ones', (['(0)', 'self.max_len'], {'dtype': 'torch.long'}), '(0, self.max_len, dtype=torch.long)\n', (10810, 10845), False, 'import torch\n'), ((10892, 10937), 'torch.ones', 'torch.ones', (['(0)', 'self.max_len'], {'dtype': 'torch.long'}), '(0, self.max_len, dtype=torch.long)\n', (10902, 10937), False, 'import torch\n'), ((10967, 11012), 'torch.ones', 'torch.ones', (['(0)', 'self.max_len'], {'dtype': 'torch.long'}), '(0, self.max_len, dtype=torch.long)\n', (10977, 11012), False, 'import torch\n'), ((11736, 11778), 'os.path.join', 'os.path.join', (['dataset_dir', 'label_name_file'], {}), '(dataset_dir, label_name_file)\n', (11748, 11778), False, 'import os\n'), ((12857, 12949), 'torch.utils.data.TensorDataset', 'TensorDataset', (["data_dict['input_ids']", "data_dict['attention_masks']", "data_dict['labels']"], {}), "(data_dict['input_ids'], data_dict['attention_masks'],\n data_dict['labels'])\n", (12870, 12949), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n'), ((12982, 13049), 'torch.utils.data.TensorDataset', 'TensorDataset', (["data_dict['input_ids']", "data_dict['attention_masks']"], {}), "(data_dict['input_ids'], data_dict['attention_masks'])\n", (12995, 13049), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n'), ((14581, 14626), 'numpy.delete', 'np.delete', (['self.category_vocab[i]', 'delete_idx'], {}), '(self.category_vocab[i], delete_idx)\n', (14590, 14626), True, 'import numpy as np\n'), ((15257, 15275), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (15268, 15275), False, 'from collections import defaultdict\n'), ((15349, 15380), 'tqdm.tqdm', 'tqdm', (['label_name_dataset_loader'], {}), '(label_name_dataset_loader)\n', (15353, 15380), False, 'from tqdm import tqdm\n'), ((16870, 16923), 'os.path.join', 'os.path.join', (['self.temp_dir', "(f'{rank}_' + loader_name)"], {}), "(self.temp_dir, f'{rank}_' + loader_name)\n", (16882, 16923), False, 'import os\n'), ((16934, 16976), 'torch.save', 'torch.save', (['category_words_freq', 'save_file'], {}), '(category_words_freq, save_file)\n', (16944, 16976), False, 'import torch\n'), ((17420, 17443), 'torch.load', 'torch.load', (['loader_file'], {}), '(loader_file)\n', (17430, 17443), False, 'import torch\n'), ((17959, 17984), 'os.listdir', 'os.listdir', (['self.temp_dir'], {}), '(self.temp_dir)\n', (17969, 17984), False, 'import os\n'), ((18618, 18662), 'torch.save', 'torch.save', (['self.category_vocab', 'loader_file'], {}), '(self.category_vocab, loader_file)\n', (18628, 18662), False, 'import torch\n'), ((18678, 18707), 'os.path.exists', 'os.path.exists', (['self.temp_dir'], {}), '(self.temp_dir)\n', (18692, 18707), False, 'import os\n'), ((19507, 19533), 'tqdm.tqdm', 'tqdm', (['train_dataset_loader'], {}), '(train_dataset_loader)\n', (19511, 19533), False, 'from tqdm import tqdm\n'), ((21115, 21146), 'torch.cat', 'torch.cat', (['all_input_ids'], {'dim': '(0)'}), '(all_input_ids, dim=0)\n', (21124, 21146), False, 'import torch\n'), ((21176, 21208), 'torch.cat', 'torch.cat', (['all_mask_label'], {'dim': '(0)'}), '(all_mask_label, dim=0)\n', (21185, 21208), False, 'import torch\n'), ((21238, 21270), 'torch.cat', 'torch.cat', (['all_input_mask'], {'dim': '(0)'}), '(all_input_mask, dim=0)\n', (21247, 21270), False, 'import torch\n'), ((21537, 21590), 'os.path.join', 'os.path.join', (['self.temp_dir', "(f'{rank}_' + loader_name)"], {}), "(self.temp_dir, f'{rank}_' + loader_name)\n", (21549, 21590), False, 'import os\n'), ((21601, 21633), 'torch.save', 'torch.save', (['save_dict', 'save_file'], {}), '(save_dict, save_file)\n', (21611, 21633), False, 'import torch\n'), ((22091, 22114), 'torch.load', 'torch.load', (['loader_file'], {}), '(loader_file)\n', (22101, 22114), False, 'import torch\n'), ((22155, 22198), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'loader_name'], {}), '(self.dataset_dir, loader_name)\n', (22167, 22198), False, 'import os\n'), ((22622, 22647), 'os.listdir', 'os.listdir', (['self.temp_dir'], {}), '(self.temp_dir)\n', (22632, 22647), False, 'import os\n'), ((22908, 22970), 'torch.cat', 'torch.cat', (["[res['all_input_ids'] for res in gather_res]"], {'dim': '(0)'}), "([res['all_input_ids'] for res in gather_res], dim=0)\n", (22917, 22970), False, 'import torch\n'), ((23000, 23063), 'torch.cat', 'torch.cat', (["[res['all_mask_label'] for res in gather_res]"], {'dim': '(0)'}), "([res['all_mask_label'] for res in gather_res], dim=0)\n", (23009, 23063), False, 'import torch\n'), ((23093, 23156), 'torch.cat', 'torch.cat', (["[res['all_input_mask'] for res in gather_res]"], {'dim': '(0)'}), "([res['all_input_mask'] for res in gather_res], dim=0)\n", (23102, 23156), False, 'import torch\n'), ((23681, 23719), 'torch.save', 'torch.save', (['self.mcp_data', 'loader_file'], {}), '(self.mcp_data, loader_file)\n', (23691, 23719), False, 'import torch\n'), ((23735, 23764), 'os.path.exists', 'os.path.exists', (['self.temp_dir'], {}), '(self.temp_dir)\n', (23749, 23764), False, 'import os\n'), ((27828, 27851), 'torch.load', 'torch.load', (['loader_file'], {}), '(loader_file)\n', (27838, 27851), False, 'import torch\n'), ((28411, 28446), 'torch.arange', 'torch.arange', (['idx', '(idx + target_num)'], {}), '(idx, idx + target_num)\n', (28423, 28446), False, 'import torch\n'), ((28961, 28987), 'torch.ones_like', 'torch.ones_like', (['input_ids'], {}), '(input_ids)\n', (28976, 28987), False, 'import torch\n'), ((29050, 29077), 'torch.ones_like', 'torch.ones_like', (['input_mask'], {}), '(input_mask)\n', (29065, 29077), False, 'import torch\n'), ((29135, 29157), 'torch.ones_like', 'torch.ones_like', (['preds'], {}), '(preds)\n', (29150, 29157), False, 'import torch\n'), ((29557, 29584), 'torch.sum', 'torch.sum', (['all_preds'], {'dim': '(0)'}), '(all_preds, dim=0)\n', (29566, 29584), False, 'import torch\n'), ((30211, 30234), 'tqdm.tqdm', 'tqdm', (['self_train_loader'], {}), '(self_train_loader)\n', (30215, 30234), False, 'from tqdm import tqdm\n'), ((31869, 31913), 'torch.distributed.all_gather', 'dist.all_gather', (['gather_list', 'avg_train_loss'], {}), '(gather_list, avg_train_loss)\n', (31884, 31913), True, 'import torch.distributed as dist\n'), ((31943, 31968), 'torch.tensor', 'torch.tensor', (['gather_list'], {}), '(gather_list)\n', (31955, 31968), False, 'import torch\n'), ((33805, 33848), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'loader_name'], {}), '(self.dataset_dir, loader_name)\n', (33817, 33848), False, 'import os\n'), ((37400, 37423), 'torch.load', 'torch.load', (['loader_file'], {}), '(loader_file)\n', (37410, 37423), False, 'import torch\n'), ((1301, 1312), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (1310, 1312), False, 'from multiprocessing import cpu_count\n'), ((5407, 5443), 'os.path.join', 'os.path.join', (['dataset_dir', 'text_file'], {}), '(dataset_dir, text_file)\n', (5419, 5443), False, 'import os\n'), ((5743, 5773), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'self.num_cpus'}), '(n_jobs=self.num_cpus)\n', (5751, 5773), False, 'from joblib import Parallel, delayed\n'), ((6399, 6419), 'torch.tensor', 'torch.tensor', (['labels'], {}), '(labels)\n', (6411, 6419), False, 'import torch\n'), ((6924, 6947), 'torch.load', 'torch.load', (['loader_file'], {}), '(loader_file)\n', (6934, 6947), False, 'import torch\n'), ((7584, 7628), 'torch.cat', 'torch.cat', (['[result[0] for result in results]'], {}), '([result[0] for result in results])\n', (7593, 7628), False, 'import torch\n'), ((7679, 7723), 'torch.cat', 'torch.cat', (['[result[1] for result in results]'], {}), '([result[1] for result in results])\n', (7688, 7723), False, 'import torch\n'), ((7757, 7801), 'torch.cat', 'torch.cat', (['[result[2] for result in results]'], {}), '([result[2] for result in results])\n', (7766, 7801), False, 'import torch\n'), ((8185, 8234), 'os.path.join', 'os.path.join', (['dataset_dir', 'label_name_loader_name'], {}), '(dataset_dir, label_name_loader_name)\n', (8197, 8234), False, 'import os\n'), ((8326, 8366), 'torch.save', 'torch.save', (['label_name_data', 'loader_file'], {}), '(label_name_data, loader_file)\n', (8336, 8366), False, 'import torch\n'), ((17531, 17560), 'os.path.exists', 'os.path.exists', (['self.temp_dir'], {}), '(self.temp_dir)\n', (17545, 17560), False, 'import os\n'), ((17578, 17604), 'os.makedirs', 'os.makedirs', (['self.temp_dir'], {}), '(self.temp_dir)\n', (17589, 17604), False, 'import os\n'), ((18260, 18278), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (18271, 18278), False, 'from collections import defaultdict\n'), ((18725, 18753), 'shutil.rmtree', 'shutil.rmtree', (['self.temp_dir'], {}), '(self.temp_dir)\n', (18738, 18753), False, 'import shutil\n'), ((22298, 22327), 'os.path.exists', 'os.path.exists', (['self.temp_dir'], {}), '(self.temp_dir)\n', (22312, 22327), False, 'import os\n'), ((22345, 22371), 'os.makedirs', 'os.makedirs', (['self.temp_dir'], {}), '(self.temp_dir)\n', (22356, 22371), False, 'import os\n'), ((23782, 23810), 'shutil.rmtree', 'shutil.rmtree', (['self.temp_dir'], {}), '(self.temp_dir)\n', (23795, 23810), False, 'import shutil\n'), ((26786, 26811), 'torch.tensor', 'torch.tensor', (['gather_list'], {}), '(gather_list)\n', (26798, 26811), False, 'import torch\n'), ((26982, 27025), 'os.path.join', 'os.path.join', (['self.dataset_dir', 'loader_name'], {}), '(self.dataset_dir, loader_name)\n', (26994, 27025), False, 'import os\n'), ((29364, 29398), 'torch.cat', 'torch.cat', (['gather_input_ids'], {'dim': '(0)'}), '(gather_input_ids, dim=0)\n', (29373, 29398), False, 'import torch\n'), ((29426, 29461), 'torch.cat', 'torch.cat', (['gather_input_mask'], {'dim': '(0)'}), '(gather_input_mask, dim=0)\n', (29435, 29461), False, 'import torch\n'), ((29488, 29518), 'torch.cat', 'torch.cat', (['gather_preds'], {'dim': '(0)'}), '(gather_preds, dim=0)\n', (29497, 29518), False, 'import torch\n'), ((31548, 31580), 'torch.distributed.all_gather', 'dist.all_gather', (['gather_acc', 'acc'], {}), '(gather_acc, acc)\n', (31563, 31580), True, 'import torch.distributed as dist\n'), ((31792, 31823), 'torch.ones_like', 'torch.ones_like', (['avg_train_loss'], {}), '(avg_train_loss)\n', (31807, 31823), False, 'import torch\n'), ((34601, 34687), 'torch.multiprocessing.spawn', 'mp.spawn', (['self.self_train_dist'], {'nprocs': 'self.world_size', 'args': '(epochs, loader_name)'}), '(self.self_train_dist, nprocs=self.world_size, args=(epochs,\n loader_name))\n', (34609, 34687), True, 'import torch.multiprocessing as mp\n'), ((36296, 36327), 'torch.cat', 'torch.cat', (['all_input_ids'], {'dim': '(0)'}), '(all_input_ids, dim=0)\n', (36305, 36327), False, 'import torch\n'), ((36361, 36393), 'torch.cat', 'torch.cat', (['all_input_mask'], {'dim': '(0)'}), '(all_input_mask, dim=0)\n', (36370, 36393), False, 'import torch\n'), ((36422, 36449), 'torch.cat', 'torch.cat', (['all_preds'], {'dim': '(0)'}), '(all_preds, dim=0)\n', (36431, 36449), False, 'import torch\n'), ((37606, 37633), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['test_set'], {}), '(test_set)\n', (37623, 37633), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n'), ((1281, 1292), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (1290, 1292), False, 'from multiprocessing import cpu_count\n'), ((3841, 3856), 'numpy.max', 'np.max', (['doc_len'], {}), '(doc_len)\n', (3847, 3856), True, 'import numpy as np\n'), ((3872, 3888), 'numpy.mean', 'np.mean', (['doc_len'], {}), '(doc_len)\n', (3879, 3888), True, 'import numpy as np\n'), ((3904, 3919), 'numpy.std', 'np.std', (['doc_len'], {}), '(doc_len)\n', (3910, 3919), True, 'import numpy as np\n'), ((3951, 3968), 'numpy.array', 'np.array', (['doc_len'], {}), '(doc_len)\n', (3959, 3968), True, 'import numpy as np\n'), ((6258, 6295), 'os.path.join', 'os.path.join', (['dataset_dir', 'label_file'], {}), '(dataset_dir, label_file)\n', (6270, 6295), False, 'import os\n'), ((7080, 7116), 'os.path.join', 'os.path.join', (['dataset_dir', 'text_file'], {}), '(dataset_dir, text_file)\n', (7092, 7116), False, 'import os\n'), ((7440, 7470), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'self.num_cpus'}), '(n_jobs=self.num_cpus)\n', (7448, 7470), False, 'from joblib import Parallel, delayed\n'), ((15516, 15531), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15529, 15531), False, 'import torch\n'), ((16373, 16429), 'torch.topk', 'torch.topk', (['predictions[match_idx]', 'top_pred_num'], {'dim': '(-1)'}), '(predictions[match_idx], top_pred_num, dim=-1)\n', (16383, 16429), False, 'import torch\n'), ((19659, 19674), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (19672, 19674), False, 'import torch\n'), ((20049, 20094), 'torch.topk', 'torch.topk', (['predictions', 'top_pred_num'], {'dim': '(-1)'}), '(predictions, top_pred_num, dim=-1)\n', (20059, 20094), False, 'import torch\n'), ((25129, 25153), 'tqdm.tqdm', 'tqdm', (['mcp_dataset_loader'], {}), '(mcp_dataset_loader)\n', (25133, 25153), False, 'from tqdm import tqdm\n'), ((26583, 26614), 'torch.ones_like', 'torch.ones_like', (['avg_train_loss'], {}), '(avg_train_loss)\n', (26598, 26614), False, 'import torch\n'), ((26708, 26752), 'torch.distributed.all_gather', 'dist.all_gather', (['gather_list', 'avg_train_loss'], {}), '(gather_list, avg_train_loss)\n', (26723, 26752), True, 'import torch.distributed as dist\n'), ((29621, 29645), 'torch.sum', 'torch.sum', (['weight'], {'dim': '(1)'}), '(weight, dim=1)\n', (29630, 29645), False, 'import torch\n'), ((30793, 30814), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (30806, 30814), False, 'from torch import nn\n'), ((31478, 31498), 'torch.ones_like', 'torch.ones_like', (['acc'], {}), '(acc)\n', (31493, 31498), False, 'import torch\n'), ((35260, 35275), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (35273, 35275), False, 'import torch\n'), ((36583, 36612), 'torch.cat', 'torch.cat', (['pred_labels'], {'dim': '(0)'}), '(pred_labels, dim=0)\n', (36592, 36612), False, 'import torch\n'), ((36644, 36674), 'torch.cat', 'torch.cat', (['truth_labels'], {'dim': '(0)'}), '(truth_labels, dim=0)\n', (36653, 36674), False, 'import torch\n'), ((5341, 5377), 'os.path.join', 'os.path.join', (['dataset_dir', 'text_file'], {}), '(dataset_dir, text_file)\n', (5353, 5377), False, 'import os\n'), ((5774, 5794), 'joblib.delayed', 'delayed', (['self.encode'], {}), '(self.encode)\n', (5781, 5794), False, 'from joblib import Parallel, delayed\n'), ((36901, 36930), 'torch.cat', 'torch.cat', (['pred_labels'], {'dim': '(0)'}), '(pred_labels, dim=0)\n', (36910, 36930), False, 'import torch\n'), ((6188, 6225), 'os.path.join', 'os.path.join', (['dataset_dir', 'label_file'], {}), '(dataset_dir, label_file)\n', (6200, 6225), False, 'import os\n'), ((7010, 7046), 'os.path.join', 'os.path.join', (['dataset_dir', 'text_file'], {}), '(dataset_dir, text_file)\n', (7022, 7046), False, 'import os\n'), ((7471, 7506), 'joblib.delayed', 'delayed', (['self.label_name_occurrence'], {}), '(self.label_name_occurrence)\n', (7478, 7506), False, 'from joblib import Parallel, delayed\n'), ((18071, 18101), 'os.path.join', 'os.path.join', (['self.temp_dir', 'f'], {}), '(self.temp_dir, f)\n', (18083, 18101), False, 'import os\n'), ((20568, 20596), 'torch.sum', 'torch.sum', (['valid_idx'], {'dim': '(-1)'}), '(valid_idx, dim=-1)\n', (20577, 20596), False, 'import torch\n'), ((22734, 22764), 'os.path.join', 'os.path.join', (['self.temp_dir', 'f'], {}), '(self.temp_dir, f)\n', (22746, 22764), False, 'import os\n'), ((20205, 20233), 'torch.zeros_like', 'torch.zeros_like', (['sorted_res'], {}), '(sorted_res)\n', (20221, 20233), False, 'import torch\n'), ((20691, 20717), 'torch.ones_like', 'torch.ones_like', (['input_ids'], {}), '(input_ids)\n', (20706, 20717), False, 'import torch\n'), ((31603, 31627), 'torch.tensor', 'torch.tensor', (['gather_acc'], {}), '(gather_acc)\n', (31615, 31627), False, 'import torch\n'), ((35851, 35869), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (35861, 35869), False, 'from torch import nn\n'), ((36011, 36039), 'torch.argmax', 'torch.argmax', (['logits'], {'dim': '(-1)'}), '(logits, dim=-1)\n', (36023, 36039), False, 'import torch\n'), ((36190, 36218), 'torch.argmax', 'torch.argmax', (['logits'], {'dim': '(-1)'}), '(logits, dim=-1)\n', (36202, 36218), False, 'import torch\n')]
#!/usr/bin/env python import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2' import sys import csv import numpy as np import pandas as pd import random from time import time, strftime, gmtime, sleep from optparse import OptionParser from pylsl import StreamInlet, resolve_byprop from sklearn.linear_model import LinearRegression import subprocess currentpath = os.path.dirname(os.path.realpath(sys.argv[0])) # dejitter timestamps dejitter = False # how long to wait for the Muse device to connect muse_connect_timout = 5 parser = OptionParser() parser.add_option("-d", "--duration", dest="duration", type='int', default=10, help="duration of the recording in seconds.") parser.add_option("-p", "--path", dest="path", type='str', help="Directory for the recording file.") parser.add_option("-s", "--sample", dest="sample", type='str', help="Record sample for specific term (1/2/3)") (options, args) = parser.parse_args() record_sample = False record_sample_term = None if options.sample: record_sample = True print("NOTICE: Creating sample dataset for term: " + str(options.sample)) record_sample_term = options.sample else: print("NOTICE: Creating training dataset with random terms") if not options.path: print("ERROR: please use -p to specify the datapath to the recorded csv files!") sys.exit(1) fname = (options.path + "/data_%s.csv" % strftime("%Y-%m-%d-%H.%M.%S", gmtime())) # search for the last word id in eventually already existing datafiles last_data_file = None for file in sorted(os.listdir(options.path)): if file.endswith(".csv"): if not "eeg_data" in file: print(os.path.join(options.path, file)) last_data_file = os.path.join(options.path, file) if last_data_file: print("Found existing datafiles! Getting currentWord from last datafiles: " + last_data_file) line = subprocess.check_output(['tail', '-1', last_data_file]) line = str(line) linesplit = line.split(",") #print(linesplit[1]) print("Starting currentWord from " + str(linesplit[1])) currentWord = int(linesplit[1]) currentWord = currentWord + 1 else: print("Did not found any existing datafiles! Starting currentWord from 1") currentWord = 1 print("-- currentWord: " + str(currentWord)) eeg_stream = False print("looking for an EEG stream...") streams = resolve_byprop('type', 'EEG', timeout=2) if len(streams) == 0: print("No EEG stream running yet. Trying to start the Muse EEG stream ...") eeg_stream = subprocess.Popen([ currentpath + "/bci-stream"]) sleep(muse_connect_timout) streams = resolve_byprop('type', 'EEG', timeout=2) if len(streams) == 0: raise(RuntimeError, "Cant find EEG stream") else: print("Success: found Muse EEG stream") print("Start aquiring data") inlet = StreamInlet(streams[0], max_chunklen=12) eeg_time_correction = inlet.time_correction() inlet_marker = False #print("looking for a Markers stream...") #marker_streams = resolve_byprop('type', 'Markers', timeout=2) #if marker_streams: # inlet_marker = StreamInlet(marker_streams[0]) # marker_time_correction = inlet_marker.time_correction() #else: # inlet_marker = False # print("Cant find Markers stream") info = inlet.info() description = info.desc() freq = info.nominal_srate() Nchan = info.channel_count() ch = description.child('channels').first_child() ch_names = [ch.child_value('label')] for i in range(1, Nchan): ch = ch.next_sibling() ch_names.append(ch.child_value('label')) # Word Capturing #currentWord = 1 currentTerm = "1" t_word = time() + 1 * 2 words = [] terms = [] termBank = ["1", "2", "3"] subdisplay = False res = [] timestamps = [] markers = [] t_init = time() print('Start recording at time t=%.3f' % t_init) print(currentTerm) while (time() - t_init) < options.duration: if time() >= t_word: if subdisplay: subdisplay.kill() # Check for new word if time() >= t_word: # sample or training data recording ? if record_sample: currentTerm = record_sample_term else: currentTerm = random.choice(termBank) print(str(currentWord) +": " +currentTerm) subdisplay = subprocess.Popen([ "/usr/bin/display", currentpath + "/images/" + currentTerm + ".png"]) currentWord += 1 t_word = time() + 1 * 2 try: data, timestamp = inlet.pull_chunk(timeout=1.0, max_samples=12) if timestamp: res.append(data) timestamps.extend(timestamp) words.extend([currentWord] * len(timestamp)) terms.extend([currentTerm] * len(timestamp)) if inlet_marker: marker, timestamp = inlet_marker.pull_sample(timeout=0.0) if timestamp: markers.append([marker, timestamp]) except KeyboardInterrupt: break if subdisplay: subdisplay.kill() res = np.concatenate(res, axis=0) timestamps = np.array(timestamps) if dejitter: y = timestamps X = np.atleast_2d(np.arange(0, len(y))).T lr = LinearRegression() lr.fit(X, y) timestamps = lr.predict(X) res = np.c_[timestamps, words, terms, res] data = pd.DataFrame(data=res, columns=['timestamps'] + ['words'] + ['terms'] + ch_names) data['Marker'] = 0 # process markers: for marker in markers: # find index of margers ix = np.argmin(np.abs(marker[1] - timestamps)) val = timestamps[ix] data.loc[ix, 'Marker'] = marker[0][0] data.to_csv(fname, float_format='%.3f', index=False) print('Wrote datafile: ' + fname) if eeg_stream: print("Found running EEG stream. Stopping it") eeg_stream.kill() print("Success")
[ "subprocess.check_output", "numpy.abs", "os.listdir", "random.choice", "pylsl.StreamInlet", "subprocess.Popen", "os.path.join", "optparse.OptionParser", "pylsl.resolve_byprop", "time.sleep", "os.path.realpath", "numpy.array", "time.gmtime", "numpy.concatenate", "sys.exit", "pandas.DataFrame", "time.time", "sklearn.linear_model.LinearRegression" ]
[((531, 545), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (543, 545), False, 'from optparse import OptionParser\n'), ((2457, 2497), 'pylsl.resolve_byprop', 'resolve_byprop', (['"""type"""', '"""EEG"""'], {'timeout': '(2)'}), "('type', 'EEG', timeout=2)\n", (2471, 2497), False, 'from pylsl import StreamInlet, resolve_byprop\n'), ((2916, 2956), 'pylsl.StreamInlet', 'StreamInlet', (['streams[0]'], {'max_chunklen': '(12)'}), '(streams[0], max_chunklen=12)\n', (2927, 2956), False, 'from pylsl import StreamInlet, resolve_byprop\n'), ((3822, 3828), 'time.time', 'time', ([], {}), '()\n', (3826, 3828), False, 'from time import time, strftime, gmtime, sleep\n'), ((5016, 5043), 'numpy.concatenate', 'np.concatenate', (['res'], {'axis': '(0)'}), '(res, axis=0)\n', (5030, 5043), True, 'import numpy as np\n'), ((5057, 5077), 'numpy.array', 'np.array', (['timestamps'], {}), '(timestamps)\n', (5065, 5077), True, 'import numpy as np\n'), ((5284, 5369), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'res', 'columns': "(['timestamps'] + ['words'] + ['terms'] + ch_names)"}), "(data=res, columns=['timestamps'] + ['words'] + ['terms'] +\n ch_names)\n", (5296, 5369), True, 'import pandas as pd\n'), ((375, 404), 'os.path.realpath', 'os.path.realpath', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (391, 404), False, 'import os\n'), ((1424, 1435), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1432, 1435), False, 'import sys\n'), ((1632, 1656), 'os.listdir', 'os.listdir', (['options.path'], {}), '(options.path)\n', (1642, 1656), False, 'import os\n'), ((1972, 2027), 'subprocess.check_output', 'subprocess.check_output', (["['tail', '-1', last_data_file]"], {}), "(['tail', '-1', last_data_file])\n", (1995, 2027), False, 'import subprocess\n'), ((2618, 2665), 'subprocess.Popen', 'subprocess.Popen', (["[currentpath + '/bci-stream']"], {}), "([currentpath + '/bci-stream'])\n", (2634, 2665), False, 'import subprocess\n'), ((2671, 2697), 'time.sleep', 'sleep', (['muse_connect_timout'], {}), '(muse_connect_timout)\n', (2676, 2697), False, 'from time import time, strftime, gmtime, sleep\n'), ((2712, 2752), 'pylsl.resolve_byprop', 'resolve_byprop', (['"""type"""', '"""EEG"""'], {'timeout': '(2)'}), "('type', 'EEG', timeout=2)\n", (2726, 2752), False, 'from pylsl import StreamInlet, resolve_byprop\n'), ((3691, 3697), 'time.time', 'time', ([], {}), '()\n', (3695, 3697), False, 'from time import time, strftime, gmtime, sleep\n'), ((5166, 5184), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (5182, 5184), False, 'from sklearn.linear_model import LinearRegression\n'), ((3904, 3910), 'time.time', 'time', ([], {}), '()\n', (3908, 3910), False, 'from time import time, strftime, gmtime, sleep\n'), ((3948, 3954), 'time.time', 'time', ([], {}), '()\n', (3952, 3954), False, 'from time import time, strftime, gmtime, sleep\n'), ((4048, 4054), 'time.time', 'time', ([], {}), '()\n', (4052, 4054), False, 'from time import time, strftime, gmtime, sleep\n'), ((4320, 4411), 'subprocess.Popen', 'subprocess.Popen', (["['/usr/bin/display', currentpath + '/images/' + currentTerm + '.png']"], {}), "(['/usr/bin/display', currentpath + '/images/' +\n currentTerm + '.png'])\n", (4336, 4411), False, 'import subprocess\n'), ((5475, 5505), 'numpy.abs', 'np.abs', (['(marker[1] - timestamps)'], {}), '(marker[1] - timestamps)\n', (5481, 5505), True, 'import numpy as np\n'), ((1508, 1516), 'time.gmtime', 'gmtime', ([], {}), '()\n', (1514, 1516), False, 'from time import time, strftime, gmtime, sleep\n'), ((1805, 1837), 'os.path.join', 'os.path.join', (['options.path', 'file'], {}), '(options.path, file)\n', (1817, 1837), False, 'import os\n'), ((4223, 4246), 'random.choice', 'random.choice', (['termBank'], {}), '(termBank)\n', (4236, 4246), False, 'import random\n'), ((4452, 4458), 'time.time', 'time', ([], {}), '()\n', (4456, 4458), False, 'from time import time, strftime, gmtime, sleep\n'), ((1742, 1774), 'os.path.join', 'os.path.join', (['options.path', 'file'], {}), '(options.path, file)\n', (1754, 1774), False, 'import os\n')]
# Hungarian algorithm (Kuhn-Munkres) for solving the linear sum assignment # problem. Taken from scikit-learn. Based on original code by <NAME>, # adapted to NumPy by <NAME>. # Further improvements by <NAME>, <NAME> and <NAME>. # # Copyright (c) 2008 <NAME> <<EMAIL>>, <NAME> # Author: <NAME>, <NAME> # License: 3-clause BSD import numpy as np def linear_sum_assignment(cost_matrix): """Solve the linear sum assignment problem. The linear sum assignment problem is also known as minimum weight matching in bipartite graphs. A problem instance is described by a matrix C, where each C[i,j] is the cost of matching vertex i of the first partite set (a "worker") and vertex j of the second set (a "job"). The goal is to find a complete assignment of workers to jobs of minimal cost. Formally, let X be a boolean matrix where :math:`X[i,j] = 1` iff row i is assigned to column j. Then the optimal assignment has cost .. math:: \min \sum_i \sum_j C_{i,j} X_{i,j} s.t. each row is assignment to at most one column, and each column to at most one row. This function can also solve a generalization of the classic assignment problem where the cost matrix is rectangular. If it has more rows than columns, then not every row needs to be assigned to a column, and vice versa. The method used is the Hungarian algorithm, also known as the Munkres or Kuhn-Munkres algorithm. Parameters ---------- cost_matrix : array The cost matrix of the bipartite graph. Returns ------- row_ind, col_ind : array An array of row indices and one of corresponding column indices giving the optimal assignment. The cost of the assignment can be computed as ``cost_matrix[row_ind, col_ind].sum()``. The row indices will be sorted; in the case of a square cost matrix they will be equal to ``numpy.arange(cost_matrix.shape[0])``. Notes ----- .. versionadded:: 0.17.0 Examples -------- >>> cost = np.array([[4, 1, 3], [2, 0, 5], [3, 2, 2]]) >>> from scipy.optimize import linear_sum_assignment >>> row_ind, col_ind = linear_sum_assignment(cost) >>> col_ind array([1, 0, 2]) >>> cost[row_ind, col_ind].sum() 5 References ---------- 1. http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html 2. <NAME>. The Hungarian Method for the assignment problem. *Naval Research Logistics Quarterly*, 2:83-97, 1955. 3. <NAME>. Variants of the Hungarian method for assignment problems. *Naval Research Logistics Quarterly*, 3: 253-258, 1956. 4. <NAME>. Algorithms for the Assignment and Transportation Problems. *J. SIAM*, 5(1):32-38, March, 1957. 5. https://en.wikipedia.org/wiki/Hungarian_algorithm """ cost_matrix = np.asarray(cost_matrix) if len(cost_matrix.shape) != 2: raise ValueError("expected a matrix (2-d array), got a %r array" % (cost_matrix.shape,)) # The algorithm expects more columns than rows in the cost matrix. if cost_matrix.shape[1] < cost_matrix.shape[0]: cost_matrix = cost_matrix.T transposed = True else: transposed = False state = _Hungary(cost_matrix) # No need to bother with assignments if one of the dimensions # of the cost matrix is zero-length. step = None if 0 in cost_matrix.shape else _step1 while step is not None: step = step(state) if transposed: marked = state.marked.T else: marked = state.marked return np.where(marked == 1) class _Hungary(object): """State of the Hungarian algorithm. Parameters ---------- cost_matrix : 2D matrix The cost matrix. Must have shape[1] >= shape[0]. """ def __init__(self, cost_matrix): self.C = cost_matrix.copy() n, m = self.C.shape self.row_uncovered = np.ones(n, dtype=bool) self.col_uncovered = np.ones(m, dtype=bool) self.Z0_r = 0 self.Z0_c = 0 self.path = np.zeros((n + m, 2), dtype=int) self.marked = np.zeros((n, m), dtype=int) def _clear_covers(self): """Clear all covered matrix cells""" self.row_uncovered[:] = True self.col_uncovered[:] = True # Individual steps of the algorithm follow, as a state machine: they return # the next step to be taken (function to be called), if any. def _step1(state): """Steps 1 and 2 in the Wikipedia page.""" # Step 1: For each row of the matrix, find the smallest element and # subtract it from every element in its row. state.C -= state.C.min(axis=1)[:, np.newaxis] # Step 2: Find a zero (Z) in the resulting matrix. If there is no # starred zero in its row or column, star Z. Repeat for each element # in the matrix. for i, j in zip(*np.where(state.C == 0)): if state.col_uncovered[j] and state.row_uncovered[i]: state.marked[i, j] = 1 state.col_uncovered[j] = False state.row_uncovered[i] = False state._clear_covers() return _step3 def _step3(state): """ Cover each column containing a starred zero. If n columns are covered, the starred zeros describe a complete set of unique assignments. In this case, Go to DONE, otherwise, Go to Step 4. """ marked = (state.marked == 1) state.col_uncovered[np.any(marked, axis=0)] = False if marked.sum() < state.C.shape[0]: return _step4 def _step4(state): """ Find a noncovered zero and prime it. If there is no starred zero in the row containing this primed zero, Go to Step 5. Otherwise, cover this row and uncover the column containing the starred zero. Continue in this manner until there are no uncovered zeros left. Save the smallest uncovered value and Go to Step 6. """ # We convert to int as numpy operations are faster on int C = (state.C == 0).astype(int) covered_C = C * state.row_uncovered[:, np.newaxis] covered_C *= np.asarray(state.col_uncovered, dtype=int) n = state.C.shape[0] m = state.C.shape[1] while True: # Find an uncovered zero row, col = np.unravel_index(np.argmax(covered_C), (n, m)) if covered_C[row, col] == 0: return _step6 else: state.marked[row, col] = 2 # Find the first starred element in the row star_col = np.argmax(state.marked[row] == 1) if state.marked[row, star_col] != 1: # Could not find one state.Z0_r = row state.Z0_c = col return _step5 else: col = star_col state.row_uncovered[row] = False state.col_uncovered[col] = True covered_C[:, col] = C[:, col] * ( np.asarray(state.row_uncovered, dtype=int)) covered_C[row] = 0 def _step5(state): """ Construct a series of alternating primed and starred zeros as follows. Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote the starred zero in the column of Z0 (if any). Let Z2 denote the primed zero in the row of Z1 (there will always be one). Continue until the series terminates at a primed zero that has no starred zero in its column. Unstar each starred zero of the series, star each primed zero of the series, erase all primes and uncover every line in the matrix. Return to Step 3 """ count = 0 path = state.path path[count, 0] = state.Z0_r path[count, 1] = state.Z0_c while True: # Find the first starred element in the col defined by # the path. row = np.argmax(state.marked[:, path[count, 1]] == 1) if state.marked[row, path[count, 1]] != 1: # Could not find one break else: count += 1 path[count, 0] = row path[count, 1] = path[count - 1, 1] # Find the first prime element in the row defined by the # first path step col = np.argmax(state.marked[path[count, 0]] == 2) if state.marked[row, col] != 2: col = -1 count += 1 path[count, 0] = path[count - 1, 0] path[count, 1] = col # Convert paths for i in range(count + 1): if state.marked[path[i, 0], path[i, 1]] == 1: state.marked[path[i, 0], path[i, 1]] = 0 else: state.marked[path[i, 0], path[i, 1]] = 1 state._clear_covers() # Erase all prime markings state.marked[state.marked == 2] = 0 return _step3 def _step6(state): """ Add the value found in Step 4 to every element of each covered row, and subtract it from every element of each uncovered column. Return to Step 4 without altering any stars, primes, or covered lines. """ # the smallest uncovered value in the matrix if np.any(state.row_uncovered) and np.any(state.col_uncovered): minval = np.min(state.C[state.row_uncovered], axis=0) minval = np.min(minval[state.col_uncovered]) state.C[~state.row_uncovered] += minval state.C[:, state.col_uncovered] -= minval return _step4
[ "numpy.ones", "numpy.where", "numpy.asarray", "numpy.argmax", "numpy.any", "numpy.zeros", "numpy.min" ]
[((2927, 2950), 'numpy.asarray', 'np.asarray', (['cost_matrix'], {}), '(cost_matrix)\n', (2937, 2950), True, 'import numpy as np\n'), ((3713, 3734), 'numpy.where', 'np.where', (['(marked == 1)'], {}), '(marked == 1)\n', (3721, 3734), True, 'import numpy as np\n'), ((6247, 6289), 'numpy.asarray', 'np.asarray', (['state.col_uncovered'], {'dtype': 'int'}), '(state.col_uncovered, dtype=int)\n', (6257, 6289), True, 'import numpy as np\n'), ((4074, 4096), 'numpy.ones', 'np.ones', (['n'], {'dtype': 'bool'}), '(n, dtype=bool)\n', (4081, 4096), True, 'import numpy as np\n'), ((4127, 4149), 'numpy.ones', 'np.ones', (['m'], {'dtype': 'bool'}), '(m, dtype=bool)\n', (4134, 4149), True, 'import numpy as np\n'), ((4217, 4248), 'numpy.zeros', 'np.zeros', (['(n + m, 2)'], {'dtype': 'int'}), '((n + m, 2), dtype=int)\n', (4225, 4248), True, 'import numpy as np\n'), ((4272, 4299), 'numpy.zeros', 'np.zeros', (['(n, m)'], {'dtype': 'int'}), '((n, m), dtype=int)\n', (4280, 4299), True, 'import numpy as np\n'), ((5595, 5617), 'numpy.any', 'np.any', (['marked'], {'axis': '(0)'}), '(marked, axis=0)\n', (5601, 5617), True, 'import numpy as np\n'), ((8001, 8048), 'numpy.argmax', 'np.argmax', (['(state.marked[:, path[count, 1]] == 1)'], {}), '(state.marked[:, path[count, 1]] == 1)\n', (8010, 8048), True, 'import numpy as np\n'), ((8386, 8430), 'numpy.argmax', 'np.argmax', (['(state.marked[path[count, 0]] == 2)'], {}), '(state.marked[path[count, 0]] == 2)\n', (8395, 8430), True, 'import numpy as np\n'), ((9258, 9285), 'numpy.any', 'np.any', (['state.row_uncovered'], {}), '(state.row_uncovered)\n', (9264, 9285), True, 'import numpy as np\n'), ((9290, 9317), 'numpy.any', 'np.any', (['state.col_uncovered'], {}), '(state.col_uncovered)\n', (9296, 9317), True, 'import numpy as np\n'), ((9337, 9381), 'numpy.min', 'np.min', (['state.C[state.row_uncovered]'], {'axis': '(0)'}), '(state.C[state.row_uncovered], axis=0)\n', (9343, 9381), True, 'import numpy as np\n'), ((9400, 9435), 'numpy.min', 'np.min', (['minval[state.col_uncovered]'], {}), '(minval[state.col_uncovered])\n', (9406, 9435), True, 'import numpy as np\n'), ((5032, 5054), 'numpy.where', 'np.where', (['(state.C == 0)'], {}), '(state.C == 0)\n', (5040, 5054), True, 'import numpy as np\n'), ((6432, 6452), 'numpy.argmax', 'np.argmax', (['covered_C'], {}), '(covered_C)\n', (6441, 6452), True, 'import numpy as np\n'), ((6663, 6696), 'numpy.argmax', 'np.argmax', (['(state.marked[row] == 1)'], {}), '(state.marked[row] == 1)\n', (6672, 6696), True, 'import numpy as np\n'), ((7106, 7148), 'numpy.asarray', 'np.asarray', (['state.row_uncovered'], {'dtype': 'int'}), '(state.row_uncovered, dtype=int)\n', (7116, 7148), True, 'import numpy as np\n')]
from abc import ABC, abstractmethod import numpy as np import pandas as pd from pvrpm.core.enums import ConfigKeys as ck from pvrpm.core.case import SamCase from pvrpm.core.utils import sample, get_higher_components from pvrpm.core.modules.monitor import IndepMonitor class Failure(ABC): """ This abstract class defines how a failure should be set up """ def __init__( self, level: str, comp_level_df: pd.DataFrame, case: SamCase, indep_monitoring: IndepMonitor = None, ): """ Initalizes a failure instance Args: level (str): The component level this failure is apart of comp_level_df (:obj:`pd.DataFrame`): The component level dataframe containing the simulation data case (:obj:`SamCase`): The SAM case for this simulation indep_monitoring (:obj:`IndepMonitoring`, Optional): For updating static monitoring during simulation """ super().__init__() self.level = level self.df = comp_level_df self.case = case self.fails_per_day = {} self.indep_monitoring = indep_monitoring self.last_failure_day = 0 self.mean = None self.initialize_components() @abstractmethod def initialize_components(self): """ Initalizes failure data for all components to be tracked during simulation for this failure type Note: Updates the underlying dataframes in place """ pass @abstractmethod def reinitialize_components(self, df: pd.DataFrame) -> pd.DataFrame: """ Reinitalize components in a dataframe similiar to the inital initalization. Used for when repairs or other things may occur Args: df (:obj:`pd.DataFrame`): The dataframe containing the components to reinitalize Returns: :obj:`pd.DataFrame`: The reinitalized components """ pass @abstractmethod def update(self, day: int): """ Perform a failure update for one day in the simulation: Changes state of a component to failed, incrementing failures and checking warranty only for failed components of each failure type Args: day (int): Current day in the simulation Note: Updates the underlying dataframes in place """ pass class TotalFailure(Failure): """ Describes how a total failure of a component should operate """ def initialize_components(self): component_info = self.case.config[self.level] df = self.df failure_modes = list(component_info.get(ck.FAILURE, {}).keys()) self.mean = {} # init mean for each failure mode possible_failure_times = np.zeros((component_info[ck.NUM_COMPONENT], len(failure_modes))) for i, mode in enumerate(failure_modes): self.mean[mode] = 0 # initalize failure mode by type df[f"failure_by_type_{mode}"] = 0 fail = component_info[ck.FAILURE][mode] if fail.get(ck.FRAC, None) or fail.get(ck.DECAY_FRAC, None): frac = fail[ck.FRAC] if ck.FRAC in fail else fail[ck.DECAY_FRAC] # choose a percentage of components to be defective sample_ = np.random.random_sample(size=component_info[ck.NUM_COMPONENT]) defective = sample_ < frac sample_ = sample(fail[ck.DIST], fail[ck.PARAM], component_info[ck.NUM_COMPONENT]) # only give a possible failure time if the module is defective, otherwise it is set to numpy max float value (which won't be used) possible_failure_times[:, i] = np.where(list(defective), sample_, np.finfo(np.float32).max) else: # setup failure times for each component possible_failure_times[:, i] = sample(fail[ck.DIST], fail[ck.PARAM], component_info[ck.NUM_COMPONENT]) # initalize failures per day for this failure mode self.fails_per_day[mode] = np.zeros(self.case.config[ck.LIFETIME_YRS] * 365) failure_ind = np.argmin(possible_failure_times, axis=1) df["time_to_failure"] = np.amin(possible_failure_times, axis=1) df["failure_type"] = [failure_modes[i] for i in failure_ind] def reinitialize_components(self, df: pd.DataFrame) -> pd.DataFrame: component_info = self.case.config[self.level] failure_modes = list(component_info.get(ck.FAILURE, {}).keys()) fraction_failures = [] num_repaired = len(df) possible_failure_times = np.zeros((num_repaired, len(failure_modes))) for i, mode in enumerate(failure_modes): fail = component_info[ck.FAILURE][mode] if fail.get(ck.FRAC, None) or fail.get(ck.DECAY_FRAC, None): frac = 0 if fail.get(ck.FRAC, None): fraction_failures.append(mode) frac = fail[ck.FRAC] else: frac = fail[ck.DECAY_FRAC] # choose a percentage of modules to be defective sample_ = np.random.random_sample(size=num_repaired) defective = sample_ < frac sample_ = sample(fail[ck.DIST], fail[ck.PARAM], num_repaired) # only give a possible failure time if the module is defective, otherwise it is set to numpy max float value (which won't be used) possible_failure_times[:, i] = np.where( list(defective), sample_, np.finfo(np.float32).max, ) else: # setup failure times for each component possible_failure_times[:, i] = sample(fail[ck.DIST], fail[ck.PARAM], num_repaired) failure_ind = np.argmin(possible_failure_times, axis=1) df["time_to_failure"] = np.amin(possible_failure_times, axis=1) df["failure_type"] = [failure_modes[i] for i in failure_ind] # now, need to make sure that our fractional failures percentages are met for all components in this level # TODO: need to speed this up somehow if fraction_failures: # removes the diminishing effect where at the beginning of the simulation frac modules are a defective failure, then frac of frac is defective, etc. # possible failure times will also include whatever the current failure time is for the component, if its less then a defective one it doesn't change possible_failure_times = np.zeros((len(self.df), len(fraction_failures) + 1)) possible_failure_times.fill(np.finfo(np.float32).max) # NOTE: i think i should just instead of doing the whole df, find the fraction, then sample that fraction from the components and just update those using the same method below for i, mode in enumerate(fraction_failures): counts = (self.df["failure_type"].astype(str) == mode).sum() frac = counts / len(self.df) fail = component_info[ck.FAILURE][mode] if frac >= fail[ck.FRAC]: continue sample_ = np.random.random_sample(size=len(self.df)) # we just want the difference in fractions to bump it up to the failure fraction defective = sample_ < (fail[ck.FRAC] - frac) sample_ = sample(fail[ck.DIST], fail[ck.PARAM], len(self.df)) # only give a possible failure time if the module is defective, otherwise it is set to numpy max float value (which won't be used) possible_failure_times[:, i] = np.where( list(defective), sample_, np.finfo(np.float32).max, ) possible_failure_times[:, -1] = self.df["time_to_failure"] failure_ind = np.argmin(possible_failure_times, axis=1) types = [] for comp, i in enumerate(failure_ind): if i != len(fraction_failures): types.append(fraction_failures[i]) else: types.append(self.df["failure_type"].iloc[comp]) self.df["time_to_failure"] = np.amin(possible_failure_times, axis=1) self.df["failure_type"] = np.array(types).astype(str) return df def update(self, day: int): df = self.df # decrement time to failures for operational modules # TODO: change this to state > 0 once partial failures implemented df["time_to_failure"] -= 1 failure_modes = list(self.case.config[self.level][ck.FAILURE].keys()) # TODO: change this to state > 0 once partial failures implemented mask = (df["state"] == 1) & (df["time_to_failure"] < 1) failed_comps = df.loc[mask].copy() if len(failed_comps) > 0: self.last_failure_day = day failed_comps["time_to_failure"] = 0 failed_comps["cumulative_failures"] += 1 for fail in failure_modes: fail_mask = failed_comps["failure_type"].astype(str) == fail failed_comps.loc[fail_mask, f"failure_by_type_{fail}"] += 1 self.fails_per_day[fail][day] += len(failed_comps.loc[fail_mask]) warranty_mask = failed_comps["time_left_on_warranty"] <= 0 failed_comps.loc[warranty_mask, "cumulative_oow_failures"] += 1 failed_comps["state"] = 0 # update time to detection times for component levels with only independent monitoring # which will have None for monitor times try: if failed_comps["monitor_times"].isnull().any(): # monitor and time to detection will be the time to next indep monitoring indep_monitors = list(self.case.config[self.level][ck.INDEP_MONITOR].keys()) # next indep monitoring is the min of the possible indep monitors for this component level failed_comps["monitor_times"] = np.amin(self.indep_monitoring.indep_monitoring[indep_monitors]) # in order to calculate the time to detection for component levels only monitoring by an # independment monitoring with a threshold (no interval), need to instead # set the nans that will be there to the day in the simulation when these components failed # so it can be calculated later failed_comps["monitor_times"] = failed_comps["monitor_times"].fillna(day) failed_comps["time_to_detection"] = None # failed_comps["monitor_times"].copy() # fails if no monitoring defined, faster then just doing a check if the column exists or whatever except KeyError: pass df.loc[mask] = failed_comps else: # check to see when last failure was for fraction failure, and update components with new failures # if its been longer then the mean time of the distribution # this is so if repairs arent occuring due to poor monitoring, failures are still occuring failure_modes = list(self.case.config[self.level].get(ck.FAILURE, {}).keys()) fraction_failures = [] for mode in failure_modes: fail = self.case.config[self.level][ck.FAILURE][mode] if fail.get(ck.FRAC, None): # extract mean, since some distributions might not have mean defined in params if self.mean[mode] == 0: self.mean[mode] = sample(fail[ck.DIST], fail[ck.PARAM], 10000).mean() if day > (self.mean[mode] + self.last_failure_day): fraction_failures.append(mode) self.last_failure_day = day for mode in fraction_failures: # fail new fraction of components # possible failure times will also include whatever the current failure time is for the component, if its less then a defective one it doesn't change possible_failure_times = np.zeros((len(self.df), len(fraction_failures) + 1)) possible_failure_times.fill(np.finfo(np.float32).max) # NOTE: i think i should just instead of doing the whole df, find the fraction, then sample that fraction from the components and just update those using the same method below for i, mode in enumerate(fraction_failures): fail = self.case.config[self.level][ck.FAILURE][mode] sample_ = np.random.random_sample(size=len(self.df)) defective = sample_ < fail[ck.FRAC] sample_ = sample(fail[ck.DIST], fail[ck.PARAM], len(self.df)) # only give a possible failure time if the module is defective, otherwise it is set to numpy max float value (which won't be used) possible_failure_times[:, i] = np.where( list(defective), sample_, np.finfo(np.float32).max, ) possible_failure_times[:, -1] = self.df["time_to_failure"] failure_ind = np.argmin(possible_failure_times, axis=1) types = [] for comp, i in enumerate(failure_ind): if i != len(fraction_failures): types.append(fraction_failures[i]) else: types.append(self.df["failure_type"].iloc[comp]) self.df["time_to_failure"] = np.amin(possible_failure_times, axis=1) self.df["failure_type"] = np.array(types).astype(str) class PartialFailure(Failure): """ Specifies a decrease in the state of a component via a failure Unlike total failures, every defined partial failure will have its own object, instead of manaing all of them at once """ def __init__( self, level: str, comp_level_df: pd.DataFrame, case: SamCase, mode: str, indep_monitoring: IndepMonitor = None, ): """ Initalizes a partial failure instance Args: level (str): The component level this failure is apart of comp_level_df (:obj:`pd.DataFrame`): The component level dataframe containing the simulation data case (:obj:`SamCase`): The SAM case for this simulation mode (str): The name of the partial failure mode indep_monitoring (:obj:`IndepMonitoring`, Optional): For updating static monitoring during simulation """ self.mode = mode super().__init__(level, comp_level_df, case, indep_monitoring=indep_monitoring) def initialize_components(self): component_info = self.case.config[self.level] df = self.df mode = self.mode failure_times = None # initalize failure mode by type df[f"failure_by_type_{mode}"] = 0 fail = component_info[ck.PARTIAL_FAIL][mode] if fail.get(ck.FRAC, None) or fail.get(ck.DECAY_FRAC, None): frac = fail[ck.FRAC] if ck.FRAC in fail else fail[ck.DECAY_FRAC] # choose a percentage of components to be defective sample_ = np.random.random_sample(size=component_info[ck.NUM_COMPONENT]) defective = sample_ < frac sample_ = sample(fail[ck.DIST], fail[ck.PARAM], component_info[ck.NUM_COMPONENT]) # only give a possible failure time if the module is defective, otherwise it is set to numpy max float value (which won't be used) failure_times = np.where(list(defective), sample_, np.nan) else: # setup failure times for each component failure_times = sample(fail[ck.DIST], fail[ck.PARAM], component_info[ck.NUM_COMPONENT]) # initalize failures per day for this failure mode self.fails_per_day = {self.mode: np.zeros(self.case.config[ck.LIFETIME_YRS] * 365)} df[f"time_to_failure_{mode}"] = failure_times def reinitialize_components(self, df: pd.DataFrame) -> pd.DataFrame: component_info = self.case.config[self.level] num_repaired = len(df) fraction_failure = False failure_times = None mode = self.mode fail = component_info[ck.PARTIAL_FAIL][mode] if fail.get(ck.FRAC, None) or fail.get(ck.DECAY_FRAC, None): if fail.get(ck.FRAC, None): fraction_failure = True frac = fail[ck.FRAC] else: frac = fail[ck.DECAY_FRAC] # choose a percentage of modules to be defective sample_ = np.random.random_sample(size=num_repaired) defective = sample_ < frac sample_ = sample(fail[ck.DIST], fail[ck.PARAM], num_repaired) # only give a possible failure time if the module is defective, otherwise it is set to nan, partial failure is not applied failure_times = np.where(list(defective), sample_, np.nan) else: # setup failure times for each component failure_times = sample(fail[ck.DIST], fail[ck.PARAM], num_repaired) df[f"time_to_failure_{mode}"] = failure_times # now, need to make sure that our fractional failure percentage is met for all components in this level # TODO: need to speed this up somehow if fraction_failure: # removes the diminishing effect where at the beginning of the simulation frac modules are a defective failure, then frac of frac is defective, etc. # NOTE: i think i should just instead of doing the whole df, find the fraction, then sample that fraction from the components and just update those using the same method below # number currently with failure mode is going to be the number non nan time_to_failures counts = self.df[f"time_to_failure_{mode}"].isna() update_df = self.df.loc[counts].copy() frac = (~counts).sum() / len(self.df) if frac >= fail[ck.FRAC]: return df sample_ = np.random.random_sample(size=len(update_df)) # we just want the difference in fractions to bump it up to the failure fraction defective = sample_ < (fail[ck.FRAC] - frac) sample_ = sample(fail[ck.DIST], fail[ck.PARAM], len(update_df)) # only give a possible failure time if the module is defective, otherwise it is set to numpy max float value (which won't be used) failure_times = np.where( list(defective), sample_, np.nan, ) update_df[f"time_to_failure_{mode}"] = failure_times self.df.loc[counts] = update_df return df def update(self, day: int): df = self.df # decrement time to failures df[f"time_to_failure_{self.mode}"] -= 1 mask = (df["state"] == 1) & (df[f"time_to_failure_{self.mode}"] < 1) failed_comps = df.loc[mask].copy() if len(failed_comps) > 0: self.last_failure_day = day failed_comps["cumulative_failures"] += 1 failed_comps[f"failure_by_type_{self.mode}"] += 1 self.fails_per_day[self.mode][day] += len(failed_comps) warranty_mask = failed_comps["time_left_on_warranty"] <= 0 failed_comps.loc[warranty_mask, "cumulative_oow_failures"] += 1 failed_comps["state"] = 0 # update time to detection times for component levels with only static monitoring # which will have None for monitor times try: if failed_comps["monitor_times"].isnull().any(): # monitor and time to detection will be the time to next static monitoring indep_monitors = list(self.case.config[self.level][ck.INDEP_MONITOR].keys()) # next static monitoring is the min of the possible static monitors for this component level failed_comps["monitor_times"] = np.amin(self.indep_monitoring.indep_monitoring[indep_monitors]) # in order to calculate the time to detection for component levels only monitoring by an # independment monitoring with a threshold (no interval), need to instead # set the nans that will be there to the day in the simulation when these components failed # so it can be calculated later failed_comps["monitor_times"] = failed_comps["monitor_times"].fillna(day) failed_comps["time_to_detection"] = None # failed_comps["monitor_times"].copy() # fails if no monitoring defined, faster then just doing a check if the column exists or whatever except KeyError: pass df.loc[mask] = failed_comps else: # check to see when last failure was for fraction failure, and update components with new failures # if its been longer then the mean time of the distribution # this is so if repairs arent occuring due to poor monitoring, failures are still occuring fail = self.case.config[self.level][ck.PARTIAL_FAIL][self.mode] if fail.get(ck.FRAC, None): # extract mean, since some distributions might not have mean defined in params if not self.mean: self.mean = sample(fail[ck.DIST], fail[ck.PARAM], 10000).mean() if day > (self.mean + self.last_failure_day): # fail new fraction of components counts = self.df[f"time_to_failure_{self.mode}"].isna() update_df = self.df.loc[counts].copy() sample_ = np.random.random_sample(size=len(update_df)) # we just want the difference in fractions to bump it up to the failure fraction defective = sample_ < fail[ck.FRAC] sample_ = sample(fail[ck.DIST], fail[ck.PARAM], len(update_df)) # only give a possible failure time if the module is defective, otherwise it is set to numpy max float value (which won't be used) failure_times = np.where( list(defective), sample_, np.nan, ) update_df[f"time_to_failure_{self.mode}"] = failure_times self.df.loc[counts] = update_df self.last_failure_day = day
[ "numpy.random.random_sample", "numpy.amin", "pvrpm.core.utils.sample", "numpy.array", "numpy.zeros", "numpy.finfo", "numpy.argmin" ]
[((4175, 4216), 'numpy.argmin', 'np.argmin', (['possible_failure_times'], {'axis': '(1)'}), '(possible_failure_times, axis=1)\n', (4184, 4216), True, 'import numpy as np\n'), ((4249, 4288), 'numpy.amin', 'np.amin', (['possible_failure_times'], {'axis': '(1)'}), '(possible_failure_times, axis=1)\n', (4256, 4288), True, 'import numpy as np\n'), ((5894, 5935), 'numpy.argmin', 'np.argmin', (['possible_failure_times'], {'axis': '(1)'}), '(possible_failure_times, axis=1)\n', (5903, 5935), True, 'import numpy as np\n'), ((5968, 6007), 'numpy.amin', 'np.amin', (['possible_failure_times'], {'axis': '(1)'}), '(possible_failure_times, axis=1)\n', (5975, 6007), True, 'import numpy as np\n'), ((4102, 4151), 'numpy.zeros', 'np.zeros', (['(self.case.config[ck.LIFETIME_YRS] * 365)'], {}), '(self.case.config[ck.LIFETIME_YRS] * 365)\n', (4110, 4151), True, 'import numpy as np\n'), ((7981, 8022), 'numpy.argmin', 'np.argmin', (['possible_failure_times'], {'axis': '(1)'}), '(possible_failure_times, axis=1)\n', (7990, 8022), True, 'import numpy as np\n'), ((8333, 8372), 'numpy.amin', 'np.amin', (['possible_failure_times'], {'axis': '(1)'}), '(possible_failure_times, axis=1)\n', (8340, 8372), True, 'import numpy as np\n'), ((15496, 15558), 'numpy.random.random_sample', 'np.random.random_sample', ([], {'size': 'component_info[ck.NUM_COMPONENT]'}), '(size=component_info[ck.NUM_COMPONENT])\n', (15519, 15558), True, 'import numpy as np\n'), ((15621, 15692), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', 'component_info[ck.NUM_COMPONENT]'], {}), '(fail[ck.DIST], fail[ck.PARAM], component_info[ck.NUM_COMPONENT])\n', (15627, 15692), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((16004, 16075), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', 'component_info[ck.NUM_COMPONENT]'], {}), '(fail[ck.DIST], fail[ck.PARAM], component_info[ck.NUM_COMPONENT])\n', (16010, 16075), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((16177, 16226), 'numpy.zeros', 'np.zeros', (['(self.case.config[ck.LIFETIME_YRS] * 365)'], {}), '(self.case.config[ck.LIFETIME_YRS] * 365)\n', (16185, 16226), True, 'import numpy as np\n'), ((16914, 16956), 'numpy.random.random_sample', 'np.random.random_sample', ([], {'size': 'num_repaired'}), '(size=num_repaired)\n', (16937, 16956), True, 'import numpy as np\n'), ((17019, 17070), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', 'num_repaired'], {}), '(fail[ck.DIST], fail[ck.PARAM], num_repaired)\n', (17025, 17070), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((17373, 17424), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', 'num_repaired'], {}), '(fail[ck.DIST], fail[ck.PARAM], num_repaired)\n', (17379, 17424), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((3343, 3405), 'numpy.random.random_sample', 'np.random.random_sample', ([], {'size': 'component_info[ck.NUM_COMPONENT]'}), '(size=component_info[ck.NUM_COMPONENT])\n', (3366, 3405), True, 'import numpy as np\n'), ((3476, 3547), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', 'component_info[ck.NUM_COMPONENT]'], {}), '(fail[ck.DIST], fail[ck.PARAM], component_info[ck.NUM_COMPONENT])\n', (3482, 3547), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((3927, 3998), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', 'component_info[ck.NUM_COMPONENT]'], {}), '(fail[ck.DIST], fail[ck.PARAM], component_info[ck.NUM_COMPONENT])\n', (3933, 3998), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((5196, 5238), 'numpy.random.random_sample', 'np.random.random_sample', ([], {'size': 'num_repaired'}), '(size=num_repaired)\n', (5219, 5238), True, 'import numpy as np\n'), ((5309, 5360), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', 'num_repaired'], {}), '(fail[ck.DIST], fail[ck.PARAM], num_repaired)\n', (5315, 5360), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((5819, 5870), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', 'num_repaired'], {}), '(fail[ck.DIST], fail[ck.PARAM], num_repaired)\n', (5825, 5870), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((13424, 13465), 'numpy.argmin', 'np.argmin', (['possible_failure_times'], {'axis': '(1)'}), '(possible_failure_times, axis=1)\n', (13433, 13465), True, 'import numpy as np\n'), ((13804, 13843), 'numpy.amin', 'np.amin', (['possible_failure_times'], {'axis': '(1)'}), '(possible_failure_times, axis=1)\n', (13811, 13843), True, 'import numpy as np\n'), ((6722, 6742), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (6730, 6742), True, 'import numpy as np\n'), ((8411, 8426), 'numpy.array', 'np.array', (['types'], {}), '(types)\n', (8419, 8426), True, 'import numpy as np\n'), ((10172, 10235), 'numpy.amin', 'np.amin', (['self.indep_monitoring.indep_monitoring[indep_monitors]'], {}), '(self.indep_monitoring.indep_monitoring[indep_monitors])\n', (10179, 10235), True, 'import numpy as np\n'), ((20340, 20403), 'numpy.amin', 'np.amin', (['self.indep_monitoring.indep_monitoring[indep_monitors]'], {}), '(self.indep_monitoring.indep_monitoring[indep_monitors])\n', (20347, 20403), True, 'import numpy as np\n'), ((3778, 3798), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (3786, 3798), True, 'import numpy as np\n'), ((5652, 5672), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (5660, 5672), True, 'import numpy as np\n'), ((7839, 7859), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (7847, 7859), True, 'import numpy as np\n'), ((12393, 12413), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (12401, 12413), True, 'import numpy as np\n'), ((13886, 13901), 'numpy.array', 'np.array', (['types'], {}), '(types)\n', (13894, 13901), True, 'import numpy as np\n'), ((13270, 13290), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (13278, 13290), True, 'import numpy as np\n'), ((21744, 21788), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', '(10000)'], {}), '(fail[ck.DIST], fail[ck.PARAM], 10000)\n', (21750, 21788), False, 'from pvrpm.core.utils import sample, get_higher_components\n'), ((11763, 11807), 'pvrpm.core.utils.sample', 'sample', (['fail[ck.DIST]', 'fail[ck.PARAM]', '(10000)'], {}), '(fail[ck.DIST], fail[ck.PARAM], 10000)\n', (11769, 11807), False, 'from pvrpm.core.utils import sample, get_higher_components\n')]
''' load lottery tickets and evaluation support datasets: cifar10, Fashionmnist, cifar100 ''' import os import time import random import shutil import argparse import numpy as np from copy import deepcopy import matplotlib.pyplot as plt import torch import torch.optim import torch.nn as nn import torch.utils.data import torch.nn.functional as F import torchvision.models as models import torch.backends.cudnn as cudnn import torchvision.transforms as transforms import torchvision.datasets as datasets from torch.utils.data.sampler import SubsetRandomSampler from advertorch.utils import NormalizeByChannelMeanStd from utils import * from pruning_utils_2 import * from pruning_utils_unprune import * parser = argparse.ArgumentParser(description='PyTorch Evaluation Tickets') ##################################### general setting ################################################# parser.add_argument('--data', type=str, default='../../data', help='location of the data corpus') parser.add_argument('--dataset', type=str, default='cifar10', help='dataset') parser.add_argument('--arch', type=str, default='res18', help='model architecture') parser.add_argument('--seed', default=None, type=int, help='random seed') parser.add_argument('--save_dir', help='The directory used to save the trained models', default=None, type=str) parser.add_argument('--gpu', type=int, default=0, help='gpu device id') parser.add_argument('--save_model', action="store_true", help="whether saving model") ##################################### training setting ################################################# parser.add_argument('--optim', type=str, default='sgd', help='optimizer') parser.add_argument('--batch_size', type=int, default=128, help='batch size') parser.add_argument('--lr', default=0.1, type=float, help='initial learning rate') parser.add_argument('--momentum', default=0.9, type=float, help='momentum') parser.add_argument('--weight_decay', default=1e-4, type=float, help='weight decay') parser.add_argument('--epochs', default=182, type=int, help='number of total epochs to run') parser.add_argument('--warmup', default=0, type=int, help='warm up epochs') parser.add_argument('--print_freq', default=50, type=int, help='print frequency') parser.add_argument('--decreasing_lr', default='91,136', help='decreasing strategy') ##################################### Pruning setting ################################################# parser.add_argument('--pretrained', default=None, type=str, help='pretrained weight for pt') parser.add_argument('--mask_dir', default=None, type=str, help='mask direction for ticket') parser.add_argument('--conv1', action="store_true", help="whether pruning&rewind conv1") parser.add_argument('--fc', action="store_true", help="whether rewind fc") parser.add_argument('--type', type=str, default=None, choices=['ewp', 'random_path', 'betweenness', 'hessian_abs', 'taylor1_abs','intgrads','identity', 'omp']) parser.add_argument('--add-back', action="store_true", help="add back weights") parser.add_argument('--prune-type', type=str, choices=["lt", 'pt', 'st', 'mt', 'trained', 'transfer']) parser.add_argument('--num-paths', default=50000, type=int) parser.add_argument('--evaluate', action="store_true") parser.add_argument('--evaluate-p', type=float, default=0.00) parser.add_argument('--evaluate-random', action="store_true") parser.add_argument('--evaluate-full', action="store_true") parser.add_argument('--checkpoint', type=str) best_sa = 0 def main(): global args, best_sa args = parser.parse_args() print(args) print('*'*50) print('conv1 included for prune and rewind: {}'.format(args.conv1)) print('fc included for rewind: {}'.format(args.fc)) print('*'*50) torch.cuda.set_device(int(args.gpu)) os.makedirs(args.save_dir, exist_ok=True) if args.seed: setup_seed(args.seed) # prepare dataset model, train_loader, val_loader, test_loader = setup_model_dataset(args) criterion = nn.CrossEntropyLoss() if args.evaluate: state_dict = torch.load(args.checkpoint, map_location="cpu")['state_dict'] if not args.evaluate_full: current_mask = extract_mask(state_dict) print(current_mask.keys()) prune_model_custom(model, current_mask, conv1=False) check_sparsity(model, conv1=False) try: model.load_state_dict(state_dict) except: state_dict['normalize.mean'] = model.state_dict()['normalize.mean'] state_dict['normalize.std'] = model.state_dict()['normalize.std'] model.load_state_dict(state_dict) model.cuda() validate(val_loader, model, criterion) if args.evaluate_p > 0: pruning_model(model, args.evaluate_p, random=args.evaluate_random) check_sparsity(model, conv1=False) tacc = validate(val_loader, model, criterion) # evaluate on test set test_tacc = validate(test_loader, model, criterion) print(tacc) print(test_tacc) return #loading tickets model.cuda() load_ticket(model, args) decreasing_lr = list(map(int, args.decreasing_lr.split(','))) optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=args.momentum, weight_decay=args.weight_decay) scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=decreasing_lr, gamma=0.1) all_result = {} all_result['train'] = [] all_result['test_ta'] = [] all_result['ta'] = [] start_epoch = 0 remain_weight = check_sparsity(model, conv1=args.conv1) for epoch in range(start_epoch, args.epochs): print(optimizer.state_dict()['param_groups'][0]['lr']) acc = train(train_loader, model, criterion, optimizer, epoch) # evaluate on validation set tacc = validate(val_loader, model, criterion) # evaluate on test set test_tacc = validate(test_loader, model, criterion) scheduler.step() all_result['train'].append(acc) all_result['ta'].append(tacc) all_result['test_ta'].append(test_tacc) all_result['remain_weight'] = remain_weight # remember best prec@1 and save checkpoint is_best_sa = tacc > best_sa best_sa = max(tacc, best_sa) if args.save_model: save_checkpoint({ 'result': all_result, 'epoch': epoch + 1, 'state_dict': model.state_dict(), 'best_sa': best_sa, 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict() }, is_SA_best=is_best_sa, save_path=args.save_dir) else: save_checkpoint({ 'result': all_result }, is_SA_best=False, save_path=args.save_dir) plt.plot(all_result['train'], label='train_acc') plt.plot(all_result['ta'], label='val_acc') plt.plot(all_result['test_ta'], label='test_acc') plt.legend() plt.savefig(os.path.join(args.save_dir, 'net_train.png')) plt.close() check_sparsity(model, conv1=args.conv1) print('* best SA={}'.format(all_result['test_ta'][np.argmax(np.array(all_result['ta']))])) def train(train_loader, model, criterion, optimizer, epoch): losses = AverageMeter() top1 = AverageMeter() # switch to train mode model.train() start = time.time() for i, (image, target) in enumerate(train_loader): if epoch < args.warmup: warmup_lr(epoch, i+1, optimizer, one_epoch_step=len(train_loader)) image = image.cuda() target = target.cuda() # compute output output_clean = model(image) loss = criterion(output_clean, target) optimizer.zero_grad() loss.backward() optimizer.step() output = output_clean.float() loss = loss.float() # measure accuracy and record loss prec1 = accuracy(output.data, target)[0] losses.update(loss.item(), image.size(0)) top1.update(prec1.item(), image.size(0)) if i % args.print_freq == 0: end = time.time() print('Epoch: [{0}][{1}/{2}]\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Accuracy {top1.val:.3f} ({top1.avg:.3f})\t' 'Time {3:.2f}'.format( epoch, i, len(train_loader), end-start, loss=losses, top1=top1)) start = time.time() print('train_accuracy {top1.avg:.3f}'.format(top1=top1)) return top1.avg def validate(val_loader, model, criterion): """ Run evaluation """ losses = AverageMeter() top1 = AverageMeter() # switch to evaluate mode model.eval() for i, (image, target) in enumerate(val_loader): image = image.cuda() target = target.cuda() # compute output with torch.no_grad(): output = model(image) loss = criterion(output, target) output = output.float() loss = loss.float() # measure accuracy and record loss prec1 = accuracy(output.data, target)[0] losses.update(loss.item(), image.size(0)) top1.update(prec1.item(), image.size(0)) if i % args.print_freq == 0: print('Test: [{0}/{1}]\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Accuracy {top1.val:.3f} ({top1.avg:.3f})'.format( i, len(val_loader), loss=losses, top1=top1)) print('valid_accuracy {top1.avg:.3f}' .format(top1=top1)) return top1.avg def save_checkpoint(state, is_SA_best, save_path, filename='checkpoint.pth.tar'): filepath = os.path.join(save_path, filename) torch.save(state, filepath) if is_SA_best: shutil.copyfile(filepath, os.path.join(save_path, 'model_SA_best.pth.tar')) def load_ticket(model, args): # weight if args.pretrained: initalization = torch.load(args.pretrained, map_location = torch.device('cuda:'+str(args.gpu))) if 'init_weight' in initalization.keys(): print('loading from init_weight') initalization = initalization['init_weight'] elif 'state_dict' in initalization.keys(): print('loading from state_dict') initalization = initalization['state_dict'] loading_weight = extract_main_weight(initalization, fc=True, conv1=True) new_initialization = model.state_dict() if not 'normalize.std' in loading_weight: loading_weight['normalize.std'] = new_initialization['normalize.std'] loading_weight['normalize.mean'] = new_initialization['normalize.mean'] if not (args.prune_type == 'lt' or args.prune_type == 'trained'): keys = list(loading_weight.keys()) for key in keys: if key.startswith('fc') or key.startswith('conv1'): del loading_weight[key] loading_weight['fc.weight'] = new_initialization['fc.weight'] loading_weight['fc.bias'] = new_initialization['fc.bias'] loading_weight['conv1.weight'] = new_initialization['conv1.weight'] print('*number of loading weight={}'.format(len(loading_weight.keys()))) print('*number of model weight={}'.format(len(model.state_dict().keys()))) model.load_state_dict(loading_weight) # mask if args.mask_dir: print('loading mask') current_mask_weight = torch.load(args.mask_dir, map_location = torch.device('cuda:'+str(args.gpu))) if 'state_dict' in current_mask_weight.keys(): current_mask_weight = current_mask_weight['state_dict'] current_mask = extract_mask(current_mask_weight) #check_sparsity(model, conv1=args.conv1) if args.arch == 'res18': downsample = 100 else: downsample = 1000 custom_prune(model, current_mask, args.type, args.num_paths, args, args.add_back) #prune_random_betweeness(model, current_mask, int(args.num_paths), downsample=downsample, conv1=args.conv1) check_sparsity(model, conv1=args.conv1) def warmup_lr(epoch, step, optimizer, one_epoch_step): overall_steps = args.warmup*one_epoch_step current_steps = epoch*one_epoch_step + step lr = args.lr * current_steps/overall_steps lr = min(lr, args.lr) for p in optimizer.param_groups: p['lr']=lr class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res def setup_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True if __name__ == '__main__': main()
[ "torch.cuda.manual_seed_all", "torch.manual_seed", "torch.optim.lr_scheduler.MultiStepLR", "os.makedirs", "torch.nn.CrossEntropyLoss", "argparse.ArgumentParser", "torch.load", "matplotlib.pyplot.plot", "os.path.join", "random.seed", "matplotlib.pyplot.close", "numpy.array", "numpy.random.seed", "torch.save", "torch.no_grad", "time.time", "matplotlib.pyplot.legend" ]
[((719, 784), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch Evaluation Tickets"""'}), "(description='PyTorch Evaluation Tickets')\n", (742, 784), False, 'import argparse\n'), ((3787, 3828), 'os.makedirs', 'os.makedirs', (['args.save_dir'], {'exist_ok': '(True)'}), '(args.save_dir, exist_ok=True)\n', (3798, 3828), False, 'import os\n'), ((3999, 4020), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (4018, 4020), True, 'import torch.nn as nn\n'), ((5437, 5525), 'torch.optim.lr_scheduler.MultiStepLR', 'torch.optim.lr_scheduler.MultiStepLR', (['optimizer'], {'milestones': 'decreasing_lr', 'gamma': '(0.1)'}), '(optimizer, milestones=decreasing_lr,\n gamma=0.1)\n', (5473, 5525), False, 'import torch\n'), ((7533, 7544), 'time.time', 'time.time', ([], {}), '()\n', (7542, 7544), False, 'import time\n'), ((9838, 9871), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (9850, 9871), False, 'import os\n'), ((9876, 9903), 'torch.save', 'torch.save', (['state', 'filepath'], {}), '(state, filepath)\n', (9886, 9903), False, 'import torch\n'), ((13467, 13490), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (13484, 13490), False, 'import torch\n'), ((13496, 13528), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (13522, 13528), False, 'import torch\n'), ((13534, 13554), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (13548, 13554), True, 'import numpy as np\n'), ((13560, 13577), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (13571, 13577), False, 'import random\n'), ((6947, 6995), 'matplotlib.pyplot.plot', 'plt.plot', (["all_result['train']"], {'label': '"""train_acc"""'}), "(all_result['train'], label='train_acc')\n", (6955, 6995), True, 'import matplotlib.pyplot as plt\n'), ((7004, 7047), 'matplotlib.pyplot.plot', 'plt.plot', (["all_result['ta']"], {'label': '"""val_acc"""'}), "(all_result['ta'], label='val_acc')\n", (7012, 7047), True, 'import matplotlib.pyplot as plt\n'), ((7056, 7105), 'matplotlib.pyplot.plot', 'plt.plot', (["all_result['test_ta']"], {'label': '"""test_acc"""'}), "(all_result['test_ta'], label='test_acc')\n", (7064, 7105), True, 'import matplotlib.pyplot as plt\n'), ((7114, 7126), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (7124, 7126), True, 'import matplotlib.pyplot as plt\n'), ((7201, 7212), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7210, 7212), True, 'import matplotlib.pyplot as plt\n'), ((4065, 4112), 'torch.load', 'torch.load', (['args.checkpoint'], {'map_location': '"""cpu"""'}), "(args.checkpoint, map_location='cpu')\n", (4075, 4112), False, 'import torch\n'), ((7147, 7191), 'os.path.join', 'os.path.join', (['args.save_dir', '"""net_train.png"""'], {}), "(args.save_dir, 'net_train.png')\n", (7159, 7191), False, 'import os\n'), ((8277, 8288), 'time.time', 'time.time', ([], {}), '()\n', (8286, 8288), False, 'import time\n'), ((8595, 8606), 'time.time', 'time.time', ([], {}), '()\n', (8604, 8606), False, 'import time\n'), ((9034, 9049), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9047, 9049), False, 'import torch\n'), ((9957, 10005), 'os.path.join', 'os.path.join', (['save_path', '"""model_SA_best.pth.tar"""'], {}), "(save_path, 'model_SA_best.pth.tar')\n", (9969, 10005), False, 'import os\n'), ((7322, 7348), 'numpy.array', 'np.array', (["all_result['ta']"], {}), "(all_result['ta'])\n", (7330, 7348), True, 'import numpy as np\n')]
import time from absl import app, flags, logging from absl.flags import FLAGS import cv2 import numpy as np import tensorflow as tf from yolov3_tf2.models import ( YoloV3, YoloV3Tiny ) from yolov3_tf2.dataset import transform_images, load_tfrecord_dataset from yolov3_tf2.utils import draw_outputs flags.DEFINE_string('classes', './data/vocmine.names', 'path to classes file') flags.DEFINE_string('weights', './checkpoints/yolov3_train_9.tf', 'path to weights file') flags.DEFINE_boolean('tiny', False, 'yolov3 or yolov3-tiny') flags.DEFINE_integer('size', 416, 'resize images to') flags.DEFINE_string('image', './data/girl.png', 'path to input image') flags.DEFINE_string('tfrecord', None, 'tfrecord instead of image') flags.DEFINE_string('output', './output.jpg', 'path to output image') flags.DEFINE_integer('num_classes', 80, 'number of classes in the model') def main(_argv): physical_devices = tf.config.experimental.list_physical_devices('GPU') for physical_device in physical_devices: tf.config.experimental.set_memory_growth(physical_device, True) if FLAGS.tiny: yolo = YoloV3Tiny(classes=FLAGS.num_classes) else: yolo = YoloV3(classes=FLAGS.num_classes) yolo.load_weights(FLAGS.weights).expect_partial() logging.info('weights loaded') class_names = [c.strip() for c in open(FLAGS.classes).readlines()] logging.info('classes loaded') if FLAGS.tfrecord: dataset = load_tfrecord_dataset( FLAGS.tfrecord, FLAGS.classes, FLAGS.size) dataset = dataset.shuffle(512) img_raw, _label = next(iter(dataset.take(1))) else: img_raw = tf.image.decode_image( open(FLAGS.image, 'rb').read(), channels=3) img = tf.expand_dims(img_raw, 0) img = transform_images(img, FLAGS.size) t1 = time.time() boxes, scores, classes, nums = yolo(img) t2 = time.time() logging.info('time: {}'.format(t2 - t1)) logging.info('detections:') for i in range(nums[0]): logging.info('\t{}, {}, {}'.format(class_names[int(classes[0][i])], np.array(scores[0][i]), np.array(boxes[0][i]))) img = cv2.cvtColor(img_raw.numpy(), cv2.COLOR_RGB2BGR) img = draw_outputs(img, (boxes, scores, classes, nums), class_names) cv2.imwrite(FLAGS.output, img) logging.info('output saved to: {}'.format(FLAGS.output)) if __name__ == '__main__': try: app.run(main) except SystemExit: pass
[ "cv2.imwrite", "yolov3_tf2.dataset.transform_images", "tensorflow.config.experimental.set_memory_growth", "absl.flags.DEFINE_integer", "absl.logging.info", "absl.flags.DEFINE_boolean", "absl.app.run", "numpy.array", "yolov3_tf2.dataset.load_tfrecord_dataset", "yolov3_tf2.utils.draw_outputs", "time.time", "tensorflow.expand_dims", "yolov3_tf2.models.YoloV3", "absl.flags.DEFINE_string", "yolov3_tf2.models.YoloV3Tiny", "tensorflow.config.experimental.list_physical_devices" ]
[((303, 381), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""classes"""', '"""./data/vocmine.names"""', '"""path to classes file"""'], {}), "('classes', './data/vocmine.names', 'path to classes file')\n", (322, 381), False, 'from absl import app, flags, logging\n'), ((382, 475), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""weights"""', '"""./checkpoints/yolov3_train_9.tf"""', '"""path to weights file"""'], {}), "('weights', './checkpoints/yolov3_train_9.tf',\n 'path to weights file')\n", (401, 475), False, 'from absl import app, flags, logging\n'), ((492, 552), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""tiny"""', '(False)', '"""yolov3 or yolov3-tiny"""'], {}), "('tiny', False, 'yolov3 or yolov3-tiny')\n", (512, 552), False, 'from absl import app, flags, logging\n'), ((553, 606), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""size"""', '(416)', '"""resize images to"""'], {}), "('size', 416, 'resize images to')\n", (573, 606), False, 'from absl import app, flags, logging\n'), ((607, 677), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""image"""', '"""./data/girl.png"""', '"""path to input image"""'], {}), "('image', './data/girl.png', 'path to input image')\n", (626, 677), False, 'from absl import app, flags, logging\n'), ((678, 744), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""tfrecord"""', 'None', '"""tfrecord instead of image"""'], {}), "('tfrecord', None, 'tfrecord instead of image')\n", (697, 744), False, 'from absl import app, flags, logging\n'), ((745, 814), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output"""', '"""./output.jpg"""', '"""path to output image"""'], {}), "('output', './output.jpg', 'path to output image')\n", (764, 814), False, 'from absl import app, flags, logging\n'), ((815, 888), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_classes"""', '(80)', '"""number of classes in the model"""'], {}), "('num_classes', 80, 'number of classes in the model')\n", (835, 888), False, 'from absl import app, flags, logging\n'), ((931, 982), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (975, 982), True, 'import tensorflow as tf\n'), ((1291, 1321), 'absl.logging.info', 'logging.info', (['"""weights loaded"""'], {}), "('weights loaded')\n", (1303, 1321), False, 'from absl import app, flags, logging\n'), ((1398, 1428), 'absl.logging.info', 'logging.info', (['"""classes loaded"""'], {}), "('classes loaded')\n", (1410, 1428), False, 'from absl import app, flags, logging\n'), ((1760, 1786), 'tensorflow.expand_dims', 'tf.expand_dims', (['img_raw', '(0)'], {}), '(img_raw, 0)\n', (1774, 1786), True, 'import tensorflow as tf\n'), ((1797, 1830), 'yolov3_tf2.dataset.transform_images', 'transform_images', (['img', 'FLAGS.size'], {}), '(img, FLAGS.size)\n', (1813, 1830), False, 'from yolov3_tf2.dataset import transform_images, load_tfrecord_dataset\n'), ((1841, 1852), 'time.time', 'time.time', ([], {}), '()\n', (1850, 1852), False, 'import time\n'), ((1907, 1918), 'time.time', 'time.time', ([], {}), '()\n', (1916, 1918), False, 'import time\n'), ((1969, 1996), 'absl.logging.info', 'logging.info', (['"""detections:"""'], {}), "('detections:')\n", (1981, 1996), False, 'from absl import app, flags, logging\n'), ((2306, 2368), 'yolov3_tf2.utils.draw_outputs', 'draw_outputs', (['img', '(boxes, scores, classes, nums)', 'class_names'], {}), '(img, (boxes, scores, classes, nums), class_names)\n', (2318, 2368), False, 'from yolov3_tf2.utils import draw_outputs\n'), ((2373, 2403), 'cv2.imwrite', 'cv2.imwrite', (['FLAGS.output', 'img'], {}), '(FLAGS.output, img)\n', (2384, 2403), False, 'import cv2\n'), ((1036, 1099), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['physical_device', '(True)'], {}), '(physical_device, True)\n', (1076, 1099), True, 'import tensorflow as tf\n'), ((1135, 1172), 'yolov3_tf2.models.YoloV3Tiny', 'YoloV3Tiny', ([], {'classes': 'FLAGS.num_classes'}), '(classes=FLAGS.num_classes)\n', (1145, 1172), False, 'from yolov3_tf2.models import YoloV3, YoloV3Tiny\n'), ((1198, 1231), 'yolov3_tf2.models.YoloV3', 'YoloV3', ([], {'classes': 'FLAGS.num_classes'}), '(classes=FLAGS.num_classes)\n', (1204, 1231), False, 'from yolov3_tf2.models import YoloV3, YoloV3Tiny\n'), ((1471, 1535), 'yolov3_tf2.dataset.load_tfrecord_dataset', 'load_tfrecord_dataset', (['FLAGS.tfrecord', 'FLAGS.classes', 'FLAGS.size'], {}), '(FLAGS.tfrecord, FLAGS.classes, FLAGS.size)\n', (1492, 1535), False, 'from yolov3_tf2.dataset import transform_images, load_tfrecord_dataset\n'), ((2511, 2524), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (2518, 2524), False, 'from absl import app, flags, logging\n'), ((2145, 2167), 'numpy.array', 'np.array', (['scores[0][i]'], {}), '(scores[0][i])\n', (2153, 2167), True, 'import numpy as np\n'), ((2212, 2233), 'numpy.array', 'np.array', (['boxes[0][i]'], {}), '(boxes[0][i])\n', (2220, 2233), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt from time import time import numpy as np from .plotter_utils import figure_ratio, xarray_set_axes_labels, retrieve_or_create_fig_ax # Change the bands (RGB) here if you want other false color combinations def rgb(dataset, at_index=0, x_coord='longitude', y_coord='latitude', bands=['red', 'green', 'blue'], paint_on_mask = [], min_possible=0, max_possible=10000, use_data_min=False, use_data_max=False, min_inten=0.15, max_inten=1.0, width=10, fig=None, ax=None, imshow_kwargs=None): """ Creates a figure showing an area, using three specified bands as the rgb componenets. Parameters ---------- dataset: xarray.Dataset A Dataset containing at least latitude and longitude coordinates and optionally time. The coordinate order should be time, latitude, and finally longitude. Must contain the data variables specified in the `bands` parameter. at_index: int The time index to show. x_coord, y_coord, time_coord: str Names of DataArrays in `dataset_in` to use as x, y, and time coordinates. bands: list-like A list-like containing 3 names of data variables in `dataset` to use as the red, green, and blue bands, respectively. min_possible, max_possible: int The minimum and maximum valid values for the selected bands according to the platform used to retrieve the data in `dataset`. For example, for Landsat these are generally 0 and 10000, respectively. use_data_min: bool Whether to use `min_possible` or the minimum among all selected bands as the band value which has a minimal intensity. use_data_max: bool Whether to use `max_possible` or the maximum among all selected bands as the band value which has a maximal intensity. min_inten, max_inten: float The min and max intensities for any band. These can be in range [0,1]. These can be used to brighten or darken the image. width: int The width of the figure in inches. fig: matplotlib.figure.Figure The figure to use for the plot. If only `fig` is supplied, the Axes object used will be the first. ax: matplotlib.axes.Axes The axes to use for the plot. imshow_kwargs: dict The dictionary of keyword arguments passed to `ax.imshow()`. You can pass a colormap here with the key 'cmap'. Returns ------- fig, ax: matplotlib.figure.Figure, matplotlib.axes.Axes The figure and axes used for the plot. """ imshow_kwargs = {} if imshow_kwargs is None else imshow_kwargs ### < Dataset to RGB Format, needs float values between 0-1 rgb = np.stack([dataset[bands[0]], dataset[bands[1]], dataset[bands[2]]], axis = -1) # Interpolate values to be in the range [0,1] for creating the image. min_rgb = np.nanmin(rgb) if use_data_min else min_possible max_rgb = np.nanmax(rgb) if use_data_max else max_possible rgb = np.interp(rgb, (min_rgb, max_rgb), [min_inten,max_inten]) rgb = rgb.astype(float) ### > ### < takes a T/F mask, apply a color to T areas for mask, color in paint_on_mask: rgb[mask] = np.array(color)/ 255.0 ### > fig, ax = retrieve_or_create_fig_ax(fig, ax, figsize=figure_ratio(rgb.shape[:2], fixed_width = width)) xarray_set_axes_labels(dataset, ax, x_coord, y_coord) if 'time' in dataset.dims: ax.imshow(rgb[at_index], **imshow_kwargs) else: ax.imshow(rgb, **imshow_kwargs) return fig, ax
[ "numpy.stack", "numpy.array", "numpy.nanmax", "numpy.interp", "numpy.nanmin" ]
[((2732, 2808), 'numpy.stack', 'np.stack', (['[dataset[bands[0]], dataset[bands[1]], dataset[bands[2]]]'], {'axis': '(-1)'}), '([dataset[bands[0]], dataset[bands[1]], dataset[bands[2]]], axis=-1)\n', (2740, 2808), True, 'import numpy as np\n'), ((3061, 3119), 'numpy.interp', 'np.interp', (['rgb', '(min_rgb, max_rgb)', '[min_inten, max_inten]'], {}), '(rgb, (min_rgb, max_rgb), [min_inten, max_inten])\n', (3070, 3119), True, 'import numpy as np\n'), ((2939, 2953), 'numpy.nanmin', 'np.nanmin', (['rgb'], {}), '(rgb)\n', (2948, 2953), True, 'import numpy as np\n'), ((3002, 3016), 'numpy.nanmax', 'np.nanmax', (['rgb'], {}), '(rgb)\n', (3011, 3016), True, 'import numpy as np\n'), ((3284, 3299), 'numpy.array', 'np.array', (['color'], {}), '(color)\n', (3292, 3299), True, 'import numpy as np\n')]
import logging import os import numpy as np import xml.etree.ElementTree as ET from PIL import Image from paths import DATASETS_ROOT log = logging.getLogger() VOC_CATS = ['__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] class VOCLoader(): def __init__(self, year, split, segmentation=False, augmented_seg=False): assert year in ['07', '12'] self.dataset = 'voc' self.year = year self.root = os.path.join(DATASETS_ROOT, 'VOCdevkit/VOC20%s/' % year) self.split = split assert split in ['train', 'val', 'trainval', 'test'] cats = VOC_CATS self.cats_to_ids = dict(map(reversed, enumerate(cats))) self.ids_to_cats = dict(enumerate(cats)) self.num_classes = len(cats) self.categories = cats[1:] self.segmentation = segmentation self.augmented_seg = augmented_seg assert not self.segmentation or self.segmentation and self.year == '12' if self.augmented_seg: filelist = 'ImageSets/SegmentationAug/%s.txt' elif self.segmentation: filelist = 'ImageSets/Segmentation/%s.txt' else: filelist = 'ImageSets/Main/%s.txt' with open(os.path.join(self.root, filelist % self.split), 'r') as f: self.filenames = f.read().split('\n')[:-1] log.info("Created a loader VOC%s %s with %i images" % (year, split, len(self.filenames))) def load_image(self, name): im = Image.open('%sJPEGImages/%s.jpg' % (self.root, name)).convert('RGB') im = np.array(im) / 255.0 im = im.astype(np.float32) return im def get_filenames(self): return self.filenames def read_annotations(self, name): bboxes = [] cats = [] tree = ET.parse('%sAnnotations/%s.xml' % (self.root, name)) root = tree.getroot() width = int(root.find('size/width').text) height = int(root.find('size/height').text) difficulty = [] for obj in root.findall('object'): cat = self.cats_to_ids[obj.find('name').text] difficult = (int(obj.find('difficult').text) != 0) difficulty.append(difficult) cats.append(cat) bbox_tag = obj.find('bndbox') x = int(bbox_tag.find('xmin').text) y = int(bbox_tag.find('ymin').text) w = int(bbox_tag.find('xmax').text)-x h = int(bbox_tag.find('ymax').text)-y bboxes.append((x, y, w, h)) gt_cats = np.array(cats) gt_bboxes = np.array(bboxes).reshape((len(bboxes), 4)) difficulty = np.array(difficulty) seg_gt = self.read_segmentations(name, height, width) output = gt_bboxes, seg_gt, gt_cats, width, height, difficulty return output def read_segmentations(self, name, height, width): if self.segmentation: try: seg_folder = self.root + 'SegmentationClass/' seg_file = seg_folder + name + '.png' seg_map = Image.open(seg_file) except: assert self.augmented_seg seg_folder = self.root + 'SegmentationClassAug/' seg_file = seg_folder + name + '.png' seg_map = Image.open(seg_file) segmentation = np.array(seg_map, dtype=np.uint8) else: # if there is no segmentation for a particular image we fill the mask # with zeros to keep the same amount of tensors but don't learn from it segmentation = np.zeros([height, width], dtype=np.uint8) + 255 return segmentation
[ "logging.getLogger", "PIL.Image.open", "xml.etree.ElementTree.parse", "os.path.join", "numpy.array", "numpy.zeros" ]
[((143, 162), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (160, 162), False, 'import logging\n'), ((634, 690), 'os.path.join', 'os.path.join', (['DATASETS_ROOT', "('VOCdevkit/VOC20%s/' % year)"], {}), "(DATASETS_ROOT, 'VOCdevkit/VOC20%s/' % year)\n", (646, 690), False, 'import os\n'), ((1978, 2030), 'xml.etree.ElementTree.parse', 'ET.parse', (["('%sAnnotations/%s.xml' % (self.root, name))"], {}), "('%sAnnotations/%s.xml' % (self.root, name))\n", (1986, 2030), True, 'import xml.etree.ElementTree as ET\n'), ((2718, 2732), 'numpy.array', 'np.array', (['cats'], {}), '(cats)\n', (2726, 2732), True, 'import numpy as np\n'), ((2817, 2837), 'numpy.array', 'np.array', (['difficulty'], {}), '(difficulty)\n', (2825, 2837), True, 'import numpy as np\n'), ((1751, 1763), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (1759, 1763), True, 'import numpy as np\n'), ((3516, 3549), 'numpy.array', 'np.array', (['seg_map'], {'dtype': 'np.uint8'}), '(seg_map, dtype=np.uint8)\n', (3524, 3549), True, 'import numpy as np\n'), ((1411, 1457), 'os.path.join', 'os.path.join', (['self.root', '(filelist % self.split)'], {}), '(self.root, filelist % self.split)\n', (1423, 1457), False, 'import os\n'), ((1669, 1722), 'PIL.Image.open', 'Image.open', (["('%sJPEGImages/%s.jpg' % (self.root, name))"], {}), "('%sJPEGImages/%s.jpg' % (self.root, name))\n", (1679, 1722), False, 'from PIL import Image\n'), ((2753, 2769), 'numpy.array', 'np.array', (['bboxes'], {}), '(bboxes)\n', (2761, 2769), True, 'import numpy as np\n'), ((3240, 3260), 'PIL.Image.open', 'Image.open', (['seg_file'], {}), '(seg_file)\n', (3250, 3260), False, 'from PIL import Image\n'), ((3757, 3798), 'numpy.zeros', 'np.zeros', (['[height, width]'], {'dtype': 'np.uint8'}), '([height, width], dtype=np.uint8)\n', (3765, 3798), True, 'import numpy as np\n'), ((3468, 3488), 'PIL.Image.open', 'Image.open', (['seg_file'], {}), '(seg_file)\n', (3478, 3488), False, 'from PIL import Image\n')]
import numpy as np from skmultiflow.drift_detection import ADWIN def demo(): """ _test_adwin In this demo, an ADWIN object evaluates a sequence of numbers corresponding to 2 distributions. The ADWIN object indicates the indices where change is detected. The first half of the data is a sequence of randomly generated 0's and 1's. The second half of the data is a normal distribution of integers from 0 to 7. """ adwin = ADWIN() size = 2000 change_start = 999 np.random.seed(1) data_stream = np.random.randint(2, size=size) data_stream[change_start:] = np.random.randint(8, size=size-change_start) for i in range(size): adwin.add_element(data_stream[i]) if adwin.detected_change(): print('Change has been detected in data: ' + str(data_stream[i]) + ' - of index: ' + str(i)) if __name__ == '__main__': demo()
[ "skmultiflow.drift_detection.ADWIN", "numpy.random.randint", "numpy.random.seed" ]
[((463, 470), 'skmultiflow.drift_detection.ADWIN', 'ADWIN', ([], {}), '()\n', (468, 470), False, 'from skmultiflow.drift_detection import ADWIN\n'), ((514, 531), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (528, 531), True, 'import numpy as np\n'), ((550, 581), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'size'}), '(2, size=size)\n', (567, 581), True, 'import numpy as np\n'), ((615, 661), 'numpy.random.randint', 'np.random.randint', (['(8)'], {'size': '(size - change_start)'}), '(8, size=size - change_start)\n', (632, 661), True, 'import numpy as np\n')]
# ========================================================================== # # Copyright NumFOCUS # # 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.txt # # 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 re from typing import Optional, Union, Dict, Any, List, Tuple, Sequence, TYPE_CHECKING from sys import stderr as system_error_stream import numpy as np try: from numpy.typing import ArrayLike except ImportError: from numpy import ndarray as ArrayLike import warnings from sys import stderr as system_error_stream import os import builtins fileiotype = Union[str, bytes, os.PathLike] import itk.support.types as itkt from .helpers import wasm_type_from_image_type, image_type_from_wasm_type from .helpers import wasm_type_from_mesh_type, mesh_type_from_wasm_type, python_to_js from .helpers import wasm_type_from_pointset_type, pointset_type_from_wasm_type if TYPE_CHECKING: try: import xarray as xr except ImportError: pass try: import vtk except ImportError: pass __all__ = [ "output", "image", "set_nthreads", "get_nthreads", "echo", "size", "physical_size", "spacing", "origin", "index", "region", "GetArrayFromImage", "array_from_image", "GetArrayViewFromImage", "array_view_from_image", "GetImageFromArray", "image_from_array", "GetImageViewFromArray", "image_view_from_array", "array_from_vector_container", "array_view_from_vector_container", "vector_container_from_array", "GetArrayFromVnlVector", "array_from_vnl_vector", "GetVnlVectorFromArray", "vnl_vector_from_array", "GetArrayViewFromVnlVector", "array_view_from_vnl_vector", "GetVnlMatrixFromArray", "vnl_matrix_from_array", "GetArrayFromVnlMatrix", "array_from_vnl_matrix", "GetArrayViewFromVnlMatrix", "array_view_from_vnl_matrix", "GetArrayFromMatrix", "array_from_matrix", "GetMatrixFromArray", "matrix_from_array", "xarray_from_image", "image_from_xarray", "vtk_image_from_image", "image_from_vtk_image", "dict_from_image", "image_from_dict", "image_intensity_min_max", "imwrite", "imread", "meshwrite", "meshread", "mesh_from_dict", "dict_from_mesh", "pointset_from_dict", "dict_from_pointset", "transformwrite", "transformread", "search", "set_inputs", "templated_class", "pipeline", "auto_pipeline", "down_cast", "template", "class_", "ctype", "python_type", "range", "TemplateTypeError", ] def output(input): """ If input object has attribute "GetOutput()" then return an itk image, otherwise this function simply returns the input value """ if hasattr(input, "GetOutput"): return input.GetOutput() return input def image(input): warnings.warn( "WrapITK warning: itk.image() is deprecated. " "Use itk.output() instead." ) return output(input) def set_nthreads(number_of_threads: int) -> None: """ Support convenient set of the number of threads. Use example (in python): import itk itk.set_nthreads(4) ## use 4 threads """ assert number_of_threads > 0, ( "Please set a positive number of threads instead of %d" % number_of_threads ) import itk threader = itk.MultiThreaderBase.New() threader.SetGlobalDefaultNumberOfThreads(number_of_threads) def get_nthreads() -> int: """ Get the number of threads """ import itk threader = itk.MultiThreaderBase.New() return threader.GetGlobalDefaultNumberOfThreads() def echo(obj, f=system_error_stream) -> None: """Print an object to stream If the object has a method Print(), this method is used. repr(obj) is used otherwise """ print(f, obj) def size(image_or_filter: "itkt.ImageOrImageSource") -> Sequence[int]: """Return the size of an image, or of the output image of a filter This method take care of updating the needed information """ # we don't need the entire output, only its size import itk image_or_filter.UpdateOutputInformation() img = itk.output(image_or_filter) return img.GetLargestPossibleRegion().GetSize() def physical_size(image_or_filter: "itkt.ImageOrImageSource") -> Sequence[float]: """Return the physical size of an image, or of the output image of a filter This method take care of updating the needed information """ # required because range is overloaded in this module from builtins import range spacing_ = spacing(image_or_filter) size_ = size(image_or_filter) result = [] for i in range(0, spacing_.Size()): result.append(spacing_.GetElement(i) * size_.GetElement(i)) return result def spacing(image_or_filter: "itkt.ImageOrImageSource") -> Sequence[float]: """Return the spacing of an image, or of the output image of a filter This method take care of updating the needed information """ import itk # we don't need the entire output, only its size image_or_filter.UpdateOutputInformation() img = itk.output(image_or_filter) return img.GetSpacing() def origin(image_or_filter: "itkt.ImageOrImageSource") -> Sequence[float]: """Return the origin of an image, or of the output image of a filter This method take care of updating the needed information """ import itk # we don't need the entire output, only its size image_or_filter.UpdateOutputInformation() img = itk.output(image_or_filter) return img.GetOrigin() def index(image_or_filter: "itkt.ImageOrImageSource") -> Sequence[int]: """Return the index of an image, or of the output image of a filter This method take care of updating the needed information """ import itk # we don't need the entire output, only its size image_or_filter.UpdateOutputInformation() img = itk.output(image_or_filter) return img.GetLargestPossibleRegion().GetIndex() def region(image_or_filter: "itkt.ImageOrImageSource") -> "itkt.ImageRegion": """Return the region of an image, or of the output image of a filter This method take care of updating the needed information """ import itk # we don't need the entire output, only its size image_or_filter.UpdateOutputInformation() img = itk.output(image_or_filter) return img.GetLargestPossibleRegion() def _get_itk_pixelid(numpy_array_type): """Returns a ITK PixelID given a numpy array.""" import itk def _long_type(): if os.name == "nt": return itk.ULL else: return itk.UL # This is a Mapping from numpy array types to itk pixel types. _np_itk = { np.uint8: itk.UC, np.uint16: itk.US, np.uint32: itk.UI, np.uint64: _long_type(), np.int8: itk.SC, np.int16: itk.SS, np.int32: itk.SI, np.int64: itk.SL, np.float32: itk.F, np.float64: itk.D, np.complex64: itk.complex[itk.F], np.complex128: itk.complex[itk.D], } try: return _np_itk[numpy_array_type.dtype.type] except KeyError as e: for key in _np_itk: if np.issubdtype(numpy_array_type.dtype.type, key): return _np_itk[key] raise e def _GetArrayFromImage( image_or_filter, function_name: str, keep_axes: bool, update: bool, ttype ) -> np.ndarray: """Get an Array with the content of the image buffer""" # Finds the image type import itk img = itk.output(image_or_filter) if ttype is not None: if isinstance(ttype, (tuple, list)): if len(ttype) != 1: raise RuntimeError("Expected 1 component in ttype tuple.") ImageType = ttype[0] else: ImageType = ttype else: ImageType = img.__class__ keys = [k for k in itk.PyBuffer.keys() if k[0] == ImageType] if len(keys) == 0: raise RuntimeError("No suitable template parameter can be found.") # Create a numpy array of the type of the input image templatedFunction = getattr(itk.PyBuffer[keys[0]], function_name) return templatedFunction(img, keep_axes, update) def GetArrayFromImage( image_or_filter: "itkt.ImageOrImageSource", keep_axes: bool = False, update: bool = True, ttype=None, ) -> np.ndarray: """Get an array with the content of the image buffer""" return _GetArrayFromImage( image_or_filter, "GetArrayFromImage", keep_axes, update, ttype ) array_from_image = GetArrayFromImage def GetArrayViewFromImage( image_or_filter: "itkt.ImageOrImageSource", keep_axes: bool = False, update: bool = True, ttype=None, ) -> np.ndarray: """Get an array view with the content of the image buffer""" return _GetArrayFromImage( image_or_filter, "GetArrayViewFromImage", keep_axes, update, ttype ) array_view_from_image = GetArrayViewFromImage def _GetImageFromArray(arr: ArrayLike, function_name: str, is_vector: bool, ttype): """Get an ITK image from a Python array.""" import itk # Verify inputs if not isinstance(arr, np.ndarray): arr = np.asarray(arr) if ttype is not None: if is_vector: raise RuntimeError("Cannot specify both `is_vector` and `ttype`.") if isinstance(ttype, (tuple, list)): if len(ttype) != 1: raise RuntimeError("Expected 1 component in ttype tuple.") ImageType = ttype[0] else: ImageType = ttype if type(itk.template(ImageType)) != tuple or len(itk.template(ImageType)) < 2: raise RuntimeError("Cannot determine pixel type from supplied ttype.") is_vector = ( type(itk.template(ImageType)[1][0]) != itk.support.types.itkCType or itk.template(ImageType)[0] == itk.VectorImage ) else: PixelType = _get_itk_pixelid(arr) Dimension = arr.ndim if is_vector: Dimension = arr.ndim - 1 if arr.flags["C_CONTIGUOUS"]: VectorDimension = arr.shape[-1] else: VectorDimension = arr.shape[0] if PixelType == itk.UC: if VectorDimension == 3: ImageType = itk.Image[itk.RGBPixel[itk.UC], Dimension] elif VectorDimension == 4: ImageType = itk.Image[itk.RGBAPixel[itk.UC], Dimension] else: ImageType = itk.VectorImage[PixelType, Dimension] else: ImageType = itk.VectorImage[PixelType, Dimension] else: ImageType = itk.Image[PixelType, Dimension] keys = [k for k in itk.PyBuffer.keys() if k[0] == ImageType] if len(keys) == 0: raise RuntimeError( """No suitable template parameter can be found. Please specify an output type via the 'ttype' keyword parameter.""" ) templatedFunction = getattr(itk.PyBuffer[keys[0]], function_name) return templatedFunction(arr, is_vector) def GetImageFromArray( arr: ArrayLike, is_vector: bool = False, ttype=None ) -> "itkt.ImageBase": """Get an ITK image from a Python array.""" return _GetImageFromArray(arr, "GetImageFromArray", is_vector, ttype) image_from_array = GetImageFromArray def GetImageViewFromArray( arr: ArrayLike, is_vector: bool = False, ttype=None ) -> "itkt.ImageBase": """Get an ITK image view from a Python array.""" return _GetImageFromArray(arr, "GetImageViewFromArray", is_vector, ttype) image_view_from_array = GetImageViewFromArray def array_from_vector_container( container: "itkt.VectorContainer", ttype=None ) -> np.ndarray: """Get an Array with the content of the vector container""" import itk container_template = itk.template(container) IndexType = container_template[1][0] # Find container data type if ttype is not None: if isinstance(ttype, (tuple, list)): if len(ttype) != 1: raise RuntimeError("Expected 1 component in ttype tuple.") DataType = ttype[0] else: DataType = ttype else: DataType = container_template[1][1] keys = [k for k in itk.PyVectorContainer.keys() if k == (IndexType, DataType)] if len(keys) == 0: raise RuntimeError("No suitable template parameter can be found.") # Create numpy array of the type of the input container return itk.PyVectorContainer[keys[0]].array_from_vector_container(container) def array_view_from_vector_container( container: "itkt.VectorContainer", ttype=None ) -> np.ndarray: """Get an Array view with the content of the vector container""" import itk container_template = itk.template(container) IndexType = container_template[1][0] # Find container type if ttype is not None: if isinstance(ttype, (tuple, list)): if len(ttype) != 1: raise RuntimeError("Expected 1 component in ttype tuple.") DataType = ttype[0] else: DataType = ttype else: DataType = container_template[1][1] keys = [k for k in itk.PyVectorContainer.keys() if k == (IndexType, DataType)] if len(keys) == 0: raise RuntimeError("No suitable template parameter can be found.") # Create numpy array of the type of the input container return itk.PyVectorContainer[keys[0]].array_view_from_vector_container(container) def vector_container_from_array(arr: ArrayLike, ttype=None) -> "itkt.VectorContainer": """Get a vector container from a Python array""" import itk # Verify inputs if not isinstance(arr, np.ndarray): arr = np.asarray(arr) # Return VectorContainer with 64-bit index type if os.name == "nt": IndexType = itk.ULL else: IndexType = itk.UL # Find container type if ttype is not None: if isinstance(ttype, (tuple, list)): if len(ttype) != 1: raise RuntimeError("Expected 1 component in ttype tuple.") DataType = ttype[0] else: DataType = ttype else: DataType = _get_itk_pixelid(arr) keys = [k for k in itk.PyVectorContainer.keys() if k == (IndexType, DataType)] if len(keys) == 0: raise RuntimeError("No suitable template parameter can be found.") # Create numpy array of the type of the input container return itk.PyVectorContainer[keys[0]].vector_container_from_array(arr) def _GetArrayFromVnlObject(vnl_object, function_name: str, ttype) -> np.ndarray: """Get an array with the content of vnl_object""" # Finds the vnl object type import itk if ttype is not None: if isinstance(ttype, (tuple, list)): if len(ttype) != 1: raise RuntimeError("Expected 1 component in ttype tuple.") PixelType = ttype[0] else: PixelType = ttype else: PixelType = itk.template(vnl_object)[1][0] keys = [k for k in itk.PyVnl.keys() if k[0] == PixelType] if len(keys) == 0: raise RuntimeError("No suitable template parameter can be found.") # Create a numpy array of the type of the vnl object templatedFunction = getattr(itk.PyVnl[keys[0]], function_name) return templatedFunction(vnl_object) def GetArrayFromVnlVector(vnl_vector, ttype=None) -> np.ndarray: """Get an array with the content of vnl_vector""" return _GetArrayFromVnlObject(vnl_vector, "GetArrayFromVnlVector", ttype) array_from_vnl_vector = GetArrayFromVnlVector def GetArrayViewFromVnlVector(vnl_vector, ttype=None) -> np.ndarray: """Get an array view of vnl_vector""" return _GetArrayFromVnlObject(vnl_vector, "GetArrayViewFromVnlVector", ttype) array_view_from_vnl_vector = GetArrayFromVnlVector def GetArrayFromVnlMatrix(vnl_matrix, ttype=None) -> np.ndarray: """Get an array with the content of vnl_matrix""" return _GetArrayFromVnlObject(vnl_matrix, "GetArrayFromVnlMatrix", ttype) array_from_vnl_matrix = GetArrayFromVnlMatrix def GetArrayViewFromVnlMatrix(vnl_matrix, ttype=None) -> np.ndarray: """Get an array view of vnl_matrix""" return _GetArrayFromVnlObject(vnl_matrix, "GetArrayViewFromVnlMatrix", ttype) array_view_from_vnl_matrix = GetArrayViewFromVnlMatrix def _GetVnlObjectFromArray(arr: ArrayLike, function_name: str, ttype): """Get a vnl object from a Python array.""" import itk # Verify inputs if not isinstance(arr, np.ndarray): arr = np.asarray(arr) if ttype is not None: if isinstance(ttype, (tuple, list)): if len(ttype) != 1: raise RuntimeError("Expected 1 component in ttype tuple.") PixelType = ttype[0] else: PixelType = ttype else: PixelType = _get_itk_pixelid(arr) keys = [k for k in itk.PyVnl.keys() if k[0] == PixelType] if len(keys) == 0: raise RuntimeError("No suitable template parameter can be found.") templatedFunction = getattr(itk.PyVnl[keys[0]], function_name) return templatedFunction(arr) def GetVnlVectorFromArray(arr: ArrayLike, ttype=None): """Get a vnl vector from a Python array.""" return _GetVnlObjectFromArray(arr, "GetVnlVectorFromArray", ttype) vnl_vector_from_array = GetVnlVectorFromArray def GetVnlMatrixFromArray(arr: ArrayLike, ttype=None): """Get a vnl matrix from a Python array.""" return _GetVnlObjectFromArray(arr, "GetVnlMatrixFromArray", ttype) vnl_matrix_from_array = GetVnlMatrixFromArray def GetArrayFromMatrix(itk_matrix) -> np.ndarray: return GetArrayFromVnlMatrix(itk_matrix.GetVnlMatrix().as_matrix()) array_from_matrix = GetArrayFromMatrix def GetMatrixFromArray(arr: ArrayLike) -> "itkt.Matrix": import itk # Verify inputs if not isinstance(arr, np.ndarray): arr = np.asarray(arr) vnl_matrix = GetVnlMatrixFromArray(arr) dims = arr.shape PixelType = _get_itk_pixelid(arr) m = itk.Matrix[PixelType, dims[0], dims[1]](vnl_matrix) return m matrix_from_array = GetMatrixFromArray def xarray_from_image(l_image: "itkt.ImageOrImageSource") -> "xr.DataArray": """Convert an itk.Image to an xarray.DataArray. Origin and spacing metadata is preserved in the xarray's coords. The Direction is set in the `direction` attribute. Dims are labeled as `x`, `y`, `z`, `t`, and `c`. This interface is and behavior is experimental and is subject to possible future changes.""" import xarray as xr import itk import numpy as np array_view = itk.array_view_from_image(l_image) l_spacing = itk.spacing(l_image) l_origin = itk.origin(l_image) l_size = itk.size(l_image) direction = np.flip(itk.array_from_matrix(l_image.GetDirection())) image_dimension = l_image.GetImageDimension() image_dims: Tuple[str, str, str] = ("x", "y", "z", "t") coords = {} for l_index, dim in enumerate(image_dims[:image_dimension]): coords[dim] = np.linspace( l_origin[l_index], l_origin[l_index] + (l_size[l_index] - 1) * l_spacing[l_index], l_size[l_index], dtype=np.float64, ) dims = list(reversed(image_dims[:image_dimension])) components = l_image.GetNumberOfComponentsPerPixel() if components > 1: dims.append("c") coords["c"] = np.arange(components, dtype=np.uint32) direction = np.flip(itk.array_from_matrix(l_image.GetDirection())) attrs = {"direction": direction} metadata = dict(l_image) ignore_keys = {"direction", "origin", "spacing"} for key in metadata: if not key in ignore_keys: attrs[key] = metadata[key] data_array = xr.DataArray(array_view, dims=dims, coords=coords, attrs=attrs) return data_array def image_from_xarray(data_array: "xr.DataArray") -> "itkt.ImageBase": """Convert an xarray.DataArray to an itk.Image. Metadata encoded with xarray_from_image is applied to the itk.Image. This interface is and behavior is experimental and is subject to possible future changes.""" import numpy as np import itk if not {"t", "z", "y", "x", "c"}.issuperset(data_array.dims): raise ValueError('Unsupported dims, supported dims: "t", "z", "y", "x", "c".') image_dims = list({"t", "z", "y", "x"}.intersection(set(data_array.dims))) image_dims.sort(reverse=True) image_dimension = len(image_dims) ordered_dims = ("t", "z", "y", "x")[-image_dimension:] is_vector = "c" in data_array.dims if is_vector: ordered_dims = ordered_dims + ("c",) values = data_array.values if ordered_dims != data_array.dims: dest = list(builtins.range(len(ordered_dims))) source = dest.copy() for ii in builtins.range(len(ordered_dims)): source[ii] = data_array.dims.index(ordered_dims[ii]) values = np.moveaxis(values, source, dest).copy() itk_image = itk.image_view_from_array(values, is_vector=is_vector) l_origin = [0.0] * image_dimension l_spacing = [1.0] * image_dimension for l_index, dim in enumerate(image_dims): coords = data_array.coords[dim] if coords.shape[0] > 1: l_origin[l_index] = float(coords[0]) l_spacing[l_index] = float(coords[1]) - float(coords[0]) l_spacing.reverse() itk_image.SetSpacing(l_spacing) l_origin.reverse() itk_image.SetOrigin(l_origin) if "direction" in data_array.attrs: direction = data_array.attrs["direction"] itk_image.SetDirection(np.flip(direction)) ignore_keys = {"direction", "origin", "spacing"} for key in data_array.attrs: if not key in ignore_keys: itk_image[key] = data_array.attrs[key] return itk_image def vtk_image_from_image(l_image: "itkt.ImageOrImageSource") -> "vtk.vtkImageData": """Convert an itk.Image to a vtk.vtkImageData.""" import itk import vtk from vtk.util.numpy_support import numpy_to_vtk array = itk.array_view_from_image(l_image) vtk_image = vtk.vtkImageData() data_array = numpy_to_vtk(array.reshape(-1)) data_array.SetNumberOfComponents(l_image.GetNumberOfComponentsPerPixel()) data_array.SetName("Scalars") # Always set Scalars for (future?) multi-component volume rendering vtk_image.GetPointData().SetScalars(data_array) dim = l_image.GetImageDimension() l_spacing = [1.0] * 3 l_spacing[:dim] = l_image.GetSpacing() vtk_image.SetSpacing(l_spacing) l_origin = [0.0] * 3 l_origin[:dim] = l_image.GetOrigin() vtk_image.SetOrigin(l_origin) dims = [1] * 3 dims[:dim] = itk.size(l_image) vtk_image.SetDimensions(dims) # Copy direction matrix for VTK>=9 import vtk if vtk.vtkVersion.GetVTKMajorVersion() >= 9: l_direction = l_image.GetDirection() direction = itk.array_from_matrix(l_direction).flatten().tolist() if len(direction) == 4: # Change 2d matrix to 3d direction = [ direction[0], direction[1], 0.0, direction[2], direction[3], 0.0, 0.0, 0.0, 1.0, ] vtk_image.SetDirectionMatrix(direction) if l_image.GetImageDimension() == 3: PixelType = itk.template(l_image)[1][0] if PixelType == itk.Vector: vtk_image.GetPointData().SetVectors(data_array) elif PixelType == itk.CovariantVector: vtk_image.GetPointData().SetVectors(data_array) elif PixelType == itk.SymmetricSecondRankTensor: vtk_image.GetPointData().SetTensors(data_array) elif PixelType == itk.DiffusionTensor3D: vtk_image.GetPointData().SetTensors(data_array) return vtk_image def image_from_vtk_image(vtk_image: "vtk.vtkImageData") -> "itkt.ImageBase": """Convert a vtk.vtkImageData to an itk.Image.""" import itk from vtk.util.numpy_support import vtk_to_numpy point_data = vtk_image.GetPointData() array = vtk_to_numpy(point_data.GetScalars()) array = array.reshape(-1) is_vector = point_data.GetScalars().GetNumberOfComponents() != 1 dims = list(vtk_image.GetDimensions()) if is_vector and dims[-1] == 1: # 2D dims = dims[:2] dims.reverse() dims.append(point_data.GetScalars().GetNumberOfComponents()) else: dims.reverse() array.shape = tuple(dims) l_image = itk.image_view_from_array(array, is_vector) dim = l_image.GetImageDimension() l_spacing = [1.0] * dim l_spacing[:dim] = vtk_image.GetSpacing()[:dim] l_image.SetSpacing(l_spacing) l_origin = [0.0] * dim l_origin[:dim] = vtk_image.GetOrigin()[:dim] l_image.SetOrigin(l_origin) # Direction support with VTK 9 import vtk if vtk.vtkVersion.GetVTKMajorVersion() >= 9: direction = vtk_image.GetDirectionMatrix() if dim == 3: direction_array = np.identity(3) for y in (0, 1, 2): for x in (0, 1, 2): direction_array[x, y] = direction.GetElement(x, y) elif dim == 2: direction_array = np.identity(2) for y in (0, 1): for x in (0, 1): direction_array[x, y] = direction.GetElement(x, y) l_direction = itk.matrix_from_array(direction_array) l_image.SetDirection(l_direction) return l_image def dict_from_image(image: "itkt.Image") -> Dict: """Serialize a Python itk.Image object to a pickable Python dictionary.""" import itk pixel_arr = itk.array_view_from_image(image) imageType = wasm_type_from_image_type(image) return dict( imageType=imageType, origin=tuple(image.GetOrigin()), spacing=tuple(image.GetSpacing()), size=tuple(image.GetBufferedRegion().GetSize()), direction=np.asarray(image.GetDirection()), data=pixel_arr, ) def image_from_dict(image_dict: Dict) -> "itkt.Image": """Deserialize an dictionary representing an itk.Image object.""" import itk ImageType = image_type_from_wasm_type(image_dict["imageType"]) image = itk.PyBuffer[ImageType].GetImageViewFromArray(image_dict["data"]) image.SetOrigin(image_dict["origin"]) image.SetSpacing(image_dict["spacing"]) image.SetDirection(image_dict["direction"]) return image def mesh_from_dict(mesh_dict: Dict) -> "itkt.Mesh": """Deserialize an dictionary representing an itk.Mesh object.""" import itk MeshType = mesh_type_from_wasm_type(mesh_dict["meshType"]) mesh = MeshType.New() mesh.SetObjectName(mesh_dict["name"]) points = mesh_dict["points"] points = itk.vector_container_from_array(points) mesh.SetPoints(points) point_data = mesh_dict["pointData"] point_data = itk.vector_container_from_array(point_data) mesh.SetPointData(point_data) cells = mesh_dict["cells"] cells = itk.vector_container_from_array(cells) mesh.SetCellsArray(cells) cell_data = mesh_dict["cellData"] cell_data = itk.vector_container_from_array(cell_data) mesh.SetCellData(cell_data) return mesh def dict_from_mesh(mesh: "itkt.Mesh") -> Dict: """Serialize a Python itk.Mesh object to a pickable Python dictionary.""" import itk mesh_template = itk.template(mesh) pixel_type, mangle, pixel_type_components = wasm_type_from_mesh_type(mesh) number_of_points = mesh.GetNumberOfPoints() number_of_cells = mesh.GetNumberOfCells() if number_of_cells == 0: cells_array = np.array([], np.uint) else: cells_array = itk.array_view_from_vector_container(mesh.GetCellsArray()) if number_of_points == 0: points_array = np.array([], np.float32) else: points_array = itk.array_view_from_vector_container(mesh.GetPoints()).flatten() point_data = mesh.GetPointData() if point_data.Size() == 0: point_data_numpy = np.array([], mangle) else: point_data_numpy = itk.array_view_from_vector_container(point_data) cell_data = mesh.GetCellData() if cell_data.Size() == 0: cell_data_numpy = np.array([], mangle) else: cell_data_numpy = itk.array_view_from_vector_container(cell_data) if os.name == "nt": cell_component_type = python_to_js(itk.ULL) else: cell_component_type = python_to_js(itk.UL) point_component_type = python_to_js(itk.F) # Currently use the same data type for point and cell data mesh_type = dict() mesh_type["dimension"] = mesh_template[1][1] mesh_type["pointComponentType"] = point_component_type mesh_type["pointPixelComponentType"] = mangle mesh_type["pointPixelType"] = pixel_type mesh_type["pointPixelComponents"] = pixel_type_components mesh_type["cellComponentType"] = cell_component_type mesh_type["cellPixelComponentType"] = mangle mesh_type["cellPixelType"] = pixel_type mesh_type["cellPixelComponents"] = pixel_type_components cell_buffer_size = cells_array.size return dict( meshType=mesh_type, name=mesh.GetObjectName(), dimension=mesh_template[1][1], numberOfPoints=number_of_points, points=points_array, numberOfPointPixels=point_data.Size(), pointData=point_data_numpy, numberOfCells=number_of_cells, cells=cells_array, numberOfCellPixels=cell_data.Size(), cellData=cell_data_numpy, cellBufferSize=cell_buffer_size, ) def pointset_from_dict(pointset_dict: Dict) -> "itkt.PointSet": """Deserialize an dictionary representing an itk.PointSet object.""" import itk MeshType = pointset_type_from_wasm_type(pointset_dict["pointSetType"]) mesh = MeshType.New() mesh.SetObjectName(pointset_dict["name"]) points = pointset_dict["points"] points = itk.vector_container_from_array(points) mesh.SetPoints(points) point_data = pointset_dict["pointData"] point_data = itk.vector_container_from_array(point_data) mesh.SetPointData(point_data) return mesh def dict_from_pointset(pointset: "itkt.PointSet") -> Dict: """Serialize a Python itk.PointSet object to a pickable Python dictionary.""" import itk pointset_template = itk.template(pointset) pixel_type, mangle, pixel_type_components = wasm_type_from_pointset_type(pointset) number_of_points = pointset.GetNumberOfPoints() if number_of_points == 0: points_array = np.array([], np.float32) else: points_array = itk.array_view_from_vector_container(pointset.GetPoints()).flatten() point_data = pointset.GetPointData() if point_data.Size() == 0: point_data_numpy = np.array([], mangle) else: point_data_numpy = itk.array_view_from_vector_container(point_data) if os.name == "nt": cell_component_type = python_to_js(itk.ULL) else: cell_component_type = python_to_js(itk.UL) point_component_type = python_to_js(itk.F) # Currently use the same data type for point and cell data pointset_type = dict() pointset_type["dimension"] = pointset_template[1][1] pointset_type["pointComponentType"] = point_component_type pointset_type["pointPixelComponentType"] = mangle pointset_type["pointPixelType"] = pixel_type pointset_type["pointPixelComponents"] = pixel_type_components return dict( pointSetType=pointset_type, name=pointset.GetObjectName(), dimension=pointset_template[1][1], numberOfPoints=number_of_points, points=points_array, numberOfPointPixels=point_data.Size(), pointData=point_data_numpy, ) def image_intensity_min_max(image_or_filter: "itkt.ImageOrImageSource"): """Return the minimum and maximum of values in a image of in the output image of a filter The minimum and maximum values are returned in a tuple: (min, max) image_intensity_min_max() take care of updating the pipeline """ import itk img = itk.output(image_or_filter) img.UpdateOutputInformation() img.Update() # don't put that calculator in the automatic pipeline tmp_auto_pipeline = auto_pipeline.current auto_pipeline.current = None comp = itk.MinimumMaximumImageCalculator[img].New(Image=img) auto_pipeline.current = tmp_auto_pipeline comp.Compute() return comp.GetMinimum(), comp.GetMaximum() # range is a python function, and should not be overridden # the current use of the function name "range" is for backward # compatibility, but should be considered for removal in the future def range(image_or_filter): return image_intensity_min_max(image_or_filter) def imwrite( image_or_filter: "itkt.ImageOrImageSource", filename: fileiotype, compression: bool = False, imageio: Optional["itkt.ImageIOBase"] = None, ) -> None: """Write a image or the output image of a filter to a file. Parameters ---------- image_or_filter : Image or filter that produces an image to write to the file. filename : Target output file path. compression : Use compression when writing if the format supports it. imageio : Use the provided itk.ImageIOBase derived instance to write the file. The writer is instantiated with the image type of the image in parameter (or, again, with the output image of the filter in parameter). """ import itk img = itk.output(image_or_filter) img.UpdateOutputInformation() # don't put that writer in the automatic pipeline tmp_auto_pipeline = auto_pipeline.current auto_pipeline.current = None writer = itk.ImageFileWriter[type(img)].New( Input=img, FileName=f"{filename}", UseCompression=compression ) auto_pipeline.current = tmp_auto_pipeline if imageio: writer.SetImageIO(imageio) writer.Update() def imread( filename: fileiotype, pixel_type: Optional["itkt.PixelTypes"] = None, fallback_only: bool = False, imageio: Optional["itkt.ImageIOBase"] = None, ) -> "itkt.ImageBase": """Read an image from a file or series of files and return an itk.Image. Parameters ---------- filename : File path for a single file, a list of files for an image series, or a directory for a DICOM image series. pixel_type : Image pixel type to cast to when loading. fallback_only : If true, first try to automatically deduce the image pixel type, and only use the given `pixel_type` if automatic deduction fails. imageio : Use the provided itk.ImageIOBase derived instance to read the file. Returns ------- image : The resulting itk.Image. The reader is instantiated with the image type of the image file if `pixel_type` is not provided (default). The dimension of the image is automatically deduced from the dimension stored on disk. If the filename provided is a directory then the directory is assumed to be for a DICOM series volume. If there is exactly one DICOM series volume in that directory, the reader will use an itk.ImageSeriesReader object to read the the DICOM filenames within that directory. If the given filename is a list or a tuple of file names, the reader will use an itk.ImageSeriesReader object to read the files. If `fallback_only` is set to `True`, `imread()` will first try to automatically deduce the image pixel_type, and only use the given `pixel_type` if automatic deduction fails. Failures typically happen if the pixel type is not supported (e.g. it is not currently wrapped). """ import itk from itk.support.extras import TemplateTypeError if fallback_only: if pixel_type is None: raise Exception( "pixel_type must be set when using the fallback_only option" ) try: return imread(filename) except (KeyError, TemplateTypeError): pass if type(filename) not in [list, tuple]: import os if os.path.isdir(filename): # read DICOM series of 1 image in a folder, refer to: https://github.com/RSIP-Vision/medio names_generator = itk.GDCMSeriesFileNames.New() names_generator.SetUseSeriesDetails(True) names_generator.AddSeriesRestriction("0008|0021") # Series Date names_generator.SetDirectory(f"{filename}") series_uid = names_generator.GetSeriesUIDs() if len(series_uid) == 0: raise FileNotFoundError(f"no DICOMs in: {filename}.") if len(series_uid) > 1: raise OSError( f"the directory: {filename} contains more than one DICOM series." ) series_identifier = series_uid[0] filename = names_generator.GetFileNames(series_identifier) if type(filename) in [list, tuple]: template_reader_type = itk.ImageSeriesReader io_filename = f"{filename[0]}" increase_dimension = True kwargs = {"FileNames": [f"{f}" for f in filename]} else: template_reader_type = itk.ImageFileReader io_filename = f"{filename}" increase_dimension = False kwargs = {"FileName": f"{filename}"} if imageio: kwargs["ImageIO"] = imageio if pixel_type: image_IO = itk.ImageIOFactory.CreateImageIO( io_filename, itk.CommonEnums.IOFileMode_ReadMode ) if not image_IO: raise RuntimeError("No ImageIO is registered to handle the given file.") image_IO.SetFileName(io_filename) image_IO.ReadImageInformation() dimension = image_IO.GetNumberOfDimensions() # Increase dimension if last dimension is not of size one. if increase_dimension and image_IO.GetDimensions(dimension - 1) != 1: dimension += 1 is_vlv = False try: is_vlv = itk.template(pixel_type)[0] is itk.VariableLengthVector except KeyError: pass if is_vlv: ImageType = itk.VectorImage[itk.template(pixel_type)[1][0], dimension] else: ImageType = itk.Image[pixel_type, dimension] reader = template_reader_type[ImageType].New(**kwargs) else: reader = template_reader_type.New(**kwargs) reader.Update() return reader.GetOutput() def meshwrite( mesh: "itkt.Mesh", filename: fileiotype, compression: bool = False ) -> None: """Write a mesh to a file. The writer is instantiated according to the type of the input mesh. """ import itk mesh.UpdateOutputInformation() # don't put that writer in the automatic pipeline tmp_auto_pipeline = auto_pipeline.current auto_pipeline.current = None writer = itk.MeshFileWriter[type(mesh)].New( Input=mesh, FileName=f"{filename}", UseCompression=compression ) auto_pipeline.current = tmp_auto_pipeline writer.Update() def meshread( filename: fileiotype, pixel_type: Optional["itkt.PixelTypes"] = None, fallback_only: bool = False, ) -> "itkt.Mesh": """Read a mesh from a file and return an itk.Mesh. The reader is instantiated with the mesh type of the mesh file if `pixel_type` is not provided (default). The dimension of the mesh is automatically found. If `fallback_only` is set to `True`, `meshread()` will first try to automatically deduce the image pixel_type, and only use the given `pixel_type` if automatic deduction fails. Failures typically happen if the pixel type is not supported (e.g. it is not currently wrapped). """ import itk if fallback_only: if pixel_type is None: raise Exception( "pixel_type must be set when using the fallback_only option" ) try: return meshread(filename) except (KeyError, itk.TemplateTypeError): pass TemplateReaderType = itk.MeshFileReader io_filename = f"{filename}" increase_dimension = False kwargs = {"FileName": f"{filename}"} if pixel_type: meshIO = itk.MeshIOFactory.CreateMeshIO( io_filename, itk.CommonEnums.IOFileMode_ReadMode ) if not meshIO: raise RuntimeError("No MeshIO is registered to handle the given file.") meshIO.SetFileName(io_filename) meshIO.ReadMeshInformation() dimension = meshIO.GetPointDimension() # Increase dimension if last dimension is not of size one. if increase_dimension and meshIO.GetDimensions(dimension - 1) != 1: dimension += 1 MeshType = itk.Mesh[pixel_type, dimension] reader = TemplateReaderType[MeshType].New(**kwargs) else: reader = TemplateReaderType.New(**kwargs) reader.Update() return reader.GetOutput() def transformread(filename: fileiotype) -> List["itkt.TransformBase"]: """Read an itk Transform file. Parameters ---------- filename: Path to the transform file (typically a .h5 file). Returns ------- A Python list containing the transforms in the file. """ import itk reader = itk.TransformFileReaderTemplate[itk.D].New() reader.SetFileName(f"{filename}") reader.Update() transforms = [] transform_list = reader.GetModifiableTransformList() while not transform_list.empty(): transform = transform_list.pop() transforms.append(itk.down_cast(transform)) transforms.reverse() return transforms def transformwrite( transforms: List["itkt.TransformBase"], filename: fileiotype, compression: bool = False, ) -> None: """Write an itk Transform file. Parameters ---------- transforms: list of itk.TransformBaseTemplate[itk.D] Python list of the transforms to write. filename: Path to the transform file (typically a .h5 file). compression: Use compression, if the file format supports it. """ import itk writer = itk.TransformFileWriterTemplate[itk.D].New() writer.SetFileName(f"{filename}") writer.SetUseCompression(compression) for transform in transforms: writer.AddTransform(transform) writer.Update() def search(s: str, case_sensitive: bool = False) -> List[str]: # , fuzzy=True): """Search for a class name in the itk module.""" s = s.replace(" ", "") if not case_sensitive: s = s.lower() import itk names = sorted(dir(itk)) # exact match first if case_sensitive: res = [n for n in names if s == n] else: res = [n for n in names if s == n.lower()] # then exact match inside the name if case_sensitive: res += [n for n in names if s in n and s != n] else: res += [n for n in names if s in n.lower() and s != n.lower()] # if fuzzy: # try: # everything now requires editdist # import editdist # if case_sensitive: # res.sort(key=lambda x: editdist.distance(x, s)) # else: # res.sort(key=lambda x: (editdist.distance(x.lower(), s), x)) # except: # pass return res def _snake_to_camel(keyword: str): # Helpers for set_inputs snake case to CamelCase keyword argument conversion _snake_underscore_re = re.compile("(_)([a-z0-9A-Z])") def _underscore_upper(match_obj): return match_obj.group(2).upper() camel = keyword[0].upper() if _snake_underscore_re.search(keyword[1:]): return camel + _snake_underscore_re.sub(_underscore_upper, keyword[1:]) return camel + keyword[1:] def set_inputs( new_itk_object, inargs: Optional[Sequence[Any]] = None, inkargs: Optional[Dict[str, Any]] = None, ): """Set the inputs of the given objects, according to the non named or the named parameters in args and kargs This function tries to assign all the non named parameters in the input of the new_itk_object - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. set_inputs( obj, kargs={'Threshold': 10} ) calls obj.SetThreshold(10) This is the function use in the enhanced New() method to manage the inputs. It can be used to produce a similar behavior: def SetInputs(self, *args, **kargs): import itk itk.set_inputs(self, *args, **kargs) """ # Fix bug with Mutable Default Arguments # https://docs.python-guide.org/writing/gotchas/ args: List[Any] = inargs if inargs else [] kargs: Dict[str, Any] = inkargs if inkargs else {} # try to get the images from the filters in args args = [output(arg) for arg in args] # args without name are filter used to set input image # # count SetInput calls to call SetInput, SetInput2, SetInput3, ... # useful with filter which take 2 input (or more) like SubtractImageFiler # Ex: subtract image2.png to image1.png and save the result in result.png # r1 = itk.ImageFileReader.US2.New(FileName='image1.png') # r2 = itk.ImageFileReader.US2.New(FileName='image2.png') # s = itk.SubtractImageFilter.US2US2US2.New(r1, r2) # itk.ImageFileWriter.US2.New(s, FileName='result.png').Update() setInputNb: int = -1 try: for setInputNb, arg in enumerate(args): methodName = "SetInput%i" % (setInputNb + 1) if methodName in dir(new_itk_object): # first try to use methods called SetInput1, SetInput2, ... # those method should have more chances to work in case of # multiple input types getattr(new_itk_object, methodName)(arg) else: # no method called SetInput? # try with the standard SetInput(nb, input) new_itk_object.SetInput(setInputNb, arg) except TypeError as e: # the exception have (at least) to possible reasons: # + the filter don't take the input number as first argument # + arg is an object of wrong type # # if it's not the first input, re-raise the exception if setInputNb != 0: raise e # it's the first input, try to use the SetInput() method without input # number new_itk_object.SetInput(args[0]) # but raise an exception if there is more than 1 argument if len(args) > 1: raise TypeError("Object accepts only 1 input.") except AttributeError: # There is no SetInput() method, try SetImage # but before, check the number of inputs if len(args) > 1: raise TypeError("Object accepts only 1 input.") methodList = ["SetImage", "SetInputImage"] methodName = None for m in methodList: if m in dir(new_itk_object): methodName = m if methodName: getattr(new_itk_object, methodName)(args[0]) else: raise AttributeError("No method found to set the input.") # named args : name is the function name, value is argument(s) for attribName, value in kargs.items(): # use Set as prefix. It allow to use a shorter and more intuitive # call (Ex: itk.ImageFileReader.UC2.New(FileName='image.png')) than # with the full name # (Ex: itk.ImageFileReader.UC2.New(SetFileName='image.png')) if attribName not in ["auto_progress", "template_parameters"]: if attribName.islower(): attribName = _snake_to_camel(attribName) attrib = getattr(new_itk_object, "Set" + attribName) # Do not use try-except mechanism as this leads to # segfaults. Instead limit the number of types that are # tested. The list of tested type could maybe be replaced by # a test that would check for iterables. import itk if type(value) in [list, tuple]: try: output_value = [itk.output(x) for x in value] attrib(*output_value) except Exception: attrib(itk.output(value)) else: attrib(itk.output(value)) class templated_class: """This class is used to mimic the behavior of the templated C++ classes. It is used this way: class CustomClass: # class definition here CustomClass = templated_class(CustomClass) customObject = CustomClass[template, parameters].New() The template parameters are passed to the custom class constructor as a named parameter 'template_parameters' in a tuple. The custom class may implement a static method check_template_parameters(parameters) which should raise an exception if the template parameters provided are not suitable to instantiate the custom class. """ def __init__(self, cls) -> None: """cls is the custom class""" self.__cls__ = cls self.__templates__ = {} def New(self, *args, **kargs): """Use the parameters to infer the types of the template parameters.""" # extract the types from the arguments to instantiate the class import itk types = tuple(class_(o) for o in args) return self[types].New(*args, **kargs) def __getitem__(self, template_parameters): """Return a pair class-template parameters ready to be instantiated. The template parameters may be validated if the custom class provide the static method check_template_parameters(parameters). """ if not isinstance(template_parameters, tuple): template_parameters = (template_parameters,) return templated_class.__templated_class_and_parameters__( self, template_parameters ) def check_template_parameters(self, template_parameters) -> None: """Check the template parameters passed in parameter.""" # this method is there mainly to make possible to reuse it in the # custom class constructor after having used templated_class(). # Without that, the following example doesn't work: # # class CustomClass: # def __init__(self, *args, **kargs): # template_parameters = kargs["template_parameters"] # CustomClass.check_template_parameters(template_parameters) # other init stuff # def check_template_parameters(template_parameters): # check, really # pass # CustomClass = templated_class(CustomClass) # self.__cls__.check_template_parameters(template_parameters) def add_template(self, name: str, params): if not isinstance(params, list) and not isinstance(params, tuple): params = (params,) params = tuple(params) val = self[params] self.__templates__[params] = val setattr(self, name, val) def add_image_templates(self, *args) -> None: import itk if not args: return combinations = [[t] for t in args[0]] for types in args[1:]: temp = [] for t in types: for c in combinations: temp.append(c + [t]) combinations = temp for d in itk.DIMS: for c in combinations: parameters = [] name = "" for t in c: parameters.append(itk.Image[t, d]) name += "I" + t.short_name + str(d) self.add_template(name, tuple(parameters)) class __templated_class_and_parameters__: """Inner class used to store the pair class-template parameters ready to instantiate. """ def __init__(self, l_templated_class, l_template_parameters) -> None: self.__templated_class__ = l_templated_class self.__template_parameters__ = l_template_parameters if "check_template_parameters" in dir(l_templated_class.__cls__): l_templated_class.__cls__.check_template_parameters( l_template_parameters ) def New(self, *args, **kargs): """A New() method to mimic the ITK default behavior, even if the class doesn't provide any New() method. """ kargs["template_parameters"] = self.__template_parameters__ if "New" in dir(self.__templated_class__.__cls__): obj = self.__templated_class__.__cls__.New(*args, **kargs) else: obj = self.__templated_class__.__cls__(*args, **kargs) setattr(obj, "__template_parameters__", self.__template_parameters__) setattr(obj, "__templated_class__", self.__templated_class__) return obj def __call__(self, *args, **kargs): return self.New(*args, **kargs) def keys(self): return self.__templates__.keys() def values(self): return list(self.__templates__.values()) def items(self): return list(self.__templates__.items()) # everything after this comment is for dict interface # and is a copy/paste from DictMixin # only methods to edit dictionary are not there def __iter__(self) -> str: yield from self.keys() def has_key(self, key: str): return key in self.__templates__ def __contains__(self, key: str): return key in self def get(self, key: str, default: Optional[str] = None) -> Optional[str]: return self.get(key, default) def __len__(self): return len(self.keys()) class pipeline: """A convenient class to store the reference to the filters of a pipeline With this class, a method can create a pipeline of several filters and return it without losing the references to the filters in this pipeline. The pipeline object act almost like a filter (it has a GetOutput() method) and thus can be simply integrated in another pipeline. """ def __init__(self, *args, **kargs) -> None: self.clear() self.input = None self.filters: List[Any] = [] set_inputs(self, args, kargs) def connect(self, l_filter) -> None: """Connect a new l_filter to the pipeline The output of the first l_filter will be used as the input of this one and the l_filter passed as parameter will be added to the list """ if self.GetOutput() is not None: set_inputs(l_filter, [self.GetOutput()]) self.append(l_filter) def append(self, l_filter) -> None: """Add a new l_filter to the pipeline The new l_filter will not be connected. The user must connect it. """ self.filters.append(l_filter) def clear(self) -> None: """Clear the filter list""" self.filters = [] def GetOutput(self, l_index: int = 0): """Return the output of the pipeline If another output is needed, use pipeline.filters[-1].GetAnotherOutput() instead of this method, subclass pipeline to implement another GetOutput() method, or use expose() """ if len(self.filters) == 0: return self.GetInput() else: l_filter = self.filters[-1] if hasattr(l_filter, "__getitem__"): return l_filter[l_index] try: return l_filter.GetOutput(l_index) except Exception: if l_index == 0: return l_filter.GetOutput() else: raise ValueError("Index can only be 0 on that object") def GetNumberOfOutputs(self) -> int: """Return the number of outputs""" if len(self.filters) == 0: return 1 else: return self.filters[-1].GetNumberOfOutputs() def SetInput(self, l_input) -> None: """Set the l_input of the pipeline""" if len(self.filters) != 0: set_inputs(self.filters[0], [l_input]) self.l_input = l_input def GetInput(self): """Get the input of the pipeline""" return self.input def Update(self): """Update the pipeline""" if len(self.filters) > 0: return self.filters[-1].Update() def UpdateLargestPossibleRegion(self): """Update the pipeline""" if len(self.filters) > 0: return self.filters[-1].UpdateLargestPossibleRegion() def UpdateOutputInformation(self) -> None: if "UpdateOutputInformation" in dir(self.filters[-1]): self.filters[-1].UpdateOutputInformation() else: self.Update() def __len__(self): return self.GetNumberOfOutputs() def __getitem__(self, item): return self.GetOutput(item) def __call__(self, *args, **kargs): set_inputs(self, args, kargs) self.UpdateLargestPossibleRegion() return self def expose(self, name: str, new_name: Optional[str] = None, position: int = -1): """Expose an attribute from a filter of the mini-pipeline. Once called, the pipeline instance has a new Set/Get set of methods to access directly the corresponding method of one of the filter of the pipeline. Ex: p.expose( "Radius" ) p.SetRadius( 5 ) p.GetRadius( 5 ) By default, the attribute usable on the pipeline instance has the same name than the one of the filter, but it can be changed by providing a value to new_name. The last filter of the pipeline is used by default, but another one may be used by giving its position. Ex: p.expose("Radius", "SmoothingNeighborhood", 2) p.GetSmoothingNeighborhood() """ if new_name is None: new_name = name src = self.filters[position] ok: bool = False set_name: str = "Set" + name if set_name in dir(src): setattr(self, "Set" + new_name, getattr(src, set_name)) ok = True get_name = "Get" + name if get_name in dir(src): setattr(self, "Get" + new_name, getattr(src, get_name)) ok = True if not ok: raise RuntimeError(f"No attribute {name} at position {position}.") class auto_pipeline(pipeline): current = None def __init__(self, *args, **kargs) -> None: pipeline.__init__(self, *args, **kargs) self.Start() def Start(self) -> None: auto_pipeline.current = self @staticmethod def Stop() -> None: auto_pipeline.current = None def down_cast(obj: "itkt.LightObject"): """Down cast an itk.LightObject (or a object of a subclass) to its most specialized type. """ import itk from itk.support.template_class import itkTemplate class_name: str = obj.GetNameOfClass() t = getattr(itk, class_name) if isinstance(t, itkTemplate): for c in t.values(): try: return c.cast(obj) except Exception: # fail silently for now pass raise RuntimeError(f"Can't downcast to a specialization of {class_name}") else: return t.cast(obj) def attribute_list(inputobject, name: str): """Returns a list of the specified attributes for the objects in the image. i: the input LabelImage name: the attribute name """ import itk img = itk.output(inputobject) relabel = itk.StatisticsRelabelLabelMapFilter[img].New( img, Attribute=name, ReverseOrdering=True, InPlace=False ) relabel.UpdateLargestPossibleRegion() r = relabel.GetOutput() l_list: List[Any] = [] # required because range is overloaded in this module import sys from builtins import range for i in range(1, r.GetNumberOfLabelObjects() + 1): l_list.append(r.GetLabelObject(i).__getattribute__("Get" + name)()) return l_list def attributes_list(inputObject, names: List[str]): """Returns a list of the specified attributes for the objects in the image. i: the input LabelImage name: the attribute name """ import itk img = itk.output(inputObject) relabel = itk.StatisticsRelabelLabelMapFilter[img].New( img, Attribute=names[0], ReverseOrdering=True, InPlace=False ) relabel.UpdateLargestPossibleRegion() r = relabel.GetOutput() l_list: List[Any] = [] # required because range is overloaded in this module from builtins import range for i in range(1, r.GetNumberOfLabelObjects() + 1): attrs = [] for name in names: attrs.append(r.GetLabelObject(i).__getattribute__("Get" + name)()) l_list.append(tuple(attrs)) return l_list def attribute_dict(inputobject, name: str): """Returns a dict with the attribute values in keys and a list of the corresponding objects in value i: the input LabelImage name: the name of the attribute """ import itk img = itk.output(inputobject) relabel = itk.StatisticsRelabelLabelMapFilter[img].New( img, Attribute=name, ReverseOrdering=True, InPlace=False ) relabel.UpdateLargestPossibleRegion() r = relabel.GetOutput() d = {} # required because range is overloaded in this module from builtins import range for i in range(1, r.GetNumberOfLabelObjects() + 1): lo = r.GetLabelObject(i) v = lo.__getattribute__("Get" + name)() l_list = d.get(v, []) l_list.append(lo) d[v] = l_list return d def number_of_objects(image_or_filter) -> int: """Returns the number of objets in the image. img: the input LabelImage """ import itk image_or_filter.UpdateLargestPossibleRegion() img = itk.output(image_or_filter) return img.GetNumberOfLabelObjects() def ipython_kw_matches(text: str): """Match named ITK object's named parameters""" import IPython import itk import re import inspect from itk.support import template_class regexp = re.compile( r""" '.*?' | # single quoted strings or ".*?" | # double quoted strings or \w+ | # identifier \S # other characters """, re.VERBOSE | re.DOTALL, ) ip = IPython.get_ipython() if "." in text: # a parameter cannot be dotted return [] # 1. Find the nearest identifier that comes before an unclosed # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo". if ip.Completer.readline: text_until_cursor = ip.Completer.readline.get_line_buffer()[ : ip.Completer.readline.get_endidx() ] else: # IPython >= 5.0.0, which is based on the Python Prompt Toolkit text_until_cursor = ip.Completer.text_until_cursor tokens = regexp.findall(text_until_cursor) tokens.reverse() iter_tokens = iter(tokens) open_par = 0 for token in iter_tokens: if token == ")": open_par -= 1 elif token == "(": open_par += 1 if open_par > 0: # found the last unclosed parenthesis break else: return [] # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) ids = [] is_id = re.compile(r"\w+$").match while True: try: ids.append(iter_tokens.next()) if not is_id(ids[-1]): ids.pop() break if not iter_tokens.next() == ".": break except StopIteration: break # lookup the candidate callable matches either using global_matches # or attr_matches for dotted names if len(ids) == 1: callable_matches = ip.Completer.global_matches(ids[0]) else: callable_matches = ip.Completer.attr_matches(".".join(ids[::-1])) arg_matches = [] for callable_match in callable_matches: # drop the .New at this end, so we can search in the class members if callable_match.endswith(".New"): callable_match = callable_match[:-4] elif not re.findall("([A-Z])", callable_match): # True if snake case # Split at the last '.' occurrence split_name_parts = callable_match.split(".") namespace = split_name_parts[:-1] function_name = split_name_parts[-1] # Find corresponding object name object_name = _snake_to_camel(function_name) # Check that this object actually exists try: object_callable_match = ".".join(namespace + [object_name]) eval(object_callable_match, ip.Completer.namespace) # Reconstruct full object name callable_match = object_callable_match except AttributeError: # callable_match is not a snake case function with a # corresponding object. pass try: l_object = eval(callable_match, ip.Completer.namespace) if isinstance(l_object, template_class.itkTemplate): # this is a template - lets grab the first entry to search for # the methods l_object = l_object.values()[0] named_args = [] is_in: bool = isinstance(l_object, itk.LightObject) if is_in or ( inspect.isclass(l_object) and issubclass(l_object, itk.LightObject) ): named_args = [n[3:] for n in dir(l_object) if n.startswith("Set")] except Exception as e: print(e) continue for namedArg in named_args: if namedArg.startswith(text): arg_matches.append(f"{namedArg}=") return arg_matches def template(cl): """Return the template of a class (or of the class of an object) and its parameters template() returns a tuple with 2 elements: - the first one is the itkTemplate object - the second is a tuple containing the template parameters """ from itk.support.template_class import itkTemplateBase return itkTemplateBase.__template_instantiations_object_to_name__[class_(cl)] def ctype(s: str) -> "itkt.itkCType": """Return the c type corresponding to the string passed in parameter The string can contain some extra spaces. see also itkCType """ from itk.support.types import itkCType ret = itkCType.GetCType(" ".join(s.split())) if ret is None: raise KeyError(f"Unrecognized C type '{s}'") return ret def class_(obj): """Return a class from an object Often in itk, the __class__ is not what the user is expecting. class_() should do a better job """ import inspect if inspect.isclass(obj): # obj is already a class ! return obj else: return obj.__class__ def python_type(object_ref) -> str: """Returns the Python type name of an object The Python name corresponding to the given instantiated object is printed. This includes both the Python name and the parameters of the object. A user can copy and paste the printed value to instantiate a new object of the same type.""" from itk.support.template_class import itkTemplate from itk.support.types import itkCType def in_itk(name): import itk # Remove "itk::" and "std::" from template name. # Only happens for ITK objects. shortname: str = name.split("::")[-1] shortname = shortname.split("itk")[-1] namespace = itk # A type cannot be part of ITK if its name was not modified above. This # check avoids having an input of type `list` and return `itk.list` that # also exists. likely_itk: bool = shortname != name or name[:3] == "vnl" if likely_itk and hasattr(namespace, shortname): return namespace.__name__ + "." + shortname # Prepend name with 'itk.' else: return name def recursive(l_obj, level: int): try: type_name, param_list = template(l_obj) name = in_itk(type_name.__name__) parameters = [] for t in param_list: parameters.append(recursive(t, level + 1)) return name + "[" + ",".join(parameters) + "]" except KeyError: if isinstance(l_obj, itkCType): # Handles CTypes differently return "itk." + l_obj.short_name elif hasattr(l_obj, "__name__"): # This should be where most ITK types end up. return in_itk(l_obj.__name__) elif ( not isinstance(l_obj, type) and type(l_obj) != itkTemplate and level != 0 ): # l_obj should actually be considered a value, not a type, # or it is already an itkTemplate type. # A value can be an integer that is a template parameter. # This does not happen at the first level of the recursion # as it is not possible that this object would be a template # parameter. Checking the level `0` allows e.g. to find the # type of an object that is a `list` or an `int`. return str(l_obj) else: return in_itk(type(l_obj).__name__) return recursive(object_ref, 0) class TemplateTypeError(TypeError): def __init__(self, template_type, input_type): def tuple_to_string_type(t): if type(t) == tuple: return ", ".join(python_type(x) for x in t) else: python_type(t) import itk # Special case for ITK readers: Add extra information. extra_eg: str = "" if template_type in [ itk.ImageFileReader, itk.ImageSeriesReader, itk.MeshFileReader, ]: extra_eg = """ or e.g.: image = itk.imread(my_input_filename, itk.F) """ python_template_type = python_type(template_type) python_input_type = tuple_to_string_type(input_type) type_list = "\n".join([python_type(x[0]) for x in template_type.keys()]) eg_type = ", ".join([python_type(x) for x in list(template_type.keys())[0]]) msg: str = """{template_type} is not wrapped for input type `{input_type}`. To limit the size of the package, only a limited number of types are available in ITK Python. To print the supported types, run the following command in your python environment: {template_type}.GetTypes() Possible solutions: * If you are an application user: ** Convert your input image into a supported format (see below). ** Contact developer to report the issue. * If you are an application developer, force input images to be loaded in a supported pixel type. e.g.: instance = {template_type}[{eg_type}].New(my_input){extra_eg} * (Advanced) If you are an application developer, build ITK Python yourself and turned to `ON` the corresponding CMake option to wrap the pixel type or image dimension you need. When configuring ITK with CMake, you can set `ITK_WRAP_${{type}}` (replace ${{type}} with appropriate pixel type such as `double`). If you need to support images with 4 or 5 dimensions, you can add these dimensions to the list of dimensions in the CMake variable `ITK_WRAP_IMAGE_DIMS`. Supported input types: {type_list} """.format( template_type=python_template_type, input_type=python_input_type, type_list=type_list, eg_type=eg_type, extra_eg=extra_eg, ) TypeError.__init__(self, msg) # install progress callback and custom completer if we are in ipython # interpreter try: import itkConfig import IPython if IPython.get_ipython(): IPython.get_ipython().Completer.matchers.insert(0, ipython_kw_matches) # some cleanup del itkConfig, IPython except (ImportError, AttributeError): # fail silently pass
[ "itk.PyBuffer.keys", "re.compile", "itk.down_cast", "itk.output", "numpy.array", "numpy.moveaxis", "numpy.arange", "itk.array_from_matrix", "numpy.flip", "itk.origin", "numpy.asarray", "itk.ImageIOFactory.CreateImageIO", "itk.MeshIOFactory.CreateMeshIO", "numpy.issubdtype", "numpy.linspace", "os.path.isdir", "itk.PyVnl.keys", "warnings.warn", "itk.PyVectorContainer.keys", "itk.MultiThreaderBase.New", "IPython.get_ipython", "numpy.identity", "vtk.vtkVersion.GetVTKMajorVersion", "itk.template", "itk.GDCMSeriesFileNames.New", "vtk.vtkImageData", "re.findall", "itk.size", "itk.spacing", "itk.array_view_from_vector_container", "itk.vector_container_from_array", "itk.array_view_from_image", "itk.matrix_from_array", "xarray.DataArray", "inspect.isclass", "itk.image_view_from_array" ]
[((3438, 3529), 'warnings.warn', 'warnings.warn', (['"""WrapITK warning: itk.image() is deprecated. Use itk.output() instead."""'], {}), "(\n 'WrapITK warning: itk.image() is deprecated. Use itk.output() instead.')\n", (3451, 3529), False, 'import warnings\n'), ((3940, 3967), 'itk.MultiThreaderBase.New', 'itk.MultiThreaderBase.New', ([], {}), '()\n', (3965, 3967), False, 'import itk\n'), ((4138, 4165), 'itk.MultiThreaderBase.New', 'itk.MultiThreaderBase.New', ([], {}), '()\n', (4163, 4165), False, 'import itk\n'), ((4761, 4788), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (4771, 4788), False, 'import itk\n'), ((5728, 5755), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (5738, 5755), False, 'import itk\n'), ((6129, 6156), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (6139, 6156), False, 'import itk\n'), ((6525, 6552), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (6535, 6552), False, 'import itk\n'), ((6954, 6981), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (6964, 6981), False, 'import itk\n'), ((8166, 8193), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (8176, 8193), False, 'import itk\n'), ((12472, 12495), 'itk.template', 'itk.template', (['container'], {}), '(container)\n', (12484, 12495), False, 'import itk\n'), ((13415, 13438), 'itk.template', 'itk.template', (['container'], {}), '(container)\n', (13427, 13438), False, 'import itk\n'), ((19282, 19316), 'itk.array_view_from_image', 'itk.array_view_from_image', (['l_image'], {}), '(l_image)\n', (19307, 19316), False, 'import itk\n'), ((19333, 19353), 'itk.spacing', 'itk.spacing', (['l_image'], {}), '(l_image)\n', (19344, 19353), False, 'import itk\n'), ((19369, 19388), 'itk.origin', 'itk.origin', (['l_image'], {}), '(l_image)\n', (19379, 19388), False, 'import itk\n'), ((19402, 19419), 'itk.size', 'itk.size', (['l_image'], {}), '(l_image)\n', (19410, 19419), False, 'import itk\n'), ((20424, 20487), 'xarray.DataArray', 'xr.DataArray', (['array_view'], {'dims': 'dims', 'coords': 'coords', 'attrs': 'attrs'}), '(array_view, dims=dims, coords=coords, attrs=attrs)\n', (20436, 20487), True, 'import xarray as xr\n'), ((21664, 21718), 'itk.image_view_from_array', 'itk.image_view_from_array', (['values'], {'is_vector': 'is_vector'}), '(values, is_vector=is_vector)\n', (21689, 21718), False, 'import itk\n'), ((22723, 22757), 'itk.array_view_from_image', 'itk.array_view_from_image', (['l_image'], {}), '(l_image)\n', (22748, 22757), False, 'import itk\n'), ((22775, 22793), 'vtk.vtkImageData', 'vtk.vtkImageData', ([], {}), '()\n', (22791, 22793), False, 'import vtk\n'), ((23358, 23375), 'itk.size', 'itk.size', (['l_image'], {}), '(l_image)\n', (23366, 23375), False, 'import itk\n'), ((25231, 25274), 'itk.image_view_from_array', 'itk.image_view_from_array', (['array', 'is_vector'], {}), '(array, is_vector)\n', (25256, 25274), False, 'import itk\n'), ((26377, 26409), 'itk.array_view_from_image', 'itk.array_view_from_image', (['image'], {}), '(image)\n', (26402, 26409), False, 'import itk\n'), ((27485, 27524), 'itk.vector_container_from_array', 'itk.vector_container_from_array', (['points'], {}), '(points)\n', (27516, 27524), False, 'import itk\n'), ((27610, 27653), 'itk.vector_container_from_array', 'itk.vector_container_from_array', (['point_data'], {}), '(point_data)\n', (27641, 27653), False, 'import itk\n'), ((27732, 27770), 'itk.vector_container_from_array', 'itk.vector_container_from_array', (['cells'], {}), '(cells)\n', (27763, 27770), False, 'import itk\n'), ((27856, 27898), 'itk.vector_container_from_array', 'itk.vector_container_from_array', (['cell_data'], {}), '(cell_data)\n', (27887, 27898), False, 'import itk\n'), ((28111, 28129), 'itk.template', 'itk.template', (['mesh'], {}), '(mesh)\n', (28123, 28129), False, 'import itk\n'), ((30654, 30693), 'itk.vector_container_from_array', 'itk.vector_container_from_array', (['points'], {}), '(points)\n', (30685, 30693), False, 'import itk\n'), ((30783, 30826), 'itk.vector_container_from_array', 'itk.vector_container_from_array', (['point_data'], {}), '(point_data)\n', (30814, 30826), False, 'import itk\n'), ((31060, 31082), 'itk.template', 'itk.template', (['pointset'], {}), '(pointset)\n', (31072, 31082), False, 'import itk\n'), ((32811, 32838), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (32821, 32838), False, 'import itk\n'), ((34248, 34275), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (34258, 34275), False, 'import itk\n'), ((44250, 44280), 're.compile', 're.compile', (['"""(_)([a-z0-9A-Z])"""'], {}), "('(_)([a-z0-9A-Z])')\n", (44260, 44280), False, 'import re\n'), ((60532, 60555), 'itk.output', 'itk.output', (['inputobject'], {}), '(inputobject)\n', (60542, 60555), False, 'import itk\n'), ((61265, 61288), 'itk.output', 'itk.output', (['inputObject'], {}), '(inputObject)\n', (61275, 61288), False, 'import itk\n'), ((62100, 62123), 'itk.output', 'itk.output', (['inputobject'], {}), '(inputobject)\n', (62110, 62123), False, 'import itk\n'), ((62868, 62895), 'itk.output', 'itk.output', (['image_or_filter'], {}), '(image_or_filter)\n', (62878, 62895), False, 'import itk\n'), ((63150, 63424), 're.compile', 're.compile', (['"""\n \'.*?\' | # single quoted strings or\n ".*?" | # double quoted strings or\n \\\\w+ | # identifier\n \\\\S # other characters\n """', '(re.VERBOSE | re.DOTALL)'], {}), '(\n """\n \'.*?\' | # single quoted strings or\n ".*?" | # double quoted strings or\n \\\\w+ | # identifier\n \\\\S # other characters\n """\n , re.VERBOSE | re.DOTALL)\n', (63160, 63424), False, 'import re\n'), ((63446, 63467), 'IPython.get_ipython', 'IPython.get_ipython', ([], {}), '()\n', (63465, 63467), False, 'import IPython\n'), ((67944, 67964), 'inspect.isclass', 'inspect.isclass', (['obj'], {}), '(obj)\n', (67959, 67964), False, 'import inspect\n'), ((73021, 73042), 'IPython.get_ipython', 'IPython.get_ipython', ([], {}), '()\n', (73040, 73042), False, 'import IPython\n'), ((9817, 9832), 'numpy.asarray', 'np.asarray', (['arr'], {}), '(arr)\n', (9827, 9832), True, 'import numpy as np\n'), ((14373, 14388), 'numpy.asarray', 'np.asarray', (['arr'], {}), '(arr)\n', (14383, 14388), True, 'import numpy as np\n'), ((17209, 17224), 'numpy.asarray', 'np.asarray', (['arr'], {}), '(arr)\n', (17219, 17224), True, 'import numpy as np\n'), ((18556, 18571), 'numpy.asarray', 'np.asarray', (['arr'], {}), '(arr)\n', (18566, 18571), True, 'import numpy as np\n'), ((19705, 19838), 'numpy.linspace', 'np.linspace', (['l_origin[l_index]', '(l_origin[l_index] + (l_size[l_index] - 1) * l_spacing[l_index])', 'l_size[l_index]'], {'dtype': 'np.float64'}), '(l_origin[l_index], l_origin[l_index] + (l_size[l_index] - 1) *\n l_spacing[l_index], l_size[l_index], dtype=np.float64)\n', (19716, 19838), True, 'import numpy as np\n'), ((20078, 20116), 'numpy.arange', 'np.arange', (['components'], {'dtype': 'np.uint32'}), '(components, dtype=np.uint32)\n', (20087, 20116), True, 'import numpy as np\n'), ((23472, 23507), 'vtk.vtkVersion.GetVTKMajorVersion', 'vtk.vtkVersion.GetVTKMajorVersion', ([], {}), '()\n', (23505, 23507), False, 'import vtk\n'), ((25593, 25628), 'vtk.vtkVersion.GetVTKMajorVersion', 'vtk.vtkVersion.GetVTKMajorVersion', ([], {}), '()\n', (25626, 25628), False, 'import vtk\n'), ((26114, 26152), 'itk.matrix_from_array', 'itk.matrix_from_array', (['direction_array'], {}), '(direction_array)\n', (26135, 26152), False, 'import itk\n'), ((28356, 28377), 'numpy.array', 'np.array', (['[]', 'np.uint'], {}), '([], np.uint)\n', (28364, 28377), True, 'import numpy as np\n'), ((28523, 28547), 'numpy.array', 'np.array', (['[]', 'np.float32'], {}), '([], np.float32)\n', (28531, 28547), True, 'import numpy as np\n'), ((28742, 28762), 'numpy.array', 'np.array', (['[]', 'mangle'], {}), '([], mangle)\n', (28750, 28762), True, 'import numpy as np\n'), ((28800, 28848), 'itk.array_view_from_vector_container', 'itk.array_view_from_vector_container', (['point_data'], {}), '(point_data)\n', (28836, 28848), False, 'import itk\n'), ((28941, 28961), 'numpy.array', 'np.array', (['[]', 'mangle'], {}), '([], mangle)\n', (28949, 28961), True, 'import numpy as np\n'), ((28998, 29045), 'itk.array_view_from_vector_container', 'itk.array_view_from_vector_container', (['cell_data'], {}), '(cell_data)\n', (29034, 29045), False, 'import itk\n'), ((31277, 31301), 'numpy.array', 'np.array', (['[]', 'np.float32'], {}), '([], np.float32)\n', (31285, 31301), True, 'import numpy as np\n'), ((31504, 31524), 'numpy.array', 'np.array', (['[]', 'mangle'], {}), '([], mangle)\n', (31512, 31524), True, 'import numpy as np\n'), ((31562, 31610), 'itk.array_view_from_vector_container', 'itk.array_view_from_vector_container', (['point_data'], {}), '(point_data)\n', (31598, 31610), False, 'import itk\n'), ((36891, 36914), 'os.path.isdir', 'os.path.isdir', (['filename'], {}), '(filename)\n', (36904, 36914), False, 'import os\n'), ((38210, 38297), 'itk.ImageIOFactory.CreateImageIO', 'itk.ImageIOFactory.CreateImageIO', (['io_filename', 'itk.CommonEnums.IOFileMode_ReadMode'], {}), '(io_filename, itk.CommonEnums.\n IOFileMode_ReadMode)\n', (38242, 38297), False, 'import itk\n'), ((40985, 41070), 'itk.MeshIOFactory.CreateMeshIO', 'itk.MeshIOFactory.CreateMeshIO', (['io_filename', 'itk.CommonEnums.IOFileMode_ReadMode'], {}), '(io_filename, itk.CommonEnums.IOFileMode_ReadMode\n )\n', (41015, 41070), False, 'import itk\n'), ((64452, 64471), 're.compile', 're.compile', (['"""\\\\w+$"""'], {}), "('\\\\w+$')\n", (64462, 64471), False, 'import re\n'), ((8516, 8535), 'itk.PyBuffer.keys', 'itk.PyBuffer.keys', ([], {}), '()\n', (8533, 8535), False, 'import itk\n'), ((11366, 11385), 'itk.PyBuffer.keys', 'itk.PyBuffer.keys', ([], {}), '()\n', (11383, 11385), False, 'import itk\n'), ((12899, 12927), 'itk.PyVectorContainer.keys', 'itk.PyVectorContainer.keys', ([], {}), '()\n', (12925, 12927), False, 'import itk\n'), ((13837, 13865), 'itk.PyVectorContainer.keys', 'itk.PyVectorContainer.keys', ([], {}), '()\n', (13863, 13865), False, 'import itk\n'), ((14885, 14913), 'itk.PyVectorContainer.keys', 'itk.PyVectorContainer.keys', ([], {}), '()\n', (14911, 14913), False, 'import itk\n'), ((15702, 15718), 'itk.PyVnl.keys', 'itk.PyVnl.keys', ([], {}), '()\n', (15716, 15718), False, 'import itk\n'), ((17556, 17572), 'itk.PyVnl.keys', 'itk.PyVnl.keys', ([], {}), '()\n', (17570, 17572), False, 'import itk\n'), ((22274, 22292), 'numpy.flip', 'np.flip', (['direction'], {}), '(direction)\n', (22281, 22292), True, 'import numpy as np\n'), ((25737, 25751), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (25748, 25751), True, 'import numpy as np\n'), ((37049, 37078), 'itk.GDCMSeriesFileNames.New', 'itk.GDCMSeriesFileNames.New', ([], {}), '()\n', (37076, 37078), False, 'import itk\n'), ((42329, 42353), 'itk.down_cast', 'itk.down_cast', (['transform'], {}), '(transform)\n', (42342, 42353), False, 'import itk\n'), ((7827, 7874), 'numpy.issubdtype', 'np.issubdtype', (['numpy_array_type.dtype.type', 'key'], {}), '(numpy_array_type.dtype.type, key)\n', (7840, 7874), True, 'import numpy as np\n'), ((15648, 15672), 'itk.template', 'itk.template', (['vnl_object'], {}), '(vnl_object)\n', (15660, 15672), False, 'import itk\n'), ((21607, 21640), 'numpy.moveaxis', 'np.moveaxis', (['values', 'source', 'dest'], {}), '(values, source, dest)\n', (21618, 21640), True, 'import numpy as np\n'), ((24076, 24097), 'itk.template', 'itk.template', (['l_image'], {}), '(l_image)\n', (24088, 24097), False, 'import itk\n'), ((25944, 25958), 'numpy.identity', 'np.identity', (['(2)'], {}), '(2)\n', (25955, 25958), True, 'import numpy as np\n'), ((65279, 65316), 're.findall', 're.findall', (['"""([A-Z])"""', 'callable_match'], {}), "('([A-Z])', callable_match)\n", (65289, 65316), False, 'import re\n'), ((10206, 10229), 'itk.template', 'itk.template', (['ImageType'], {}), '(ImageType)\n', (10218, 10229), False, 'import itk\n'), ((10247, 10270), 'itk.template', 'itk.template', (['ImageType'], {}), '(ImageType)\n', (10259, 10270), False, 'import itk\n'), ((10475, 10498), 'itk.template', 'itk.template', (['ImageType'], {}), '(ImageType)\n', (10487, 10498), False, 'import itk\n'), ((38789, 38813), 'itk.template', 'itk.template', (['pixel_type'], {}), '(pixel_type)\n', (38801, 38813), False, 'import itk\n'), ((49172, 49189), 'itk.output', 'itk.output', (['value'], {}), '(value)\n', (49182, 49189), False, 'import itk\n'), ((66559, 66584), 'inspect.isclass', 'inspect.isclass', (['l_object'], {}), '(l_object)\n', (66574, 66584), False, 'import inspect\n'), ((23579, 23613), 'itk.array_from_matrix', 'itk.array_from_matrix', (['l_direction'], {}), '(l_direction)\n', (23600, 23613), False, 'import itk\n'), ((48979, 48992), 'itk.output', 'itk.output', (['x'], {}), '(x)\n', (48989, 48992), False, 'import itk\n'), ((73052, 73073), 'IPython.get_ipython', 'IPython.get_ipython', ([], {}), '()\n', (73071, 73073), False, 'import IPython\n'), ((10399, 10422), 'itk.template', 'itk.template', (['ImageType'], {}), '(ImageType)\n', (10411, 10422), False, 'import itk\n'), ((38946, 38970), 'itk.template', 'itk.template', (['pixel_type'], {}), '(pixel_type)\n', (38958, 38970), False, 'import itk\n'), ((49112, 49129), 'itk.output', 'itk.output', (['value'], {}), '(value)\n', (49122, 49129), False, 'import itk\n')]
import pandas as pd from scipy.stats import t import numpy as np import requests def make_dataframe(r): rows = [] for item in r['data']: rows.append([item['lat'], item['lon'], item['aqi'], item['station']['name']]) df = pd.DataFrame(rows, columns=['lat', 'lon', 'aqi', 'name']) df['aqi'] = pd.to_numeric(df.aqi, errors='coerce') return df def one_samp_t_test(df, diff): return diff / ( df['aqi'].var() / df.count()) ** (1 / 2) def get_request_data(url): return requests.get(url).json() class Air_Quality_Analytics(): def __init__(self): self.base_url = "https://api.waqi.info/feed/" self.city_str = "" self.url = self.base_url + self.city_str + "/?token=<PASSWORD>" def get_local_air_quality_comparison(self, city_str, tolerance=2.0): self.city_str = city_str token = "<PASSWORD>" req_data = get_request_data(self.base_url + self.city_str + "/?token=" + token) lat, lng = req_data['data']['city']['geo'] latlngbx = str(lat) + "," + str(lng) + "," + str(lat + tolerance) + "," + str(lng + tolerance) r = requests.get("https://api.waqi.info/" + f"/map/bounds/?latlng={latlngbx}&token={token}").json() if len(r['data']) > 0: local_df = make_dataframe(r) air_quality_comp = { 'deviation': 'Not found', 'probability': 'Not found' } deviation = local_df[local_df['name'].str.contains(city_str)]['aqi'].mean() - local_df['aqi'].mean() if not np.isnan(deviation): air_quality_comp['deviation'] = deviation probability = one_samp_t_test(local_df[local_df['name'].str.contains(city_str)], deviation) probability = t.sf(np.abs(probability), local_df.count() - 1)[0] if not np.isnan(probability): air_quality_comp['probability'] = probability return air_quality_comp def get_air_quality_index(self, city_str): self.city_str = city_str try: return get_request_data(self.base_url + self.city_str + "/?token=<PASSWORD>")[ 'data']["aqi"] except: pass # AQA = Air_Quality_Analytics() # print(AQA.get_local_air_quality_comparison('Los Angeles'))
[ "numpy.abs", "requests.get", "pandas.to_numeric", "numpy.isnan", "pandas.DataFrame" ]
[((242, 299), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': "['lat', 'lon', 'aqi', 'name']"}), "(rows, columns=['lat', 'lon', 'aqi', 'name'])\n", (254, 299), True, 'import pandas as pd\n'), ((316, 354), 'pandas.to_numeric', 'pd.to_numeric', (['df.aqi'], {'errors': '"""coerce"""'}), "(df.aqi, errors='coerce')\n", (329, 354), True, 'import pandas as pd\n'), ((511, 528), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (523, 528), False, 'import requests\n'), ((1138, 1230), 'requests.get', 'requests.get', (["('https://api.waqi.info/' + f'/map/bounds/?latlng={latlngbx}&token={token}')"], {}), "('https://api.waqi.info/' +\n f'/map/bounds/?latlng={latlngbx}&token={token}')\n", (1150, 1230), False, 'import requests\n'), ((1572, 1591), 'numpy.isnan', 'np.isnan', (['deviation'], {}), '(deviation)\n', (1580, 1591), True, 'import numpy as np\n'), ((1853, 1874), 'numpy.isnan', 'np.isnan', (['probability'], {}), '(probability)\n', (1861, 1874), True, 'import numpy as np\n'), ((1787, 1806), 'numpy.abs', 'np.abs', (['probability'], {}), '(probability)\n', (1793, 1806), True, 'import numpy as np\n')]
# Copyright 2017 The TensorFlow Authors. 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. # ============================================================================== """Tests for object_detection.core.preprocessor.""" import numpy as np import six import tensorflow as tf from object_detection.tensorflow_detect.core import standard_fields as fields, \ preprocessor, preprocessor_cache if six.PY2: import mock # pylint: disable=g-import-not-at-top else: from unittest import mock # pylint: disable=g-import-not-at-top class PreprocessorTest(tf.test.TestCase): def createColorfulTestImage(self): ch255 = tf.fill([1, 100, 200, 1], tf.constant(255, dtype=tf.uint8)) ch128 = tf.fill([1, 100, 200, 1], tf.constant(128, dtype=tf.uint8)) ch0 = tf.fill([1, 100, 200, 1], tf.constant(0, dtype=tf.uint8)) imr = tf.concat([ch255, ch0, ch0], 3) img = tf.concat([ch255, ch255, ch0], 3) imb = tf.concat([ch255, ch0, ch255], 3) imw = tf.concat([ch128, ch128, ch128], 3) imu = tf.concat([imr, img], 2) imd = tf.concat([imb, imw], 2) im = tf.concat([imu, imd], 1) return im def createTestImages(self): images_r = tf.constant([[[128, 128, 128, 128], [0, 0, 128, 128], [0, 128, 128, 128], [192, 192, 128, 128]]], dtype=tf.uint8) images_r = tf.expand_dims(images_r, 3) images_g = tf.constant([[[0, 0, 128, 128], [0, 0, 128, 128], [0, 128, 192, 192], [192, 192, 128, 192]]], dtype=tf.uint8) images_g = tf.expand_dims(images_g, 3) images_b = tf.constant([[[128, 128, 192, 0], [0, 0, 128, 192], [0, 128, 128, 0], [192, 192, 192, 128]]], dtype=tf.uint8) images_b = tf.expand_dims(images_b, 3) images = tf.concat([images_r, images_g, images_b], 3) return images def createEmptyTestBoxes(self): boxes = tf.constant([[]], dtype=tf.float32) return boxes def createTestBoxes(self): boxes = tf.constant( [[0.0, 0.25, 0.75, 1.0], [0.25, 0.5, 0.75, 1.0]], dtype=tf.float32) return boxes def createTestLabelScores(self): return tf.constant([1.0, 0.5], dtype=tf.float32) def createTestLabelScoresWithMissingScore(self): return tf.constant([0.5, np.nan], dtype=tf.float32) def createTestMasks(self): mask = np.array([ [[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]], [[255.0, 255.0, 0.0], [255.0, 255.0, 0.0], [255.0, 255.0, 0.0]]]) return tf.constant(mask, dtype=tf.float32) def createTestKeypoints(self): keypoints = np.array([ [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], [[0.4, 0.4], [0.5, 0.5], [0.6, 0.6]], ]) return tf.constant(keypoints, dtype=tf.float32) def createTestKeypointsInsideCrop(self): keypoints = np.array([ [[0.4, 0.4], [0.5, 0.5], [0.6, 0.6]], [[0.4, 0.4], [0.5, 0.5], [0.6, 0.6]], ]) return tf.constant(keypoints, dtype=tf.float32) def createTestKeypointsOutsideCrop(self): keypoints = np.array([ [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], ]) return tf.constant(keypoints, dtype=tf.float32) def createKeypointFlipPermutation(self): return np.array([0, 2, 1], dtype=np.int32) def createTestLabels(self): labels = tf.constant([1, 2], dtype=tf.int32) return labels def createTestBoxesOutOfImage(self): boxes = tf.constant( [[-0.1, 0.25, 0.75, 1], [0.25, 0.5, 0.75, 1.1]], dtype=tf.float32) return boxes def createTestMultiClassScores(self): return tf.constant([[1.0, 0.0], [0.5, 0.5]], dtype=tf.float32) def expectedImagesAfterNormalization(self): images_r = tf.constant([[[0, 0, 0, 0], [-1, -1, 0, 0], [-1, 0, 0, 0], [0.5, 0.5, 0, 0]]], dtype=tf.float32) images_r = tf.expand_dims(images_r, 3) images_g = tf.constant([[[-1, -1, 0, 0], [-1, -1, 0, 0], [-1, 0, 0.5, 0.5], [0.5, 0.5, 0, 0.5]]], dtype=tf.float32) images_g = tf.expand_dims(images_g, 3) images_b = tf.constant([[[0, 0, 0.5, -1], [-1, -1, 0, 0.5], [-1, 0, 0, -1], [0.5, 0.5, 0.5, 0]]], dtype=tf.float32) images_b = tf.expand_dims(images_b, 3) images = tf.concat([images_r, images_g, images_b], 3) return images def expectedMaxImageAfterColorScale(self): images_r = tf.constant([[[0.1, 0.1, 0.1, 0.1], [-0.9, -0.9, 0.1, 0.1], [-0.9, 0.1, 0.1, 0.1], [0.6, 0.6, 0.1, 0.1]]], dtype=tf.float32) images_r = tf.expand_dims(images_r, 3) images_g = tf.constant([[[-0.9, -0.9, 0.1, 0.1], [-0.9, -0.9, 0.1, 0.1], [-0.9, 0.1, 0.6, 0.6], [0.6, 0.6, 0.1, 0.6]]], dtype=tf.float32) images_g = tf.expand_dims(images_g, 3) images_b = tf.constant([[[0.1, 0.1, 0.6, -0.9], [-0.9, -0.9, 0.1, 0.6], [-0.9, 0.1, 0.1, -0.9], [0.6, 0.6, 0.6, 0.1]]], dtype=tf.float32) images_b = tf.expand_dims(images_b, 3) images = tf.concat([images_r, images_g, images_b], 3) return images def expectedMinImageAfterColorScale(self): images_r = tf.constant([[[-0.1, -0.1, -0.1, -0.1], [-1, -1, -0.1, -0.1], [-1, -0.1, -0.1, -0.1], [0.4, 0.4, -0.1, -0.1]]], dtype=tf.float32) images_r = tf.expand_dims(images_r, 3) images_g = tf.constant([[[-1, -1, -0.1, -0.1], [-1, -1, -0.1, -0.1], [-1, -0.1, 0.4, 0.4], [0.4, 0.4, -0.1, 0.4]]], dtype=tf.float32) images_g = tf.expand_dims(images_g, 3) images_b = tf.constant([[[-0.1, -0.1, 0.4, -1], [-1, -1, -0.1, 0.4], [-1, -0.1, -0.1, -1], [0.4, 0.4, 0.4, -0.1]]], dtype=tf.float32) images_b = tf.expand_dims(images_b, 3) images = tf.concat([images_r, images_g, images_b], 3) return images def expectedImagesAfterLeftRightFlip(self): images_r = tf.constant([[[0, 0, 0, 0], [0, 0, -1, -1], [0, 0, 0, -1], [0, 0, 0.5, 0.5]]], dtype=tf.float32) images_r = tf.expand_dims(images_r, 3) images_g = tf.constant([[[0, 0, -1, -1], [0, 0, -1, -1], [0.5, 0.5, 0, -1], [0.5, 0, 0.5, 0.5]]], dtype=tf.float32) images_g = tf.expand_dims(images_g, 3) images_b = tf.constant([[[-1, 0.5, 0, 0], [0.5, 0, -1, -1], [-1, 0, 0, -1], [0, 0.5, 0.5, 0.5]]], dtype=tf.float32) images_b = tf.expand_dims(images_b, 3) images = tf.concat([images_r, images_g, images_b], 3) return images def expectedImagesAfterUpDownFlip(self): images_r = tf.constant([[[0.5, 0.5, 0, 0], [-1, 0, 0, 0], [-1, -1, 0, 0], [0, 0, 0, 0]]], dtype=tf.float32) images_r = tf.expand_dims(images_r, 3) images_g = tf.constant([[[0.5, 0.5, 0, 0.5], [-1, 0, 0.5, 0.5], [-1, -1, 0, 0], [-1, -1, 0, 0]]], dtype=tf.float32) images_g = tf.expand_dims(images_g, 3) images_b = tf.constant([[[0.5, 0.5, 0.5, 0], [-1, 0, 0, -1], [-1, -1, 0, 0.5], [0, 0, 0.5, -1]]], dtype=tf.float32) images_b = tf.expand_dims(images_b, 3) images = tf.concat([images_r, images_g, images_b], 3) return images def expectedImagesAfterRot90(self): images_r = tf.constant([[[0, 0, 0, 0], [0, 0, 0, 0], [0, -1, 0, 0.5], [0, -1, -1, 0.5]]], dtype=tf.float32) images_r = tf.expand_dims(images_r, 3) images_g = tf.constant([[[0, 0, 0.5, 0.5], [0, 0, 0.5, 0], [-1, -1, 0, 0.5], [-1, -1, -1, 0.5]]], dtype=tf.float32) images_g = tf.expand_dims(images_g, 3) images_b = tf.constant([[[-1, 0.5, -1, 0], [0.5, 0, 0, 0.5], [0, -1, 0, 0.5], [0, -1, -1, 0.5]]], dtype=tf.float32) images_b = tf.expand_dims(images_b, 3) images = tf.concat([images_r, images_g, images_b], 3) return images def expectedBoxesAfterLeftRightFlip(self): boxes = tf.constant([[0.0, 0.0, 0.75, 0.75], [0.25, 0.0, 0.75, 0.5]], dtype=tf.float32) return boxes def expectedBoxesAfterUpDownFlip(self): boxes = tf.constant([[0.25, 0.25, 1.0, 1.0], [0.25, 0.5, 0.75, 1.0]], dtype=tf.float32) return boxes def expectedBoxesAfterRot90(self): boxes = tf.constant( [[0.0, 0.0, 0.75, 0.75], [0.0, 0.25, 0.5, 0.75]], dtype=tf.float32) return boxes def expectedMasksAfterLeftRightFlip(self): mask = np.array([ [[0.0, 0.0, 255.0], [0.0, 0.0, 255.0], [0.0, 0.0, 255.0]], [[0.0, 255.0, 255.0], [0.0, 255.0, 255.0], [0.0, 255.0, 255.0]]]) return tf.constant(mask, dtype=tf.float32) def expectedMasksAfterUpDownFlip(self): mask = np.array([ [[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]], [[255.0, 255.0, 0.0], [255.0, 255.0, 0.0], [255.0, 255.0, 0.0]]]) return tf.constant(mask, dtype=tf.float32) def expectedMasksAfterRot90(self): mask = np.array([ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [255.0, 255.0, 255.0]], [[0.0, 0.0, 0.0], [255.0, 255.0, 255.0], [255.0, 255.0, 255.0]]]) return tf.constant(mask, dtype=tf.float32) def expectedLabelScoresAfterThresholding(self): return tf.constant([1.0], dtype=tf.float32) def expectedBoxesAfterThresholding(self): return tf.constant([[0.0, 0.25, 0.75, 1.0]], dtype=tf.float32) def expectedLabelsAfterThresholding(self): return tf.constant([1], dtype=tf.float32) def expectedMultiClassScoresAfterThresholding(self): return tf.constant([[1.0, 0.0]], dtype=tf.float32) def expectedMasksAfterThresholding(self): mask = np.array([ [[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]]]) return tf.constant(mask, dtype=tf.float32) def expectedKeypointsAfterThresholding(self): keypoints = np.array([ [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]] ]) return tf.constant(keypoints, dtype=tf.float32) def expectedLabelScoresAfterThresholdingWithMissingScore(self): return tf.constant([np.nan], dtype=tf.float32) def expectedBoxesAfterThresholdingWithMissingScore(self): return tf.constant([[0.25, 0.5, 0.75, 1]], dtype=tf.float32) def expectedLabelsAfterThresholdingWithMissingScore(self): return tf.constant([2], dtype=tf.float32) def testRgbToGrayscale(self): images = self.createTestImages() grayscale_images = preprocessor._rgb_to_grayscale(images) expected_images = tf.image.rgb_to_grayscale(images) with self.test_session() as sess: (grayscale_images, expected_images) = sess.run( [grayscale_images, expected_images]) self.assertAllEqual(expected_images, grayscale_images) def testNormalizeImage(self): preprocess_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 256, 'target_minval': -1, 'target_maxval': 1 })] images = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images} tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images = tensor_dict[fields.InputDataFields.image] images_expected = self.expectedImagesAfterNormalization() with self.test_session() as sess: (images_, images_expected_) = sess.run( [images, images_expected]) images_shape_ = images_.shape images_expected_shape_ = images_expected_.shape expected_shape = [1, 4, 4, 3] self.assertAllEqual(images_expected_shape_, images_shape_) self.assertAllEqual(images_shape_, expected_shape) self.assertAllClose(images_, images_expected_) def testRetainBoxesAboveThreshold(self): boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() (retained_boxes, retained_labels, retained_label_scores) = preprocessor.retain_boxes_above_threshold( boxes, labels, label_scores, threshold=0.6) with self.test_session() as sess: (retained_boxes_, retained_labels_, retained_label_scores_, expected_retained_boxes_, expected_retained_labels_, expected_retained_label_scores_) = sess.run([ retained_boxes, retained_labels, retained_label_scores, self.expectedBoxesAfterThresholding(), self.expectedLabelsAfterThresholding(), self.expectedLabelScoresAfterThresholding()]) self.assertAllClose( retained_boxes_, expected_retained_boxes_) self.assertAllClose( retained_labels_, expected_retained_labels_) self.assertAllClose( retained_label_scores_, expected_retained_label_scores_) def testRetainBoxesAboveThresholdWithMultiClassScores(self): boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() multiclass_scores = self.createTestMultiClassScores() (_, _, _, retained_multiclass_scores) = preprocessor.retain_boxes_above_threshold( boxes, labels, label_scores, multiclass_scores=multiclass_scores, threshold=0.6) with self.test_session() as sess: (retained_multiclass_scores_, expected_retained_multiclass_scores_) = sess.run([ retained_multiclass_scores, self.expectedMultiClassScoresAfterThresholding() ]) self.assertAllClose(retained_multiclass_scores_, expected_retained_multiclass_scores_) def testRetainBoxesAboveThresholdWithMasks(self): boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() masks = self.createTestMasks() _, _, _, retained_masks = preprocessor.retain_boxes_above_threshold( boxes, labels, label_scores, masks, threshold=0.6) with self.test_session() as sess: retained_masks_, expected_retained_masks_ = sess.run([ retained_masks, self.expectedMasksAfterThresholding()]) self.assertAllClose( retained_masks_, expected_retained_masks_) def testRetainBoxesAboveThresholdWithKeypoints(self): boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() keypoints = self.createTestKeypoints() (_, _, _, retained_keypoints) = preprocessor.retain_boxes_above_threshold( boxes, labels, label_scores, keypoints=keypoints, threshold=0.6) with self.test_session() as sess: (retained_keypoints_, expected_retained_keypoints_) = sess.run([ retained_keypoints, self.expectedKeypointsAfterThresholding()]) self.assertAllClose( retained_keypoints_, expected_retained_keypoints_) def testRetainBoxesAboveThresholdWithMissingScore(self): boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScoresWithMissingScore() (retained_boxes, retained_labels, retained_label_scores) = preprocessor.retain_boxes_above_threshold( boxes, labels, label_scores, threshold=0.6) with self.test_session() as sess: (retained_boxes_, retained_labels_, retained_label_scores_, expected_retained_boxes_, expected_retained_labels_, expected_retained_label_scores_) = sess.run([ retained_boxes, retained_labels, retained_label_scores, self.expectedBoxesAfterThresholdingWithMissingScore(), self.expectedLabelsAfterThresholdingWithMissingScore(), self.expectedLabelScoresAfterThresholdingWithMissingScore()]) self.assertAllClose( retained_boxes_, expected_retained_boxes_) self.assertAllClose( retained_labels_, expected_retained_labels_) self.assertAllClose( retained_label_scores_, expected_retained_label_scores_) def testFlipBoxesLeftRight(self): boxes = self.createTestBoxes() flipped_boxes = preprocessor._flip_boxes_left_right(boxes) expected_boxes = self.expectedBoxesAfterLeftRightFlip() with self.test_session() as sess: flipped_boxes, expected_boxes = sess.run([flipped_boxes, expected_boxes]) self.assertAllEqual(flipped_boxes.flatten(), expected_boxes.flatten()) def testFlipBoxesUpDown(self): boxes = self.createTestBoxes() flipped_boxes = preprocessor._flip_boxes_up_down(boxes) expected_boxes = self.expectedBoxesAfterUpDownFlip() with self.test_session() as sess: flipped_boxes, expected_boxes = sess.run([flipped_boxes, expected_boxes]) self.assertAllEqual(flipped_boxes.flatten(), expected_boxes.flatten()) def testRot90Boxes(self): boxes = self.createTestBoxes() rotated_boxes = preprocessor._rot90_boxes(boxes) expected_boxes = self.expectedBoxesAfterRot90() with self.test_session() as sess: rotated_boxes, expected_boxes = sess.run([rotated_boxes, expected_boxes]) self.assertAllEqual(rotated_boxes.flatten(), expected_boxes.flatten()) def testFlipMasksLeftRight(self): test_mask = self.createTestMasks() flipped_mask = preprocessor._flip_masks_left_right(test_mask) expected_mask = self.expectedMasksAfterLeftRightFlip() with self.test_session() as sess: flipped_mask, expected_mask = sess.run([flipped_mask, expected_mask]) self.assertAllEqual(flipped_mask.flatten(), expected_mask.flatten()) def testFlipMasksUpDown(self): test_mask = self.createTestMasks() flipped_mask = preprocessor._flip_masks_up_down(test_mask) expected_mask = self.expectedMasksAfterUpDownFlip() with self.test_session() as sess: flipped_mask, expected_mask = sess.run([flipped_mask, expected_mask]) self.assertAllEqual(flipped_mask.flatten(), expected_mask.flatten()) def testRot90Masks(self): test_mask = self.createTestMasks() rotated_mask = preprocessor._rot90_masks(test_mask) expected_mask = self.expectedMasksAfterRot90() with self.test_session() as sess: rotated_mask, expected_mask = sess.run([rotated_mask, expected_mask]) self.assertAllEqual(rotated_mask.flatten(), expected_mask.flatten()) def _testPreprocessorCache(self, preprocess_options, test_boxes=False, test_masks=False, test_keypoints=False, num_runs=4): cache = preprocessor_cache.PreprocessorCache() images = self.createTestImages() boxes = self.createTestBoxes() classes = self.createTestLabels() masks = self.createTestMasks() keypoints = self.createTestKeypoints() preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_instance_masks=test_masks, include_keypoints=test_keypoints) out = [] for i in range(num_runs): tensor_dict = { fields.InputDataFields.image: images, } num_outputs = 1 if test_boxes: tensor_dict[fields.InputDataFields.groundtruth_boxes] = boxes tensor_dict[fields.InputDataFields.groundtruth_classes] = classes num_outputs += 1 if test_masks: tensor_dict[fields.InputDataFields.groundtruth_instance_masks] = masks num_outputs += 1 if test_keypoints: tensor_dict[fields.InputDataFields.groundtruth_keypoints] = keypoints num_outputs += 1 out.append(preprocessor.preprocess( tensor_dict, preprocess_options, preprocessor_arg_map, cache)) with self.test_session() as sess: to_run = [] for i in range(num_runs): to_run.append(out[i][fields.InputDataFields.image]) if test_boxes: to_run.append(out[i][fields.InputDataFields.groundtruth_boxes]) if test_masks: to_run.append( out[i][fields.InputDataFields.groundtruth_instance_masks]) if test_keypoints: to_run.append(out[i][fields.InputDataFields.groundtruth_keypoints]) out_array = sess.run(to_run) for i in range(num_outputs, len(out_array)): self.assertAllClose(out_array[i], out_array[i - num_outputs]) def testRandomHorizontalFlip(self): preprocess_options = [(preprocessor.random_horizontal_flip, {})] images = self.expectedImagesAfterNormalization() boxes = self.createTestBoxes() tensor_dict = {fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes} images_expected1 = self.expectedImagesAfterLeftRightFlip() boxes_expected1 = self.expectedBoxesAfterLeftRightFlip() images_expected2 = images boxes_expected2 = boxes tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images = tensor_dict[fields.InputDataFields.image] boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] boxes_diff1 = tf.squared_difference(boxes, boxes_expected1) boxes_diff2 = tf.squared_difference(boxes, boxes_expected2) boxes_diff = tf.multiply(boxes_diff1, boxes_diff2) boxes_diff_expected = tf.zeros_like(boxes_diff) images_diff1 = tf.squared_difference(images, images_expected1) images_diff2 = tf.squared_difference(images, images_expected2) images_diff = tf.multiply(images_diff1, images_diff2) images_diff_expected = tf.zeros_like(images_diff) with self.test_session() as sess: (images_diff_, images_diff_expected_, boxes_diff_, boxes_diff_expected_) = sess.run([images_diff, images_diff_expected, boxes_diff, boxes_diff_expected]) self.assertAllClose(boxes_diff_, boxes_diff_expected_) self.assertAllClose(images_diff_, images_diff_expected_) def testRandomHorizontalFlipWithEmptyBoxes(self): preprocess_options = [(preprocessor.random_horizontal_flip, {})] images = self.expectedImagesAfterNormalization() boxes = self.createEmptyTestBoxes() tensor_dict = {fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes} images_expected1 = self.expectedImagesAfterLeftRightFlip() boxes_expected = self.createEmptyTestBoxes() images_expected2 = images tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images = tensor_dict[fields.InputDataFields.image] boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] images_diff1 = tf.squared_difference(images, images_expected1) images_diff2 = tf.squared_difference(images, images_expected2) images_diff = tf.multiply(images_diff1, images_diff2) images_diff_expected = tf.zeros_like(images_diff) with self.test_session() as sess: (images_diff_, images_diff_expected_, boxes_, boxes_expected_) = sess.run([images_diff, images_diff_expected, boxes, boxes_expected]) self.assertAllClose(boxes_, boxes_expected_) self.assertAllClose(images_diff_, images_diff_expected_) def testRandomHorizontalFlipWithCache(self): keypoint_flip_permutation = self.createKeypointFlipPermutation() preprocess_options = [ (preprocessor.random_horizontal_flip, {'keypoint_flip_permutation': keypoint_flip_permutation})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=True, test_keypoints=True) def testRunRandomHorizontalFlipWithMaskAndKeypoints(self): preprocess_options = [(preprocessor.random_horizontal_flip, {})] image_height = 3 image_width = 3 images = tf.random_uniform([1, image_height, image_width, 3]) boxes = self.createTestBoxes() masks = self.createTestMasks() keypoints = self.createTestKeypoints() keypoint_flip_permutation = self.createKeypointFlipPermutation() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_instance_masks: masks, fields.InputDataFields.groundtruth_keypoints: keypoints } preprocess_options = [ (preprocessor.random_horizontal_flip, {'keypoint_flip_permutation': keypoint_flip_permutation})] preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_instance_masks=True, include_keypoints=True) tensor_dict = preprocessor.preprocess( tensor_dict, preprocess_options, func_arg_map=preprocessor_arg_map) boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] masks = tensor_dict[fields.InputDataFields.groundtruth_instance_masks] keypoints = tensor_dict[fields.InputDataFields.groundtruth_keypoints] with self.test_session() as sess: boxes, masks, keypoints = sess.run([boxes, masks, keypoints]) self.assertTrue(boxes is not None) self.assertTrue(masks is not None) self.assertTrue(keypoints is not None) def testRandomVerticalFlip(self): preprocess_options = [(preprocessor.random_vertical_flip, {})] images = self.expectedImagesAfterNormalization() boxes = self.createTestBoxes() tensor_dict = {fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes} images_expected1 = self.expectedImagesAfterUpDownFlip() boxes_expected1 = self.expectedBoxesAfterUpDownFlip() images_expected2 = images boxes_expected2 = boxes tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images = tensor_dict[fields.InputDataFields.image] boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] boxes_diff1 = tf.squared_difference(boxes, boxes_expected1) boxes_diff2 = tf.squared_difference(boxes, boxes_expected2) boxes_diff = tf.multiply(boxes_diff1, boxes_diff2) boxes_diff_expected = tf.zeros_like(boxes_diff) images_diff1 = tf.squared_difference(images, images_expected1) images_diff2 = tf.squared_difference(images, images_expected2) images_diff = tf.multiply(images_diff1, images_diff2) images_diff_expected = tf.zeros_like(images_diff) with self.test_session() as sess: (images_diff_, images_diff_expected_, boxes_diff_, boxes_diff_expected_) = sess.run([images_diff, images_diff_expected, boxes_diff, boxes_diff_expected]) self.assertAllClose(boxes_diff_, boxes_diff_expected_) self.assertAllClose(images_diff_, images_diff_expected_) def testRandomVerticalFlipWithEmptyBoxes(self): preprocess_options = [(preprocessor.random_vertical_flip, {})] images = self.expectedImagesAfterNormalization() boxes = self.createEmptyTestBoxes() tensor_dict = {fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes} images_expected1 = self.expectedImagesAfterUpDownFlip() boxes_expected = self.createEmptyTestBoxes() images_expected2 = images tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images = tensor_dict[fields.InputDataFields.image] boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] images_diff1 = tf.squared_difference(images, images_expected1) images_diff2 = tf.squared_difference(images, images_expected2) images_diff = tf.multiply(images_diff1, images_diff2) images_diff_expected = tf.zeros_like(images_diff) with self.test_session() as sess: (images_diff_, images_diff_expected_, boxes_, boxes_expected_) = sess.run([images_diff, images_diff_expected, boxes, boxes_expected]) self.assertAllClose(boxes_, boxes_expected_) self.assertAllClose(images_diff_, images_diff_expected_) def testRandomVerticalFlipWithCache(self): keypoint_flip_permutation = self.createKeypointFlipPermutation() preprocess_options = [ (preprocessor.random_vertical_flip, {'keypoint_flip_permutation': keypoint_flip_permutation})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=True, test_keypoints=True) def testRunRandomVerticalFlipWithMaskAndKeypoints(self): preprocess_options = [(preprocessor.random_vertical_flip, {})] image_height = 3 image_width = 3 images = tf.random_uniform([1, image_height, image_width, 3]) boxes = self.createTestBoxes() masks = self.createTestMasks() keypoints = self.createTestKeypoints() keypoint_flip_permutation = self.createKeypointFlipPermutation() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_instance_masks: masks, fields.InputDataFields.groundtruth_keypoints: keypoints } preprocess_options = [ (preprocessor.random_vertical_flip, {'keypoint_flip_permutation': keypoint_flip_permutation})] preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_instance_masks=True, include_keypoints=True) tensor_dict = preprocessor.preprocess( tensor_dict, preprocess_options, func_arg_map=preprocessor_arg_map) boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] masks = tensor_dict[fields.InputDataFields.groundtruth_instance_masks] keypoints = tensor_dict[fields.InputDataFields.groundtruth_keypoints] with self.test_session() as sess: boxes, masks, keypoints = sess.run([boxes, masks, keypoints]) self.assertTrue(boxes is not None) self.assertTrue(masks is not None) self.assertTrue(keypoints is not None) def testRandomRotation90(self): preprocess_options = [(preprocessor.random_rotation90, {})] images = self.expectedImagesAfterNormalization() boxes = self.createTestBoxes() tensor_dict = {fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes} images_expected1 = self.expectedImagesAfterRot90() boxes_expected1 = self.expectedBoxesAfterRot90() images_expected2 = images boxes_expected2 = boxes tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images = tensor_dict[fields.InputDataFields.image] boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] boxes_diff1 = tf.squared_difference(boxes, boxes_expected1) boxes_diff2 = tf.squared_difference(boxes, boxes_expected2) boxes_diff = tf.multiply(boxes_diff1, boxes_diff2) boxes_diff_expected = tf.zeros_like(boxes_diff) images_diff1 = tf.squared_difference(images, images_expected1) images_diff2 = tf.squared_difference(images, images_expected2) images_diff = tf.multiply(images_diff1, images_diff2) images_diff_expected = tf.zeros_like(images_diff) with self.test_session() as sess: (images_diff_, images_diff_expected_, boxes_diff_, boxes_diff_expected_) = sess.run([images_diff, images_diff_expected, boxes_diff, boxes_diff_expected]) self.assertAllClose(boxes_diff_, boxes_diff_expected_) self.assertAllClose(images_diff_, images_diff_expected_) def testRandomRotation90WithEmptyBoxes(self): preprocess_options = [(preprocessor.random_rotation90, {})] images = self.expectedImagesAfterNormalization() boxes = self.createEmptyTestBoxes() tensor_dict = {fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes} images_expected1 = self.expectedImagesAfterRot90() boxes_expected = self.createEmptyTestBoxes() images_expected2 = images tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images = tensor_dict[fields.InputDataFields.image] boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] images_diff1 = tf.squared_difference(images, images_expected1) images_diff2 = tf.squared_difference(images, images_expected2) images_diff = tf.multiply(images_diff1, images_diff2) images_diff_expected = tf.zeros_like(images_diff) with self.test_session() as sess: (images_diff_, images_diff_expected_, boxes_, boxes_expected_) = sess.run([images_diff, images_diff_expected, boxes, boxes_expected]) self.assertAllClose(boxes_, boxes_expected_) self.assertAllClose(images_diff_, images_diff_expected_) def testRandomRotation90WithCache(self): preprocess_options = [(preprocessor.random_rotation90, {})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=True, test_keypoints=True) def testRunRandomRotation90WithMaskAndKeypoints(self): preprocess_options = [(preprocessor.random_rotation90, {})] image_height = 3 image_width = 3 images = tf.random_uniform([1, image_height, image_width, 3]) boxes = self.createTestBoxes() masks = self.createTestMasks() keypoints = self.createTestKeypoints() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_instance_masks: masks, fields.InputDataFields.groundtruth_keypoints: keypoints } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_instance_masks=True, include_keypoints=True) tensor_dict = preprocessor.preprocess( tensor_dict, preprocess_options, func_arg_map=preprocessor_arg_map) boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] masks = tensor_dict[fields.InputDataFields.groundtruth_instance_masks] keypoints = tensor_dict[fields.InputDataFields.groundtruth_keypoints] with self.test_session() as sess: boxes, masks, keypoints = sess.run([boxes, masks, keypoints]) self.assertTrue(boxes is not None) self.assertTrue(masks is not None) self.assertTrue(keypoints is not None) def testRandomPixelValueScale(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_pixel_value_scale, {})) images = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images} tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images_min = tf.to_float(images) * 0.9 / 255.0 images_max = tf.to_float(images) * 1.1 / 255.0 images = tensor_dict[fields.InputDataFields.image] values_greater = tf.greater_equal(images, images_min) values_less = tf.less_equal(images, images_max) values_true = tf.fill([1, 4, 4, 3], True) with self.test_session() as sess: (values_greater_, values_less_, values_true_) = sess.run( [values_greater, values_less, values_true]) self.assertAllClose(values_greater_, values_true_) self.assertAllClose(values_less_, values_true_) def testRandomPixelValueScaleWithCache(self): preprocess_options = [] preprocess_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocess_options.append((preprocessor.random_pixel_value_scale, {})) self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=False, test_keypoints=False) def testRandomImageScale(self): preprocess_options = [(preprocessor.random_image_scale, {})] images_original = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images_original} tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images_scaled = tensor_dict[fields.InputDataFields.image] images_original_shape = tf.shape(images_original) images_scaled_shape = tf.shape(images_scaled) with self.test_session() as sess: (images_original_shape_, images_scaled_shape_) = sess.run( [images_original_shape, images_scaled_shape]) self.assertTrue( images_original_shape_[1] * 0.5 <= images_scaled_shape_[1]) self.assertTrue( images_original_shape_[1] * 2.0 >= images_scaled_shape_[1]) self.assertTrue( images_original_shape_[2] * 0.5 <= images_scaled_shape_[2]) self.assertTrue( images_original_shape_[2] * 2.0 >= images_scaled_shape_[2]) def testRandomImageScaleWithCache(self): preprocess_options = [(preprocessor.random_image_scale, {})] self._testPreprocessorCache(preprocess_options, test_boxes=False, test_masks=False, test_keypoints=False) def testRandomRGBtoGray(self): preprocess_options = [(preprocessor.random_rgb_to_gray, {})] images_original = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images_original} tensor_dict = preprocessor.preprocess(tensor_dict, preprocess_options) images_gray = tensor_dict[fields.InputDataFields.image] images_gray_r, images_gray_g, images_gray_b = tf.split( value=images_gray, num_or_size_splits=3, axis=3) images_r, images_g, images_b = tf.split( value=images_original, num_or_size_splits=3, axis=3) images_r_diff1 = tf.squared_difference(tf.to_float(images_r), tf.to_float(images_gray_r)) images_r_diff2 = tf.squared_difference(tf.to_float(images_gray_r), tf.to_float(images_gray_g)) images_r_diff = tf.multiply(images_r_diff1, images_r_diff2) images_g_diff1 = tf.squared_difference(tf.to_float(images_g), tf.to_float(images_gray_g)) images_g_diff2 = tf.squared_difference(tf.to_float(images_gray_g), tf.to_float(images_gray_b)) images_g_diff = tf.multiply(images_g_diff1, images_g_diff2) images_b_diff1 = tf.squared_difference(tf.to_float(images_b), tf.to_float(images_gray_b)) images_b_diff2 = tf.squared_difference(tf.to_float(images_gray_b), tf.to_float(images_gray_r)) images_b_diff = tf.multiply(images_b_diff1, images_b_diff2) image_zero1 = tf.constant(0, dtype=tf.float32, shape=[1, 4, 4, 1]) with self.test_session() as sess: (images_r_diff_, images_g_diff_, images_b_diff_, image_zero1_) = sess.run( [images_r_diff, images_g_diff, images_b_diff, image_zero1]) self.assertAllClose(images_r_diff_, image_zero1_) self.assertAllClose(images_g_diff_, image_zero1_) self.assertAllClose(images_b_diff_, image_zero1_) def testRandomRGBtoGrayWithCache(self): preprocess_options = [( preprocessor.random_rgb_to_gray, {'probability': 0.5})] self._testPreprocessorCache(preprocess_options, test_boxes=False, test_masks=False, test_keypoints=False) def testRandomAdjustBrightness(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_adjust_brightness, {})) images_original = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images_original} tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images_bright = tensor_dict[fields.InputDataFields.image] image_original_shape = tf.shape(images_original) image_bright_shape = tf.shape(images_bright) with self.test_session() as sess: (image_original_shape_, image_bright_shape_) = sess.run( [image_original_shape, image_bright_shape]) self.assertAllEqual(image_original_shape_, image_bright_shape_) def testRandomAdjustBrightnessWithCache(self): preprocess_options = [] preprocess_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocess_options.append((preprocessor.random_adjust_brightness, {})) self._testPreprocessorCache(preprocess_options, test_boxes=False, test_masks=False, test_keypoints=False) def testRandomAdjustContrast(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_adjust_contrast, {})) images_original = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images_original} tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images_contrast = tensor_dict[fields.InputDataFields.image] image_original_shape = tf.shape(images_original) image_contrast_shape = tf.shape(images_contrast) with self.test_session() as sess: (image_original_shape_, image_contrast_shape_) = sess.run( [image_original_shape, image_contrast_shape]) self.assertAllEqual(image_original_shape_, image_contrast_shape_) def testRandomAdjustContrastWithCache(self): preprocess_options = [] preprocess_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocess_options.append((preprocessor.random_adjust_contrast, {})) self._testPreprocessorCache(preprocess_options, test_boxes=False, test_masks=False, test_keypoints=False) def testRandomAdjustHue(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_adjust_hue, {})) images_original = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images_original} tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images_hue = tensor_dict[fields.InputDataFields.image] image_original_shape = tf.shape(images_original) image_hue_shape = tf.shape(images_hue) with self.test_session() as sess: (image_original_shape_, image_hue_shape_) = sess.run( [image_original_shape, image_hue_shape]) self.assertAllEqual(image_original_shape_, image_hue_shape_) def testRandomAdjustHueWithCache(self): preprocess_options = [] preprocess_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocess_options.append((preprocessor.random_adjust_hue, {})) self._testPreprocessorCache(preprocess_options, test_boxes=False, test_masks=False, test_keypoints=False) def testRandomDistortColor(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_distort_color, {})) images_original = self.createTestImages() images_original_shape = tf.shape(images_original) tensor_dict = {fields.InputDataFields.image: images_original} tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images_distorted_color = tensor_dict[fields.InputDataFields.image] images_distorted_color_shape = tf.shape(images_distorted_color) with self.test_session() as sess: (images_original_shape_, images_distorted_color_shape_) = sess.run( [images_original_shape, images_distorted_color_shape]) self.assertAllEqual(images_original_shape_, images_distorted_color_shape_) def testRandomDistortColorWithCache(self): preprocess_options = [] preprocess_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocess_options.append((preprocessor.random_distort_color, {})) self._testPreprocessorCache(preprocess_options, test_boxes=False, test_masks=False, test_keypoints=False) def testRandomJitterBoxes(self): preprocessing_options = [] preprocessing_options.append((preprocessor.random_jitter_boxes, {})) boxes = self.createTestBoxes() boxes_shape = tf.shape(boxes) tensor_dict = {fields.InputDataFields.groundtruth_boxes: boxes} tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) distorted_boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes] distorted_boxes_shape = tf.shape(distorted_boxes) with self.test_session() as sess: (boxes_shape_, distorted_boxes_shape_) = sess.run( [boxes_shape, distorted_boxes_shape]) self.assertAllEqual(boxes_shape_, distorted_boxes_shape_) def testRandomCropImage(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_crop_image, {})) images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } distorted_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] boxes_rank = tf.rank(boxes) distorted_boxes_rank = tf.rank(distorted_boxes) images_rank = tf.rank(images) distorted_images_rank = tf.rank(distorted_images) self.assertEqual(3, distorted_images.get_shape()[3]) with self.test_session() as sess: (boxes_rank_, distorted_boxes_rank_, images_rank_, distorted_images_rank_) = sess.run([ boxes_rank, distorted_boxes_rank, images_rank, distorted_images_rank ]) self.assertAllEqual(boxes_rank_, distorted_boxes_rank_) self.assertAllEqual(images_rank_, distorted_images_rank_) def testRandomCropImageWithCache(self): preprocess_options = [(preprocessor.random_rgb_to_gray, {'probability': 0.5}), (preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1, }), (preprocessor.random_crop_image, {})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=False, test_keypoints=False) def testRandomCropImageGrayscale(self): preprocessing_options = [(preprocessor.rgb_to_gray, {}), (preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1, }), (preprocessor.random_crop_image, {})] images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] boxes_rank = tf.rank(boxes) distorted_boxes_rank = tf.rank(distorted_boxes) images_rank = tf.rank(images) distorted_images_rank = tf.rank(distorted_images) self.assertEqual(1, distorted_images.get_shape()[3]) with self.test_session() as sess: session_results = sess.run([ boxes_rank, distorted_boxes_rank, images_rank, distorted_images_rank ]) (boxes_rank_, distorted_boxes_rank_, images_rank_, distorted_images_rank_) = session_results self.assertAllEqual(boxes_rank_, distorted_boxes_rank_) self.assertAllEqual(images_rank_, distorted_images_rank_) def testRandomCropImageWithBoxOutOfImage(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_crop_image, {})) images = self.createTestImages() boxes = self.createTestBoxesOutOfImage() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } distorted_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] boxes_rank = tf.rank(boxes) distorted_boxes_rank = tf.rank(distorted_boxes) images_rank = tf.rank(images) distorted_images_rank = tf.rank(distorted_images) with self.test_session() as sess: (boxes_rank_, distorted_boxes_rank_, images_rank_, distorted_images_rank_) = sess.run( [boxes_rank, distorted_boxes_rank, images_rank, distorted_images_rank]) self.assertAllEqual(boxes_rank_, distorted_boxes_rank_) self.assertAllEqual(images_rank_, distorted_images_rank_) def testRandomCropImageWithRandomCoefOne(self): preprocessing_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })] images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_label_scores: label_scores } tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images = tensor_dict[fields.InputDataFields.image] preprocessing_options = [(preprocessor.random_crop_image, { 'random_coef': 1.0 })] distorted_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] distorted_label_scores = distorted_tensor_dict[ fields.InputDataFields.groundtruth_label_scores] boxes_shape = tf.shape(boxes) distorted_boxes_shape = tf.shape(distorted_boxes) images_shape = tf.shape(images) distorted_images_shape = tf.shape(distorted_images) with self.test_session() as sess: (boxes_shape_, distorted_boxes_shape_, images_shape_, distorted_images_shape_, images_, distorted_images_, boxes_, distorted_boxes_, labels_, distorted_labels_, label_scores_, distorted_label_scores_) = sess.run( [boxes_shape, distorted_boxes_shape, images_shape, distorted_images_shape, images, distorted_images, boxes, distorted_boxes, labels, distorted_labels, label_scores, distorted_label_scores]) self.assertAllEqual(boxes_shape_, distorted_boxes_shape_) self.assertAllEqual(images_shape_, distorted_images_shape_) self.assertAllClose(images_, distorted_images_) self.assertAllClose(boxes_, distorted_boxes_) self.assertAllEqual(labels_, distorted_labels_) self.assertAllEqual(label_scores_, distorted_label_scores_) def testRandomCropWithMockSampleDistortedBoundingBox(self): preprocessing_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })] images = self.createColorfulTestImage() boxes = tf.constant([[0.1, 0.1, 0.8, 0.3], [0.2, 0.4, 0.75, 0.75], [0.3, 0.1, 0.4, 0.7]], dtype=tf.float32) labels = tf.constant([1, 7, 11], dtype=tf.int32) tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images = tensor_dict[fields.InputDataFields.image] preprocessing_options = [(preprocessor.random_crop_image, {})] with mock.patch.object( tf.image, 'sample_distorted_bounding_box') as mock_sample_distorted_bounding_box: mock_sample_distorted_bounding_box.return_value = (tf.constant( [6, 143, 0], dtype=tf.int32), tf.constant( [190, 237, -1], dtype=tf.int32), tf.constant( [[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)) distorted_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] expected_boxes = tf.constant([[0.178947, 0.07173, 0.75789469, 0.66244733], [0.28421, 0.0, 0.38947365, 0.57805908]], dtype=tf.float32) expected_labels = tf.constant([7, 11], dtype=tf.int32) with self.test_session() as sess: (distorted_boxes_, distorted_labels_, expected_boxes_, expected_labels_) = sess.run( [distorted_boxes, distorted_labels, expected_boxes, expected_labels]) self.assertAllClose(distorted_boxes_, expected_boxes_) self.assertAllEqual(distorted_labels_, expected_labels_) def testRandomCropImageWithMultiClassScores(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_crop_image, {})) images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() multiclass_scores = self.createTestMultiClassScores() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.multiclass_scores: multiclass_scores } distorted_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_multiclass_scores = distorted_tensor_dict[ fields.InputDataFields.multiclass_scores] boxes_rank = tf.rank(boxes) distorted_boxes_rank = tf.rank(distorted_boxes) images_rank = tf.rank(images) distorted_images_rank = tf.rank(distorted_images) multiclass_scores_rank = tf.rank(multiclass_scores) distorted_multiclass_scores_rank = tf.rank(distorted_multiclass_scores) with self.test_session() as sess: (boxes_rank_, distorted_boxes_, distorted_boxes_rank_, images_rank_, distorted_images_rank_, multiclass_scores_rank_, distorted_multiclass_scores_rank_, distorted_multiclass_scores_) = sess.run([ boxes_rank, distorted_boxes, distorted_boxes_rank, images_rank, distorted_images_rank, multiclass_scores_rank, distorted_multiclass_scores_rank, distorted_multiclass_scores ]) self.assertAllEqual(boxes_rank_, distorted_boxes_rank_) self.assertAllEqual(images_rank_, distorted_images_rank_) self.assertAllEqual(multiclass_scores_rank_, distorted_multiclass_scores_rank_) self.assertAllEqual(distorted_boxes_.shape[0], distorted_multiclass_scores_.shape[0]) def testStrictRandomCropImageWithLabelScores(self): image = self.createColorfulTestImage()[0] boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() with mock.patch.object( tf.image, 'sample_distorted_bounding_box' ) as mock_sample_distorted_bounding_box: mock_sample_distorted_bounding_box.return_value = ( tf.constant([6, 143, 0], dtype=tf.int32), tf.constant([190, 237, -1], dtype=tf.int32), tf.constant([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)) new_image, new_boxes, new_labels, new_label_scores = ( preprocessor._strict_random_crop_image( image, boxes, labels, label_scores)) with self.test_session() as sess: new_image, new_boxes, new_labels, new_label_scores = ( sess.run( [new_image, new_boxes, new_labels, new_label_scores]) ) expected_boxes = np.array( [[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0]], dtype=np.float32) self.assertAllEqual(new_image.shape, [190, 237, 3]) self.assertAllEqual(new_label_scores, [1.0, 0.5]) self.assertAllClose( new_boxes.flatten(), expected_boxes.flatten()) def testStrictRandomCropImageWithMasks(self): image = self.createColorfulTestImage()[0] boxes = self.createTestBoxes() labels = self.createTestLabels() masks = tf.random_uniform([2, 200, 400], dtype=tf.float32) with mock.patch.object( tf.image, 'sample_distorted_bounding_box' ) as mock_sample_distorted_bounding_box: mock_sample_distorted_bounding_box.return_value = ( tf.constant([6, 143, 0], dtype=tf.int32), tf.constant([190, 237, -1], dtype=tf.int32), tf.constant([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)) new_image, new_boxes, new_labels, new_masks = ( preprocessor._strict_random_crop_image( image, boxes, labels, masks=masks)) with self.test_session() as sess: new_image, new_boxes, new_labels, new_masks = sess.run( [new_image, new_boxes, new_labels, new_masks]) expected_boxes = np.array( [[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0]], dtype=np.float32) self.assertAllEqual(new_image.shape, [190, 237, 3]) self.assertAllEqual(new_masks.shape, [2, 190, 237]) self.assertAllClose( new_boxes.flatten(), expected_boxes.flatten()) def testStrictRandomCropImageWithKeypoints(self): image = self.createColorfulTestImage()[0] boxes = self.createTestBoxes() labels = self.createTestLabels() keypoints = self.createTestKeypoints() with mock.patch.object( tf.image, 'sample_distorted_bounding_box' ) as mock_sample_distorted_bounding_box: mock_sample_distorted_bounding_box.return_value = ( tf.constant([6, 143, 0], dtype=tf.int32), tf.constant([190, 237, -1], dtype=tf.int32), tf.constant([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)) new_image, new_boxes, new_labels, new_keypoints = ( preprocessor._strict_random_crop_image( image, boxes, labels, keypoints=keypoints)) with self.test_session() as sess: new_image, new_boxes, new_labels, new_keypoints = sess.run( [new_image, new_boxes, new_labels, new_keypoints]) expected_boxes = np.array([ [0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0],], dtype=np.float32) expected_keypoints = np.array([ [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], [[0.38947368, 0.07173], [0.49473682, 0.24050637], [0.60000002, 0.40928277]] ], dtype=np.float32) self.assertAllEqual(new_image.shape, [190, 237, 3]) self.assertAllClose( new_boxes.flatten(), expected_boxes.flatten()) self.assertAllClose( new_keypoints.flatten(), expected_keypoints.flatten()) def testRunRandomCropImageWithMasks(self): image = self.createColorfulTestImage() boxes = self.createTestBoxes() labels = self.createTestLabels() masks = tf.random_uniform([2, 200, 400], dtype=tf.float32) tensor_dict = { fields.InputDataFields.image: image, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_instance_masks: masks, } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_instance_masks=True) preprocessing_options = [(preprocessor.random_crop_image, {})] with mock.patch.object( tf.image, 'sample_distorted_bounding_box' ) as mock_sample_distorted_bounding_box: mock_sample_distorted_bounding_box.return_value = ( tf.constant([6, 143, 0], dtype=tf.int32), tf.constant([190, 237, -1], dtype=tf.int32), tf.constant([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)) distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_image = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] distorted_masks = distorted_tensor_dict[ fields.InputDataFields.groundtruth_instance_masks] with self.test_session() as sess: (distorted_image_, distorted_boxes_, distorted_labels_, distorted_masks_) = sess.run( [distorted_image, distorted_boxes, distorted_labels, distorted_masks]) expected_boxes = np.array([ [0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0], ], dtype=np.float32) self.assertAllEqual(distorted_image_.shape, [1, 190, 237, 3]) self.assertAllEqual(distorted_masks_.shape, [2, 190, 237]) self.assertAllEqual(distorted_labels_, [1, 2]) self.assertAllClose( distorted_boxes_.flatten(), expected_boxes.flatten()) def testRunRandomCropImageWithKeypointsInsideCrop(self): image = self.createColorfulTestImage() boxes = self.createTestBoxes() labels = self.createTestLabels() keypoints = self.createTestKeypointsInsideCrop() tensor_dict = { fields.InputDataFields.image: image, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_keypoints: keypoints } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_keypoints=True) preprocessing_options = [(preprocessor.random_crop_image, {})] with mock.patch.object( tf.image, 'sample_distorted_bounding_box' ) as mock_sample_distorted_bounding_box: mock_sample_distorted_bounding_box.return_value = ( tf.constant([6, 143, 0], dtype=tf.int32), tf.constant([190, 237, -1], dtype=tf.int32), tf.constant([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)) distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_image = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] distorted_keypoints = distorted_tensor_dict[ fields.InputDataFields.groundtruth_keypoints] with self.test_session() as sess: (distorted_image_, distorted_boxes_, distorted_labels_, distorted_keypoints_) = sess.run( [distorted_image, distorted_boxes, distorted_labels, distorted_keypoints]) expected_boxes = np.array([ [0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0], ], dtype=np.float32) expected_keypoints = np.array([ [[0.38947368, 0.07173], [0.49473682, 0.24050637], [0.60000002, 0.40928277]], [[0.38947368, 0.07173], [0.49473682, 0.24050637], [0.60000002, 0.40928277]] ]) self.assertAllEqual(distorted_image_.shape, [1, 190, 237, 3]) self.assertAllEqual(distorted_labels_, [1, 2]) self.assertAllClose( distorted_boxes_.flatten(), expected_boxes.flatten()) self.assertAllClose( distorted_keypoints_.flatten(), expected_keypoints.flatten()) def testRunRandomCropImageWithKeypointsOutsideCrop(self): image = self.createColorfulTestImage() boxes = self.createTestBoxes() labels = self.createTestLabels() keypoints = self.createTestKeypointsOutsideCrop() tensor_dict = { fields.InputDataFields.image: image, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_keypoints: keypoints } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_keypoints=True) preprocessing_options = [(preprocessor.random_crop_image, {})] with mock.patch.object( tf.image, 'sample_distorted_bounding_box' ) as mock_sample_distorted_bounding_box: mock_sample_distorted_bounding_box.return_value = ( tf.constant([6, 143, 0], dtype=tf.int32), tf.constant([190, 237, -1], dtype=tf.int32), tf.constant([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)) distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_image = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] distorted_keypoints = distorted_tensor_dict[ fields.InputDataFields.groundtruth_keypoints] with self.test_session() as sess: (distorted_image_, distorted_boxes_, distorted_labels_, distorted_keypoints_) = sess.run( [distorted_image, distorted_boxes, distorted_labels, distorted_keypoints]) expected_boxes = np.array([ [0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0], ], dtype=np.float32) expected_keypoints = np.array([ [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], ]) self.assertAllEqual(distorted_image_.shape, [1, 190, 237, 3]) self.assertAllEqual(distorted_labels_, [1, 2]) self.assertAllClose( distorted_boxes_.flatten(), expected_boxes.flatten()) self.assertAllClose( distorted_keypoints_.flatten(), expected_keypoints.flatten()) def testRunRetainBoxesAboveThreshold(self): boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() tensor_dict = { fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_label_scores: label_scores } preprocessing_options = [ (preprocessor.retain_boxes_above_threshold, {'threshold': 0.6}) ] preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_label_scores=True) retained_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) retained_boxes = retained_tensor_dict[ fields.InputDataFields.groundtruth_boxes] retained_labels = retained_tensor_dict[ fields.InputDataFields.groundtruth_classes] retained_label_scores = retained_tensor_dict[ fields.InputDataFields.groundtruth_label_scores] with self.test_session() as sess: (retained_boxes_, retained_labels_, retained_label_scores_, expected_retained_boxes_, expected_retained_labels_, expected_retained_label_scores_) = sess.run( [retained_boxes, retained_labels, retained_label_scores, self.expectedBoxesAfterThresholding(), self.expectedLabelsAfterThresholding(), self.expectedLabelScoresAfterThresholding()]) self.assertAllClose(retained_boxes_, expected_retained_boxes_) self.assertAllClose(retained_labels_, expected_retained_labels_) self.assertAllClose( retained_label_scores_, expected_retained_label_scores_) def testRunRetainBoxesAboveThresholdWithMasks(self): boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() masks = self.createTestMasks() tensor_dict = { fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_label_scores: label_scores, fields.InputDataFields.groundtruth_instance_masks: masks } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_label_scores=True, include_instance_masks=True) preprocessing_options = [ (preprocessor.retain_boxes_above_threshold, {'threshold': 0.6}) ] retained_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) retained_masks = retained_tensor_dict[ fields.InputDataFields.groundtruth_instance_masks] with self.test_session() as sess: (retained_masks_, expected_masks_) = sess.run( [retained_masks, self.expectedMasksAfterThresholding()]) self.assertAllClose(retained_masks_, expected_masks_) def testRunRetainBoxesAboveThresholdWithKeypoints(self): boxes = self.createTestBoxes() labels = self.createTestLabels() label_scores = self.createTestLabelScores() keypoints = self.createTestKeypoints() tensor_dict = { fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_label_scores: label_scores, fields.InputDataFields.groundtruth_keypoints: keypoints } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_label_scores=True, include_keypoints=True) preprocessing_options = [ (preprocessor.retain_boxes_above_threshold, {'threshold': 0.6}) ] retained_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) retained_keypoints = retained_tensor_dict[ fields.InputDataFields.groundtruth_keypoints] with self.test_session() as sess: (retained_keypoints_, expected_keypoints_) = sess.run( [retained_keypoints, self.expectedKeypointsAfterThresholding()]) self.assertAllClose(retained_keypoints_, expected_keypoints_) def testRandomCropToAspectRatioWithCache(self): preprocess_options = [(preprocessor.random_crop_to_aspect_ratio, {})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=False, test_keypoints=False) def testRunRandomCropToAspectRatioWithMasks(self): image = self.createColorfulTestImage() boxes = self.createTestBoxes() labels = self.createTestLabels() masks = tf.random_uniform([2, 200, 400], dtype=tf.float32) tensor_dict = { fields.InputDataFields.image: image, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_instance_masks: masks } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_instance_masks=True) preprocessing_options = [(preprocessor.random_crop_to_aspect_ratio, {})] with mock.patch.object(preprocessor, '_random_integer') as mock_random_integer: mock_random_integer.return_value = tf.constant(0, dtype=tf.int32) distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_image = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] distorted_masks = distorted_tensor_dict[ fields.InputDataFields.groundtruth_instance_masks] with self.test_session() as sess: (distorted_image_, distorted_boxes_, distorted_labels_, distorted_masks_) = sess.run([ distorted_image, distorted_boxes, distorted_labels, distorted_masks ]) expected_boxes = np.array([0.0, 0.5, 0.75, 1.0], dtype=np.float32) self.assertAllEqual(distorted_image_.shape, [1, 200, 200, 3]) self.assertAllEqual(distorted_labels_, [1]) self.assertAllClose(distorted_boxes_.flatten(), expected_boxes.flatten()) self.assertAllEqual(distorted_masks_.shape, [1, 200, 200]) def testRunRandomCropToAspectRatioWithKeypoints(self): image = self.createColorfulTestImage() boxes = self.createTestBoxes() labels = self.createTestLabels() keypoints = self.createTestKeypoints() tensor_dict = { fields.InputDataFields.image: image, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_keypoints: keypoints } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_keypoints=True) preprocessing_options = [(preprocessor.random_crop_to_aspect_ratio, {})] with mock.patch.object(preprocessor, '_random_integer') as mock_random_integer: mock_random_integer.return_value = tf.constant(0, dtype=tf.int32) distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_image = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] distorted_keypoints = distorted_tensor_dict[ fields.InputDataFields.groundtruth_keypoints] with self.test_session() as sess: (distorted_image_, distorted_boxes_, distorted_labels_, distorted_keypoints_) = sess.run([ distorted_image, distorted_boxes, distorted_labels, distorted_keypoints ]) expected_boxes = np.array([0.0, 0.5, 0.75, 1.0], dtype=np.float32) expected_keypoints = np.array( [[0.1, 0.2], [0.2, 0.4], [0.3, 0.6]], dtype=np.float32) self.assertAllEqual(distorted_image_.shape, [1, 200, 200, 3]) self.assertAllEqual(distorted_labels_, [1]) self.assertAllClose(distorted_boxes_.flatten(), expected_boxes.flatten()) self.assertAllClose(distorted_keypoints_.flatten(), expected_keypoints.flatten()) def testRandomPadToAspectRatioWithCache(self): preprocess_options = [(preprocessor.random_pad_to_aspect_ratio, {})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=True, test_keypoints=True) def testRunRandomPadToAspectRatioWithMinMaxPaddedSizeRatios(self): image = self.createColorfulTestImage() boxes = self.createTestBoxes() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: image, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels } preprocessor_arg_map = preprocessor.get_default_func_arg_map() preprocessing_options = [(preprocessor.random_pad_to_aspect_ratio, {'min_padded_size_ratio': (4.0, 4.0), 'max_padded_size_ratio': (4.0, 4.0)})] distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_image = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] with self.test_session() as sess: distorted_image_, distorted_boxes_, distorted_labels_ = sess.run([ distorted_image, distorted_boxes, distorted_labels]) expected_boxes = np.array( [[0.0, 0.125, 0.1875, 0.5], [0.0625, 0.25, 0.1875, 0.5]], dtype=np.float32) self.assertAllEqual(distorted_image_.shape, [1, 800, 800, 3]) self.assertAllEqual(distorted_labels_, [1, 2]) self.assertAllClose(distorted_boxes_.flatten(), expected_boxes.flatten()) def testRunRandomPadToAspectRatioWithMasks(self): image = self.createColorfulTestImage() boxes = self.createTestBoxes() labels = self.createTestLabels() masks = tf.random_uniform([2, 200, 400], dtype=tf.float32) tensor_dict = { fields.InputDataFields.image: image, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_instance_masks: masks } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_instance_masks=True) preprocessing_options = [(preprocessor.random_pad_to_aspect_ratio, {})] distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_image = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] distorted_masks = distorted_tensor_dict[ fields.InputDataFields.groundtruth_instance_masks] with self.test_session() as sess: (distorted_image_, distorted_boxes_, distorted_labels_, distorted_masks_) = sess.run([ distorted_image, distorted_boxes, distorted_labels, distorted_masks ]) expected_boxes = np.array( [[0.0, 0.25, 0.375, 1.0], [0.125, 0.5, 0.375, 1.0]], dtype=np.float32) self.assertAllEqual(distorted_image_.shape, [1, 400, 400, 3]) self.assertAllEqual(distorted_labels_, [1, 2]) self.assertAllClose(distorted_boxes_.flatten(), expected_boxes.flatten()) self.assertAllEqual(distorted_masks_.shape, [2, 400, 400]) def testRunRandomPadToAspectRatioWithKeypoints(self): image = self.createColorfulTestImage() boxes = self.createTestBoxes() labels = self.createTestLabels() keypoints = self.createTestKeypoints() tensor_dict = { fields.InputDataFields.image: image, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.groundtruth_keypoints: keypoints } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_keypoints=True) preprocessing_options = [(preprocessor.random_pad_to_aspect_ratio, {})] distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_image = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_labels = distorted_tensor_dict[ fields.InputDataFields.groundtruth_classes] distorted_keypoints = distorted_tensor_dict[ fields.InputDataFields.groundtruth_keypoints] with self.test_session() as sess: (distorted_image_, distorted_boxes_, distorted_labels_, distorted_keypoints_) = sess.run([ distorted_image, distorted_boxes, distorted_labels, distorted_keypoints ]) expected_boxes = np.array( [[0.0, 0.25, 0.375, 1.0], [0.125, 0.5, 0.375, 1.0]], dtype=np.float32) expected_keypoints = np.array([ [[0.05, 0.1], [0.1, 0.2], [0.15, 0.3]], [[0.2, 0.4], [0.25, 0.5], [0.3, 0.6]], ], dtype=np.float32) self.assertAllEqual(distorted_image_.shape, [1, 400, 400, 3]) self.assertAllEqual(distorted_labels_, [1, 2]) self.assertAllClose(distorted_boxes_.flatten(), expected_boxes.flatten()) self.assertAllClose(distorted_keypoints_.flatten(), expected_keypoints.flatten()) def testRandomPadImageWithCache(self): preprocess_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1,}), (preprocessor.random_pad_image, {})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=True, test_keypoints=True) def testRandomPadImage(self): preprocessing_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })] images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images = tensor_dict[fields.InputDataFields.image] preprocessing_options = [(preprocessor.random_pad_image, {})] padded_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) padded_images = padded_tensor_dict[fields.InputDataFields.image] padded_boxes = padded_tensor_dict[ fields.InputDataFields.groundtruth_boxes] boxes_shape = tf.shape(boxes) padded_boxes_shape = tf.shape(padded_boxes) images_shape = tf.shape(images) padded_images_shape = tf.shape(padded_images) with self.test_session() as sess: (boxes_shape_, padded_boxes_shape_, images_shape_, padded_images_shape_, boxes_, padded_boxes_) = sess.run( [boxes_shape, padded_boxes_shape, images_shape, padded_images_shape, boxes, padded_boxes]) self.assertAllEqual(boxes_shape_, padded_boxes_shape_) self.assertTrue((images_shape_[1] >= padded_images_shape_[1] * 0.5).all) self.assertTrue((images_shape_[2] >= padded_images_shape_[2] * 0.5).all) self.assertTrue((images_shape_[1] <= padded_images_shape_[1]).all) self.assertTrue((images_shape_[2] <= padded_images_shape_[2]).all) self.assertTrue(np.all((boxes_[:, 2] - boxes_[:, 0]) >= ( padded_boxes_[:, 2] - padded_boxes_[:, 0]))) self.assertTrue(np.all((boxes_[:, 3] - boxes_[:, 1]) >= ( padded_boxes_[:, 3] - padded_boxes_[:, 1]))) def testRandomCropPadImageWithCache(self): preprocess_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1,}), (preprocessor.random_crop_pad_image, {})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=True, test_keypoints=True) def testRandomCropPadImageWithRandomCoefOne(self): preprocessing_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })] images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) images = tensor_dict[fields.InputDataFields.image] preprocessing_options = [(preprocessor.random_crop_pad_image, { 'random_coef': 1.0 })] padded_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) padded_images = padded_tensor_dict[fields.InputDataFields.image] padded_boxes = padded_tensor_dict[ fields.InputDataFields.groundtruth_boxes] boxes_shape = tf.shape(boxes) padded_boxes_shape = tf.shape(padded_boxes) images_shape = tf.shape(images) padded_images_shape = tf.shape(padded_images) with self.test_session() as sess: (boxes_shape_, padded_boxes_shape_, images_shape_, padded_images_shape_, boxes_, padded_boxes_) = sess.run( [boxes_shape, padded_boxes_shape, images_shape, padded_images_shape, boxes, padded_boxes]) self.assertAllEqual(boxes_shape_, padded_boxes_shape_) self.assertTrue((images_shape_[1] >= padded_images_shape_[1] * 0.5).all) self.assertTrue((images_shape_[2] >= padded_images_shape_[2] * 0.5).all) self.assertTrue((images_shape_[1] <= padded_images_shape_[1]).all) self.assertTrue((images_shape_[2] <= padded_images_shape_[2]).all) self.assertTrue(np.all((boxes_[:, 2] - boxes_[:, 0]) >= ( padded_boxes_[:, 2] - padded_boxes_[:, 0]))) self.assertTrue(np.all((boxes_[:, 3] - boxes_[:, 1]) >= ( padded_boxes_[:, 3] - padded_boxes_[:, 1]))) def testRandomCropToAspectRatio(self): images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } tensor_dict = preprocessor.preprocess(tensor_dict, []) images = tensor_dict[fields.InputDataFields.image] preprocessing_options = [(preprocessor.random_crop_to_aspect_ratio, { 'aspect_ratio': 2.0 })] cropped_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) cropped_images = cropped_tensor_dict[fields.InputDataFields.image] cropped_boxes = cropped_tensor_dict[ fields.InputDataFields.groundtruth_boxes] boxes_shape = tf.shape(boxes) cropped_boxes_shape = tf.shape(cropped_boxes) images_shape = tf.shape(images) cropped_images_shape = tf.shape(cropped_images) with self.test_session() as sess: (boxes_shape_, cropped_boxes_shape_, images_shape_, cropped_images_shape_) = sess.run([ boxes_shape, cropped_boxes_shape, images_shape, cropped_images_shape ]) self.assertAllEqual(boxes_shape_, cropped_boxes_shape_) self.assertEqual(images_shape_[1], cropped_images_shape_[1] * 2) self.assertEqual(images_shape_[2], cropped_images_shape_[2]) def testRandomPadToAspectRatio(self): images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } tensor_dict = preprocessor.preprocess(tensor_dict, []) images = tensor_dict[fields.InputDataFields.image] preprocessing_options = [(preprocessor.random_pad_to_aspect_ratio, { 'aspect_ratio': 2.0 })] padded_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) padded_images = padded_tensor_dict[fields.InputDataFields.image] padded_boxes = padded_tensor_dict[ fields.InputDataFields.groundtruth_boxes] boxes_shape = tf.shape(boxes) padded_boxes_shape = tf.shape(padded_boxes) images_shape = tf.shape(images) padded_images_shape = tf.shape(padded_images) with self.test_session() as sess: (boxes_shape_, padded_boxes_shape_, images_shape_, padded_images_shape_) = sess.run([ boxes_shape, padded_boxes_shape, images_shape, padded_images_shape ]) self.assertAllEqual(boxes_shape_, padded_boxes_shape_) self.assertEqual(images_shape_[1], padded_images_shape_[1]) self.assertEqual(2 * images_shape_[2], padded_images_shape_[2]) def testRandomBlackPatchesWithCache(self): preprocess_options = [] preprocess_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocess_options.append((preprocessor.random_black_patches, { 'size_to_image_ratio': 0.5 })) self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=True, test_keypoints=True) def testRandomBlackPatches(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_black_patches, { 'size_to_image_ratio': 0.5 })) images = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images} blacked_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) blacked_images = blacked_tensor_dict[fields.InputDataFields.image] images_shape = tf.shape(images) blacked_images_shape = tf.shape(blacked_images) with self.test_session() as sess: (images_shape_, blacked_images_shape_) = sess.run( [images_shape, blacked_images_shape]) self.assertAllEqual(images_shape_, blacked_images_shape_) def testRandomResizeMethodWithCache(self): preprocess_options = [] preprocess_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocess_options.append((preprocessor.random_resize_method, { 'target_size': (75, 150) })) self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=True, test_keypoints=True) def testRandomResizeMethod(self): preprocessing_options = [] preprocessing_options.append((preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 })) preprocessing_options.append((preprocessor.random_resize_method, { 'target_size': (75, 150) })) images = self.createTestImages() tensor_dict = {fields.InputDataFields.image: images} resized_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) resized_images = resized_tensor_dict[fields.InputDataFields.image] resized_images_shape = tf.shape(resized_images) expected_images_shape = tf.constant([1, 75, 150, 3], dtype=tf.int32) with self.test_session() as sess: (expected_images_shape_, resized_images_shape_) = sess.run( [expected_images_shape, resized_images_shape]) self.assertAllEqual(expected_images_shape_, resized_images_shape_) def testResizeImageWithMasks(self): """Tests image resizing, checking output sizes.""" in_image_shape_list = [[60, 40, 3], [15, 30, 3]] in_masks_shape_list = [[15, 60, 40], [10, 15, 30]] height = 50 width = 100 expected_image_shape_list = [[50, 100, 3], [50, 100, 3]] expected_masks_shape_list = [[15, 50, 100], [10, 50, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip(in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.random_uniform(in_image_shape) in_masks = tf.random_uniform(in_masks_shape) out_image, out_masks, _ = preprocessor.resize_image( in_image, in_masks, new_height=height, new_width=width) out_image_shape = tf.shape(out_image) out_masks_shape = tf.shape(out_masks) with self.test_session() as sess: out_image_shape, out_masks_shape = sess.run( [out_image_shape, out_masks_shape]) self.assertAllEqual(out_image_shape, expected_image_shape) self.assertAllEqual(out_masks_shape, expected_mask_shape) def testResizeImageWithMasksTensorInputHeightAndWidth(self): """Tests image resizing, checking output sizes.""" in_image_shape_list = [[60, 40, 3], [15, 30, 3]] in_masks_shape_list = [[15, 60, 40], [10, 15, 30]] height = tf.constant(50, dtype=tf.int32) width = tf.constant(100, dtype=tf.int32) expected_image_shape_list = [[50, 100, 3], [50, 100, 3]] expected_masks_shape_list = [[15, 50, 100], [10, 50, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip(in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.random_uniform(in_image_shape) in_masks = tf.random_uniform(in_masks_shape) out_image, out_masks, _ = preprocessor.resize_image( in_image, in_masks, new_height=height, new_width=width) out_image_shape = tf.shape(out_image) out_masks_shape = tf.shape(out_masks) with self.test_session() as sess: out_image_shape, out_masks_shape = sess.run( [out_image_shape, out_masks_shape]) self.assertAllEqual(out_image_shape, expected_image_shape) self.assertAllEqual(out_masks_shape, expected_mask_shape) def testResizeImageWithNoInstanceMask(self): """Tests image resizing, checking output sizes.""" in_image_shape_list = [[60, 40, 3], [15, 30, 3]] in_masks_shape_list = [[0, 60, 40], [0, 15, 30]] height = 50 width = 100 expected_image_shape_list = [[50, 100, 3], [50, 100, 3]] expected_masks_shape_list = [[0, 50, 100], [0, 50, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip(in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.random_uniform(in_image_shape) in_masks = tf.random_uniform(in_masks_shape) out_image, out_masks, _ = preprocessor.resize_image( in_image, in_masks, new_height=height, new_width=width) out_image_shape = tf.shape(out_image) out_masks_shape = tf.shape(out_masks) with self.test_session() as sess: out_image_shape, out_masks_shape = sess.run( [out_image_shape, out_masks_shape]) self.assertAllEqual(out_image_shape, expected_image_shape) self.assertAllEqual(out_masks_shape, expected_mask_shape) def testResizeToRangePreservesStaticSpatialShape(self): """Tests image resizing, checking output sizes.""" in_shape_list = [[60, 40, 3], [15, 30, 3], [15, 50, 3]] min_dim = 50 max_dim = 100 expected_shape_list = [[75, 50, 3], [50, 100, 3], [30, 100, 3]] for in_shape, expected_shape in zip(in_shape_list, expected_shape_list): in_image = tf.random_uniform(in_shape) out_image, _ = preprocessor.resize_to_range( in_image, min_dimension=min_dim, max_dimension=max_dim) self.assertAllEqual(out_image.get_shape().as_list(), expected_shape) def testResizeToRangeWithDynamicSpatialShape(self): """Tests image resizing, checking output sizes.""" in_shape_list = [[60, 40, 3], [15, 30, 3], [15, 50, 3]] min_dim = 50 max_dim = 100 expected_shape_list = [[75, 50, 3], [50, 100, 3], [30, 100, 3]] for in_shape, expected_shape in zip(in_shape_list, expected_shape_list): in_image = tf.placeholder(tf.float32, shape=(None, None, 3)) out_image, _ = preprocessor.resize_to_range( in_image, min_dimension=min_dim, max_dimension=max_dim) out_image_shape = tf.shape(out_image) with self.test_session() as sess: out_image_shape = sess.run(out_image_shape, feed_dict={in_image: np.random.randn(*in_shape)}) self.assertAllEqual(out_image_shape, expected_shape) def testResizeToRangeWithPadToMaxDimensionReturnsCorrectShapes(self): in_shape_list = [[60, 40, 3], [15, 30, 3], [15, 50, 3]] min_dim = 50 max_dim = 100 expected_shape_list = [[100, 100, 3], [100, 100, 3], [100, 100, 3]] for in_shape, expected_shape in zip(in_shape_list, expected_shape_list): in_image = tf.placeholder(tf.float32, shape=(None, None, 3)) out_image, _ = preprocessor.resize_to_range( in_image, min_dimension=min_dim, max_dimension=max_dim, pad_to_max_dimension=True) self.assertAllEqual(out_image.shape.as_list(), expected_shape) out_image_shape = tf.shape(out_image) with self.test_session() as sess: out_image_shape = sess.run( out_image_shape, feed_dict={in_image: np.random.randn(*in_shape)}) self.assertAllEqual(out_image_shape, expected_shape) def testResizeToRangeWithPadToMaxDimensionReturnsCorrectTensor(self): in_image_np = np.array([[[0, 1, 2]]], np.float32) ex_image_np = np.array( [[[0, 1, 2], [123.68, 116.779, 103.939]], [[123.68, 116.779, 103.939], [123.68, 116.779, 103.939]]], np.float32) min_dim = 1 max_dim = 2 in_image = tf.placeholder(tf.float32, shape=(None, None, 3)) out_image, _ = preprocessor.resize_to_range( in_image, min_dimension=min_dim, max_dimension=max_dim, pad_to_max_dimension=True, per_channel_pad_value=(123.68, 116.779, 103.939)) with self.test_session() as sess: out_image_np = sess.run(out_image, feed_dict={in_image: in_image_np}) self.assertAllClose(ex_image_np, out_image_np) def testResizeToRangeWithMasksPreservesStaticSpatialShape(self): """Tests image resizing, checking output sizes.""" in_image_shape_list = [[60, 40, 3], [15, 30, 3]] in_masks_shape_list = [[15, 60, 40], [10, 15, 30]] min_dim = 50 max_dim = 100 expected_image_shape_list = [[75, 50, 3], [50, 100, 3]] expected_masks_shape_list = [[15, 75, 50], [10, 50, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip(in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.random_uniform(in_image_shape) in_masks = tf.random_uniform(in_masks_shape) out_image, out_masks, _ = preprocessor.resize_to_range( in_image, in_masks, min_dimension=min_dim, max_dimension=max_dim) self.assertAllEqual(out_masks.get_shape().as_list(), expected_mask_shape) self.assertAllEqual(out_image.get_shape().as_list(), expected_image_shape) def testResizeToRangeWithMasksAndPadToMaxDimension(self): """Tests image resizing, checking output sizes.""" in_image_shape_list = [[60, 40, 3], [15, 30, 3]] in_masks_shape_list = [[15, 60, 40], [10, 15, 30]] min_dim = 50 max_dim = 100 expected_image_shape_list = [[100, 100, 3], [100, 100, 3]] expected_masks_shape_list = [[15, 100, 100], [10, 100, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip( in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.placeholder(tf.float32, shape=(None, None, 3)) in_masks = tf.placeholder(tf.float32, shape=(None, None, None)) out_image, out_masks, _ = preprocessor.resize_to_range( in_image, in_masks, min_dimension=min_dim, max_dimension=max_dim, pad_to_max_dimension=True) out_image_shape = tf.shape(out_image) out_masks_shape = tf.shape(out_masks) with self.test_session() as sess: out_image_shape, out_masks_shape = sess.run( [out_image_shape, out_masks_shape], feed_dict={ in_image: np.random.randn(*in_image_shape), in_masks: np.random.randn(*in_masks_shape) }) self.assertAllEqual(out_image_shape, expected_image_shape) self.assertAllEqual(out_masks_shape, expected_mask_shape) def testResizeToRangeWithMasksAndDynamicSpatialShape(self): """Tests image resizing, checking output sizes.""" in_image_shape_list = [[60, 40, 3], [15, 30, 3]] in_masks_shape_list = [[15, 60, 40], [10, 15, 30]] min_dim = 50 max_dim = 100 expected_image_shape_list = [[75, 50, 3], [50, 100, 3]] expected_masks_shape_list = [[15, 75, 50], [10, 50, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip(in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.placeholder(tf.float32, shape=(None, None, 3)) in_masks = tf.placeholder(tf.float32, shape=(None, None, None)) in_masks = tf.random_uniform(in_masks_shape) out_image, out_masks, _ = preprocessor.resize_to_range( in_image, in_masks, min_dimension=min_dim, max_dimension=max_dim) out_image_shape = tf.shape(out_image) out_masks_shape = tf.shape(out_masks) with self.test_session() as sess: out_image_shape, out_masks_shape = sess.run( [out_image_shape, out_masks_shape], feed_dict={ in_image: np.random.randn(*in_image_shape), in_masks: np.random.randn(*in_masks_shape) }) self.assertAllEqual(out_image_shape, expected_image_shape) self.assertAllEqual(out_masks_shape, expected_mask_shape) def testResizeToRangeWithInstanceMasksTensorOfSizeZero(self): """Tests image resizing, checking output sizes.""" in_image_shape_list = [[60, 40, 3], [15, 30, 3]] in_masks_shape_list = [[0, 60, 40], [0, 15, 30]] min_dim = 50 max_dim = 100 expected_image_shape_list = [[75, 50, 3], [50, 100, 3]] expected_masks_shape_list = [[0, 75, 50], [0, 50, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip(in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.random_uniform(in_image_shape) in_masks = tf.random_uniform(in_masks_shape) out_image, out_masks, _ = preprocessor.resize_to_range( in_image, in_masks, min_dimension=min_dim, max_dimension=max_dim) out_image_shape = tf.shape(out_image) out_masks_shape = tf.shape(out_masks) with self.test_session() as sess: out_image_shape, out_masks_shape = sess.run( [out_image_shape, out_masks_shape]) self.assertAllEqual(out_image_shape, expected_image_shape) self.assertAllEqual(out_masks_shape, expected_mask_shape) def testResizeToRange4DImageTensor(self): image = tf.random_uniform([1, 200, 300, 3]) with self.assertRaises(ValueError): preprocessor.resize_to_range(image, 500, 600) def testResizeToRangeSameMinMax(self): """Tests image resizing, checking output sizes.""" in_shape_list = [[312, 312, 3], [299, 299, 3]] min_dim = 320 max_dim = 320 expected_shape_list = [[320, 320, 3], [320, 320, 3]] for in_shape, expected_shape in zip(in_shape_list, expected_shape_list): in_image = tf.random_uniform(in_shape) out_image, _ = preprocessor.resize_to_range( in_image, min_dimension=min_dim, max_dimension=max_dim) out_image_shape = tf.shape(out_image) with self.test_session() as sess: out_image_shape = sess.run(out_image_shape) self.assertAllEqual(out_image_shape, expected_shape) def testResizeToMinDimensionTensorShapes(self): in_image_shape_list = [[60, 55, 3], [15, 30, 3]] in_masks_shape_list = [[15, 60, 55], [10, 15, 30]] min_dim = 50 expected_image_shape_list = [[60, 55, 3], [50, 100, 3]] expected_masks_shape_list = [[15, 60, 55], [10, 50, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip(in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.placeholder(tf.float32, shape=(None, None, 3)) in_masks = tf.placeholder(tf.float32, shape=(None, None, None)) in_masks = tf.random_uniform(in_masks_shape) out_image, out_masks, _ = preprocessor.resize_to_min_dimension( in_image, in_masks, min_dimension=min_dim) out_image_shape = tf.shape(out_image) out_masks_shape = tf.shape(out_masks) with self.test_session() as sess: out_image_shape, out_masks_shape = sess.run( [out_image_shape, out_masks_shape], feed_dict={ in_image: np.random.randn(*in_image_shape), in_masks: np.random.randn(*in_masks_shape) }) self.assertAllEqual(out_image_shape, expected_image_shape) self.assertAllEqual(out_masks_shape, expected_mask_shape) def testResizeToMinDimensionWithInstanceMasksTensorOfSizeZero(self): """Tests image resizing, checking output sizes.""" in_image_shape_list = [[60, 40, 3], [15, 30, 3]] in_masks_shape_list = [[0, 60, 40], [0, 15, 30]] min_dim = 50 expected_image_shape_list = [[75, 50, 3], [50, 100, 3]] expected_masks_shape_list = [[0, 75, 50], [0, 50, 100]] for (in_image_shape, expected_image_shape, in_masks_shape, expected_mask_shape) in zip(in_image_shape_list, expected_image_shape_list, in_masks_shape_list, expected_masks_shape_list): in_image = tf.random_uniform(in_image_shape) in_masks = tf.random_uniform(in_masks_shape) out_image, out_masks, _ = preprocessor.resize_to_min_dimension( in_image, in_masks, min_dimension=min_dim) out_image_shape = tf.shape(out_image) out_masks_shape = tf.shape(out_masks) with self.test_session() as sess: out_image_shape, out_masks_shape = sess.run( [out_image_shape, out_masks_shape]) self.assertAllEqual(out_image_shape, expected_image_shape) self.assertAllEqual(out_masks_shape, expected_mask_shape) def testResizeToMinDimensionRaisesErrorOn4DImage(self): image = tf.random_uniform([1, 200, 300, 3]) with self.assertRaises(ValueError): preprocessor.resize_to_min_dimension(image, 500) def testScaleBoxesToPixelCoordinates(self): """Tests box scaling, checking scaled values.""" in_shape = [60, 40, 3] in_boxes = [[0.1, 0.2, 0.4, 0.6], [0.5, 0.3, 0.9, 0.7]] expected_boxes = [[6., 8., 24., 24.], [30., 12., 54., 28.]] in_image = tf.random_uniform(in_shape) in_boxes = tf.constant(in_boxes) _, out_boxes = preprocessor.scale_boxes_to_pixel_coordinates( in_image, boxes=in_boxes) with self.test_session() as sess: out_boxes = sess.run(out_boxes) self.assertAllClose(out_boxes, expected_boxes) def testScaleBoxesToPixelCoordinatesWithKeypoints(self): """Tests box and keypoint scaling, checking scaled values.""" in_shape = [60, 40, 3] in_boxes = self.createTestBoxes() in_keypoints = self.createTestKeypoints() expected_boxes = [[0., 10., 45., 40.], [15., 20., 45., 40.]] expected_keypoints = [ [[6., 4.], [12., 8.], [18., 12.]], [[24., 16.], [30., 20.], [36., 24.]], ] in_image = tf.random_uniform(in_shape) _, out_boxes, out_keypoints = preprocessor.scale_boxes_to_pixel_coordinates( in_image, boxes=in_boxes, keypoints=in_keypoints) with self.test_session() as sess: out_boxes_, out_keypoints_ = sess.run([out_boxes, out_keypoints]) self.assertAllClose(out_boxes_, expected_boxes) self.assertAllClose(out_keypoints_, expected_keypoints) def testSubtractChannelMean(self): """Tests whether channel means have been subtracted.""" with self.test_session(): image = tf.zeros((240, 320, 3)) means = [1, 2, 3] actual = preprocessor.subtract_channel_mean(image, means=means) actual = actual.eval() self.assertTrue((actual[:, :, 0] == -1).all()) self.assertTrue((actual[:, :, 1] == -2).all()) self.assertTrue((actual[:, :, 2] == -3).all()) def testOneHotEncoding(self): """Tests one hot encoding of multiclass labels.""" with self.test_session(): labels = tf.constant([1, 4, 2], dtype=tf.int32) one_hot = preprocessor.one_hot_encoding(labels, num_classes=5) one_hot = one_hot.eval() self.assertAllEqual([0, 1, 1, 0, 1], one_hot) def testSSDRandomCropWithCache(self): preprocess_options = [ (preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 }), (preprocessor.ssd_random_crop, {})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=False, test_keypoints=False) def testSSDRandomCrop(self): preprocessing_options = [ (preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 }), (preprocessor.ssd_random_crop, {})] images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } distorted_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] images_rank = tf.rank(images) distorted_images_rank = tf.rank(distorted_images) boxes_rank = tf.rank(boxes) distorted_boxes_rank = tf.rank(distorted_boxes) with self.test_session() as sess: (boxes_rank_, distorted_boxes_rank_, images_rank_, distorted_images_rank_) = sess.run( [boxes_rank, distorted_boxes_rank, images_rank, distorted_images_rank]) self.assertAllEqual(boxes_rank_, distorted_boxes_rank_) self.assertAllEqual(images_rank_, distorted_images_rank_) def testSSDRandomCropWithMultiClassScores(self): preprocessing_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 }), (preprocessor.ssd_random_crop, {})] images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() multiclass_scores = self.createTestMultiClassScores() tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, fields.InputDataFields.multiclass_scores: multiclass_scores, } preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_multiclass_scores=True) distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] distorted_multiclass_scores = distorted_tensor_dict[ fields.InputDataFields.multiclass_scores] images_rank = tf.rank(images) distorted_images_rank = tf.rank(distorted_images) boxes_rank = tf.rank(boxes) distorted_boxes_rank = tf.rank(distorted_boxes) multiclass_scores_rank = tf.rank(multiclass_scores) distorted_multiclass_scores_rank = tf.rank(distorted_multiclass_scores) with self.test_session() as sess: (boxes_rank_, distorted_boxes_, distorted_boxes_rank_, images_rank_, distorted_images_rank_, multiclass_scores_rank_, distorted_multiclass_scores_, distorted_multiclass_scores_rank_) = sess.run([ boxes_rank, distorted_boxes, distorted_boxes_rank, images_rank, distorted_images_rank, multiclass_scores_rank, distorted_multiclass_scores, distorted_multiclass_scores_rank ]) self.assertAllEqual(boxes_rank_, distorted_boxes_rank_) self.assertAllEqual(images_rank_, distorted_images_rank_) self.assertAllEqual(multiclass_scores_rank_, distorted_multiclass_scores_rank_) self.assertAllEqual(distorted_boxes_.shape[0], distorted_multiclass_scores_.shape[0]) def testSSDRandomCropPad(self): images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() preprocessing_options = [ (preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 }), (preprocessor.ssd_random_crop_pad, {})] tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } distorted_tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] images_rank = tf.rank(images) distorted_images_rank = tf.rank(distorted_images) boxes_rank = tf.rank(boxes) distorted_boxes_rank = tf.rank(distorted_boxes) with self.test_session() as sess: (boxes_rank_, distorted_boxes_rank_, images_rank_, distorted_images_rank_) = sess.run([ boxes_rank, distorted_boxes_rank, images_rank, distorted_images_rank ]) self.assertAllEqual(boxes_rank_, distorted_boxes_rank_) self.assertAllEqual(images_rank_, distorted_images_rank_) def testSSDRandomCropFixedAspectRatioWithCache(self): preprocess_options = [ (preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 }), (preprocessor.ssd_random_crop_fixed_aspect_ratio, {})] self._testPreprocessorCache(preprocess_options, test_boxes=True, test_masks=False, test_keypoints=False) def _testSSDRandomCropFixedAspectRatio(self, include_label_scores, include_multiclass_scores, include_instance_masks, include_keypoints): images = self.createTestImages() boxes = self.createTestBoxes() labels = self.createTestLabels() preprocessing_options = [(preprocessor.normalize_image, { 'original_minval': 0, 'original_maxval': 255, 'target_minval': 0, 'target_maxval': 1 }), (preprocessor.ssd_random_crop_fixed_aspect_ratio, {})] tensor_dict = { fields.InputDataFields.image: images, fields.InputDataFields.groundtruth_boxes: boxes, fields.InputDataFields.groundtruth_classes: labels, } if include_label_scores: label_scores = self.createTestLabelScores() tensor_dict[fields.InputDataFields.groundtruth_label_scores] = ( label_scores) if include_multiclass_scores: multiclass_scores = self.createTestMultiClassScores() tensor_dict[fields.InputDataFields.multiclass_scores] = ( multiclass_scores) if include_instance_masks: masks = self.createTestMasks() tensor_dict[fields.InputDataFields.groundtruth_instance_masks] = masks if include_keypoints: keypoints = self.createTestKeypoints() tensor_dict[fields.InputDataFields.groundtruth_keypoints] = keypoints preprocessor_arg_map = preprocessor.get_default_func_arg_map( include_label_scores=include_label_scores, include_multiclass_scores=include_multiclass_scores, include_instance_masks=include_instance_masks, include_keypoints=include_keypoints) distorted_tensor_dict = preprocessor.preprocess( tensor_dict, preprocessing_options, func_arg_map=preprocessor_arg_map) distorted_images = distorted_tensor_dict[fields.InputDataFields.image] distorted_boxes = distorted_tensor_dict[ fields.InputDataFields.groundtruth_boxes] images_rank = tf.rank(images) distorted_images_rank = tf.rank(distorted_images) boxes_rank = tf.rank(boxes) distorted_boxes_rank = tf.rank(distorted_boxes) with self.test_session() as sess: (boxes_rank_, distorted_boxes_rank_, images_rank_, distorted_images_rank_) = sess.run( [boxes_rank, distorted_boxes_rank, images_rank, distorted_images_rank]) self.assertAllEqual(boxes_rank_, distorted_boxes_rank_) self.assertAllEqual(images_rank_, distorted_images_rank_) def testSSDRandomCropFixedAspectRatio(self): self._testSSDRandomCropFixedAspectRatio(include_label_scores=False, include_multiclass_scores=False, include_instance_masks=False, include_keypoints=False) def testSSDRandomCropFixedAspectRatioWithMultiClassScores(self): self._testSSDRandomCropFixedAspectRatio(include_label_scores=False, include_multiclass_scores=True, include_instance_masks=False, include_keypoints=False) def testSSDRandomCropFixedAspectRatioWithMasksAndKeypoints(self): self._testSSDRandomCropFixedAspectRatio(include_label_scores=False, include_multiclass_scores=False, include_instance_masks=True, include_keypoints=True) def testSSDRandomCropFixedAspectRatioWithLabelScoresMasksAndKeypoints(self): self._testSSDRandomCropFixedAspectRatio(include_label_scores=True, include_multiclass_scores=False, include_instance_masks=True, include_keypoints=True) def testConvertClassLogitsToSoftmax(self): multiclass_scores = tf.constant( [[1.0, 0.0], [0.5, 0.5], [1000, 1]], dtype=tf.float32) temperature = 2.0 converted_multiclass_scores = ( preprocessor.convert_class_logits_to_softmax( multiclass_scores=multiclass_scores, temperature=temperature)) expected_converted_multiclass_scores = [[[0.62245935, 0.37754068], [0.5, 0.5], [1, 0]]] with self.test_session() as sess: (converted_multiclass_scores_) = sess.run([converted_multiclass_scores]) self.assertAllClose(converted_multiclass_scores_, expected_converted_multiclass_scores) if __name__ == '__main__': tf.test.main()
[ "tensorflow.shape", "tensorflow.split", "tensorflow.multiply", "numpy.array", "object_detection.tensorflow_detect.core.preprocessor.resize_image", "object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map", "object_detection.tensorflow_detect.core.preprocessor.scale_boxes_to_pixel_coordinates", "object_detection.tensorflow_detect.core.preprocessor.subtract_channel_mean", "object_detection.tensorflow_detect.core.preprocessor._rot90_masks", "tensorflow.squared_difference", "tensorflow.placeholder", "tensorflow.rank", "tensorflow.concat", "object_detection.tensorflow_detect.core.preprocessor._strict_random_crop_image", "tensorflow.zeros_like", "object_detection.tensorflow_detect.core.preprocessor._flip_masks_up_down", "object_detection.tensorflow_detect.core.preprocessor._flip_boxes_left_right", "object_detection.tensorflow_detect.core.preprocessor.convert_class_logits_to_softmax", "tensorflow.zeros", "tensorflow.image.rgb_to_grayscale", "object_detection.tensorflow_detect.core.preprocessor.resize_to_min_dimension", "object_detection.tensorflow_detect.core.preprocessor.one_hot_encoding", "object_detection.tensorflow_detect.core.preprocessor._rot90_boxes", "object_detection.tensorflow_detect.core.preprocessor.resize_to_range", "tensorflow.expand_dims", "object_detection.tensorflow_detect.core.preprocessor_cache.PreprocessorCache", "numpy.random.randn", "object_detection.tensorflow_detect.core.preprocessor._flip_boxes_up_down", "object_detection.tensorflow_detect.core.preprocessor.retain_boxes_above_threshold", "tensorflow.fill", "tensorflow.to_float", "object_detection.tensorflow_detect.core.preprocessor._rgb_to_grayscale", "tensorflow.test.main", "object_detection.tensorflow_detect.core.preprocessor._flip_masks_left_right", "tensorflow.random_uniform", "tensorflow.constant", "tensorflow.less_equal", "unittest.mock.patch.object", "object_detection.tensorflow_detect.core.preprocessor.preprocess", "numpy.all", "tensorflow.greater_equal" ]
[((125987, 126001), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (125999, 126001), True, 'import tensorflow as tf\n'), ((1360, 1391), 'tensorflow.concat', 'tf.concat', (['[ch255, ch0, ch0]', '(3)'], {}), '([ch255, ch0, ch0], 3)\n', (1369, 1391), True, 'import tensorflow as tf\n'), ((1402, 1435), 'tensorflow.concat', 'tf.concat', (['[ch255, ch255, ch0]', '(3)'], {}), '([ch255, ch255, ch0], 3)\n', (1411, 1435), True, 'import tensorflow as tf\n'), ((1446, 1479), 'tensorflow.concat', 'tf.concat', (['[ch255, ch0, ch255]', '(3)'], {}), '([ch255, ch0, ch255], 3)\n', (1455, 1479), True, 'import tensorflow as tf\n'), ((1490, 1525), 'tensorflow.concat', 'tf.concat', (['[ch128, ch128, ch128]', '(3)'], {}), '([ch128, ch128, ch128], 3)\n', (1499, 1525), True, 'import tensorflow as tf\n'), ((1536, 1560), 'tensorflow.concat', 'tf.concat', (['[imr, img]', '(2)'], {}), '([imr, img], 2)\n', (1545, 1560), True, 'import tensorflow as tf\n'), ((1571, 1595), 'tensorflow.concat', 'tf.concat', (['[imb, imw]', '(2)'], {}), '([imb, imw], 2)\n', (1580, 1595), True, 'import tensorflow as tf\n'), ((1605, 1629), 'tensorflow.concat', 'tf.concat', (['[imu, imd]', '(1)'], {}), '([imu, imd], 1)\n', (1614, 1629), True, 'import tensorflow as tf\n'), ((1690, 1808), 'tensorflow.constant', 'tf.constant', (['[[[128, 128, 128, 128], [0, 0, 128, 128], [0, 128, 128, 128], [192, 192, \n 128, 128]]]'], {'dtype': 'tf.uint8'}), '([[[128, 128, 128, 128], [0, 0, 128, 128], [0, 128, 128, 128], [\n 192, 192, 128, 128]]], dtype=tf.uint8)\n', (1701, 1808), True, 'import tensorflow as tf\n'), ((1875, 1902), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_r', '(3)'], {}), '(images_r, 3)\n', (1889, 1902), True, 'import tensorflow as tf\n'), ((1918, 2031), 'tensorflow.constant', 'tf.constant', (['[[[0, 0, 128, 128], [0, 0, 128, 128], [0, 128, 192, 192], [192, 192, 128, 192]]\n ]'], {'dtype': 'tf.uint8'}), '([[[0, 0, 128, 128], [0, 0, 128, 128], [0, 128, 192, 192], [192,\n 192, 128, 192]]], dtype=tf.uint8)\n', (1929, 2031), True, 'import tensorflow as tf\n'), ((2099, 2126), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_g', '(3)'], {}), '(images_g, 3)\n', (2113, 2126), True, 'import tensorflow as tf\n'), ((2142, 2255), 'tensorflow.constant', 'tf.constant', (['[[[128, 128, 192, 0], [0, 0, 128, 192], [0, 128, 128, 0], [192, 192, 192, 128]]\n ]'], {'dtype': 'tf.uint8'}), '([[[128, 128, 192, 0], [0, 0, 128, 192], [0, 128, 128, 0], [192,\n 192, 192, 128]]], dtype=tf.uint8)\n', (2153, 2255), True, 'import tensorflow as tf\n'), ((2323, 2350), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_b', '(3)'], {}), '(images_b, 3)\n', (2337, 2350), True, 'import tensorflow as tf\n'), ((2364, 2408), 'tensorflow.concat', 'tf.concat', (['[images_r, images_g, images_b]', '(3)'], {}), '([images_r, images_g, images_b], 3)\n', (2373, 2408), True, 'import tensorflow as tf\n'), ((2474, 2509), 'tensorflow.constant', 'tf.constant', (['[[]]'], {'dtype': 'tf.float32'}), '([[]], dtype=tf.float32)\n', (2485, 2509), True, 'import tensorflow as tf\n'), ((2569, 2648), 'tensorflow.constant', 'tf.constant', (['[[0.0, 0.25, 0.75, 1.0], [0.25, 0.5, 0.75, 1.0]]'], {'dtype': 'tf.float32'}), '([[0.0, 0.25, 0.75, 1.0], [0.25, 0.5, 0.75, 1.0]], dtype=tf.float32)\n', (2580, 2648), True, 'import tensorflow as tf\n'), ((2722, 2763), 'tensorflow.constant', 'tf.constant', (['[1.0, 0.5]'], {'dtype': 'tf.float32'}), '([1.0, 0.5], dtype=tf.float32)\n', (2733, 2763), True, 'import tensorflow as tf\n'), ((2827, 2871), 'tensorflow.constant', 'tf.constant', (['[0.5, np.nan]'], {'dtype': 'tf.float32'}), '([0.5, np.nan], dtype=tf.float32)\n', (2838, 2871), True, 'import tensorflow as tf\n'), ((2913, 3052), 'numpy.array', 'np.array', (['[[[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]], [[255.0, 255.0,\n 0.0], [255.0, 255.0, 0.0], [255.0, 255.0, 0.0]]]'], {}), '([[[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]], [[\n 255.0, 255.0, 0.0], [255.0, 255.0, 0.0], [255.0, 255.0, 0.0]]])\n', (2921, 3052), True, 'import numpy as np\n'), ((3112, 3147), 'tensorflow.constant', 'tf.constant', (['mask'], {'dtype': 'tf.float32'}), '(mask, dtype=tf.float32)\n', (3123, 3147), True, 'import tensorflow as tf\n'), ((3198, 3289), 'numpy.array', 'np.array', (['[[[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], [[0.4, 0.4], [0.5, 0.5], [0.6, 0.6]]]'], {}), '([[[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], [[0.4, 0.4], [0.5, 0.5], [\n 0.6, 0.6]]])\n', (3206, 3289), True, 'import numpy as np\n'), ((3319, 3359), 'tensorflow.constant', 'tf.constant', (['keypoints'], {'dtype': 'tf.float32'}), '(keypoints, dtype=tf.float32)\n', (3330, 3359), True, 'import tensorflow as tf\n'), ((3420, 3511), 'numpy.array', 'np.array', (['[[[0.4, 0.4], [0.5, 0.5], [0.6, 0.6]], [[0.4, 0.4], [0.5, 0.5], [0.6, 0.6]]]'], {}), '([[[0.4, 0.4], [0.5, 0.5], [0.6, 0.6]], [[0.4, 0.4], [0.5, 0.5], [\n 0.6, 0.6]]])\n', (3428, 3511), True, 'import numpy as np\n'), ((3541, 3581), 'tensorflow.constant', 'tf.constant', (['keypoints'], {'dtype': 'tf.float32'}), '(keypoints, dtype=tf.float32)\n', (3552, 3581), True, 'import tensorflow as tf\n'), ((3643, 3734), 'numpy.array', 'np.array', (['[[[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]]]'], {}), '([[[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], [[0.1, 0.1], [0.2, 0.2], [\n 0.3, 0.3]]])\n', (3651, 3734), True, 'import numpy as np\n'), ((3764, 3804), 'tensorflow.constant', 'tf.constant', (['keypoints'], {'dtype': 'tf.float32'}), '(keypoints, dtype=tf.float32)\n', (3775, 3804), True, 'import tensorflow as tf\n'), ((3860, 3895), 'numpy.array', 'np.array', (['[0, 2, 1]'], {'dtype': 'np.int32'}), '([0, 2, 1], dtype=np.int32)\n', (3868, 3895), True, 'import numpy as np\n'), ((3940, 3975), 'tensorflow.constant', 'tf.constant', (['[1, 2]'], {'dtype': 'tf.int32'}), '([1, 2], dtype=tf.int32)\n', (3951, 3975), True, 'import tensorflow as tf\n'), ((4046, 4124), 'tensorflow.constant', 'tf.constant', (['[[-0.1, 0.25, 0.75, 1], [0.25, 0.5, 0.75, 1.1]]'], {'dtype': 'tf.float32'}), '([[-0.1, 0.25, 0.75, 1], [0.25, 0.5, 0.75, 1.1]], dtype=tf.float32)\n', (4057, 4124), True, 'import tensorflow as tf\n'), ((4203, 4258), 'tensorflow.constant', 'tf.constant', (['[[1.0, 0.0], [0.5, 0.5]]'], {'dtype': 'tf.float32'}), '([[1.0, 0.0], [0.5, 0.5]], dtype=tf.float32)\n', (4214, 4258), True, 'import tensorflow as tf\n'), ((4321, 4422), 'tensorflow.constant', 'tf.constant', (['[[[0, 0, 0, 0], [-1, -1, 0, 0], [-1, 0, 0, 0], [0.5, 0.5, 0, 0]]]'], {'dtype': 'tf.float32'}), '([[[0, 0, 0, 0], [-1, -1, 0, 0], [-1, 0, 0, 0], [0.5, 0.5, 0, 0]\n ]], dtype=tf.float32)\n', (4332, 4422), True, 'import tensorflow as tf\n'), ((4489, 4516), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_r', '(3)'], {}), '(images_r, 3)\n', (4503, 4516), True, 'import tensorflow as tf\n'), ((4532, 4640), 'tensorflow.constant', 'tf.constant', (['[[[-1, -1, 0, 0], [-1, -1, 0, 0], [-1, 0, 0.5, 0.5], [0.5, 0.5, 0, 0.5]]]'], {'dtype': 'tf.float32'}), '([[[-1, -1, 0, 0], [-1, -1, 0, 0], [-1, 0, 0.5, 0.5], [0.5, 0.5,\n 0, 0.5]]], dtype=tf.float32)\n', (4543, 4640), True, 'import tensorflow as tf\n'), ((4708, 4735), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_g', '(3)'], {}), '(images_g, 3)\n', (4722, 4735), True, 'import tensorflow as tf\n'), ((4751, 4859), 'tensorflow.constant', 'tf.constant', (['[[[0, 0, 0.5, -1], [-1, -1, 0, 0.5], [-1, 0, 0, -1], [0.5, 0.5, 0.5, 0]]]'], {'dtype': 'tf.float32'}), '([[[0, 0, 0.5, -1], [-1, -1, 0, 0.5], [-1, 0, 0, -1], [0.5, 0.5,\n 0.5, 0]]], dtype=tf.float32)\n', (4762, 4859), True, 'import tensorflow as tf\n'), ((4927, 4954), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_b', '(3)'], {}), '(images_b, 3)\n', (4941, 4954), True, 'import tensorflow as tf\n'), ((4968, 5012), 'tensorflow.concat', 'tf.concat', (['[images_r, images_g, images_b]', '(3)'], {}), '([images_r, images_g, images_b], 3)\n', (4977, 5012), True, 'import tensorflow as tf\n'), ((5092, 5220), 'tensorflow.constant', 'tf.constant', (['[[[0.1, 0.1, 0.1, 0.1], [-0.9, -0.9, 0.1, 0.1], [-0.9, 0.1, 0.1, 0.1], [0.6,\n 0.6, 0.1, 0.1]]]'], {'dtype': 'tf.float32'}), '([[[0.1, 0.1, 0.1, 0.1], [-0.9, -0.9, 0.1, 0.1], [-0.9, 0.1, 0.1,\n 0.1], [0.6, 0.6, 0.1, 0.1]]], dtype=tf.float32)\n', (5103, 5220), True, 'import tensorflow as tf\n'), ((5288, 5315), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_r', '(3)'], {}), '(images_r, 3)\n', (5302, 5315), True, 'import tensorflow as tf\n'), ((5331, 5462), 'tensorflow.constant', 'tf.constant', (['[[[-0.9, -0.9, 0.1, 0.1], [-0.9, -0.9, 0.1, 0.1], [-0.9, 0.1, 0.6, 0.6], [\n 0.6, 0.6, 0.1, 0.6]]]'], {'dtype': 'tf.float32'}), '([[[-0.9, -0.9, 0.1, 0.1], [-0.9, -0.9, 0.1, 0.1], [-0.9, 0.1, \n 0.6, 0.6], [0.6, 0.6, 0.1, 0.6]]], dtype=tf.float32)\n', (5342, 5462), True, 'import tensorflow as tf\n'), ((5529, 5556), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_g', '(3)'], {}), '(images_g, 3)\n', (5543, 5556), True, 'import tensorflow as tf\n'), ((5572, 5703), 'tensorflow.constant', 'tf.constant', (['[[[0.1, 0.1, 0.6, -0.9], [-0.9, -0.9, 0.1, 0.6], [-0.9, 0.1, 0.1, -0.9], [\n 0.6, 0.6, 0.6, 0.1]]]'], {'dtype': 'tf.float32'}), '([[[0.1, 0.1, 0.6, -0.9], [-0.9, -0.9, 0.1, 0.6], [-0.9, 0.1, \n 0.1, -0.9], [0.6, 0.6, 0.6, 0.1]]], dtype=tf.float32)\n', (5583, 5703), True, 'import tensorflow as tf\n'), ((5770, 5797), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_b', '(3)'], {}), '(images_b, 3)\n', (5784, 5797), True, 'import tensorflow as tf\n'), ((5811, 5855), 'tensorflow.concat', 'tf.concat', (['[images_r, images_g, images_b]', '(3)'], {}), '([images_r, images_g, images_b], 3)\n', (5820, 5855), True, 'import tensorflow as tf\n'), ((5935, 6069), 'tensorflow.constant', 'tf.constant', (['[[[-0.1, -0.1, -0.1, -0.1], [-1, -1, -0.1, -0.1], [-1, -0.1, -0.1, -0.1], [\n 0.4, 0.4, -0.1, -0.1]]]'], {'dtype': 'tf.float32'}), '([[[-0.1, -0.1, -0.1, -0.1], [-1, -1, -0.1, -0.1], [-1, -0.1, -\n 0.1, -0.1], [0.4, 0.4, -0.1, -0.1]]], dtype=tf.float32)\n', (5946, 6069), True, 'import tensorflow as tf\n'), ((6136, 6163), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_r', '(3)'], {}), '(images_r, 3)\n', (6150, 6163), True, 'import tensorflow as tf\n'), ((6179, 6306), 'tensorflow.constant', 'tf.constant', (['[[[-1, -1, -0.1, -0.1], [-1, -1, -0.1, -0.1], [-1, -0.1, 0.4, 0.4], [0.4, \n 0.4, -0.1, 0.4]]]'], {'dtype': 'tf.float32'}), '([[[-1, -1, -0.1, -0.1], [-1, -1, -0.1, -0.1], [-1, -0.1, 0.4, \n 0.4], [0.4, 0.4, -0.1, 0.4]]], dtype=tf.float32)\n', (6190, 6306), True, 'import tensorflow as tf\n'), ((6373, 6400), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_g', '(3)'], {}), '(images_g, 3)\n', (6387, 6400), True, 'import tensorflow as tf\n'), ((6416, 6543), 'tensorflow.constant', 'tf.constant', (['[[[-0.1, -0.1, 0.4, -1], [-1, -1, -0.1, 0.4], [-1, -0.1, -0.1, -1], [0.4, \n 0.4, 0.4, -0.1]]]'], {'dtype': 'tf.float32'}), '([[[-0.1, -0.1, 0.4, -1], [-1, -1, -0.1, 0.4], [-1, -0.1, -0.1, \n -1], [0.4, 0.4, 0.4, -0.1]]], dtype=tf.float32)\n', (6427, 6543), True, 'import tensorflow as tf\n'), ((6610, 6637), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_b', '(3)'], {}), '(images_b, 3)\n', (6624, 6637), True, 'import tensorflow as tf\n'), ((6651, 6695), 'tensorflow.concat', 'tf.concat', (['[images_r, images_g, images_b]', '(3)'], {}), '([images_r, images_g, images_b], 3)\n', (6660, 6695), True, 'import tensorflow as tf\n'), ((6776, 6877), 'tensorflow.constant', 'tf.constant', (['[[[0, 0, 0, 0], [0, 0, -1, -1], [0, 0, 0, -1], [0, 0, 0.5, 0.5]]]'], {'dtype': 'tf.float32'}), '([[[0, 0, 0, 0], [0, 0, -1, -1], [0, 0, 0, -1], [0, 0, 0.5, 0.5]\n ]], dtype=tf.float32)\n', (6787, 6877), True, 'import tensorflow as tf\n'), ((6944, 6971), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_r', '(3)'], {}), '(images_r, 3)\n', (6958, 6971), True, 'import tensorflow as tf\n'), ((6987, 7096), 'tensorflow.constant', 'tf.constant', (['[[[0, 0, -1, -1], [0, 0, -1, -1], [0.5, 0.5, 0, -1], [0.5, 0, 0.5, 0.5]]]'], {'dtype': 'tf.float32'}), '([[[0, 0, -1, -1], [0, 0, -1, -1], [0.5, 0.5, 0, -1], [0.5, 0, \n 0.5, 0.5]]], dtype=tf.float32)\n', (6998, 7096), True, 'import tensorflow as tf\n'), ((7163, 7190), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_g', '(3)'], {}), '(images_g, 3)\n', (7177, 7190), True, 'import tensorflow as tf\n'), ((7206, 7315), 'tensorflow.constant', 'tf.constant', (['[[[-1, 0.5, 0, 0], [0.5, 0, -1, -1], [-1, 0, 0, -1], [0, 0.5, 0.5, 0.5]]]'], {'dtype': 'tf.float32'}), '([[[-1, 0.5, 0, 0], [0.5, 0, -1, -1], [-1, 0, 0, -1], [0, 0.5, \n 0.5, 0.5]]], dtype=tf.float32)\n', (7217, 7315), True, 'import tensorflow as tf\n'), ((7382, 7409), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_b', '(3)'], {}), '(images_b, 3)\n', (7396, 7409), True, 'import tensorflow as tf\n'), ((7423, 7467), 'tensorflow.concat', 'tf.concat', (['[images_r, images_g, images_b]', '(3)'], {}), '([images_r, images_g, images_b], 3)\n', (7432, 7467), True, 'import tensorflow as tf\n'), ((7545, 7646), 'tensorflow.constant', 'tf.constant', (['[[[0.5, 0.5, 0, 0], [-1, 0, 0, 0], [-1, -1, 0, 0], [0, 0, 0, 0]]]'], {'dtype': 'tf.float32'}), '([[[0.5, 0.5, 0, 0], [-1, 0, 0, 0], [-1, -1, 0, 0], [0, 0, 0, 0]\n ]], dtype=tf.float32)\n', (7556, 7646), True, 'import tensorflow as tf\n'), ((7713, 7740), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_r', '(3)'], {}), '(images_r, 3)\n', (7727, 7740), True, 'import tensorflow as tf\n'), ((7756, 7865), 'tensorflow.constant', 'tf.constant', (['[[[0.5, 0.5, 0, 0.5], [-1, 0, 0.5, 0.5], [-1, -1, 0, 0], [-1, -1, 0, 0]]]'], {'dtype': 'tf.float32'}), '([[[0.5, 0.5, 0, 0.5], [-1, 0, 0.5, 0.5], [-1, -1, 0, 0], [-1, -\n 1, 0, 0]]], dtype=tf.float32)\n', (7767, 7865), True, 'import tensorflow as tf\n'), ((7932, 7959), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_g', '(3)'], {}), '(images_g, 3)\n', (7946, 7959), True, 'import tensorflow as tf\n'), ((7975, 8084), 'tensorflow.constant', 'tf.constant', (['[[[0.5, 0.5, 0.5, 0], [-1, 0, 0, -1], [-1, -1, 0, 0.5], [0, 0, 0.5, -1]]]'], {'dtype': 'tf.float32'}), '([[[0.5, 0.5, 0.5, 0], [-1, 0, 0, -1], [-1, -1, 0, 0.5], [0, 0, \n 0.5, -1]]], dtype=tf.float32)\n', (7986, 8084), True, 'import tensorflow as tf\n'), ((8151, 8178), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_b', '(3)'], {}), '(images_b, 3)\n', (8165, 8178), True, 'import tensorflow as tf\n'), ((8192, 8236), 'tensorflow.concat', 'tf.concat', (['[images_r, images_g, images_b]', '(3)'], {}), '([images_r, images_g, images_b], 3)\n', (8201, 8236), True, 'import tensorflow as tf\n'), ((8309, 8410), 'tensorflow.constant', 'tf.constant', (['[[[0, 0, 0, 0], [0, 0, 0, 0], [0, -1, 0, 0.5], [0, -1, -1, 0.5]]]'], {'dtype': 'tf.float32'}), '([[[0, 0, 0, 0], [0, 0, 0, 0], [0, -1, 0, 0.5], [0, -1, -1, 0.5]\n ]], dtype=tf.float32)\n', (8320, 8410), True, 'import tensorflow as tf\n'), ((8477, 8504), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_r', '(3)'], {}), '(images_r, 3)\n', (8491, 8504), True, 'import tensorflow as tf\n'), ((8520, 8629), 'tensorflow.constant', 'tf.constant', (['[[[0, 0, 0.5, 0.5], [0, 0, 0.5, 0], [-1, -1, 0, 0.5], [-1, -1, -1, 0.5]]]'], {'dtype': 'tf.float32'}), '([[[0, 0, 0.5, 0.5], [0, 0, 0.5, 0], [-1, -1, 0, 0.5], [-1, -1, \n -1, 0.5]]], dtype=tf.float32)\n', (8531, 8629), True, 'import tensorflow as tf\n'), ((8696, 8723), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_g', '(3)'], {}), '(images_g, 3)\n', (8710, 8723), True, 'import tensorflow as tf\n'), ((8739, 8848), 'tensorflow.constant', 'tf.constant', (['[[[-1, 0.5, -1, 0], [0.5, 0, 0, 0.5], [0, -1, 0, 0.5], [0, -1, -1, 0.5]]]'], {'dtype': 'tf.float32'}), '([[[-1, 0.5, -1, 0], [0.5, 0, 0, 0.5], [0, -1, 0, 0.5], [0, -1, \n -1, 0.5]]], dtype=tf.float32)\n', (8750, 8848), True, 'import tensorflow as tf\n'), ((8915, 8942), 'tensorflow.expand_dims', 'tf.expand_dims', (['images_b', '(3)'], {}), '(images_b, 3)\n', (8929, 8942), True, 'import tensorflow as tf\n'), ((8956, 9000), 'tensorflow.concat', 'tf.concat', (['[images_r, images_g, images_b]', '(3)'], {}), '([images_r, images_g, images_b], 3)\n', (8965, 9000), True, 'import tensorflow as tf\n'), ((9077, 9156), 'tensorflow.constant', 'tf.constant', (['[[0.0, 0.0, 0.75, 0.75], [0.25, 0.0, 0.75, 0.5]]'], {'dtype': 'tf.float32'}), '([[0.0, 0.0, 0.75, 0.75], [0.25, 0.0, 0.75, 0.5]], dtype=tf.float32)\n', (9088, 9156), True, 'import tensorflow as tf\n'), ((9253, 9332), 'tensorflow.constant', 'tf.constant', (['[[0.25, 0.25, 1.0, 1.0], [0.25, 0.5, 0.75, 1.0]]'], {'dtype': 'tf.float32'}), '([[0.25, 0.25, 1.0, 1.0], [0.25, 0.5, 0.75, 1.0]], dtype=tf.float32)\n', (9264, 9332), True, 'import tensorflow as tf\n'), ((9424, 9503), 'tensorflow.constant', 'tf.constant', (['[[0.0, 0.0, 0.75, 0.75], [0.0, 0.25, 0.5, 0.75]]'], {'dtype': 'tf.float32'}), '([[0.0, 0.0, 0.75, 0.75], [0.0, 0.25, 0.5, 0.75]], dtype=tf.float32)\n', (9435, 9503), True, 'import tensorflow as tf\n'), ((9587, 9725), 'numpy.array', 'np.array', (['[[[0.0, 0.0, 255.0], [0.0, 0.0, 255.0], [0.0, 0.0, 255.0]], [[0.0, 255.0, \n 255.0], [0.0, 255.0, 255.0], [0.0, 255.0, 255.0]]]'], {}), '([[[0.0, 0.0, 255.0], [0.0, 0.0, 255.0], [0.0, 0.0, 255.0]], [[0.0,\n 255.0, 255.0], [0.0, 255.0, 255.0], [0.0, 255.0, 255.0]]])\n', (9595, 9725), True, 'import numpy as np\n'), ((9786, 9821), 'tensorflow.constant', 'tf.constant', (['mask'], {'dtype': 'tf.float32'}), '(mask, dtype=tf.float32)\n', (9797, 9821), True, 'import tensorflow as tf\n'), ((9876, 10015), 'numpy.array', 'np.array', (['[[[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]], [[255.0, 255.0,\n 0.0], [255.0, 255.0, 0.0], [255.0, 255.0, 0.0]]]'], {}), '([[[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]], [[\n 255.0, 255.0, 0.0], [255.0, 255.0, 0.0], [255.0, 255.0, 0.0]]])\n', (9884, 10015), True, 'import numpy as np\n'), ((10075, 10110), 'tensorflow.constant', 'tf.constant', (['mask'], {'dtype': 'tf.float32'}), '(mask, dtype=tf.float32)\n', (10086, 10110), True, 'import tensorflow as tf\n'), ((10160, 10298), 'numpy.array', 'np.array', (['[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [255.0, 255.0, 255.0]], [[0.0, 0.0, 0.0\n ], [255.0, 255.0, 255.0], [255.0, 255.0, 255.0]]]'], {}), '([[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [255.0, 255.0, 255.0]], [[0.0,\n 0.0, 0.0], [255.0, 255.0, 255.0], [255.0, 255.0, 255.0]]])\n', (10168, 10298), True, 'import numpy as np\n'), ((10359, 10394), 'tensorflow.constant', 'tf.constant', (['mask'], {'dtype': 'tf.float32'}), '(mask, dtype=tf.float32)\n', (10370, 10394), True, 'import tensorflow as tf\n'), ((10457, 10493), 'tensorflow.constant', 'tf.constant', (['[1.0]'], {'dtype': 'tf.float32'}), '([1.0], dtype=tf.float32)\n', (10468, 10493), True, 'import tensorflow as tf\n'), ((10550, 10605), 'tensorflow.constant', 'tf.constant', (['[[0.0, 0.25, 0.75, 1.0]]'], {'dtype': 'tf.float32'}), '([[0.0, 0.25, 0.75, 1.0]], dtype=tf.float32)\n', (10561, 10605), True, 'import tensorflow as tf\n'), ((10663, 10697), 'tensorflow.constant', 'tf.constant', (['[1]'], {'dtype': 'tf.float32'}), '([1], dtype=tf.float32)\n', (10674, 10697), True, 'import tensorflow as tf\n'), ((10765, 10808), 'tensorflow.constant', 'tf.constant', (['[[1.0, 0.0]]'], {'dtype': 'tf.float32'}), '([[1.0, 0.0]], dtype=tf.float32)\n', (10776, 10808), True, 'import tensorflow as tf\n'), ((10865, 10934), 'numpy.array', 'np.array', (['[[[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]]]'], {}), '([[[255.0, 0.0, 0.0], [255.0, 0.0, 0.0], [255.0, 0.0, 0.0]]])\n', (10873, 10934), True, 'import numpy as np\n'), ((10973, 11008), 'tensorflow.constant', 'tf.constant', (['mask'], {'dtype': 'tf.float32'}), '(mask, dtype=tf.float32)\n', (10984, 11008), True, 'import tensorflow as tf\n'), ((11074, 11122), 'numpy.array', 'np.array', (['[[[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]]]'], {}), '([[[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]]])\n', (11082, 11122), True, 'import numpy as np\n'), ((11148, 11188), 'tensorflow.constant', 'tf.constant', (['keypoints'], {'dtype': 'tf.float32'}), '(keypoints, dtype=tf.float32)\n', (11159, 11188), True, 'import tensorflow as tf\n'), ((11267, 11306), 'tensorflow.constant', 'tf.constant', (['[np.nan]'], {'dtype': 'tf.float32'}), '([np.nan], dtype=tf.float32)\n', (11278, 11306), True, 'import tensorflow as tf\n'), ((11379, 11432), 'tensorflow.constant', 'tf.constant', (['[[0.25, 0.5, 0.75, 1]]'], {'dtype': 'tf.float32'}), '([[0.25, 0.5, 0.75, 1]], dtype=tf.float32)\n', (11390, 11432), True, 'import tensorflow as tf\n'), ((11506, 11540), 'tensorflow.constant', 'tf.constant', (['[2]'], {'dtype': 'tf.float32'}), '([2], dtype=tf.float32)\n', (11517, 11540), True, 'import tensorflow as tf\n'), ((11634, 11672), 'object_detection.tensorflow_detect.core.preprocessor._rgb_to_grayscale', 'preprocessor._rgb_to_grayscale', (['images'], {}), '(images)\n', (11664, 11672), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((11695, 11728), 'tensorflow.image.rgb_to_grayscale', 'tf.image.rgb_to_grayscale', (['images'], {}), '(images)\n', (11720, 11728), True, 'import tensorflow as tf\n'), ((12259, 12315), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (12282, 12315), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((13088, 13177), 'object_detection.tensorflow_detect.core.preprocessor.retain_boxes_above_threshold', 'preprocessor.retain_boxes_above_threshold', (['boxes', 'labels', 'label_scores'], {'threshold': '(0.6)'}), '(boxes, labels, label_scores,\n threshold=0.6)\n', (13129, 13177), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((14173, 14299), 'object_detection.tensorflow_detect.core.preprocessor.retain_boxes_above_threshold', 'preprocessor.retain_boxes_above_threshold', (['boxes', 'labels', 'label_scores'], {'multiclass_scores': 'multiclass_scores', 'threshold': '(0.6)'}), '(boxes, labels, label_scores,\n multiclass_scores=multiclass_scores, threshold=0.6)\n', (14214, 14299), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((14941, 15037), 'object_detection.tensorflow_detect.core.preprocessor.retain_boxes_above_threshold', 'preprocessor.retain_boxes_above_threshold', (['boxes', 'labels', 'label_scores', 'masks'], {'threshold': '(0.6)'}), '(boxes, labels, label_scores,\n masks, threshold=0.6)\n', (14982, 15037), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((15545, 15655), 'object_detection.tensorflow_detect.core.preprocessor.retain_boxes_above_threshold', 'preprocessor.retain_boxes_above_threshold', (['boxes', 'labels', 'label_scores'], {'keypoints': 'keypoints', 'threshold': '(0.6)'}), '(boxes, labels, label_scores,\n keypoints=keypoints, threshold=0.6)\n', (15586, 15655), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((16216, 16305), 'object_detection.tensorflow_detect.core.preprocessor.retain_boxes_above_threshold', 'preprocessor.retain_boxes_above_threshold', (['boxes', 'labels', 'label_scores'], {'threshold': '(0.6)'}), '(boxes, labels, label_scores,\n threshold=0.6)\n', (16257, 16305), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((17150, 17192), 'object_detection.tensorflow_detect.core.preprocessor._flip_boxes_left_right', 'preprocessor._flip_boxes_left_right', (['boxes'], {}), '(boxes)\n', (17185, 17192), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((17537, 17576), 'object_detection.tensorflow_detect.core.preprocessor._flip_boxes_up_down', 'preprocessor._flip_boxes_up_down', (['boxes'], {}), '(boxes)\n', (17569, 17576), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((17913, 17945), 'object_detection.tensorflow_detect.core.preprocessor._rot90_boxes', 'preprocessor._rot90_boxes', (['boxes'], {}), '(boxes)\n', (17938, 17945), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((18288, 18334), 'object_detection.tensorflow_detect.core.preprocessor._flip_masks_left_right', 'preprocessor._flip_masks_left_right', (['test_mask'], {}), '(test_mask)\n', (18323, 18334), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((18675, 18718), 'object_detection.tensorflow_detect.core.preprocessor._flip_masks_up_down', 'preprocessor._flip_masks_up_down', (['test_mask'], {}), '(test_mask)\n', (18707, 18718), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((19051, 19087), 'object_detection.tensorflow_detect.core.preprocessor._rot90_masks', 'preprocessor._rot90_masks', (['test_mask'], {}), '(test_mask)\n', (19076, 19087), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((19612, 19650), 'object_detection.tensorflow_detect.core.preprocessor_cache.PreprocessorCache', 'preprocessor_cache.PreprocessorCache', ([], {}), '()\n', (19648, 19650), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((19866, 19976), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_instance_masks': 'test_masks', 'include_keypoints': 'test_keypoints'}), '(include_instance_masks=test_masks,\n include_keypoints=test_keypoints)\n', (19903, 19976), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((21833, 21889), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (21856, 21889), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((22030, 22075), 'tensorflow.squared_difference', 'tf.squared_difference', (['boxes', 'boxes_expected1'], {}), '(boxes, boxes_expected1)\n', (22051, 22075), True, 'import tensorflow as tf\n'), ((22094, 22139), 'tensorflow.squared_difference', 'tf.squared_difference', (['boxes', 'boxes_expected2'], {}), '(boxes, boxes_expected2)\n', (22115, 22139), True, 'import tensorflow as tf\n'), ((22157, 22194), 'tensorflow.multiply', 'tf.multiply', (['boxes_diff1', 'boxes_diff2'], {}), '(boxes_diff1, boxes_diff2)\n', (22168, 22194), True, 'import tensorflow as tf\n'), ((22221, 22246), 'tensorflow.zeros_like', 'tf.zeros_like', (['boxes_diff'], {}), '(boxes_diff)\n', (22234, 22246), True, 'import tensorflow as tf\n'), ((22267, 22314), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected1'], {}), '(images, images_expected1)\n', (22288, 22314), True, 'import tensorflow as tf\n'), ((22334, 22381), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected2'], {}), '(images, images_expected2)\n', (22355, 22381), True, 'import tensorflow as tf\n'), ((22400, 22439), 'tensorflow.multiply', 'tf.multiply', (['images_diff1', 'images_diff2'], {}), '(images_diff1, images_diff2)\n', (22411, 22439), True, 'import tensorflow as tf\n'), ((22467, 22493), 'tensorflow.zeros_like', 'tf.zeros_like', (['images_diff'], {}), '(images_diff)\n', (22480, 22493), True, 'import tensorflow as tf\n'), ((23365, 23421), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (23388, 23421), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((23563, 23610), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected1'], {}), '(images, images_expected1)\n', (23584, 23610), True, 'import tensorflow as tf\n'), ((23630, 23677), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected2'], {}), '(images, images_expected2)\n', (23651, 23677), True, 'import tensorflow as tf\n'), ((23696, 23735), 'tensorflow.multiply', 'tf.multiply', (['images_diff1', 'images_diff2'], {}), '(images_diff1, images_diff2)\n', (23707, 23735), True, 'import tensorflow as tf\n'), ((23763, 23789), 'tensorflow.zeros_like', 'tf.zeros_like', (['images_diff'], {}), '(images_diff)\n', (23776, 23789), True, 'import tensorflow as tf\n'), ((24772, 24824), 'tensorflow.random_uniform', 'tf.random_uniform', (['[1, image_height, image_width, 3]'], {}), '([1, image_height, image_width, 3])\n', (24789, 24824), True, 'import tensorflow as tf\n'), ((25434, 25528), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_instance_masks': '(True)', 'include_keypoints': '(True)'}), '(include_instance_masks=True,\n include_keypoints=True)\n', (25471, 25528), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((25552, 25648), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocess_options, func_arg_map=\n preprocessor_arg_map)\n', (25575, 25648), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((26612, 26668), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (26635, 26668), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((26809, 26854), 'tensorflow.squared_difference', 'tf.squared_difference', (['boxes', 'boxes_expected1'], {}), '(boxes, boxes_expected1)\n', (26830, 26854), True, 'import tensorflow as tf\n'), ((26873, 26918), 'tensorflow.squared_difference', 'tf.squared_difference', (['boxes', 'boxes_expected2'], {}), '(boxes, boxes_expected2)\n', (26894, 26918), True, 'import tensorflow as tf\n'), ((26936, 26973), 'tensorflow.multiply', 'tf.multiply', (['boxes_diff1', 'boxes_diff2'], {}), '(boxes_diff1, boxes_diff2)\n', (26947, 26973), True, 'import tensorflow as tf\n'), ((27000, 27025), 'tensorflow.zeros_like', 'tf.zeros_like', (['boxes_diff'], {}), '(boxes_diff)\n', (27013, 27025), True, 'import tensorflow as tf\n'), ((27046, 27093), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected1'], {}), '(images, images_expected1)\n', (27067, 27093), True, 'import tensorflow as tf\n'), ((27113, 27160), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected2'], {}), '(images, images_expected2)\n', (27134, 27160), True, 'import tensorflow as tf\n'), ((27179, 27218), 'tensorflow.multiply', 'tf.multiply', (['images_diff1', 'images_diff2'], {}), '(images_diff1, images_diff2)\n', (27190, 27218), True, 'import tensorflow as tf\n'), ((27246, 27272), 'tensorflow.zeros_like', 'tf.zeros_like', (['images_diff'], {}), '(images_diff)\n', (27259, 27272), True, 'import tensorflow as tf\n'), ((28137, 28193), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (28160, 28193), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((28335, 28382), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected1'], {}), '(images, images_expected1)\n', (28356, 28382), True, 'import tensorflow as tf\n'), ((28402, 28449), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected2'], {}), '(images, images_expected2)\n', (28423, 28449), True, 'import tensorflow as tf\n'), ((28468, 28507), 'tensorflow.multiply', 'tf.multiply', (['images_diff1', 'images_diff2'], {}), '(images_diff1, images_diff2)\n', (28479, 28507), True, 'import tensorflow as tf\n'), ((28535, 28561), 'tensorflow.zeros_like', 'tf.zeros_like', (['images_diff'], {}), '(images_diff)\n', (28548, 28561), True, 'import tensorflow as tf\n'), ((29536, 29588), 'tensorflow.random_uniform', 'tf.random_uniform', (['[1, image_height, image_width, 3]'], {}), '([1, image_height, image_width, 3])\n', (29553, 29588), True, 'import tensorflow as tf\n'), ((30196, 30290), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_instance_masks': '(True)', 'include_keypoints': '(True)'}), '(include_instance_masks=True,\n include_keypoints=True)\n', (30233, 30290), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((30314, 30410), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocess_options, func_arg_map=\n preprocessor_arg_map)\n', (30337, 30410), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((31359, 31415), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (31382, 31415), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((31556, 31601), 'tensorflow.squared_difference', 'tf.squared_difference', (['boxes', 'boxes_expected1'], {}), '(boxes, boxes_expected1)\n', (31577, 31601), True, 'import tensorflow as tf\n'), ((31620, 31665), 'tensorflow.squared_difference', 'tf.squared_difference', (['boxes', 'boxes_expected2'], {}), '(boxes, boxes_expected2)\n', (31641, 31665), True, 'import tensorflow as tf\n'), ((31683, 31720), 'tensorflow.multiply', 'tf.multiply', (['boxes_diff1', 'boxes_diff2'], {}), '(boxes_diff1, boxes_diff2)\n', (31694, 31720), True, 'import tensorflow as tf\n'), ((31747, 31772), 'tensorflow.zeros_like', 'tf.zeros_like', (['boxes_diff'], {}), '(boxes_diff)\n', (31760, 31772), True, 'import tensorflow as tf\n'), ((31793, 31840), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected1'], {}), '(images, images_expected1)\n', (31814, 31840), True, 'import tensorflow as tf\n'), ((31860, 31907), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected2'], {}), '(images, images_expected2)\n', (31881, 31907), True, 'import tensorflow as tf\n'), ((31926, 31965), 'tensorflow.multiply', 'tf.multiply', (['images_diff1', 'images_diff2'], {}), '(images_diff1, images_diff2)\n', (31937, 31965), True, 'import tensorflow as tf\n'), ((31993, 32019), 'tensorflow.zeros_like', 'tf.zeros_like', (['images_diff'], {}), '(images_diff)\n', (32006, 32019), True, 'import tensorflow as tf\n'), ((32874, 32930), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (32897, 32930), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((33072, 33119), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected1'], {}), '(images, images_expected1)\n', (33093, 33119), True, 'import tensorflow as tf\n'), ((33139, 33186), 'tensorflow.squared_difference', 'tf.squared_difference', (['images', 'images_expected2'], {}), '(images, images_expected2)\n', (33160, 33186), True, 'import tensorflow as tf\n'), ((33205, 33244), 'tensorflow.multiply', 'tf.multiply', (['images_diff1', 'images_diff2'], {}), '(images_diff1, images_diff2)\n', (33216, 33244), True, 'import tensorflow as tf\n'), ((33272, 33298), 'tensorflow.zeros_like', 'tf.zeros_like', (['images_diff'], {}), '(images_diff)\n', (33285, 33298), True, 'import tensorflow as tf\n'), ((34122, 34174), 'tensorflow.random_uniform', 'tf.random_uniform', (['[1, image_height, image_width, 3]'], {}), '([1, image_height, image_width, 3])\n', (34139, 34174), True, 'import tensorflow as tf\n'), ((34574, 34668), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_instance_masks': '(True)', 'include_keypoints': '(True)'}), '(include_instance_masks=True,\n include_keypoints=True)\n', (34611, 34668), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((34692, 34788), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocess_options, func_arg_map=\n preprocessor_arg_map)\n', (34715, 34788), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((35693, 35752), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (35716, 35752), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((35931, 35967), 'tensorflow.greater_equal', 'tf.greater_equal', (['images', 'images_min'], {}), '(images, images_min)\n', (35947, 35967), True, 'import tensorflow as tf\n'), ((35986, 36019), 'tensorflow.less_equal', 'tf.less_equal', (['images', 'images_max'], {}), '(images, images_max)\n', (35999, 36019), True, 'import tensorflow as tf\n'), ((36038, 36065), 'tensorflow.fill', 'tf.fill', (['[1, 4, 4, 3]', '(True)'], {}), '([1, 4, 4, 3], True)\n', (36045, 36065), True, 'import tensorflow as tf\n'), ((37108, 37164), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (37131, 37164), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((37255, 37280), 'tensorflow.shape', 'tf.shape', (['images_original'], {}), '(images_original)\n', (37263, 37280), True, 'import tensorflow as tf\n'), ((37307, 37330), 'tensorflow.shape', 'tf.shape', (['images_scaled'], {}), '(images_scaled)\n', (37315, 37330), True, 'import tensorflow as tf\n'), ((38406, 38462), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options'], {}), '(tensor_dict, preprocess_options)\n', (38429, 38462), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((38573, 38630), 'tensorflow.split', 'tf.split', ([], {'value': 'images_gray', 'num_or_size_splits': '(3)', 'axis': '(3)'}), '(value=images_gray, num_or_size_splits=3, axis=3)\n', (38581, 38630), True, 'import tensorflow as tf\n'), ((38675, 38736), 'tensorflow.split', 'tf.split', ([], {'value': 'images_original', 'num_or_size_splits': '(3)', 'axis': '(3)'}), '(value=images_original, num_or_size_splits=3, axis=3)\n', (38683, 38736), True, 'import tensorflow as tf\n'), ((39045, 39088), 'tensorflow.multiply', 'tf.multiply', (['images_r_diff1', 'images_r_diff2'], {}), '(images_r_diff1, images_r_diff2)\n', (39056, 39088), True, 'import tensorflow as tf\n'), ((39388, 39431), 'tensorflow.multiply', 'tf.multiply', (['images_g_diff1', 'images_g_diff2'], {}), '(images_g_diff1, images_g_diff2)\n', (39399, 39431), True, 'import tensorflow as tf\n'), ((39731, 39774), 'tensorflow.multiply', 'tf.multiply', (['images_b_diff1', 'images_b_diff2'], {}), '(images_b_diff1, images_b_diff2)\n', (39742, 39774), True, 'import tensorflow as tf\n'), ((39793, 39845), 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': 'tf.float32', 'shape': '[1, 4, 4, 1]'}), '(0, dtype=tf.float32, shape=[1, 4, 4, 1])\n', (39804, 39845), True, 'import tensorflow as tf\n'), ((41015, 41074), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (41038, 41074), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((41164, 41189), 'tensorflow.shape', 'tf.shape', (['images_original'], {}), '(images_original)\n', (41172, 41189), True, 'import tensorflow as tf\n'), ((41215, 41238), 'tensorflow.shape', 'tf.shape', (['images_bright'], {}), '(images_bright)\n', (41223, 41238), True, 'import tensorflow as tf\n'), ((42478, 42537), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (42501, 42537), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((42629, 42654), 'tensorflow.shape', 'tf.shape', (['images_original'], {}), '(images_original)\n', (42637, 42654), True, 'import tensorflow as tf\n'), ((42682, 42707), 'tensorflow.shape', 'tf.shape', (['images_contrast'], {}), '(images_contrast)\n', (42690, 42707), True, 'import tensorflow as tf\n'), ((43939, 43998), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (43962, 43998), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((44085, 44110), 'tensorflow.shape', 'tf.shape', (['images_original'], {}), '(images_original)\n', (44093, 44110), True, 'import tensorflow as tf\n'), ((44133, 44153), 'tensorflow.shape', 'tf.shape', (['images_hue'], {}), '(images_hue)\n', (44141, 44153), True, 'import tensorflow as tf\n'), ((45310, 45335), 'tensorflow.shape', 'tf.shape', (['images_original'], {}), '(images_original)\n', (45318, 45335), True, 'import tensorflow as tf\n'), ((45420, 45479), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (45443, 45479), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((45586, 45618), 'tensorflow.shape', 'tf.shape', (['images_distorted_color'], {}), '(images_distorted_color)\n', (45594, 45618), True, 'import tensorflow as tf\n'), ((46609, 46624), 'tensorflow.shape', 'tf.shape', (['boxes'], {}), '(boxes)\n', (46617, 46624), True, 'import tensorflow as tf\n'), ((46711, 46770), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (46734, 46770), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((46875, 46900), 'tensorflow.shape', 'tf.shape', (['distorted_boxes'], {}), '(distorted_boxes)\n', (46883, 46900), True, 'import tensorflow as tf\n'), ((47762, 47821), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (47785, 47821), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((48061, 48075), 'tensorflow.rank', 'tf.rank', (['boxes'], {}), '(boxes)\n', (48068, 48075), True, 'import tensorflow as tf\n'), ((48103, 48127), 'tensorflow.rank', 'tf.rank', (['distorted_boxes'], {}), '(distorted_boxes)\n', (48110, 48127), True, 'import tensorflow as tf\n'), ((48146, 48161), 'tensorflow.rank', 'tf.rank', (['images'], {}), '(images)\n', (48153, 48161), True, 'import tensorflow as tf\n'), ((48190, 48215), 'tensorflow.rank', 'tf.rank', (['distorted_images'], {}), '(distorted_images)\n', (48197, 48215), True, 'import tensorflow as tf\n'), ((50156, 50215), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (50179, 50215), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((50412, 50426), 'tensorflow.rank', 'tf.rank', (['boxes'], {}), '(boxes)\n', (50419, 50426), True, 'import tensorflow as tf\n'), ((50454, 50478), 'tensorflow.rank', 'tf.rank', (['distorted_boxes'], {}), '(distorted_boxes)\n', (50461, 50478), True, 'import tensorflow as tf\n'), ((50497, 50512), 'tensorflow.rank', 'tf.rank', (['images'], {}), '(images)\n', (50504, 50512), True, 'import tensorflow as tf\n'), ((50541, 50566), 'tensorflow.rank', 'tf.rank', (['distorted_images'], {}), '(distorted_images)\n', (50548, 50566), True, 'import tensorflow as tf\n'), ((51702, 51761), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (51725, 51761), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((52001, 52015), 'tensorflow.rank', 'tf.rank', (['boxes'], {}), '(boxes)\n', (52008, 52015), True, 'import tensorflow as tf\n'), ((52043, 52067), 'tensorflow.rank', 'tf.rank', (['distorted_boxes'], {}), '(distorted_boxes)\n', (52050, 52067), True, 'import tensorflow as tf\n'), ((52086, 52101), 'tensorflow.rank', 'tf.rank', (['images'], {}), '(images)\n', (52093, 52101), True, 'import tensorflow as tf\n'), ((52130, 52155), 'tensorflow.rank', 'tf.rank', (['distorted_images'], {}), '(distorted_images)\n', (52137, 52155), True, 'import tensorflow as tf\n'), ((53189, 53248), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (53212, 53248), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((53432, 53491), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (53455, 53491), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((53940, 53955), 'tensorflow.shape', 'tf.shape', (['boxes'], {}), '(boxes)\n', (53948, 53955), True, 'import tensorflow as tf\n'), ((53984, 54009), 'tensorflow.shape', 'tf.shape', (['distorted_boxes'], {}), '(distorted_boxes)\n', (53992, 54009), True, 'import tensorflow as tf\n'), ((54029, 54045), 'tensorflow.shape', 'tf.shape', (['images'], {}), '(images)\n', (54037, 54045), True, 'import tensorflow as tf\n'), ((54075, 54101), 'tensorflow.shape', 'tf.shape', (['distorted_images'], {}), '(distorted_images)\n', (54083, 54101), True, 'import tensorflow as tf\n'), ((55281, 55385), 'tensorflow.constant', 'tf.constant', (['[[0.1, 0.1, 0.8, 0.3], [0.2, 0.4, 0.75, 0.75], [0.3, 0.1, 0.4, 0.7]]'], {'dtype': 'tf.float32'}), '([[0.1, 0.1, 0.8, 0.3], [0.2, 0.4, 0.75, 0.75], [0.3, 0.1, 0.4, \n 0.7]], dtype=tf.float32)\n', (55292, 55385), True, 'import tensorflow as tf\n'), ((55444, 55483), 'tensorflow.constant', 'tf.constant', (['[1, 7, 11]'], {'dtype': 'tf.int32'}), '([1, 7, 11], dtype=tf.int32)\n', (55455, 55483), True, 'import tensorflow as tf\n'), ((55692, 55751), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (55715, 55751), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((58040, 58099), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (58063, 58099), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((58446, 58460), 'tensorflow.rank', 'tf.rank', (['boxes'], {}), '(boxes)\n', (58453, 58460), True, 'import tensorflow as tf\n'), ((58488, 58512), 'tensorflow.rank', 'tf.rank', (['distorted_boxes'], {}), '(distorted_boxes)\n', (58495, 58512), True, 'import tensorflow as tf\n'), ((58531, 58546), 'tensorflow.rank', 'tf.rank', (['images'], {}), '(images)\n', (58538, 58546), True, 'import tensorflow as tf\n'), ((58575, 58600), 'tensorflow.rank', 'tf.rank', (['distorted_images'], {}), '(distorted_images)\n', (58582, 58600), True, 'import tensorflow as tf\n'), ((58630, 58656), 'tensorflow.rank', 'tf.rank', (['multiclass_scores'], {}), '(multiclass_scores)\n', (58637, 58656), True, 'import tensorflow as tf\n'), ((58696, 58732), 'tensorflow.rank', 'tf.rank', (['distorted_multiclass_scores'], {}), '(distorted_multiclass_scores)\n', (58703, 58732), True, 'import tensorflow as tf\n'), ((61062, 61112), 'tensorflow.random_uniform', 'tf.random_uniform', (['[2, 200, 400]'], {'dtype': 'tf.float32'}), '([2, 200, 400], dtype=tf.float32)\n', (61079, 61112), True, 'import tensorflow as tf\n'), ((63926, 63976), 'tensorflow.random_uniform', 'tf.random_uniform', (['[2, 200, 400]'], {'dtype': 'tf.float32'}), '([2, 200, 400], dtype=tf.float32)\n', (63943, 63976), True, 'import tensorflow as tf\n'), ((64260, 64326), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_instance_masks': '(True)'}), '(include_instance_masks=True)\n', (64297, 64326), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((66494, 66555), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_keypoints': '(True)'}), '(include_keypoints=True)\n', (66531, 66555), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((69048, 69109), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_keypoints': '(True)'}), '(include_keypoints=True)\n', (69085, 69109), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((71567, 71631), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_label_scores': '(True)'}), '(include_label_scores=True)\n', (71604, 71631), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((71668, 71767), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (71691, 71767), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((73268, 73365), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_label_scores': '(True)', 'include_instance_masks': '(True)'}), '(include_label_scores=True,\n include_instance_masks=True)\n', (73305, 73365), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((73516, 73615), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (73539, 73615), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((74482, 74574), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_label_scores': '(True)', 'include_keypoints': '(True)'}), '(include_label_scores=True,\n include_keypoints=True)\n', (74519, 74574), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((74725, 74824), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (74748, 74824), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((75695, 75745), 'tensorflow.random_uniform', 'tf.random_uniform', (['[2, 200, 400]'], {'dtype': 'tf.float32'}), '([2, 200, 400], dtype=tf.float32)\n', (75712, 75745), True, 'import tensorflow as tf\n'), ((76028, 76094), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_instance_masks': '(True)'}), '(include_instance_masks=True)\n', (76065, 76094), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((77996, 78057), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_keypoints': '(True)'}), '(include_keypoints=True)\n', (78033, 78057), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((80367, 80406), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {}), '()\n', (80404, 80406), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((80645, 80744), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (80668, 80744), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((81727, 81777), 'tensorflow.random_uniform', 'tf.random_uniform', (['[2, 200, 400]'], {'dtype': 'tf.float32'}), '([2, 200, 400], dtype=tf.float32)\n', (81744, 81777), True, 'import tensorflow as tf\n'), ((82060, 82126), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_instance_masks': '(True)'}), '(include_instance_masks=True)\n', (82097, 82126), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((82242, 82341), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (82265, 82341), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((83847, 83908), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_keypoints': '(True)'}), '(include_keypoints=True)\n', (83884, 83908), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((84024, 84123), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (84047, 84123), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((86363, 86422), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (86386, 86422), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((86570, 86629), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (86593, 86629), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((86856, 86871), 'tensorflow.shape', 'tf.shape', (['boxes'], {}), '(boxes)\n', (86864, 86871), True, 'import tensorflow as tf\n'), ((86897, 86919), 'tensorflow.shape', 'tf.shape', (['padded_boxes'], {}), '(padded_boxes)\n', (86905, 86919), True, 'import tensorflow as tf\n'), ((86939, 86955), 'tensorflow.shape', 'tf.shape', (['images'], {}), '(images)\n', (86947, 86955), True, 'import tensorflow as tf\n'), ((86982, 87005), 'tensorflow.shape', 'tf.shape', (['padded_images'], {}), '(padded_images)\n', (86990, 87005), True, 'import tensorflow as tf\n'), ((88912, 88971), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (88935, 88971), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((89156, 89215), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (89179, 89215), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((89442, 89457), 'tensorflow.shape', 'tf.shape', (['boxes'], {}), '(boxes)\n', (89450, 89457), True, 'import tensorflow as tf\n'), ((89483, 89505), 'tensorflow.shape', 'tf.shape', (['padded_boxes'], {}), '(padded_boxes)\n', (89491, 89505), True, 'import tensorflow as tf\n'), ((89525, 89541), 'tensorflow.shape', 'tf.shape', (['images'], {}), '(images)\n', (89533, 89541), True, 'import tensorflow as tf\n'), ((89568, 89591), 'tensorflow.shape', 'tf.shape', (['padded_images'], {}), '(padded_images)\n', (89576, 89591), True, 'import tensorflow as tf\n'), ((90827, 90867), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', '[]'], {}), '(tensor_dict, [])\n', (90850, 90867), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((91060, 91119), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (91083, 91119), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((91351, 91366), 'tensorflow.shape', 'tf.shape', (['boxes'], {}), '(boxes)\n', (91359, 91366), True, 'import tensorflow as tf\n'), ((91393, 91416), 'tensorflow.shape', 'tf.shape', (['cropped_boxes'], {}), '(cropped_boxes)\n', (91401, 91416), True, 'import tensorflow as tf\n'), ((91436, 91452), 'tensorflow.shape', 'tf.shape', (['images'], {}), '(images)\n', (91444, 91452), True, 'import tensorflow as tf\n'), ((91480, 91504), 'tensorflow.shape', 'tf.shape', (['cropped_images'], {}), '(cropped_images)\n', (91488, 91504), True, 'import tensorflow as tf\n'), ((92292, 92332), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', '[]'], {}), '(tensor_dict, [])\n', (92315, 92332), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((92523, 92582), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (92546, 92582), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((92809, 92824), 'tensorflow.shape', 'tf.shape', (['boxes'], {}), '(boxes)\n', (92817, 92824), True, 'import tensorflow as tf\n'), ((92850, 92872), 'tensorflow.shape', 'tf.shape', (['padded_boxes'], {}), '(padded_boxes)\n', (92858, 92872), True, 'import tensorflow as tf\n'), ((92892, 92908), 'tensorflow.shape', 'tf.shape', (['images'], {}), '(images)\n', (92900, 92908), True, 'import tensorflow as tf\n'), ((92935, 92958), 'tensorflow.shape', 'tf.shape', (['padded_images'], {}), '(padded_images)\n', (92943, 92958), True, 'import tensorflow as tf\n'), ((94451, 94510), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (94474, 94510), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((94651, 94667), 'tensorflow.shape', 'tf.shape', (['images'], {}), '(images)\n', (94659, 94667), True, 'import tensorflow as tf\n'), ((94695, 94719), 'tensorflow.shape', 'tf.shape', (['blacked_images'], {}), '(blacked_images)\n', (94703, 94719), True, 'import tensorflow as tf\n'), ((95993, 96052), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (96016, 96052), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((96201, 96225), 'tensorflow.shape', 'tf.shape', (['resized_images'], {}), '(resized_images)\n', (96209, 96225), True, 'import tensorflow as tf\n'), ((96254, 96298), 'tensorflow.constant', 'tf.constant', (['[1, 75, 150, 3]'], {'dtype': 'tf.int32'}), '([1, 75, 150, 3], dtype=tf.int32)\n', (96265, 96298), True, 'import tensorflow as tf\n'), ((98057, 98088), 'tensorflow.constant', 'tf.constant', (['(50)'], {'dtype': 'tf.int32'}), '(50, dtype=tf.int32)\n', (98068, 98088), True, 'import tensorflow as tf\n'), ((98101, 98133), 'tensorflow.constant', 'tf.constant', (['(100)'], {'dtype': 'tf.int32'}), '(100, dtype=tf.int32)\n', (98112, 98133), True, 'import tensorflow as tf\n'), ((102853, 102888), 'numpy.array', 'np.array', (['[[[0, 1, 2]]]', 'np.float32'], {}), '([[[0, 1, 2]]], np.float32)\n', (102861, 102888), True, 'import numpy as np\n'), ((102907, 103033), 'numpy.array', 'np.array', (['[[[0, 1, 2], [123.68, 116.779, 103.939]], [[123.68, 116.779, 103.939], [\n 123.68, 116.779, 103.939]]]', 'np.float32'], {}), '([[[0, 1, 2], [123.68, 116.779, 103.939]], [[123.68, 116.779, \n 103.939], [123.68, 116.779, 103.939]]], np.float32)\n', (102915, 103033), True, 'import numpy as np\n'), ((103095, 103144), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, 3)'}), '(tf.float32, shape=(None, None, 3))\n', (103109, 103144), True, 'import tensorflow as tf\n'), ((103164, 103335), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim', 'pad_to_max_dimension': '(True)', 'per_channel_pad_value': '(123.68, 116.779, 103.939)'}), '(in_image, min_dimension=min_dim, max_dimension\n =max_dim, pad_to_max_dimension=True, per_channel_pad_value=(123.68, \n 116.779, 103.939))\n', (103192, 103335), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((108997, 109032), 'tensorflow.random_uniform', 'tf.random_uniform', (['[1, 200, 300, 3]'], {}), '([1, 200, 300, 3])\n', (109014, 109032), True, 'import tensorflow as tf\n'), ((112581, 112616), 'tensorflow.random_uniform', 'tf.random_uniform', (['[1, 200, 300, 3]'], {}), '([1, 200, 300, 3])\n', (112598, 112616), True, 'import tensorflow as tf\n'), ((113018, 113045), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_shape'], {}), '(in_shape)\n', (113035, 113045), True, 'import tensorflow as tf\n'), ((113061, 113082), 'tensorflow.constant', 'tf.constant', (['in_boxes'], {}), '(in_boxes)\n', (113072, 113082), True, 'import tensorflow as tf\n'), ((113102, 113173), 'object_detection.tensorflow_detect.core.preprocessor.scale_boxes_to_pixel_coordinates', 'preprocessor.scale_boxes_to_pixel_coordinates', (['in_image'], {'boxes': 'in_boxes'}), '(in_image, boxes=in_boxes)\n', (113147, 113173), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((113775, 113802), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_shape'], {}), '(in_shape)\n', (113792, 113802), True, 'import tensorflow as tf\n'), ((113837, 113936), 'object_detection.tensorflow_detect.core.preprocessor.scale_boxes_to_pixel_coordinates', 'preprocessor.scale_boxes_to_pixel_coordinates', (['in_image'], {'boxes': 'in_boxes', 'keypoints': 'in_keypoints'}), '(in_image, boxes=in_boxes,\n keypoints=in_keypoints)\n', (113882, 113936), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((116063, 116122), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (116086, 116122), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((116364, 116379), 'tensorflow.rank', 'tf.rank', (['images'], {}), '(images)\n', (116371, 116379), True, 'import tensorflow as tf\n'), ((116408, 116433), 'tensorflow.rank', 'tf.rank', (['distorted_images'], {}), '(distorted_images)\n', (116415, 116433), True, 'import tensorflow as tf\n'), ((116451, 116465), 'tensorflow.rank', 'tf.rank', (['boxes'], {}), '(boxes)\n', (116458, 116465), True, 'import tensorflow as tf\n'), ((116493, 116517), 'tensorflow.rank', 'tf.rank', (['distorted_boxes'], {}), '(distorted_boxes)\n', (116500, 116517), True, 'import tensorflow as tf\n'), ((117606, 117675), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_multiclass_scores': '(True)'}), '(include_multiclass_scores=True)\n', (117643, 117675), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((117713, 117812), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (117736, 117812), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((118113, 118128), 'tensorflow.rank', 'tf.rank', (['images'], {}), '(images)\n', (118120, 118128), True, 'import tensorflow as tf\n'), ((118157, 118182), 'tensorflow.rank', 'tf.rank', (['distorted_images'], {}), '(distorted_images)\n', (118164, 118182), True, 'import tensorflow as tf\n'), ((118200, 118214), 'tensorflow.rank', 'tf.rank', (['boxes'], {}), '(boxes)\n', (118207, 118214), True, 'import tensorflow as tf\n'), ((118242, 118266), 'tensorflow.rank', 'tf.rank', (['distorted_boxes'], {}), '(distorted_boxes)\n', (118249, 118266), True, 'import tensorflow as tf\n'), ((118296, 118322), 'tensorflow.rank', 'tf.rank', (['multiclass_scores'], {}), '(multiclass_scores)\n', (118303, 118322), True, 'import tensorflow as tf\n'), ((118362, 118398), 'tensorflow.rank', 'tf.rank', (['distorted_multiclass_scores'], {}), '(distorted_multiclass_scores)\n', (118369, 118398), True, 'import tensorflow as tf\n'), ((119858, 119917), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (119881, 119917), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((120159, 120174), 'tensorflow.rank', 'tf.rank', (['images'], {}), '(images)\n', (120166, 120174), True, 'import tensorflow as tf\n'), ((120203, 120228), 'tensorflow.rank', 'tf.rank', (['distorted_images'], {}), '(distorted_images)\n', (120210, 120228), True, 'import tensorflow as tf\n'), ((120246, 120260), 'tensorflow.rank', 'tf.rank', (['boxes'], {}), '(boxes)\n', (120253, 120260), True, 'import tensorflow as tf\n'), ((120288, 120312), 'tensorflow.rank', 'tf.rank', (['distorted_boxes'], {}), '(distorted_boxes)\n', (120295, 120312), True, 'import tensorflow as tf\n'), ((122733, 122965), 'object_detection.tensorflow_detect.core.preprocessor.get_default_func_arg_map', 'preprocessor.get_default_func_arg_map', ([], {'include_label_scores': 'include_label_scores', 'include_multiclass_scores': 'include_multiclass_scores', 'include_instance_masks': 'include_instance_masks', 'include_keypoints': 'include_keypoints'}), '(include_label_scores=\n include_label_scores, include_multiclass_scores=\n include_multiclass_scores, include_instance_masks=\n include_instance_masks, include_keypoints=include_keypoints)\n', (122770, 122965), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((123012, 123111), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (123035, 123111), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((123304, 123319), 'tensorflow.rank', 'tf.rank', (['images'], {}), '(images)\n', (123311, 123319), True, 'import tensorflow as tf\n'), ((123348, 123373), 'tensorflow.rank', 'tf.rank', (['distorted_images'], {}), '(distorted_images)\n', (123355, 123373), True, 'import tensorflow as tf\n'), ((123391, 123405), 'tensorflow.rank', 'tf.rank', (['boxes'], {}), '(boxes)\n', (123398, 123405), True, 'import tensorflow as tf\n'), ((123433, 123457), 'tensorflow.rank', 'tf.rank', (['distorted_boxes'], {}), '(distorted_boxes)\n', (123440, 123457), True, 'import tensorflow as tf\n'), ((125315, 125381), 'tensorflow.constant', 'tf.constant', (['[[1.0, 0.0], [0.5, 0.5], [1000, 1]]'], {'dtype': 'tf.float32'}), '([[1.0, 0.0], [0.5, 0.5], [1000, 1]], dtype=tf.float32)\n', (125326, 125381), True, 'import tensorflow as tf\n'), ((125458, 125569), 'object_detection.tensorflow_detect.core.preprocessor.convert_class_logits_to_softmax', 'preprocessor.convert_class_logits_to_softmax', ([], {'multiclass_scores': 'multiclass_scores', 'temperature': 'temperature'}), '(multiclass_scores=\n multiclass_scores, temperature=temperature)\n', (125502, 125569), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((1176, 1208), 'tensorflow.constant', 'tf.constant', (['(255)'], {'dtype': 'tf.uint8'}), '(255, dtype=tf.uint8)\n', (1187, 1208), True, 'import tensorflow as tf\n'), ((1248, 1280), 'tensorflow.constant', 'tf.constant', (['(128)'], {'dtype': 'tf.uint8'}), '(128, dtype=tf.uint8)\n', (1259, 1280), True, 'import tensorflow as tf\n'), ((1318, 1348), 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': 'tf.uint8'}), '(0, dtype=tf.uint8)\n', (1329, 1348), True, 'import tensorflow as tf\n'), ((38789, 38810), 'tensorflow.to_float', 'tf.to_float', (['images_r'], {}), '(images_r)\n', (38800, 38810), True, 'import tensorflow as tf\n'), ((38855, 38881), 'tensorflow.to_float', 'tf.to_float', (['images_gray_r'], {}), '(images_gray_r)\n', (38866, 38881), True, 'import tensorflow as tf\n'), ((38926, 38952), 'tensorflow.to_float', 'tf.to_float', (['images_gray_r'], {}), '(images_gray_r)\n', (38937, 38952), True, 'import tensorflow as tf\n'), ((38997, 39023), 'tensorflow.to_float', 'tf.to_float', (['images_gray_g'], {}), '(images_gray_g)\n', (39008, 39023), True, 'import tensorflow as tf\n'), ((39132, 39153), 'tensorflow.to_float', 'tf.to_float', (['images_g'], {}), '(images_g)\n', (39143, 39153), True, 'import tensorflow as tf\n'), ((39198, 39224), 'tensorflow.to_float', 'tf.to_float', (['images_gray_g'], {}), '(images_gray_g)\n', (39209, 39224), True, 'import tensorflow as tf\n'), ((39269, 39295), 'tensorflow.to_float', 'tf.to_float', (['images_gray_g'], {}), '(images_gray_g)\n', (39280, 39295), True, 'import tensorflow as tf\n'), ((39340, 39366), 'tensorflow.to_float', 'tf.to_float', (['images_gray_b'], {}), '(images_gray_b)\n', (39351, 39366), True, 'import tensorflow as tf\n'), ((39475, 39496), 'tensorflow.to_float', 'tf.to_float', (['images_b'], {}), '(images_b)\n', (39486, 39496), True, 'import tensorflow as tf\n'), ((39541, 39567), 'tensorflow.to_float', 'tf.to_float', (['images_gray_b'], {}), '(images_gray_b)\n', (39552, 39567), True, 'import tensorflow as tf\n'), ((39612, 39638), 'tensorflow.to_float', 'tf.to_float', (['images_gray_b'], {}), '(images_gray_b)\n', (39623, 39638), True, 'import tensorflow as tf\n'), ((39683, 39709), 'tensorflow.to_float', 'tf.to_float', (['images_gray_r'], {}), '(images_gray_r)\n', (39694, 39709), True, 'import tensorflow as tf\n'), ((55884, 55944), 'unittest.mock.patch.object', 'mock.patch.object', (['tf.image', '"""sample_distorted_bounding_box"""'], {}), "(tf.image, 'sample_distorted_bounding_box')\n", (55901, 55944), False, 'from unittest import mock\n'), ((56284, 56343), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {}), '(tensor_dict, preprocessing_options)\n', (56307, 56343), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((56623, 56744), 'tensorflow.constant', 'tf.constant', (['[[0.178947, 0.07173, 0.75789469, 0.66244733], [0.28421, 0.0, 0.38947365, \n 0.57805908]]'], {'dtype': 'tf.float32'}), '([[0.178947, 0.07173, 0.75789469, 0.66244733], [0.28421, 0.0, \n 0.38947365, 0.57805908]], dtype=tf.float32)\n', (56634, 56744), True, 'import tensorflow as tf\n'), ((56835, 56871), 'tensorflow.constant', 'tf.constant', (['[7, 11]'], {'dtype': 'tf.int32'}), '([7, 11], dtype=tf.int32)\n', (56846, 56871), True, 'import tensorflow as tf\n'), ((59797, 59857), 'unittest.mock.patch.object', 'mock.patch.object', (['tf.image', '"""sample_distorted_bounding_box"""'], {}), "(tf.image, 'sample_distorted_bounding_box')\n", (59814, 59857), False, 'from unittest import mock\n'), ((60228, 60302), 'object_detection.tensorflow_detect.core.preprocessor._strict_random_crop_image', 'preprocessor._strict_random_crop_image', (['image', 'boxes', 'labels', 'label_scores'], {}), '(image, boxes, labels, label_scores)\n', (60266, 60302), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((61122, 61182), 'unittest.mock.patch.object', 'mock.patch.object', (['tf.image', '"""sample_distorted_bounding_box"""'], {}), "(tf.image, 'sample_distorted_bounding_box')\n", (61139, 61182), False, 'from unittest import mock\n'), ((61546, 61619), 'object_detection.tensorflow_detect.core.preprocessor._strict_random_crop_image', 'preprocessor._strict_random_crop_image', (['image', 'boxes', 'labels'], {'masks': 'masks'}), '(image, boxes, labels, masks=masks)\n', (61584, 61619), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((62382, 62442), 'unittest.mock.patch.object', 'mock.patch.object', (['tf.image', '"""sample_distorted_bounding_box"""'], {}), "(tf.image, 'sample_distorted_bounding_box')\n", (62399, 62442), False, 'from unittest import mock\n'), ((62810, 62896), 'object_detection.tensorflow_detect.core.preprocessor._strict_random_crop_image', 'preprocessor._strict_random_crop_image', (['image', 'boxes', 'labels'], {'keypoints': 'keypoints'}), '(image, boxes, labels, keypoints=\n keypoints)\n', (62848, 62896), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((64414, 64474), 'unittest.mock.patch.object', 'mock.patch.object', (['tf.image', '"""sample_distorted_bounding_box"""'], {}), "(tf.image, 'sample_distorted_bounding_box')\n", (64431, 64474), False, 'from unittest import mock\n'), ((64804, 64903), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (64827, 64903), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((66643, 66703), 'unittest.mock.patch.object', 'mock.patch.object', (['tf.image', '"""sample_distorted_bounding_box"""'], {}), "(tf.image, 'sample_distorted_bounding_box')\n", (66660, 66703), False, 'from unittest import mock\n'), ((67033, 67132), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (67056, 67132), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((69197, 69257), 'unittest.mock.patch.object', 'mock.patch.object', (['tf.image', '"""sample_distorted_bounding_box"""'], {}), "(tf.image, 'sample_distorted_bounding_box')\n", (69214, 69257), False, 'from unittest import mock\n'), ((69587, 69686), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (69610, 69686), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((76192, 76242), 'unittest.mock.patch.object', 'mock.patch.object', (['preprocessor', '"""_random_integer"""'], {}), "(preprocessor, '_random_integer')\n", (76209, 76242), False, 'from unittest import mock\n'), ((76335, 76365), 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': 'tf.int32'}), '(0, dtype=tf.int32)\n', (76346, 76365), True, 'import tensorflow as tf\n'), ((76396, 76495), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (76419, 76495), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((78155, 78205), 'unittest.mock.patch.object', 'mock.patch.object', (['preprocessor', '"""_random_integer"""'], {}), "(preprocessor, '_random_integer')\n", (78172, 78205), False, 'from unittest import mock\n'), ((78298, 78328), 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': 'tf.int32'}), '(0, dtype=tf.int32)\n', (78309, 78328), True, 'import tensorflow as tf\n'), ((78359, 78458), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocessing_options'], {'func_arg_map': 'preprocessor_arg_map'}), '(tensor_dict, preprocessing_options, func_arg_map=\n preprocessor_arg_map)\n', (78382, 78458), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((81214, 81303), 'numpy.array', 'np.array', (['[[0.0, 0.125, 0.1875, 0.5], [0.0625, 0.25, 0.1875, 0.5]]'], {'dtype': 'np.float32'}), '([[0.0, 0.125, 0.1875, 0.5], [0.0625, 0.25, 0.1875, 0.5]], dtype=np\n .float32)\n', (81222, 81303), True, 'import numpy as np\n'), ((82968, 83047), 'numpy.array', 'np.array', (['[[0.0, 0.25, 0.375, 1.0], [0.125, 0.5, 0.375, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.25, 0.375, 1.0], [0.125, 0.5, 0.375, 1.0]], dtype=np.float32)\n', (82976, 83047), True, 'import numpy as np\n'), ((84768, 84847), 'numpy.array', 'np.array', (['[[0.0, 0.25, 0.375, 1.0], [0.125, 0.5, 0.375, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.25, 0.375, 1.0], [0.125, 0.5, 0.375, 1.0]], dtype=np.float32)\n', (84776, 84847), True, 'import numpy as np\n'), ((84886, 84997), 'numpy.array', 'np.array', (['[[[0.05, 0.1], [0.1, 0.2], [0.15, 0.3]], [[0.2, 0.4], [0.25, 0.5], [0.3, 0.6]]]'], {'dtype': 'np.float32'}), '([[[0.05, 0.1], [0.1, 0.2], [0.15, 0.3]], [[0.2, 0.4], [0.25, 0.5],\n [0.3, 0.6]]], dtype=np.float32)\n', (84894, 84997), True, 'import numpy as np\n'), ((97244, 97277), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_image_shape'], {}), '(in_image_shape)\n', (97261, 97277), True, 'import tensorflow as tf\n'), ((97295, 97328), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_masks_shape'], {}), '(in_masks_shape)\n', (97312, 97328), True, 'import tensorflow as tf\n'), ((97361, 97447), 'object_detection.tensorflow_detect.core.preprocessor.resize_image', 'preprocessor.resize_image', (['in_image', 'in_masks'], {'new_height': 'height', 'new_width': 'width'}), '(in_image, in_masks, new_height=height, new_width=\n width)\n', (97386, 97447), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((97478, 97497), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (97486, 97497), True, 'import tensorflow as tf\n'), ((97522, 97541), 'tensorflow.shape', 'tf.shape', (['out_masks'], {}), '(out_masks)\n', (97530, 97541), True, 'import tensorflow as tf\n'), ((98584, 98617), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_image_shape'], {}), '(in_image_shape)\n', (98601, 98617), True, 'import tensorflow as tf\n'), ((98635, 98668), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_masks_shape'], {}), '(in_masks_shape)\n', (98652, 98668), True, 'import tensorflow as tf\n'), ((98701, 98787), 'object_detection.tensorflow_detect.core.preprocessor.resize_image', 'preprocessor.resize_image', (['in_image', 'in_masks'], {'new_height': 'height', 'new_width': 'width'}), '(in_image, in_masks, new_height=height, new_width=\n width)\n', (98726, 98787), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((98818, 98837), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (98826, 98837), True, 'import tensorflow as tf\n'), ((98862, 98881), 'tensorflow.shape', 'tf.shape', (['out_masks'], {}), '(out_masks)\n', (98870, 98881), True, 'import tensorflow as tf\n'), ((99846, 99879), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_image_shape'], {}), '(in_image_shape)\n', (99863, 99879), True, 'import tensorflow as tf\n'), ((99897, 99930), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_masks_shape'], {}), '(in_masks_shape)\n', (99914, 99930), True, 'import tensorflow as tf\n'), ((99963, 100049), 'object_detection.tensorflow_detect.core.preprocessor.resize_image', 'preprocessor.resize_image', (['in_image', 'in_masks'], {'new_height': 'height', 'new_width': 'width'}), '(in_image, in_masks, new_height=height, new_width=\n width)\n', (99988, 100049), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((100080, 100099), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (100088, 100099), True, 'import tensorflow as tf\n'), ((100124, 100143), 'tensorflow.shape', 'tf.shape', (['out_masks'], {}), '(out_masks)\n', (100132, 100143), True, 'import tensorflow as tf\n'), ((100791, 100818), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_shape'], {}), '(in_shape)\n', (100808, 100818), True, 'import tensorflow as tf\n'), ((100840, 100929), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim'}), '(in_image, min_dimension=min_dim, max_dimension\n =max_dim)\n', (100868, 100929), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((101379, 101428), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, 3)'}), '(tf.float32, shape=(None, None, 3))\n', (101393, 101428), True, 'import tensorflow as tf\n'), ((101450, 101539), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim'}), '(in_image, min_dimension=min_dim, max_dimension\n =max_dim)\n', (101478, 101539), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((101570, 101589), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (101578, 101589), True, 'import tensorflow as tf\n'), ((102209, 102258), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, 3)'}), '(tf.float32, shape=(None, None, 3))\n', (102223, 102258), True, 'import tensorflow as tf\n'), ((102280, 102396), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim', 'pad_to_max_dimension': '(True)'}), '(in_image, min_dimension=min_dim, max_dimension\n =max_dim, pad_to_max_dimension=True)\n', (102308, 102396), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((102526, 102545), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (102534, 102545), True, 'import tensorflow as tf\n'), ((104249, 104282), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_image_shape'], {}), '(in_image_shape)\n', (104266, 104282), True, 'import tensorflow as tf\n'), ((104300, 104333), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_masks_shape'], {}), '(in_masks_shape)\n', (104317, 104333), True, 'import tensorflow as tf\n'), ((104366, 104464), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image', 'in_masks'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim'}), '(in_image, in_masks, min_dimension=min_dim,\n max_dimension=max_dim)\n', (104394, 104464), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((105262, 105311), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, 3)'}), '(tf.float32, shape=(None, None, 3))\n', (105276, 105311), True, 'import tensorflow as tf\n'), ((105329, 105381), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, None)'}), '(tf.float32, shape=(None, None, None))\n', (105343, 105381), True, 'import tensorflow as tf\n'), ((105414, 105539), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image', 'in_masks'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim', 'pad_to_max_dimension': '(True)'}), '(in_image, in_masks, min_dimension=min_dim,\n max_dimension=max_dim, pad_to_max_dimension=True)\n', (105442, 105539), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((105611, 105630), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (105619, 105630), True, 'import tensorflow as tf\n'), ((105655, 105674), 'tensorflow.shape', 'tf.shape', (['out_masks'], {}), '(out_masks)\n', (105663, 105674), True, 'import tensorflow as tf\n'), ((106817, 106866), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, 3)'}), '(tf.float32, shape=(None, None, 3))\n', (106831, 106866), True, 'import tensorflow as tf\n'), ((106884, 106936), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, None)'}), '(tf.float32, shape=(None, None, None))\n', (106898, 106936), True, 'import tensorflow as tf\n'), ((106954, 106987), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_masks_shape'], {}), '(in_masks_shape)\n', (106971, 106987), True, 'import tensorflow as tf\n'), ((107020, 107118), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image', 'in_masks'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim'}), '(in_image, in_masks, min_dimension=min_dim,\n max_dimension=max_dim)\n', (107048, 107118), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((107150, 107169), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (107158, 107169), True, 'import tensorflow as tf\n'), ((107194, 107213), 'tensorflow.shape', 'tf.shape', (['out_masks'], {}), '(out_masks)\n', (107202, 107213), True, 'import tensorflow as tf\n'), ((108354, 108387), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_image_shape'], {}), '(in_image_shape)\n', (108371, 108387), True, 'import tensorflow as tf\n'), ((108405, 108438), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_masks_shape'], {}), '(in_masks_shape)\n', (108422, 108438), True, 'import tensorflow as tf\n'), ((108471, 108569), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image', 'in_masks'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim'}), '(in_image, in_masks, min_dimension=min_dim,\n max_dimension=max_dim)\n', (108499, 108569), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((108601, 108620), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (108609, 108620), True, 'import tensorflow as tf\n'), ((108645, 108664), 'tensorflow.shape', 'tf.shape', (['out_masks'], {}), '(out_masks)\n', (108653, 108664), True, 'import tensorflow as tf\n'), ((109079, 109124), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['image', '(500)', '(600)'], {}), '(image, 500, 600)\n', (109107, 109124), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((109461, 109488), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_shape'], {}), '(in_shape)\n', (109478, 109488), True, 'import tensorflow as tf\n'), ((109510, 109599), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_range', 'preprocessor.resize_to_range', (['in_image'], {'min_dimension': 'min_dim', 'max_dimension': 'max_dim'}), '(in_image, min_dimension=min_dim, max_dimension\n =max_dim)\n', (109538, 109599), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((109630, 109649), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (109638, 109649), True, 'import tensorflow as tf\n'), ((110428, 110477), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, 3)'}), '(tf.float32, shape=(None, None, 3))\n', (110442, 110477), True, 'import tensorflow as tf\n'), ((110495, 110547), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, None)'}), '(tf.float32, shape=(None, None, None))\n', (110509, 110547), True, 'import tensorflow as tf\n'), ((110565, 110598), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_masks_shape'], {}), '(in_masks_shape)\n', (110582, 110598), True, 'import tensorflow as tf\n'), ((110631, 110710), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_min_dimension', 'preprocessor.resize_to_min_dimension', (['in_image', 'in_masks'], {'min_dimension': 'min_dim'}), '(in_image, in_masks, min_dimension=min_dim)\n', (110667, 110710), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((110746, 110765), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (110754, 110765), True, 'import tensorflow as tf\n'), ((110790, 110809), 'tensorflow.shape', 'tf.shape', (['out_masks'], {}), '(out_masks)\n', (110798, 110809), True, 'import tensorflow as tf\n'), ((111939, 111972), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_image_shape'], {}), '(in_image_shape)\n', (111956, 111972), True, 'import tensorflow as tf\n'), ((111990, 112023), 'tensorflow.random_uniform', 'tf.random_uniform', (['in_masks_shape'], {}), '(in_masks_shape)\n', (112007, 112023), True, 'import tensorflow as tf\n'), ((112056, 112135), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_min_dimension', 'preprocessor.resize_to_min_dimension', (['in_image', 'in_masks'], {'min_dimension': 'min_dim'}), '(in_image, in_masks, min_dimension=min_dim)\n', (112092, 112135), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((112171, 112190), 'tensorflow.shape', 'tf.shape', (['out_image'], {}), '(out_image)\n', (112179, 112190), True, 'import tensorflow as tf\n'), ((112215, 112234), 'tensorflow.shape', 'tf.shape', (['out_masks'], {}), '(out_masks)\n', (112223, 112234), True, 'import tensorflow as tf\n'), ((112663, 112711), 'object_detection.tensorflow_detect.core.preprocessor.resize_to_min_dimension', 'preprocessor.resize_to_min_dimension', (['image', '(500)'], {}), '(image, 500)\n', (112699, 112711), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((114310, 114333), 'tensorflow.zeros', 'tf.zeros', (['(240, 320, 3)'], {}), '((240, 320, 3))\n', (114318, 114333), True, 'import tensorflow as tf\n'), ((114373, 114427), 'object_detection.tensorflow_detect.core.preprocessor.subtract_channel_mean', 'preprocessor.subtract_channel_mean', (['image'], {'means': 'means'}), '(image, means=means)\n', (114407, 114427), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((114750, 114788), 'tensorflow.constant', 'tf.constant', (['[1, 4, 2]'], {'dtype': 'tf.int32'}), '([1, 4, 2], dtype=tf.int32)\n', (114761, 114788), True, 'import tensorflow as tf\n'), ((114805, 114857), 'object_detection.tensorflow_detect.core.preprocessor.one_hot_encoding', 'preprocessor.one_hot_encoding', (['labels'], {'num_classes': '(5)'}), '(labels, num_classes=5)\n', (114834, 114857), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((20585, 20674), 'object_detection.tensorflow_detect.core.preprocessor.preprocess', 'preprocessor.preprocess', (['tensor_dict', 'preprocess_options', 'preprocessor_arg_map', 'cache'], {}), '(tensor_dict, preprocess_options,\n preprocessor_arg_map, cache)\n', (20608, 20674), False, 'from object_detection.tensorflow_detect.core import standard_fields as fields, preprocessor, preprocessor_cache\n'), ((35770, 35789), 'tensorflow.to_float', 'tf.to_float', (['images'], {}), '(images)\n', (35781, 35789), True, 'import tensorflow as tf\n'), ((35821, 35840), 'tensorflow.to_float', 'tf.to_float', (['images'], {}), '(images)\n', (35832, 35840), True, 'import tensorflow as tf\n'), ((56058, 56098), 'tensorflow.constant', 'tf.constant', (['[6, 143, 0]'], {'dtype': 'tf.int32'}), '([6, 143, 0], dtype=tf.int32)\n', (56069, 56098), True, 'import tensorflow as tf\n'), ((56111, 56154), 'tensorflow.constant', 'tf.constant', (['[190, 237, -1]'], {'dtype': 'tf.int32'}), '([190, 237, -1], dtype=tf.int32)\n', (56122, 56154), True, 'import tensorflow as tf\n'), ((56171, 56232), 'tensorflow.constant', 'tf.constant', (['[[[0.03, 0.3575, 0.98, 0.95]]]'], {'dtype': 'tf.float32'}), '([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)\n', (56182, 56232), True, 'import tensorflow as tf\n'), ((59987, 60027), 'tensorflow.constant', 'tf.constant', (['[6, 143, 0]'], {'dtype': 'tf.int32'}), '([6, 143, 0], dtype=tf.int32)\n', (59998, 60027), True, 'import tensorflow as tf\n'), ((60039, 60082), 'tensorflow.constant', 'tf.constant', (['[190, 237, -1]'], {'dtype': 'tf.int32'}), '([190, 237, -1], dtype=tf.int32)\n', (60050, 60082), True, 'import tensorflow as tf\n'), ((60094, 60155), 'tensorflow.constant', 'tf.constant', (['[[[0.03, 0.3575, 0.98, 0.95]]]'], {'dtype': 'tf.float32'}), '([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)\n', (60105, 60155), True, 'import tensorflow as tf\n'), ((60550, 60654), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469,\n 1.0]], dtype=np.float32)\n', (60558, 60654), True, 'import numpy as np\n'), ((61312, 61352), 'tensorflow.constant', 'tf.constant', (['[6, 143, 0]'], {'dtype': 'tf.int32'}), '([6, 143, 0], dtype=tf.int32)\n', (61323, 61352), True, 'import tensorflow as tf\n'), ((61364, 61407), 'tensorflow.constant', 'tf.constant', (['[190, 237, -1]'], {'dtype': 'tf.int32'}), '([190, 237, -1], dtype=tf.int32)\n', (61375, 61407), True, 'import tensorflow as tf\n'), ((61419, 61480), 'tensorflow.constant', 'tf.constant', (['[[[0.03, 0.3575, 0.98, 0.95]]]'], {'dtype': 'tf.float32'}), '([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)\n', (61430, 61480), True, 'import tensorflow as tf\n'), ((61824, 61928), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469,\n 1.0]], dtype=np.float32)\n', (61832, 61928), True, 'import numpy as np\n'), ((62572, 62612), 'tensorflow.constant', 'tf.constant', (['[6, 143, 0]'], {'dtype': 'tf.int32'}), '([6, 143, 0], dtype=tf.int32)\n', (62583, 62612), True, 'import tensorflow as tf\n'), ((62624, 62667), 'tensorflow.constant', 'tf.constant', (['[190, 237, -1]'], {'dtype': 'tf.int32'}), '([190, 237, -1], dtype=tf.int32)\n', (62635, 62667), True, 'import tensorflow as tf\n'), ((62679, 62740), 'tensorflow.constant', 'tf.constant', (['[[[0.03, 0.3575, 0.98, 0.95]]]'], {'dtype': 'tf.float32'}), '([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)\n', (62690, 62740), True, 'import tensorflow as tf\n'), ((63105, 63209), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469,\n 1.0]], dtype=np.float32)\n', (63113, 63209), True, 'import numpy as np\n'), ((63261, 63432), 'numpy.array', 'np.array', (['[[[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], [[0.38947368, \n 0.07173], [0.49473682, 0.24050637], [0.60000002, 0.40928277]]]'], {'dtype': 'np.float32'}), '([[[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], [[\n 0.38947368, 0.07173], [0.49473682, 0.24050637], [0.60000002, 0.40928277\n ]]], dtype=np.float32)\n', (63269, 63432), True, 'import numpy as np\n'), ((64604, 64644), 'tensorflow.constant', 'tf.constant', (['[6, 143, 0]'], {'dtype': 'tf.int32'}), '([6, 143, 0], dtype=tf.int32)\n', (64615, 64644), True, 'import tensorflow as tf\n'), ((64656, 64699), 'tensorflow.constant', 'tf.constant', (['[190, 237, -1]'], {'dtype': 'tf.int32'}), '([190, 237, -1], dtype=tf.int32)\n', (64667, 64699), True, 'import tensorflow as tf\n'), ((64711, 64772), 'tensorflow.constant', 'tf.constant', (['[[[0.03, 0.3575, 0.98, 0.95]]]'], {'dtype': 'tf.float32'}), '([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)\n', (64722, 64772), True, 'import tensorflow as tf\n'), ((65562, 65666), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469,\n 1.0]], dtype=np.float32)\n', (65570, 65666), True, 'import numpy as np\n'), ((66833, 66873), 'tensorflow.constant', 'tf.constant', (['[6, 143, 0]'], {'dtype': 'tf.int32'}), '([6, 143, 0], dtype=tf.int32)\n', (66844, 66873), True, 'import tensorflow as tf\n'), ((66885, 66928), 'tensorflow.constant', 'tf.constant', (['[190, 237, -1]'], {'dtype': 'tf.int32'}), '([190, 237, -1], dtype=tf.int32)\n', (66896, 66928), True, 'import tensorflow as tf\n'), ((66940, 67001), 'tensorflow.constant', 'tf.constant', (['[[[0.03, 0.3575, 0.98, 0.95]]]'], {'dtype': 'tf.float32'}), '([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)\n', (66951, 67001), True, 'import tensorflow as tf\n'), ((67798, 67902), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469,\n 1.0]], dtype=np.float32)\n', (67806, 67902), True, 'import numpy as np\n'), ((67963, 68137), 'numpy.array', 'np.array', (['[[[0.38947368, 0.07173], [0.49473682, 0.24050637], [0.60000002, 0.40928277]\n ], [[0.38947368, 0.07173], [0.49473682, 0.24050637], [0.60000002, \n 0.40928277]]]'], {}), '([[[0.38947368, 0.07173], [0.49473682, 0.24050637], [0.60000002, \n 0.40928277]], [[0.38947368, 0.07173], [0.49473682, 0.24050637], [\n 0.60000002, 0.40928277]]])\n', (67971, 68137), True, 'import numpy as np\n'), ((69387, 69427), 'tensorflow.constant', 'tf.constant', (['[6, 143, 0]'], {'dtype': 'tf.int32'}), '([6, 143, 0], dtype=tf.int32)\n', (69398, 69427), True, 'import tensorflow as tf\n'), ((69439, 69482), 'tensorflow.constant', 'tf.constant', (['[190, 237, -1]'], {'dtype': 'tf.int32'}), '([190, 237, -1], dtype=tf.int32)\n', (69450, 69482), True, 'import tensorflow as tf\n'), ((69494, 69555), 'tensorflow.constant', 'tf.constant', (['[[[0.03, 0.3575, 0.98, 0.95]]]'], {'dtype': 'tf.float32'}), '([[[0.03, 0.3575, 0.98, 0.95]]], dtype=tf.float32)\n', (69505, 69555), True, 'import tensorflow as tf\n'), ((70352, 70456), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.0, 0.75789469, 1.0], [0.23157893, 0.24050637, 0.75789469,\n 1.0]], dtype=np.float32)\n', (70360, 70456), True, 'import numpy as np\n'), ((70517, 70643), 'numpy.array', 'np.array', (['[[[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], [[np.nan, np.nan],\n [np.nan, np.nan], [np.nan, np.nan]]]'], {}), '([[[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], [[np.nan,\n np.nan], [np.nan, np.nan], [np.nan, np.nan]]])\n', (70525, 70643), True, 'import numpy as np\n'), ((77150, 77199), 'numpy.array', 'np.array', (['[0.0, 0.5, 0.75, 1.0]'], {'dtype': 'np.float32'}), '([0.0, 0.5, 0.75, 1.0], dtype=np.float32)\n', (77158, 77199), True, 'import numpy as np\n'), ((79133, 79182), 'numpy.array', 'np.array', (['[0.0, 0.5, 0.75, 1.0]'], {'dtype': 'np.float32'}), '([0.0, 0.5, 0.75, 1.0], dtype=np.float32)\n', (79141, 79182), True, 'import numpy as np\n'), ((79212, 79276), 'numpy.array', 'np.array', (['[[0.1, 0.2], [0.2, 0.4], [0.3, 0.6]]'], {'dtype': 'np.float32'}), '([[0.1, 0.2], [0.2, 0.4], [0.3, 0.6]], dtype=np.float32)\n', (79220, 79276), True, 'import numpy as np\n'), ((87667, 87752), 'numpy.all', 'np.all', (['(boxes_[:, 2] - boxes_[:, 0] >= padded_boxes_[:, 2] - padded_boxes_[:, 0])'], {}), '(boxes_[:, 2] - boxes_[:, 0] >= padded_boxes_[:, 2] - padded_boxes_[:, 0]\n )\n', (87673, 87752), True, 'import numpy as np\n'), ((87786, 87871), 'numpy.all', 'np.all', (['(boxes_[:, 3] - boxes_[:, 1] >= padded_boxes_[:, 3] - padded_boxes_[:, 1])'], {}), '(boxes_[:, 3] - boxes_[:, 1] >= padded_boxes_[:, 3] - padded_boxes_[:, 1]\n )\n', (87792, 87871), True, 'import numpy as np\n'), ((90253, 90338), 'numpy.all', 'np.all', (['(boxes_[:, 2] - boxes_[:, 0] >= padded_boxes_[:, 2] - padded_boxes_[:, 0])'], {}), '(boxes_[:, 2] - boxes_[:, 0] >= padded_boxes_[:, 2] - padded_boxes_[:, 0]\n )\n', (90259, 90338), True, 'import numpy as np\n'), ((90372, 90457), 'numpy.all', 'np.all', (['(boxes_[:, 3] - boxes_[:, 1] >= padded_boxes_[:, 3] - padded_boxes_[:, 1])'], {}), '(boxes_[:, 3] - boxes_[:, 1] >= padded_boxes_[:, 3] - padded_boxes_[:, 1]\n )\n', (90378, 90457), True, 'import numpy as np\n'), ((101784, 101810), 'numpy.random.randn', 'np.random.randn', (['*in_shape'], {}), '(*in_shape)\n', (101799, 101810), True, 'import numpy as np\n'), ((102672, 102698), 'numpy.random.randn', 'np.random.randn', (['*in_shape'], {}), '(*in_shape)\n', (102687, 102698), True, 'import numpy as np\n'), ((105867, 105899), 'numpy.random.randn', 'np.random.randn', (['*in_image_shape'], {}), '(*in_image_shape)\n', (105882, 105899), True, 'import numpy as np\n'), ((105927, 105959), 'numpy.random.randn', 'np.random.randn', (['*in_masks_shape'], {}), '(*in_masks_shape)\n', (105942, 105959), True, 'import numpy as np\n'), ((107406, 107438), 'numpy.random.randn', 'np.random.randn', (['*in_image_shape'], {}), '(*in_image_shape)\n', (107421, 107438), True, 'import numpy as np\n'), ((107466, 107498), 'numpy.random.randn', 'np.random.randn', (['*in_masks_shape'], {}), '(*in_masks_shape)\n', (107481, 107498), True, 'import numpy as np\n'), ((111002, 111034), 'numpy.random.randn', 'np.random.randn', (['*in_image_shape'], {}), '(*in_image_shape)\n', (111017, 111034), True, 'import numpy as np\n'), ((111062, 111094), 'numpy.random.randn', 'np.random.randn', (['*in_masks_shape'], {}), '(*in_masks_shape)\n', (111077, 111094), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import logging import utool as ut import numpy as np import vtool as vt import pandas as pd from wbia.algo.graph.nx_utils import ensure_multi_index from wbia.algo.graph.state import POSTV, NEGTV, INCMP print, rrr, profile = ut.inject2(__name__) logger = logging.getLogger('wbia') class Groundtruth(object): def is_comparable(infr, aid_pairs, allow_guess=True): """ Guesses by default when real comparable information is not available. """ if infr.ibs is not None: return infr.wbia_is_comparable(aid_pairs, allow_guess) is_comp = list( infr.gen_edge_values( 'gt_comparable', edges=aid_pairs, default=True, on_missing='default' ) ) return np.array(is_comp) def is_photobomb(infr, aid_pairs): if infr.ibs is not None: return infr.wbia_is_photobomb(aid_pairs) return np.array([False] * len(aid_pairs)) def is_same(infr, aid_pairs): if infr.ibs is not None: return infr.wbia_is_same(aid_pairs) node_dict = ut.nx_node_dict(infr.graph) nid1 = [node_dict[n1]['orig_name_label'] for n1, n2 in aid_pairs] nid2 = [node_dict[n2]['orig_name_label'] for n1, n2 in aid_pairs] return np.equal(nid1, nid2) def apply_edge_truth(infr, edges=None): if edges is None: edges = list(infr.edges()) edge_truth_df = infr.match_state_df(edges) edge_truth = edge_truth_df.idxmax(axis=1).to_dict() infr.set_edge_attrs('truth', edge_truth) infr.edge_truth.update(edge_truth) def match_state_df(infr, index): """ Returns groundtruth state based on wbia controller """ index = ensure_multi_index(index, ('aid1', 'aid2')) aid_pairs = np.asarray(index.tolist()) aid_pairs = vt.ensure_shape(aid_pairs, (None, 2)) is_same = infr.is_same(aid_pairs) is_comp = infr.is_comparable(aid_pairs) match_state_df = pd.DataFrame.from_dict( dict( [ (NEGTV, ~is_same & is_comp), (POSTV, is_same & is_comp), (INCMP, ~is_comp), ] ) ) match_state_df.index = index return match_state_df def match_state_gt(infr, edge): if edge in infr.edge_truth: truth = infr.edge_truth[edge] elif hasattr(infr, 'dummy_verif'): truth = infr.dummy_verif._get_truth(edge) else: aid_pairs = np.asarray([edge]) is_same = infr.is_same(aid_pairs)[0] is_comp = infr.is_comparable(aid_pairs)[0] match_state = pd.Series( dict( [ (NEGTV, ~is_same & is_comp), (POSTV, is_same & is_comp), (INCMP, ~is_comp), ] ) ) truth = match_state.idxmax() return truth def edge_attr_df(infr, key, edges=None, default=ut.NoParam): """ constructs DataFrame using current predictions """ edge_states = infr.gen_edge_attrs(key, edges=edges, default=default) edge_states = list(edge_states) if isinstance(edges, pd.MultiIndex): index = edges else: if edges is None: edges_ = ut.take_column(edge_states, 0) else: edges_ = ut.lmap(tuple, ut.aslist(edges)) index = pd.MultiIndex.from_tuples(edges_, names=('aid1', 'aid2')) records = ut.itake_column(edge_states, 1) edge_df = pd.Series.from_array(records) edge_df.name = key edge_df.index = index return edge_df
[ "logging.getLogger", "utool.inject2", "utool.itake_column", "wbia.algo.graph.nx_utils.ensure_multi_index", "numpy.asarray", "numpy.equal", "numpy.array", "utool.take_column", "vtool.ensure_shape", "utool.nx_node_dict", "pandas.MultiIndex.from_tuples", "utool.aslist", "pandas.Series.from_array" ]
[((249, 269), 'utool.inject2', 'ut.inject2', (['__name__'], {}), '(__name__)\n', (259, 269), True, 'import utool as ut\n'), ((279, 304), 'logging.getLogger', 'logging.getLogger', (['"""wbia"""'], {}), "('wbia')\n", (296, 304), False, 'import logging\n'), ((776, 793), 'numpy.array', 'np.array', (['is_comp'], {}), '(is_comp)\n', (784, 793), True, 'import numpy as np\n'), ((1106, 1133), 'utool.nx_node_dict', 'ut.nx_node_dict', (['infr.graph'], {}), '(infr.graph)\n', (1121, 1133), True, 'import utool as ut\n'), ((1297, 1317), 'numpy.equal', 'np.equal', (['nid1', 'nid2'], {}), '(nid1, nid2)\n', (1305, 1317), True, 'import numpy as np\n'), ((1752, 1795), 'wbia.algo.graph.nx_utils.ensure_multi_index', 'ensure_multi_index', (['index', "('aid1', 'aid2')"], {}), "(index, ('aid1', 'aid2'))\n", (1770, 1795), False, 'from wbia.algo.graph.nx_utils import ensure_multi_index\n'), ((1863, 1900), 'vtool.ensure_shape', 'vt.ensure_shape', (['aid_pairs', '(None, 2)'], {}), '(aid_pairs, (None, 2))\n', (1878, 1900), True, 'import vtool as vt\n'), ((3628, 3659), 'utool.itake_column', 'ut.itake_column', (['edge_states', '(1)'], {}), '(edge_states, 1)\n', (3643, 3659), True, 'import utool as ut\n'), ((3678, 3707), 'pandas.Series.from_array', 'pd.Series.from_array', (['records'], {}), '(records)\n', (3698, 3707), True, 'import pandas as pd\n'), ((3552, 3609), 'pandas.MultiIndex.from_tuples', 'pd.MultiIndex.from_tuples', (['edges_'], {'names': "('aid1', 'aid2')"}), "(edges_, names=('aid1', 'aid2'))\n", (3577, 3609), True, 'import pandas as pd\n'), ((2571, 2589), 'numpy.asarray', 'np.asarray', (['[edge]'], {}), '([edge])\n', (2581, 2589), True, 'import numpy as np\n'), ((3425, 3455), 'utool.take_column', 'ut.take_column', (['edge_states', '(0)'], {}), '(edge_states, 0)\n', (3439, 3455), True, 'import utool as ut\n'), ((3514, 3530), 'utool.aslist', 'ut.aslist', (['edges'], {}), '(edges)\n', (3523, 3530), True, 'import utool as ut\n')]
from collections import OrderedDict import numpy as np from pypospack.qoi import Qoi class ThermalExpansion(Qoi): """ Args: temperature_min (float,int): beginning of the temperature range in Kelvin temperature_max (float,int): end of the temperature range in Kelvin temperature_step (float,int): increments of the temperature range in Kelvin time_total (int): total simulation time in fs time_step (int): simulation time step in fs """ def __init__(self,qoi_name,structures, temperature_min=0, temperature_max=2700, temperature_step=100, time_total=10, time_step=0.001, supercell=[5,5,5]): _qoi_name = qoi_name _qoi_type = 'lmps_thermal_expansion' _structures = OrderedDict() _structures['ideal'] = structures['ideal'] Qoi.__init__(self, qoi_name=_qoi_name, qoi_type=_qoi_type, structures=_structures) self.temperature_min = temperature_min self.temperature_max = temperature_max self.temperature_step = temperature_step self.time_total=time_total self.time_step=time_step self.supercell = supercell def determine_tasks(self): T = self.temperature_min while T <= self.temperature_max: if T == 0: _ideal_structure_name = self.structures['ideal'] _ideal_task_type = 'lmps_min_all' _ideal_task_name = '{}.{}'.format( _ideal_structure_name, _ideal_task_type ) _bulk_structure_name = None self.add_task( task_type=_ideal_task_type, task_name=_ideal_task_name, task_structure=_ideal_structure_name, bulk_structure_name=_bulk_structure_name, ) else: _ideal_structure_name = self.structures['ideal'] _ideal_task_type = 'lmps_npt'.format(T) _ideal_task_name = '{}.{}_{}'.format( _ideal_structure_name, _ideal_task_type, T ) _bulk_structure_name = None self.add_task( task_type=_ideal_task_type, task_name=_ideal_task_name, task_structure=_ideal_structure_name, bulk_structure_name=_bulk_structure_name, task_options={ 'temperature':T, 'time_total':self.time_total, 'time_step':self.time_step, 'supercell':self.supercell} ) T = T + self.temperature_step def calculate_thermal_expansion_coefficient(self,temperatures,lattice_constants): assert isinstance(temperatures,list) assert isinstance(lattice_constants,list) T = list(temperatures) a0 = list(lattice_constants) a0_at_0K = a0[0] for i,v in enumerate(a0): a0[i] = v/a0_at_0K-1 T = np.array(temperatures) a0 = np.array(a0) print(T) print(a0) T = T[:,np.newaxis] # T needs to be a column vector # model is y = a*x alpha_L,_,_,_ = np.linalg.lstsq(T,a0) print('alpha_L:{}'.format(alpha_L[0])) return alpha_L[0] def calculate_qois(self,task_results): _prefix = '{}.{}'.format(self.structures['ideal'],self.qoi_type) s = self.structures['ideal'] T = self.temperature_min lattice_constants = OrderedDict() while T <= self.temperature_max: if T == 0: lattice_constants[T] = np.sqrt( task_results["{}.lmps_min_all.a11".format(s)]**2 \ + task_results['{}.lmps_min_all.a12'.format(s)]**2 \ + task_results["{}.lmps_min_all.a13".format(s)]**2 ) else: try: lattice_constants[T] = task_results["{}.lmps_npt_{}.a1".format(s,T)] except KeyError as e: for k,v in task_results.items(): print(k,v) raise T = T + self.temperature_step self.qois = OrderedDict() # add lattice constants at different temperatures for k,v in lattice_constants.items(): self.qois['{}.a0_{}'.format(_prefix,T)] = v _temperatures = [k for k,v in lattice_constants.items()] _lattice_constants = [v for k,v in lattice_constants.items()] # add thermal expansion coefficient self.qois['{}.thermal_expansion_coefficient'.format(_prefix)] = \ self.calculate_thermal_expansion_coefficient( temperatures=_temperatures, lattice_constants=_lattice_constants )
[ "numpy.array", "collections.OrderedDict", "pypospack.qoi.Qoi.__init__", "numpy.linalg.lstsq" ]
[((819, 832), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (830, 832), False, 'from collections import OrderedDict\n'), ((893, 980), 'pypospack.qoi.Qoi.__init__', 'Qoi.__init__', (['self'], {'qoi_name': '_qoi_name', 'qoi_type': '_qoi_type', 'structures': '_structures'}), '(self, qoi_name=_qoi_name, qoi_type=_qoi_type, structures=\n _structures)\n', (905, 980), False, 'from pypospack.qoi import Qoi\n'), ((3368, 3390), 'numpy.array', 'np.array', (['temperatures'], {}), '(temperatures)\n', (3376, 3390), True, 'import numpy as np\n'), ((3404, 3416), 'numpy.array', 'np.array', (['a0'], {}), '(a0)\n', (3412, 3416), True, 'import numpy as np\n'), ((3576, 3598), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['T', 'a0'], {}), '(T, a0)\n', (3591, 3598), True, 'import numpy as np\n'), ((3900, 3913), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3911, 3913), False, 'from collections import OrderedDict\n'), ((4604, 4617), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4615, 4617), False, 'from collections import OrderedDict\n')]
import sys import math import random from collections import namedtuple import time from pyrf.util import (compute_usable_bins, adjust_usable_fstart_fstop, trim_to_usable_fstart_fstop, find_saturation) import numpy as np from twisted.internet import defer from pyrf.numpy_util import compute_fft import struct MAXIMUM_SPP = 32768 class correction_vector_acquire(object): data_buffer = "" v_type = "SIGNAL" dut = None complete_buffer = False d = None offset = 0 size = 0 transfer_size = 16*1024 def get_vector_loop(self, data): self.data_buffer = b"".join([self.data_buffer, data]) self.offset += len(data) if self.offset >= self.size: # we have gotten all out data, return this object if self.d is not None: self.d.callback(self) else: # more data, grab another set of data data1 = self.dut.correction_data(self.v_type, self.offset, self.transfer_size) # and add this function to the call back data1.addCallback(self.get_vector_loop) def get_vector_data(self, size): # We got out size if size is None: # size is return None threw our created deffered in get_vector if self.d is not None: self.d.callback(None) return self.size = int(size) if self.size == 0: if self.d is not None: self.d.callback(None) return if self.size < self.transfer_size: self.transfer_size = self.size # Grab our first set of data (deffered) data = self.dut.correction_data(self.v_type, self.offset, self.transfer_size) # add the self.get_vector_loop call back data.addCallback(self.get_vector_loop) # what happens to error back here? def error_b(self, failure): if self.d is not None: self.d.callback(None) return None def get_vector(self, v_type=None): # self.v_type = v_type self.offset = 0 self.data_buffer = "" # Create a defered d = defer.Deferred() self.d = d # get our size (deffered) size = self.dut.correction_size(self.v_type) size.addCallback(self.get_vector_data) size.addErrback(self.error_b) # return our deferred return d class correction_vector(object): correction_vectors = None frequency_index = None digest = None def __init__(self): self.frequency_index = [] self.dy = np.dtype(np.int32) self.dy = self.dy.newbyteorder('>') self.correction_vectors = {} def _binary_search(self, freq): # Simple binary search, modified to work the object's datastructure lo = 0 hi = len(self.frequency_index) while lo < hi: mid = (lo + hi) // 2 if self.frequency_index[mid][0] * 1e3 < freq: lo = mid + 1 else: hi = mid return lo def _interp(self, in_array, number_of_points): # array index of our orignal from 0 to size of vector - 1 x = np.arange(0.0, self.vector_size, 1.0) # our new index z = np.linspace(0.0, self.vector_size - 1, number_of_points) # interpolate to get our new vector array out_array = np.interp(z, x, in_array) return out_array def get_correction_vector(self, freq, number_of_points): # binary search, retunrs our index index = self._binary_search(freq) # get the case where we go off the end if index == len(self.frequency_index): index = index - 1 # get our vector vector = self.correction_vectors[self.frequency_index[index][1]] # convert from micro db to db vector = vector / 1000000.0 # interpolate our vector to the wanted size resampled_vector = self._interp(vector, number_of_points) return resampled_vector def buffer_to_vector(self, buffer_in): if buffer_in is None: raise ValueError if len(buffer_in) < 8 + 40: raise ValueError # Get the first 8 bytes offset = 0 size = 8 input_buffer = buffer_in[offset:offset + size] version, freq_num, vector_num, self.vector_size = struct.unpack("!HHHH", input_buffer) offset = size # Ignore the next 40 bytes, as not used know offset += 40 # grab our frequency list size = 6 * freq_num input_buffer = buffer_in[offset:offset + size] offset += size if len(input_buffer) < size: raise ValueError # loop over our buffer, adding a frequency pair to the array for i in range(freq_num): freq, index = struct.unpack("!LH", input_buffer[i*6:i*6+6]) self.frequency_index.append([freq, index]) # grab our correction vectors for i in range(vector_num): # Grab out index size = 2 input_buffer = buffer_in[offset:offset + size] index = struct.unpack(">H", input_buffer)[0] offset += size # get our correction vector size = 4 * self.vector_size input_buffer = buffer_in[offset:offset + size] micro_db = np.frombuffer(input_buffer, dtype=self.dy, count=self.vector_size) self.correction_vectors[index] = micro_db offset += size class SweepDeviceError(Exception): """ Exception for the sweep device to state an error() has occured """ pass class SweepSettings(object): """ An object used to keep track of the sweep settings """ def __init__(self): # start frequency of the results we will eventually return self.bandstart = 0.0 # stop frequency of the results we will eventually return self.bandstop = 0.0 # sweep entry's start frequency self.fstart = 0.0 # sweep entry's stop frequency self.fstop = 0.0 # sweep entry frequency step self.fstep = 0.0 # sweep entry's RFE mode self.rfe_mode = None # determine if a second entry is required self.dd_mode = False # determines if a non dd entry is needed self.beyond_dd = True # entry attenuation self.attenuation = 0 # entry ppb self.ppb = 1 # sweep entry's spp self.spp = 0.0 # sweep capture iterations self.iterations = 0 # expected spectral points self.spectral_points = 0 # determines if a sweep entry is required at the end self.make_end_entry = False # determine the frequency of the end entry self.end_entry_freq = 0.0 # how many steps are in this sweep self.step_count = 0 # what's the actual RBW of what we're capturing self.rbw = 0 def __str__(self): return "SweepSettings[ bandstart = %d, bandstop = %d, fstart = %d, fstop = %d, fstep = %d, step_count = %d, rfe_mode = %s, dd_mode = %s, beyond_dd = %s, attenuation = %s, ppb = %d, spp = %d, iterations = %d, spectral_points = %d, make_end_entry = %s, end_entry_freq = %d, rbw = %f ]" % (self.bandstart, self.bandstop, self.fstart, self.fstop, self.fstep, self.step_count, self.rfe_mode, self.dd_mode, self.beyond_dd, self.attenuation, self.ppb, self.spp, self.iterations, self.spectral_points, self.make_end_entry, self.end_entry_freq, self.rbw) class SweepPlanner(object): """ An object that plans a sweep based on given paramaters. :param dev_prop: the sweep device properties :type dev_prop: dict """ def __init__(self, dev_prop): self.dev_properties = dev_prop self._prev_settings = SweepSettings() def plan_sweep(self, fstart, fstop, rbw, mode, dev_settings = {}): """ Plan the sweep given the inputs """ # initialize the sweep settings variable sweep_settings = SweepSettings() # assign the sweep mode and start/stop sweep_settings.rfe_mode = mode sweep_settings.bandstart = fstart sweep_settings.bandstop = fstop if 'attenuator' in dev_settings: sweep_settings.attenuation = dev_settings['attenuator'] # grab the usable bw of the current mode usable_bw = self.dev_properties.USABLE_BW[mode] # calculate the required SPP to get the RBW desired sweep_settings.spp = self.dev_properties.FULL_BW[mode] / rbw # find closest multiple of 32 because hardware sweep_settings.spp = int(32 * round(float(sweep_settings.spp) / 32)) # double the points for SH/SHN mode if mode in ['SH', 'SHN']: sweep_settings.spp = sweep_settings.spp * 2 # if we're using zif mode, but we have a DD entry, we have half the SPP avaible, since DD is I-only and ZIF is IQ if (mode == 'ZIF') and sweep_settings.dd_mode: maxspp = self.dev_properties.MAX_SPP / 2 else: maxspp = self.dev_properties.MAX_SPP # adjust SPP if it's too big sweep_settings.spp = min(maxspp, sweep_settings.spp) # figure out our actual RBW (account for real vs complex data) sweep_settings.rbw = self.dev_properties.FULL_BW[mode] / sweep_settings.spp if not (mode == 'ZIF'): sweep_settings.rbw = sweep_settings.rbw * 2 # make sure our result is atleast 1 RBW big if (sweep_settings.bandstop - sweep_settings.bandstart) < sweep_settings.rbw: fstop = sweep_settings.bandstart + sweep_settings.rbw sweep_settings.bandstop = fstop # change fstart and stop by a bit to account for floating point errors # TODO: make this take into account tuning resolution fstart -= sweep_settings.rbw * 4 fstop += sweep_settings.rbw * 4 # calculate fstart frequency if fstart < self.dev_properties.MIN_TUNABLE[mode]: sweep_settings.dd_mode = True sweep_settings.fstart = self.dev_properties.MIN_TUNABLE[mode] + (usable_bw / 2) sweep_settings.step_count += 1 # make sure we don't accidentally make an fstart that's beyond our tuning range elif (fstart + (usable_bw / 2)) > self.dev_properties.MAX_TUNABLE[mode]: sweep_settings.dd_mode = False sweep_settings.fstart = self.dev_properties.MAX_TUNABLE[mode] - (usable_bw / 2) else: sweep_settings.dd_mode = False sweep_settings.fstart = fstart + (usable_bw / 2) # check if non-dd mode is required if fstop <= self.dev_properties.MIN_TUNABLE[mode]: sweep_settings.beyond_dd = False else: sweep_settings.beyond_dd = True sweep_settings.step_count += 1 # assign the sweep entry's step frequency reducing by a couple rbw to account for floating point errors # TODO: make this take into account tuning resolution sweep_settings.fstep = usable_bw - (sweep_settings.rbw * 4) # calculate the fstop of the sweep entry from fstart and how many usable_bw's we need fspan = fstop - sweep_settings.fstart - sweep_settings.rbw required_steps = round(fspan / sweep_settings.fstep) sweep_settings.fstop = sweep_settings.fstart + (required_steps * sweep_settings.fstep) sweep_settings.step_count += required_steps # make sure fstop is lower than max tunable # - it can sometimes be higher if an fstart is chosen, such that our # fstep causes our fstop to go beyond fmax to cover all the band required sweep_settings.make_end_entry = False sweep_settings.end_entry_freq = 0 if sweep_settings.fstop > self.dev_properties.MAX_TUNABLE[mode]: # go back one step sweep_settings.fstop -= sweep_settings.fstep # add an entry for fmax sweep_settings.make_end_entry = True sweep_settings.end_entry_freq = self.dev_properties.MAX_TUNABLE[mode] - (usable_bw / 2) # calculate the expected number of spectral bins required for the SweepEntry sweep_settings.spectral_points = int(round((sweep_settings.bandstop - sweep_settings.bandstart) / sweep_settings.rbw)) # return the sweep_settings return sweep_settings class SweepDevice(object): """ Virtual device that generates power spectrum from a given frequency range by sweeping the frequencies with a real device and piecing together the FFT results. :param real_device: the RF device that will be used for capturing data, typically a :class:`pyrf.devices.thinkrf.WSA` instance. :param async_callback: a callback to use for async operation (not used if *real_device* is using a blocking :class:`PlainSocketConnector`) """ # keep track of the mode rfe_mode = None # keep track of the fstart/fstop and rbw fstart = None fstop = None rbw = None # keep track of non-standard device settings device_settings = None # keep track of whether DD mode is needed dd_mode = False # keep track of the sweep settings _sweep_settings = None # keep track of the packet count packet_count = 0 # determine if a new entry is required _new_entry = True # array to place spectral data spectral_data = [] capture_count = 0 sp_corr_obj = None nf_corr_obj = None _flattening_enabled = True def __init__(self, real_device, async_callback=None): # init log string self.logstr = '' self.logtype = 'NONE' # initialize the real device self.real_device = real_device # request read permission from device self.real_device.request_read_perm() # keep track of the device properties self.dev_properties = self.real_device.properties # initialize the geolocation callback self._geo_callback_func = None self._geo_callback_data = None # initialize the sweep planner self._sweep_planner = SweepPlanner(self.dev_properties) # make sure user passes async callback if the device has async connector if real_device.async_connector(): if not async_callback: raise SweepDeviceError( "async_callback required for async operation") # disable receiving data until we are expecting it real_device.set_async_callback(None) # Function to be called when async data is done capturing def _save_correction_vector(data_buffer): if data_buffer is None: return None try: if data_buffer.v_type == "SIGNAL": self.sp_corr_obj = correction_vector() self.sp_corr_obj.buffer_to_vector(data_buffer.data_buffer) elif data_buffer.v_type == "NOISE": self.nf_corr_obj = correction_vector() self.nf_corr_obj.buffer_to_vector(data_buffer.data_buffer) except AttributeError: if data_buffer.v_type == "SIGNAL": self.sp_corr_obj = None elif data_buffer.v_type == "NOISE": self.nf_corr_obj = None # function to catch the errback of the async code. Used to handle # the case when we can get the correction vectors. def _catch_timeout(failure): failure.trap(IOError) return None vector_obj = correction_vector_acquire() vector_obj.dut = real_device vector_obj1 = correction_vector_acquire() vector_obj1.dut = real_device d1 = vector_obj.get_vector("NOISE") d1.addCallback(_save_correction_vector) d1.addErrback(_catch_timeout) d2 = vector_obj1.get_vector("SIGNAL") d2.addCallback(_save_correction_vector) d2.addErrback(_catch_timeout) else: # make sure user doesnt pass async callback if the connector uses blocking sockets if async_callback: raise SweepDeviceError( "async_callback not applicable for sync operation") def _get_correction(dut, v_type=None): if v_type.upper() == "SIGNAL" or v_type.upper() == "NOISE": v_type = v_type.upper() else: raise ValueError max_buf_size = 16*1024 offset = 0 bin_data = "" try: signal_size = dut.correction_size(v_type) except (IOError, OSError): # this will handle socket.error's raise ValueError # We have nothing to transfer if signal_size == 0: return None # check to see if tere is more data than can be transfer in one # go if signal_size > max_buf_size: # if so transfer our max buffer size transfer_size = max_buf_size else: # if not grab only what we need transfer_size = signal_size # While we still have data remaining while offset < signal_size: # get the data data_buffer = dut.correction_data(v_type, offset, transfer_size) # figure out how many bytes were transfered transfered = len(data_buffer) # append the data to the buffer of what we have allready # got bin_data = b"".join([bin_data, data_buffer]) # increase the offset offset = offset + transfered return bin_data self.sp_corr_obj = correction_vector() try: self.sp_corr_obj.buffer_to_vector(_get_correction(self.real_device, "SIGNAL")) except ValueError: self.sp_corr_obj = None self.nf_corr_obj = correction_vector() try: self.nf_corr_obj.buffer_to_vector(_get_correction(self.real_device, "NOISE")) except ValueError: self.nf_corr_obj = None self.async_callback = async_callback self.continuous = False # init the sweep id self._next_sweep_id = 0 # init last finished (technically, it hasn't finished, but for our purposes, it has) self._last_finished = True # Private function def log(self, firstmsg, *msgs): if self.logtype == 'LOG': self.logstr += firstmsg.__str__() for msg in msgs: self.logstr += ", " self.logstr += msg.__str__() self.logstr += "\n" elif self.logtype == 'PRINT': sys.stdout.write(firstmsg.__str__()) for msg in msgs: sys.stdout.write(", ") sys.stdout.write(msg.__str__()) sys.stdout.write("\n") def enable_flattening(self, enable=None): """ :param enable: enable or disable spectral flattening :type enable: bool or None """ if enable is None: return self._flattening_enabled else: self._flattening_enabled = enable def set_geolocation_callback(self, func, data = None): """ set a callback that will get called whenever the geolocation information of the device is updated. The callback function should accept two parameters. The first parameter will be the callback data that was passed in this function set_geolocation_callback(func, data, geolocation_dictionary). The geolocation_dictionary will have the following properties: - oui - seconds - altitude - longitude - speedoverground - secondsfractional - track - latitude - magneticvariation - heading See the programmer's guide for usage on each of these properties. :param func: the function to be called :param data: the data to be passed to the function :returns: None """ self._geo_callback_func = func self._geo_callback_data = data def capture_power_spectrum(self, fstart, fstop, rbw, device_settings=None, mode='SH', continuous=False): """ Initiate a data capture from the *real_device* by setting up a sweep list and starting a single sweep, and then return power spectral density data along with the **actual** sweep start and stop frequencies set (which might not be exactly the same as the requested *fstart* and *fstop*). .. note:: This function does not pipeline, and if the last sweep isn't received before starting a new one, it will generate a failure. :param int fstart: sweep starting frequency in Hz :param int fstop: sweep ending frequency in Hz :param float rbw: the resolution bandwidth (RBW) in Hz of the data to be captured (output RBW may be smaller than requested) :param device_settings: attenuation and other device settings :type device_settings: dict :param str mode: sweep mode, 'ZIF', 'SH', or 'SHN' :param bool continuous: set sweep to be continuously or not (once only) :returns: fstart, fstop, power_data """ self.log("- capture_power_spectrum", fstart, fstop, rbw, device_settings, mode, continuous) if continuous and not self.async_callback: raise SweepDeviceError( "continuous mode only applies to async operation") # see if the last sweep has finished if not self._last_finished: raise SweepDeviceError( "previous sweep must have finished before starting a new one") self._last_finished = False # increment the sweep id if self._next_sweep_id < 0x00000000ffffffff: self._next_sweep_id += 1 else: self._next_sweep_id = 0 # keep track if this is a continuous sweep self.continuous = continuous # plan the sweep self._sweep_planner = SweepPlanner(self.dev_properties) self._sweep_settings = self._sweep_planner.plan_sweep(fstart, fstop, rbw, mode, device_settings) self.log("self._sweep_settings = %s" % self._sweep_settings) # remember our last sweep for optimization purposes self._last_sweep = (fstart, fstop, rbw, mode, device_settings, continuous) # configure the device with the sweep_settings self.real_device.sweep_clear() self.real_device.sweep_add(self._sweep_settings) # configure the iteration self.real_device.sweep_iterations(1) # capture the sweep data return self._perform_full_sweep() def _perform_full_sweep(self): # perform the sweep using async socket if self.async_callback: # set the async callback self.real_device.set_async_callback(self._vrt_receive) # start the sweep sequence self._start_sweep() return # perform sweep using blocking sockets self._start_sweep() result = None while result is None: result = self._vrt_receive(self.real_device.read()) return result def _start_sweep(self): self._vrt_context = {} # initialize the array we'll use to hold results self.spectral_data = np.zeros(self._sweep_settings.spectral_points) # keep track of packets recieved self.packet_count = 0 self.real_device.sweep_start(self._next_sweep_id) def _vrt_receive(self, packet): # context packet just update our context dictionary if packet.is_context_packet(): # look for any geolocation info geo = { } for field in [ 'latitude', 'longitude', 'altitude', 'speedoverground', 'heading', 'track', 'magneticvariation' ]: if field in packet.fields: geo[field] = packet.fields[field] if geo and self._geo_callback_func: # execute callback func = self._geo_callback_func func(self._geo_callback_data, geo) self._vrt_context.update(packet.fields) self.log(packet) return # check to see if we recieved our sweep ID if not ('sweepid' in self._vrt_context): return # make sure we are receiving packets for the right sweep if not (self._vrt_context['sweepid'] == self._next_sweep_id): raise SweepDeviceError("data packets received before start of sweep received! cur = %d, next = %d" % (self._vrt_context['sweepid'], self._next_sweep_id)) # increment the packet count self.packet_count += 1 self.log("#%d of %d - %s" % (self.packet_count, self._sweep_settings.step_count, packet)) # retrieve the frequency and usable BW of the packet packet_freq = self._vrt_context['rffreq'] usable_bw = self.dev_properties.USABLE_BW[self._sweep_settings.rfe_mode] # compute the fft pow_data = compute_fft(self.real_device, packet, self._vrt_context) # calc rbw for this packet rbw = float(self.dev_properties.FULL_BW[self._sweep_settings.rfe_mode]) / len(pow_data) self.log("rbw = %f, %f" % (rbw, self._sweep_settings.rbw)) if self._flattening_enabled: # Check if we are above 50 MHz and in SH mode if packet_freq >= 50e6 and self._sweep_settings.rfe_mode == "SH": number_of_points = len(pow_data) # check if we have correction vectors (Noise) if self.nf_corr_obj is not None: # if so grab them nf_cal = \ self.nf_corr_obj.get_correction_vector(packet_freq, number_of_points) else: # if no set it to 0 nf_cal = np.zeros(number_of_points) # check if we have corrrection vectors (Spectrum) if self.sp_corr_obj is not None: # if so grab them sp_cal = \ self.sp_corr_obj.get_correction_vector(packet_freq, number_of_points) else: # if not set it to 0 sp_cal = np.zeros(number_of_points) # if the data is spectraly inverted, invert the vectors if packet.spec_inv: nf_cal = np.flipud(nf_cal) sp_cal = np.flipud(sp_cal) # calculate the correction threshold correction_thresh = (-135.0 + ((10.0 * packet_freq / 1e6) / 27000.0) + 10.0 * np.log10(rbw) + self._sweep_settings.attenuation) # creat the spectrum. per bin, if the ampltitude is above # correction threshold do pow_data - sp_cal else do pow_data - # nf_cal pow_data = np.where(pow_data < correction_thresh, pow_data - nf_cal, pow_data - sp_cal) # check if DD mode was used in this sweep if self.packet_count == 1 and self._sweep_settings.dd_mode: # copy the data into the result array self._copy_data(0, self.dev_properties.FULL_BW['DD'], pow_data, self._sweep_settings.bandstart, self._sweep_settings.bandstop, self.spectral_data); if self._sweep_settings.beyond_dd: return else: return self._emit_data() # determine the usable bins in this config self.log("===> compute_usable_bins()", self._sweep_settings.rfe_mode, self._sweep_settings.spp, 1, 0) usable_bins = compute_usable_bins(self.dev_properties, self._sweep_settings.rfe_mode, self._sweep_settings.spp, 1, 0) self.log("<--- usable_bins", usable_bins) # adjust the usable range based on spectral inversion self.log("===> adjust_usable_fstart_fstop()", "self.dev_properties", self._sweep_settings.rfe_mode, len(pow_data) * 2, 1, packet_freq, packet.spec_inv, usable_bins) usable_bins, packet_start, packet_stop = adjust_usable_fstart_fstop(self.dev_properties, self._sweep_settings.rfe_mode, len(pow_data) * 2, 1, packet_freq, packet.spec_inv, usable_bins) self.log("<--- adjust_usable_fstart_fstop", packet_start, packet_stop, usable_bins) # # WARNING: the start and stop returned from this function are HIGHLY sketchy # # calculate packet frequency range #packet_start = packet_freq - (self.dev_properties.FULL_BW[self._sweep_settings.rfe_mode] / 2) #packet_stop = packet_freq + (self.dev_properties.FULL_BW[self._sweep_settings.rfe_mode] / 2) #print "packet start/stop", packet_start, packet_stop #trim the FFT data, note decimation is 1, fshift is 0 self.log("===> trim_to_usable_fstart_fstop()", "pow_data", usable_bins, packet_start, packet_stop) trimmed_spectrum, edge_data, usable_start, usable_stop = trim_to_usable_fstart_fstop(pow_data, usable_bins, packet_start, packet_stop) self.log("<--- trim_to_usable_fstart_fstop", usable_start, usable_stop, "trimmed_spectrum", edge_data) # copy the data self._copy_data(usable_start, usable_stop, trimmed_spectrum, self._sweep_settings.bandstart, self._sweep_settings.bandstop, self.spectral_data); # if there's no more packets, emit result if self.packet_count == self._sweep_settings.step_count: return self._emit_data() # all done return def _emit_data(self): # note that we finished this sweep self._last_finished = True # if async callback is available, emit the data if self.async_callback: self.async_callback(self._sweep_settings.bandstart, self._sweep_settings.bandstop, self.spectral_data) return # return the values if using blocking sockets else: return (self._sweep_settings.bandstart, self._sweep_settings.bandstop, self.spectral_data) def _copy_data(self, src_fstart, src_fstop, src_psd, dst_fstart, dst_fstop, dst_psd): self.log("_copy_data(%d, %d, src_psd, %d, %d, dst_psd)" % (src_fstart, src_fstop, dst_fstart, dst_fstop)) # calc src len and dst len srclen = len(src_psd) dstlen = len(dst_psd) self.log("len -- src = %d, dst = %d" % (srclen, dstlen)) # calc src and dest rbw srcrbw = float(src_fstop - src_fstart) / srclen dstrbw = float(dst_fstop - dst_fstart) / dstlen self.log("rbw = %f, %f, %f" % (srcrbw, dstrbw, self._sweep_settings.rbw)) # check if packet start is before sweep start. shouldn't happen, but check anyway self.log("boundary(start) = %f / %f" % (src_fstart, dst_fstart)) if src_fstart < dst_fstart: self.log("foo") src_start_bin = int(float(dst_fstart - src_fstart) / srcrbw) else: self.log("bar") src_start_bin = 0 # check if packet stop is after sweep stop. this means we don't need the whole packet self.log("boundary(stop) = %f / %f" % (src_fstop, dst_fstop)) if src_fstop > dst_fstop: self.log("foo") src_stop_bin = srclen - int(float(src_fstop - dst_fstop) / srcrbw) else: self.log("bar") src_stop_bin = srclen # how many values are we copying? tocopy = src_stop_bin - src_start_bin # calculate dest start index if src_fstart < dst_fstart: dst_start_bin = 0 else: dst_start_bin = int(round(float(src_fstart - dst_fstart) / dstrbw)) # calculate dest stop index dst_stop_bin = dst_start_bin + tocopy if dst_stop_bin > dstlen: dst_stop_bin = dstlen # adjust tocopy tocopy = dst_stop_bin - dst_start_bin # adjust src stop bin because we adjusted tocopy src_stop_bin = src_start_bin + tocopy # copy the data, if there's data that needs copying if ((dst_stop_bin - dst_start_bin) > 0) and ((src_stop_bin - src_start_bin) > 0): self.log("dst_psd[%d:%d] = src_psd[%d:%d]" % (dst_start_bin, dst_stop_bin, src_start_bin, src_stop_bin)) dst_psd[dst_start_bin:dst_stop_bin] = src_psd[src_start_bin:src_stop_bin]
[ "numpy.log10", "numpy.arange", "pyrf.util.compute_usable_bins", "numpy.where", "numpy.flipud", "pyrf.util.trim_to_usable_fstart_fstop", "pyrf.numpy_util.compute_fft", "numpy.linspace", "struct.unpack", "numpy.zeros", "numpy.interp", "numpy.frombuffer", "numpy.dtype", "twisted.internet.defer.Deferred", "sys.stdout.write" ]
[((2239, 2255), 'twisted.internet.defer.Deferred', 'defer.Deferred', ([], {}), '()\n', (2253, 2255), False, 'from twisted.internet import defer\n'), ((2682, 2700), 'numpy.dtype', 'np.dtype', (['np.int32'], {}), '(np.int32)\n', (2690, 2700), True, 'import numpy as np\n'), ((3283, 3320), 'numpy.arange', 'np.arange', (['(0.0)', 'self.vector_size', '(1.0)'], {}), '(0.0, self.vector_size, 1.0)\n', (3292, 3320), True, 'import numpy as np\n'), ((3357, 3413), 'numpy.linspace', 'np.linspace', (['(0.0)', '(self.vector_size - 1)', 'number_of_points'], {}), '(0.0, self.vector_size - 1, number_of_points)\n', (3368, 3413), True, 'import numpy as np\n'), ((3484, 3509), 'numpy.interp', 'np.interp', (['z', 'x', 'in_array'], {}), '(z, x, in_array)\n', (3493, 3509), True, 'import numpy as np\n'), ((4480, 4516), 'struct.unpack', 'struct.unpack', (['"""!HHHH"""', 'input_buffer'], {}), "('!HHHH', input_buffer)\n", (4493, 4516), False, 'import struct\n'), ((24410, 24456), 'numpy.zeros', 'np.zeros', (['self._sweep_settings.spectral_points'], {}), '(self._sweep_settings.spectral_points)\n', (24418, 24456), True, 'import numpy as np\n'), ((26125, 26181), 'pyrf.numpy_util.compute_fft', 'compute_fft', (['self.real_device', 'packet', 'self._vrt_context'], {}), '(self.real_device, packet, self._vrt_context)\n', (26136, 26181), False, 'from pyrf.numpy_util import compute_fft\n'), ((29019, 29126), 'pyrf.util.compute_usable_bins', 'compute_usable_bins', (['self.dev_properties', 'self._sweep_settings.rfe_mode', 'self._sweep_settings.spp', '(1)', '(0)'], {}), '(self.dev_properties, self._sweep_settings.rfe_mode,\n self._sweep_settings.spp, 1, 0)\n', (29038, 29126), False, 'from pyrf.util import compute_usable_bins, adjust_usable_fstart_fstop, trim_to_usable_fstart_fstop, find_saturation\n'), ((30885, 30962), 'pyrf.util.trim_to_usable_fstart_fstop', 'trim_to_usable_fstart_fstop', (['pow_data', 'usable_bins', 'packet_start', 'packet_stop'], {}), '(pow_data, usable_bins, packet_start, packet_stop)\n', (30912, 30962), False, 'from pyrf.util import compute_usable_bins, adjust_usable_fstart_fstop, trim_to_usable_fstart_fstop, find_saturation\n'), ((4951, 5002), 'struct.unpack', 'struct.unpack', (['"""!LH"""', 'input_buffer[i * 6:i * 6 + 6]'], {}), "('!LH', input_buffer[i * 6:i * 6 + 6])\n", (4964, 5002), False, 'import struct\n'), ((5484, 5550), 'numpy.frombuffer', 'np.frombuffer', (['input_buffer'], {'dtype': 'self.dy', 'count': 'self.vector_size'}), '(input_buffer, dtype=self.dy, count=self.vector_size)\n', (5497, 5550), True, 'import numpy as np\n'), ((5257, 5290), 'struct.unpack', 'struct.unpack', (['""">H"""', 'input_buffer'], {}), "('>H', input_buffer)\n", (5270, 5290), False, 'import struct\n'), ((19649, 19671), 'sys.stdout.write', 'sys.stdout.write', (['"""\n"""'], {}), "('\\n')\n", (19665, 19671), False, 'import sys\n'), ((28262, 28338), 'numpy.where', 'np.where', (['(pow_data < correction_thresh)', '(pow_data - nf_cal)', '(pow_data - sp_cal)'], {}), '(pow_data < correction_thresh, pow_data - nf_cal, pow_data - sp_cal)\n', (28270, 28338), True, 'import numpy as np\n'), ((19566, 19588), 'sys.stdout.write', 'sys.stdout.write', (['""", """'], {}), "(', ')\n", (19582, 19588), False, 'import sys\n'), ((27039, 27065), 'numpy.zeros', 'np.zeros', (['number_of_points'], {}), '(number_of_points)\n', (27047, 27065), True, 'import numpy as np\n'), ((27508, 27534), 'numpy.zeros', 'np.zeros', (['number_of_points'], {}), '(number_of_points)\n', (27516, 27534), True, 'import numpy as np\n'), ((27673, 27690), 'numpy.flipud', 'np.flipud', (['nf_cal'], {}), '(nf_cal)\n', (27682, 27690), True, 'import numpy as np\n'), ((27720, 27737), 'numpy.flipud', 'np.flipud', (['sp_cal'], {}), '(sp_cal)\n', (27729, 27737), True, 'import numpy as np\n'), ((27970, 27983), 'numpy.log10', 'np.log10', (['rbw'], {}), '(rbw)\n', (27978, 27983), True, 'import numpy as np\n')]
# Import libraries and set random seeds for reproducibility random_seed = 1237 import random random.seed( random_seed ) import numpy as np np.random.seed( random_seed ) import tensorflow as tf tf.set_random_seed( random_seed ) # Import model and instance loader import model from instance_loader import InstanceLoader import os, sys, itertools, util from scipy import stats METRICS_LIST = [ "ABS", "REL", "KENDALLTAUB", "KENDALLTAUB_P", "PEARSON", "PEARSON_P" ] def get_metrics_from_batch( predictions_list, labels_list ): """ Gets all the metrics from a batch for a specific centrality """ bABS, bREL, bKENDALLTAUB, bKENDALLTAUB_P, bPEARSON, bPEARSON_P = (0 for _ in METRICS_LIST) for predictions, labels in zip( predictions_list, labels_list ): ABS, REL, KENDALLTAUB, KENDALLTAUB_P, PEARSON, PEARSON_P = get_metrics( predictions, labels ) bABS, bREL, bKENDALLTAUB, bKENDALLTAUB_P, bPEARSON, bPEARSON_P = map( lambda pair: pair[0] + pair[1], zip( (bABS, bREL, bKENDALLTAUB, bKENDALLTAUB_P, bPEARSON, bPEARSON_P), ( ABS, REL, KENDALLTAUB, KENDALLTAUB_P, PEARSON, PEARSON_P) ) ) #end for b = len( labels_list ) bABS, bREL, bKENDALLTAUB, bKENDALLTAUB_P, bPEARSON, bPEARSON_P = map( lambda x: x / b, (bABS, bREL, bKENDALLTAUB, bKENDALLTAUB_P, bPEARSON, bPEARSON_P) ) return bABS, bREL, bKENDALLTAUB, bKENDALLTAUB_P, bPEARSON, bPEARSON_P #end get_metrics_batch def get_metrics( predictions, labels ): """ Gets all the metrics for a specific centrality """ ABS = [ abs( p - l ) for p, l in zip( predictions, labels ) ] ABS = sum(ABS) / len(ABS) REL = [ abs( p - l ) / l for p, l in zip( predictions, labels ) if l != 0 ] REL = sum(REL) / len(REL) KENDALLTAUB, KENDALLTAUB_P = stats.kendalltau(predictions,labels) PEARSON, PEARSON_P = stats.pearsonr(predictions,labels) return ABS, REL, KENDALLTAUB, KENDALLTAUB_P, PEARSON, PEARSON_P #end def build_metrics_dict( centralities, header = False, header_prepend = "" ): """ Builds the dictionary used to log the values or the dictionary containing the headers """ metrics_dict = dict() for metric in METRICS_LIST: metrics_dict[metric] = header_prepend + metric if header else 0 for centrality in centralities: centrality_metric = "{c}_{m}".format(c=centrality,m=metric) metrics_dict[centrality_metric] = header_prepend + centrality_metric if header else 0 #end for #end for metrics_dict["loss"] = header_prepend + "loss" if header else 0 for centrality in centralities: centrality_cost = "{c}_cost".format(c=centrality) metrics_dict[centrality_cost] = header_prepend + centrality_cost if header else 0 #end for return metrics_dict #end build_metrics_dict def log_metrics_dict( metrics_dict, centralities, log_file ): """ Log a dictionary to a file. Note that it assumes one will write at least some value before the values being logged in the file and it also doesn't end a line. """ print( "\t{val}".format( val = metrics_dict["loss"] ), end = "", file = log_file ) for centrality in centralities: print( "\t{val}".format( val = metrics_dict["{c}_cost".format(c=centrality)] ), end = "", file = log_file ) #end for for metric in METRICS_LIST: print( "\t{val}".format( val = metrics_dict[metric] ), end = "", file = log_file ) #end for for centrality in centralities: for metric in METRICS_LIST: print( "\t{val}".format( val = metrics_dict["{c}_{m}".format(c=centrality,m=metric)] ), end = "", file = log_file ) #end for #end for #end log_metrics_dict def train( session, model_dict, time_steps, centralities, epochs_to_run, train_instance_loader, batch_size, test_batch_size, batches_per_epoch, test_instance_loader, epoch_logging_file, batch_logging_file, model_checkpoint_filename, log_to_stdout = False ): """ Runs the training procedure, logs the metrics and saves the model's weights to a checkpoint after every epoch. """ log_epoch( "epoch_id", build_metrics_dict( centralities, header = True, header_prepend = "train_" ), build_metrics_dict( centralities, header = True, header_prepend = "test_" ), centralities, epoch_logging_file ) log_batch( "epoch_id", "batch_id", build_metrics_dict( centralities, header = True ), centralities, batch_logging_file ) print( "Starting training for {} epochs".format( epochs_to_run ) ) for epoch_id in range( epochs_to_run ): if log_to_stdout: print( "Epoch\t{}".format( epoch_id ), end = "", file = sys.stdout ) log_metrics_dict( build_metrics_dict( centralities, header = True ), centralities, sys.stdout ) print( "", flush = True, file = sys.stdout ) #end if run_epoch( epoch_id, session, model_dict, time_steps, centralities, train_instance_loader, batch_size, test_batch_size if epoch_id != epochs_to_run - 1 else 1, batches_per_epoch, test_instance_loader, epoch_logging_file, batch_logging_file, log_to_stdout = log_to_stdout ) print( "SAVING MODEL WEIGHTS TO {}".format( model_checkpoint_filename ) ) util.save_weights( session, model_checkpoint_filename ) #end for #end train def log_epoch( epoch_id, epoch_train_metrics_dict, epoch_test_metrics_dict, centralities, epoch_logging_file ): # Log the training part of the epoch print( epoch_id, end = "", file = epoch_logging_file ) log_metrics_dict( epoch_train_metrics_dict, centralities, epoch_logging_file ) # Log the testing part of the epoch and flush the line log_metrics_dict( epoch_test_metrics_dict, centralities, epoch_logging_file ) print( "", flush = True, file = epoch_logging_file ) #end log_epoch def run_epoch( epoch_id, session, model_dict, time_steps, centralities, train_instance_loader, batch_size, test_batch_size, batches_per_epoch, test_instance_loader, epoch_logging_file, batch_logging_file, log_to_stdout = False ): """ Runs and logs a training/testing epoch """ # Build the metrics dictionary for logging epoch_train_metrics_dict = build_metrics_dict( centralities ) # Reset instance loader train_instance_loader.reset() for batch_id, batch in itertools.islice( enumerate( train_instance_loader.get_batches( batch_size ) ), batches_per_epoch ): # Run and log every training batch, accumulating the metrics batch_metrics_dict = run_batch( epoch_id, batch_id, session, model_dict, time_steps, centralities, batch, batch_logging_file, train = True, log_to_stdout = log_to_stdout ) for metric in epoch_train_metrics_dict: epoch_train_metrics_dict[metric] += batch_metrics_dict[metric] #end for #end for # Normalize the metrics by the number of batches for metric in epoch_train_metrics_dict: epoch_train_metrics_dict[metric] /= batches_per_epoch #end for # Test # Build the metrics dictionary for logging epoch_test_metrics_dict = build_metrics_dict( centralities ) # Reset instance loader test_instance_loader.reset() # Counter for the number of instances number_of_test_batches = 0 for cbat, batch in enumerate( test_instance_loader.get_batches( test_batch_size ) ): # Open a null file so that we don't log every test instance being ran as a separate batch with open(os.devnull, 'w') as nullfile: # Run and log every test instance, accumulating the metrics batch_metrics_dict = run_batch( epoch_id, "test", session, model_dict, time_steps, centralities, batch, nullfile, train = False, log_to_stdout = log_to_stdout ) #end with for metric in epoch_test_metrics_dict: epoch_test_metrics_dict[metric] += batch_metrics_dict[metric] #end for number_of_test_batches += 1 #end for # Normalize the metrics by the number of test instances for metric in epoch_test_metrics_dict: epoch_test_metrics_dict[metric] /= number_of_test_batches #end for log_epoch( epoch_id, epoch_train_metrics_dict, epoch_test_metrics_dict, centralities, epoch_logging_file ) if log_to_stdout: print( "EPOCH\t", end = "" ) log_epoch( "summary", epoch_train_metrics_dict, epoch_test_metrics_dict, centralities, sys.stdout ) #end if #end run_epoch def log_batch( epoch_id, batch_id, batch_metrics_dict, centralities, batch_logging_file ): print( "{eid}\t{bid}".format( eid = epoch_id, bid = batch_id ), end = "", file = batch_logging_file ) log_metrics_dict( batch_metrics_dict, centralities, batch_logging_file ) print( "", flush = True, file = batch_logging_file ) #end def run_batch( epoch_id, batch_id, session, model_dict, time_steps, centralities, batch, batch_logging_file, train = False, log_to_stdout = False ): """ Runs and logs a batch """ # Build metrics dictionary for logging batch_metrics_dict = build_metrics_dict( centralities ) # Transform sparse batch labels to dense labels = { centrality: util.flatten( batch["{c}".format(c=centrality)] ) for centrality in centralities } # Build the feed_dict feed_dict = { model_dict["{c}_labels".format(c=centrality)]: labels[centrality] for centrality in centralities } feed_dict[ model_dict["gnn"].matrix_placeholders["M"] ] = util.sparse_to_dense( batch["matrix"] ) feed_dict[ model_dict["gnn"].time_steps ] = time_steps feed_dict[ model_dict["nodes_n"] ] = batch["problem_n"] # Train if required if train: returned_values = session.run( model_dict["train_step"], feed_dict = feed_dict ) #end if # Get logits for batch returned_predictions = session.run( [ model_dict["{c}_predictions".format( c = centrality ) ] for centrality in centralities ], feed_dict = feed_dict ) # Get losses for batch returned_losses = session.run( [ model_dict["loss"] ] + [ model_dict["{c}_cost".format( c = centrality ) ] for centrality in centralities ], feed_dict = feed_dict ) # Update the overall loss batch_metrics_dict["loss"] = returned_losses[0] # Update each centrality's value for centrality, predictions, cost in zip( centralities, returned_predictions, returned_losses[1:] ): metric_values = get_metrics_from_batch( model.separate_batch( predictions, batch["problem_n"] ), model.separate_batch( labels[centrality], batch["problem_n"] ) ) # Update loss for the centrality batch_metrics_dict["{c}_cost".format(c=centrality)] = cost # Update every other metric for the centrality for metric, value in zip( METRICS_LIST, metric_values ): batch_metrics_dict["{c}_{m}".format(c=centrality,m=metric)] = value #end for #end for # For every metric, comput the average over the centralities for metric in METRICS_LIST: for centrality in centralities: batch_metrics_dict[metric] += batch_metrics_dict["{c}_{m}".format(c=centrality,m=metric)] #end for batch_metrics_dict[metric] /= len( centralities ) #end for # Log the batch log_batch( epoch_id, batch_id, batch_metrics_dict, centralities, batch_logging_file ) if log_to_stdout: log_batch( "batch", batch_id, batch_metrics_dict, centralities, sys.stdout ) #end if return batch_metrics_dict #end run_batch if __name__ == "__main__": embedding_size = 32 epochs_to_run = 32 batches_per_epoch = 32 batch_size = 32 test_batch_size = 32 time_steps = 32 centralities = sorted( sys.argv[1:] ) if len( centralities ) <= 0: raise ValueError( "No centrality passed" ) #end if for centrality in centralities: if centrality not in [ "betweenness","closeness","degree","eigenvector" ]: raise ValueError( "Centrality {c} not one of the accepted ones.".format( c=centrality ) ) #end if #end for fname = "centrality-" + "-".join( centralities ) # Build model print( "Building model ..." ) GNN = model.model_builder( embedding_size, centralities ) # Load instances with a predefined seed and separate random generator for reproducibility training_instance_loader_random_generator = random.Random( random_seed ) test_instance_loader_random_generator = random.Random( random_seed ) training_instance_loader = InstanceLoader("./instances", rng = training_instance_loader_random_generator ) test_instance_loader = InstanceLoader("./test-instances", rng = test_instance_loader_random_generator ) epoch_logging_file = open( "{fname}.epoch.log".format( fname = fname ), "w" ) batch_logging_file = open( "{fname}.batch.log".format( fname = fname ), "w" ) model_checkpoint_filename = fname # Disallow GPU use config = tf.ConfigProto( # device_count = {"GPU": 0 }, # inter_op_parallelism_threads = 1, # intra_op_parallelism_threads = 1, gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1/5.2) ) with tf.Session(config=config) as sess: # Initialize global variables print( "Initializing global variables ... " ) sess.run( tf.global_variables_initializer() ) train( sess, GNN, time_steps, centralities, epochs_to_run, training_instance_loader, batch_size, test_batch_size, batches_per_epoch, test_instance_loader, epoch_logging_file, batch_logging_file, model_checkpoint_filename, log_to_stdout = True ) #end Session
[ "instance_loader.InstanceLoader", "util.sparse_to_dense", "random.Random", "model.separate_batch", "tensorflow.Session", "random.seed", "util.save_weights", "tensorflow.global_variables_initializer", "model.model_builder", "numpy.random.seed", "scipy.stats.pearsonr", "tensorflow.set_random_seed", "tensorflow.GPUOptions", "scipy.stats.kendalltau" ]
[((93, 117), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (104, 117), False, 'import random\n'), ((139, 166), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (153, 166), True, 'import numpy as np\n'), ((193, 224), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['random_seed'], {}), '(random_seed)\n', (211, 224), True, 'import tensorflow as tf\n'), ((1769, 1806), 'scipy.stats.kendalltau', 'stats.kendalltau', (['predictions', 'labels'], {}), '(predictions, labels)\n', (1785, 1806), False, 'from scipy import stats\n'), ((1829, 1864), 'scipy.stats.pearsonr', 'stats.pearsonr', (['predictions', 'labels'], {}), '(predictions, labels)\n', (1843, 1864), False, 'from scipy import stats\n'), ((9790, 9827), 'util.sparse_to_dense', 'util.sparse_to_dense', (["batch['matrix']"], {}), "(batch['matrix'])\n", (9810, 9827), False, 'import os, sys, itertools, util\n'), ((12476, 12525), 'model.model_builder', 'model.model_builder', (['embedding_size', 'centralities'], {}), '(embedding_size, centralities)\n', (12495, 12525), False, 'import model\n'), ((12666, 12692), 'random.Random', 'random.Random', (['random_seed'], {}), '(random_seed)\n', (12679, 12692), False, 'import random\n'), ((12737, 12763), 'random.Random', 'random.Random', (['random_seed'], {}), '(random_seed)\n', (12750, 12763), False, 'import random\n'), ((12796, 12872), 'instance_loader.InstanceLoader', 'InstanceLoader', (['"""./instances"""'], {'rng': 'training_instance_loader_random_generator'}), "('./instances', rng=training_instance_loader_random_generator)\n", (12810, 12872), False, 'from instance_loader import InstanceLoader\n'), ((12901, 12978), 'instance_loader.InstanceLoader', 'InstanceLoader', (['"""./test-instances"""'], {'rng': 'test_instance_loader_random_generator'}), "('./test-instances', rng=test_instance_loader_random_generator)\n", (12915, 12978), False, 'from instance_loader import InstanceLoader\n'), ((5512, 5565), 'util.save_weights', 'util.save_weights', (['session', 'model_checkpoint_filename'], {}), '(session, model_checkpoint_filename)\n', (5529, 5565), False, 'import os, sys, itertools, util\n'), ((13422, 13447), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (13432, 13447), True, 'import tensorflow as tf\n'), ((10789, 10842), 'model.separate_batch', 'model.separate_batch', (['predictions', "batch['problem_n']"], {}), "(predictions, batch['problem_n'])\n", (10809, 10842), False, 'import model\n'), ((10874, 10934), 'model.separate_batch', 'model.separate_batch', (['labels[centrality]', "batch['problem_n']"], {}), "(labels[centrality], batch['problem_n'])\n", (10894, 10934), False, 'import model\n'), ((13358, 13412), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': '(1 / 5.2)'}), '(per_process_gpu_memory_fraction=1 / 5.2)\n', (13371, 13412), True, 'import tensorflow as tf\n'), ((13555, 13588), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (13586, 13588), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python import rospy import math import numpy as np from sensor_msgs.msg import LaserScan ####################################### # Laser Scan: # Header: Seq, Stamp, frame_id # Angle_min, Angle_max, Angle_Increment, Time_Increment # Scan time, range_min, range_max, ranges, intensities ####################################### class Noise_class: def __init__(self): #rospy.on_shutdown(self.save_csv) self.laser_sub = rospy.Subscriber('/base_scan', LaserScan, self.laser_callback) self.scan_pub = rospy.Publisher('/gaus_err_laser_scan', LaserScan, queue_size= 1) def laser_callback(self, msg): filtered_values = LaserScan() distance = np.array(msg.ranges) filtered_values.header = msg.header filtered_values.angle_increment = msg.angle_increment filtered_values.time_increment = msg.time_increment filtered_values.scan_time = msg.scan_time filtered_values.range_min = msg.range_min filtered_values.range_max = msg.range_max filtered_values.intensities = msg.intensities angle = filtered_values.angle_increment min_angle = msg.angle_min max_angle = msg.angle_max laser_noise_variance = rospy.get_param('laser_noise_variance') if laser_noise_variance <= 0: laser_noise_variance = 0.1 filtered_values_ranges = np.zeros(len(distance)) noise_values_ranges = np.random.normal(loc = 0, scale=laser_noise_variance, size=len(distance)) for i in range(len(distance)): filtered_values_ranges[i] = noise_values_ranges[i]+distance[i] filtered_values.ranges = filtered_values_ranges filtered_values.angle_min = min_angle filtered_values.angle_max = max_angle self.scan_pub.publish(filtered_values) if __name__ == '__main__': rospy.init_node('noiser', anonymous=True) noisy = Noise_class() try: rospy.spin() except KeyboardInterrupt: print("Shutting down")
[ "sensor_msgs.msg.LaserScan", "rospy.Subscriber", "rospy.init_node", "rospy.get_param", "numpy.array", "rospy.spin", "rospy.Publisher" ]
[((1698, 1739), 'rospy.init_node', 'rospy.init_node', (['"""noiser"""'], {'anonymous': '(True)'}), "('noiser', anonymous=True)\n", (1713, 1739), False, 'import rospy\n'), ((441, 503), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/base_scan"""', 'LaserScan', 'self.laser_callback'], {}), "('/base_scan', LaserScan, self.laser_callback)\n", (457, 503), False, 'import rospy\n'), ((522, 586), 'rospy.Publisher', 'rospy.Publisher', (['"""/gaus_err_laser_scan"""', 'LaserScan'], {'queue_size': '(1)'}), "('/gaus_err_laser_scan', LaserScan, queue_size=1)\n", (537, 586), False, 'import rospy\n'), ((642, 653), 'sensor_msgs.msg.LaserScan', 'LaserScan', ([], {}), '()\n', (651, 653), False, 'from sensor_msgs.msg import LaserScan\n'), ((667, 687), 'numpy.array', 'np.array', (['msg.ranges'], {}), '(msg.ranges)\n', (675, 687), True, 'import numpy as np\n'), ((1142, 1181), 'rospy.get_param', 'rospy.get_param', (['"""laser_noise_variance"""'], {}), "('laser_noise_variance')\n", (1157, 1181), False, 'import rospy\n'), ((1771, 1783), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (1781, 1783), False, 'import rospy\n')]
#!/usr/bin/env python3 import sys import numpy as np from example import AmiciExample class ExampleCalvetti(AmiciExample): def __init__(self): AmiciExample.__init__( self ) self.numX = 6 self.numP = 0 self.numK = 6 self.modelOptions['theta'] = [] self.modelOptions['kappa'] = [0.29, 0.74, 0.44, 0.08, 0.27, 0.18] self.modelOptions['ts'] = np.linspace(0, 20, 201) self.modelOptions['pscale'] = 0 self.solverOptions['atol'] = 1e-6 self.solverOptions['rtol'] = 1e-4 self.solverOptions['sens_ind'] = [] self.solverOptions['sensi'] = 0 self.solverOptions['sensi_meth'] = 1 def writeNoSensi(filename): ex = ExampleCalvetti() ex.writeToFile(filename, '/model_calvetti/nosensi/') def main(): if len(sys.argv) < 2: print("Error: Must provide output file as first and only argument.") sys.exit(1) filename = sys.argv[1] writeNoSensi(filename) if __name__ == "__main__": main()
[ "numpy.linspace", "example.AmiciExample.__init__", "sys.exit" ]
[((158, 185), 'example.AmiciExample.__init__', 'AmiciExample.__init__', (['self'], {}), '(self)\n', (179, 185), False, 'from example import AmiciExample\n'), ((404, 427), 'numpy.linspace', 'np.linspace', (['(0)', '(20)', '(201)'], {}), '(0, 20, 201)\n', (415, 427), True, 'import numpy as np\n'), ((922, 933), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (930, 933), False, 'import sys\n')]
from PIL import Image from tflite_runtime.interpreter import Interpreter from tflite_runtime.interpreter import load_delegate from video import create_capture import numpy as np import cv2 as cv import io import picamera import simpleaudio as sa # tf model upload def load_labels(path): with open(path, 'r') as f: return {i: line.strip() for i, line in enumerate(f.readlines())} def set_input_tensor(interpreter, image): tensor_index = interpreter.get_input_details()[0]['index'] input_tensor = interpreter.tensor(tensor_index)()[0] input_tensor[:, :] = image # check whether user wears helmet def classify_image(interpreter, image, top_k=1): set_input_tensor(interpreter, image) interpreter.invoke() output_details = interpreter.get_output_details()[0] output = np.squeeze(interpreter.get_tensor(output_details['index'])) # If the model is quantized (uint8 data), then dequantize the results if output_details['dtype'] == np.uint8: scale, zero_point = output_details['quantization'] output = scale * (output - zero_point) ordered = np.argpartition(-output, top_k) # if 0.90 above then regard user is wearing a helmet if (top_k==1) and (output[1] > 0.9): res = 1 else: res = 0 return res # for detect human face def detect(img, cascade): rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv.CASCADE_SCALE_IMAGE) if len(rects) == 0: return [] rects[:,2:] += rects[:,:2] return rects def main(): import sys, getopt checknum = 0 while True: try: # face recognizing code print('face camera ') args, video_src = getopt.getopt(sys.argv[1:2], '', ['cascade=', 'nested-cascade=']) try: video_src = video_src[0] except: video_src = 0 args = dict(args) cascade_fn = args.get('--cascade', "data/haarcascades/haarcascade_frontalface_alt.xml") nested_fn = args.get('--nested-cascade', "data/haarcascades/haarcascade_eye.xml") cascade = cv.CascadeClassifier(cv.samples.findFile(cascade_fn)) nested = cv.CascadeClassifier(cv.samples.findFile(nested_fn)) cam = create_capture(video_src, fallback='synth:bg={}:noise=0.05'.format(cv.samples.findFile('samples/data/lena.jpg'))) while True: ret, img = cam.read() gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) gray = cv.equalizeHist(gray) rects = detect(gray, cascade) vis = img.copy() if len(rects): if not nested.empty(): print('into nested') # 사람이 들어왔을 때 for x1, y1, x2, y2 in rects: roi = gray[y1:y2, x1:x2] vis_roi = vis[y1:y2, x1:x2] print('findrects') subrects = detect(roi.copy(), nested) if subrects!='[]': faceok = 'faceok.wav' fa = sa.WaveObject.from_wave_file(faceok) face = fa.play() face.wait_done() print('detect!!') break cam.release() # face recognition camera off print("helmet camera") # helmet detectecting code filename = 'helmet.wav' wave_obj = sa.WaveObject.from_wave_file(filename) helmetok = 'helmetok.wav' wave = sa.WaveObject.from_wave_file(helmetok) labels = "labels.txt" model = "model_edgetpu.tflite" interpreter = Interpreter(model, experimental_delegates=[load_delegate('libedgetpu.so.1.0')]) interpreter.allocate_tensors() _, height, width, _ = interpreter.get_input_details()[0]['shape'] # helmet detect camera on with picamera.PiCamera(resolution=(640, 480), framerate=30) as camera: camera.start_preview() try: stream = io.BytesIO() for _ in camera.capture_continuous(stream, format='jpeg', use_video_port=True): stream.seek(0) image = Image.open(stream).convert('RGB').resize((width, height),Image.ANTIALIAS) results = classify_image(interpreter, image) print("result:") print(results) stream.seek(0) stream.truncate() # 헬멧 착용여부 판단 if results==0: play_obj = wave_obj.play() play_obj.wait_done() checknum += 1 if checknum==3: checknum = 0 break; else: helm = wave.play() helm.wait_done() print('GoodBoy') break finally: camera.stop_preview() except KeyboardInterrupt: break if __name__ == '__main__': main() cv.destroyAllWindows()
[ "simpleaudio.WaveObject.from_wave_file", "getopt.getopt", "PIL.Image.open", "numpy.argpartition", "cv2.samples.findFile", "io.BytesIO", "picamera.PiCamera", "cv2.equalizeHist", "tflite_runtime.interpreter.load_delegate", "cv2.destroyAllWindows", "cv2.cvtColor" ]
[((1193, 1224), 'numpy.argpartition', 'np.argpartition', (['(-output)', 'top_k'], {}), '(-output, top_k)\n', (1208, 1224), True, 'import numpy as np\n'), ((5829, 5851), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (5849, 5851), True, 'import cv2 as cv\n'), ((1887, 1952), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:2]', '""""""', "['cascade=', 'nested-cascade=']"], {}), "(sys.argv[1:2], '', ['cascade=', 'nested-cascade='])\n", (1900, 1952), False, 'import sys, getopt\n'), ((3844, 3882), 'simpleaudio.WaveObject.from_wave_file', 'sa.WaveObject.from_wave_file', (['filename'], {}), '(filename)\n', (3872, 3882), True, 'import simpleaudio as sa\n'), ((3942, 3980), 'simpleaudio.WaveObject.from_wave_file', 'sa.WaveObject.from_wave_file', (['helmetok'], {}), '(helmetok)\n', (3970, 3980), True, 'import simpleaudio as sa\n'), ((2355, 2386), 'cv2.samples.findFile', 'cv.samples.findFile', (['cascade_fn'], {}), '(cascade_fn)\n', (2374, 2386), True, 'import cv2 as cv\n'), ((2431, 2461), 'cv2.samples.findFile', 'cv.samples.findFile', (['nested_fn'], {}), '(nested_fn)\n', (2450, 2461), True, 'import cv2 as cv\n'), ((2704, 2739), 'cv2.cvtColor', 'cv.cvtColor', (['img', 'cv.COLOR_BGR2GRAY'], {}), '(img, cv.COLOR_BGR2GRAY)\n', (2715, 2739), True, 'import cv2 as cv\n'), ((2764, 2785), 'cv2.equalizeHist', 'cv.equalizeHist', (['gray'], {}), '(gray)\n', (2779, 2785), True, 'import cv2 as cv\n'), ((4355, 4409), 'picamera.PiCamera', 'picamera.PiCamera', ([], {'resolution': '(640, 480)', 'framerate': '(30)'}), '(resolution=(640, 480), framerate=30)\n', (4372, 4409), False, 'import picamera\n'), ((4513, 4525), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (4523, 4525), False, 'import io\n'), ((2549, 2593), 'cv2.samples.findFile', 'cv.samples.findFile', (['"""samples/data/lena.jpg"""'], {}), "('samples/data/lena.jpg')\n", (2568, 2593), True, 'import cv2 as cv\n'), ((4134, 4168), 'tflite_runtime.interpreter.load_delegate', 'load_delegate', (['"""libedgetpu.so.1.0"""'], {}), "('libedgetpu.so.1.0')\n", (4147, 4168), False, 'from tflite_runtime.interpreter import load_delegate\n'), ((3419, 3455), 'simpleaudio.WaveObject.from_wave_file', 'sa.WaveObject.from_wave_file', (['faceok'], {}), '(faceok)\n', (3447, 3455), True, 'import simpleaudio as sa\n'), ((4700, 4718), 'PIL.Image.open', 'Image.open', (['stream'], {}), '(stream)\n', (4710, 4718), False, 'from PIL import Image\n')]
""" tellotracker: Allows manual operation of the drone and demo tracking mode. Requires mplayer to record/save video. Controls: - tab to lift off - WASD to move the drone - space/shift to ascend/escent slowly - Q/E to yaw slowly - arrow keys to ascend, descend, or yaw quickly - backspace to land, or P to palm-land - enter to take a picture - R to start recording video, R again to stop recording (video and photos will be saved to a timestamped file in ~/Pictures/) - Z to toggle camera zoom state (zoomed-in widescreen or high FOV 4:3) - T to toggle tracking @author <NAME>, <NAME> and <NAME> @copyright 2018 see license file for details """ import time import datetime import os import tellopy import numpy import av import cv2 from pynput import keyboard from tracker import Tracker #posenet import os import numpy as np import sys from tensorflow.lite.python.interpreter import Interpreter from PIL import Image import math import threading import traceback frame = None run_recv_thread = True def sigmoid(x): return 1 / (1 + math.exp(-x)) def argmax2d(inp_3d): """ Get the x,y positions of the heatmap of each part's argmax() """ heatmapPositions = np.zeros(shape=(17,2)) heatmapConf = np.zeros(shape=(17,1)) for i in range(17): argmax_i = np.unravel_index(inp_3d[:,:,i].argmax(), inp_3d[:,:,i].shape) max_i = inp_3d[:,:,i].max() heatmapPositions[i,:] = argmax_i heatmapConf[i,:] = max_i return heatmapPositions,heatmapConf def get_offsetVector(heatmapPositions=None,offsets=None): allArrays = np.zeros(shape=(17,2)) for idx,el in enumerate(heatmapPositions): # print(el) allArrays[idx,0] = offsets[int(el[0]),int(el[1]),idx] allArrays[idx,1] = offsets[int(el[0]),int(el[1]),17+idx] return allArrays MODEL_NAME = "pose_TFLite_model" GRAPH_NAME = 'detect.tflite' LABELMAP_NAME = 'labelmap.txt' resW, resH = '952x720'.split('x') imW, imH = int(resW), int(resH) use_TPU = False min_thresh = 0.7 # Get path to current working directory CWD_PATH = os.getcwd() # Path to .tflite file, which contains the model that is used for object detection PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME) # Path to label map file PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME) # Load the label map with open(PATH_TO_LABELS, 'r') as f: labels = [line.strip() for line in f.readlines()] # Have to do a weird fix for label map if using the COCO "starter model" from # https://www.tensorflow.org/lite/models/object_detection/overview # First label is '???', which has to be removed. if labels[0] == '???': del(labels[0]) # Load the Tensorflow Lite model. # If using Edge TPU, use special load_delegate argument if use_TPU: interpreter = Interpreter(model_path=PATH_TO_CKPT, experimental_delegates=[load_delegate('libedgetpu.so.1.0')]) print(PATH_TO_CKPT) else: interpreter = Interpreter(model_path=PATH_TO_CKPT) interpreter.allocate_tensors() # Get model details input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() height = input_details[0]['shape'][1] width = input_details[0]['shape'][2] floating_model = (input_details[0]['dtype'] == np.float32) input_mean = width/2 input_std = width/2 # Initialize frame rate calculation frame_rate_calc = 1 freq = cv2.getTickFrequency() #posenet def main(): """ Create a tello controller and show the video feed.""" tellotrack = TelloCV() # for packet in tellotrack.container.demux((tellotrack.vid_stream,)): # for frame in packet.decode(): # start = time.time() # image = tellotrack.process_frame(frame) # print("image_time",time.time()-start) # cv2.imshow('tello', image) # _ = cv2.waitKey(1) & 0xFF #posenet try: threading.Thread(target=tellotrack.recv_thread).start() while True: if frame is None: time.sleep(0.01) else: # print("frame FOUNDD") image = tellotrack.process_frame(frame) cv2.imshow('Original', image) # cv2.imshow('Canny', cv2.Canny(image, 100, 200)) cv2.waitKey(1) # long delay # time.sleep(0.5) image = None except Exception as ex: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) print(ex) finally: run_recv_thread = False cv2.destroyAllWindows() #posenet class TelloCV(object): """ TelloTracker builds keyboard controls on top of TelloPy as well as generating images from the video stream and enabling opencv support """ def __init__(self): self.prev_flight_data = None self.record = False self.tracking = False self.keydown = False self.date_fmt = '%Y-%m-%d_%H%M%S' self.speed = 30 self.drone = tellopy.Tello() self.init_drone() #posenet self.init_controls() # container for processing the packets into frames self.container = av.open(self.drone.get_video_stream()) self.vid_stream = self.container.streams.video[0] self.out_file = None self.out_stream = None self.out_name = None self.start_time = time.time() # tracking a color green_lower = (30, 50, 50) green_upper = (80, 255, 255) #red_lower = (0, 50, 50) # red_upper = (20, 255, 255) # blue_lower = (110, 50, 50) # upper_blue = (130, 255, 255) self.track_cmd = "" # self.tracker = Tracker(self.vid_stream.height, # self.vid_stream.width, # green_lower, green_upper) #posenet self.tracker = Tracker(720, 960, green_lower, green_upper) #posenet #posenet def recv_thread(self): global frame global run_recv_thread print('start recv_thread()') # drone = tellopy.Tello() try: # self.drone.connect() # self.drone.wait_for_connection(60.0) # #posenet # self.drone.start_video() # self.drone.subscribe(self.drone.EVENT_FLIGHT_DATA, # self.flight_data_handler) # self.drone.subscribe(self.drone.EVENT_FILE_RECEIVED, # self.handle_flight_received) #posenet # container = av.open(self.drone.get_video_stream()) frame_count = 0 while run_recv_thread: for f in self.container.decode(video=0): frame_count = frame_count + 1 # skip first 300 frames if frame_count < 300: continue frame = f time.sleep(0.01) except Exception as ex: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) print(ex) finally: self.drone.quit() #posenet def init_drone(self): """Connect, uneable streaming and subscribe to events""" # self.drone.log.set_level(2) self.drone.connect() self.drone.wait_for_connection(60.0) #posenet self.drone.start_video() self.drone.subscribe(self.drone.EVENT_FLIGHT_DATA, self.flight_data_handler) self.drone.subscribe(self.drone.EVENT_FILE_RECEIVED, self.handle_flight_received) def on_press(self, keyname): """handler for keyboard listener""" if self.keydown: return try: self.keydown = True keyname = str(keyname).strip('\'') print('+' + keyname) if keyname == 'Key.esc': self.drone.quit() exit(0) if keyname in self.controls: key_handler = self.controls[keyname] if isinstance(key_handler, str): getattr(self.drone, key_handler)(self.speed) else: key_handler(self.speed) except AttributeError: print('special key {0} pressed'.format(keyname)) def on_release(self, keyname): """Reset on key up from keyboard listener""" self.keydown = False keyname = str(keyname).strip('\'') print('-' + keyname) if keyname in self.controls: key_handler = self.controls[keyname] if isinstance(key_handler, str): getattr(self.drone, key_handler)(0) else: key_handler(0) def init_controls(self): """Define keys and add listener""" self.controls = { 'w': lambda speed: self.drone.forward(speed),#'forward', 's': 'backward', 'a': 'left', 'd': 'right', 'Key.space': 'up', 'Key.shift': 'down', 'Key.shift_r': 'down', 'q': 'counter_clockwise', 'e': 'clockwise', 'i': lambda speed: self.drone.flip_forward(), 'k': lambda speed: self.drone.flip_back(), 'j': lambda speed: self.drone.flip_left(), 'l': lambda speed: self.drone.flip_right(), # arrow keys for fast turns and altitude adjustments 'Key.left': lambda speed: self.drone.counter_clockwise(speed), 'Key.right': lambda speed: self.drone.clockwise(speed), 'Key.up': lambda speed: self.drone.up(speed), 'Key.down': lambda speed: self.drone.down(speed), 'Key.tab': lambda speed: self.drone.takeoff(), 'Key.backspace': lambda speed: self.drone.land(), 'p': lambda speed: self.palm_land(speed), 't': lambda speed: self.toggle_tracking(speed), 'r': lambda speed: self.toggle_recording(speed), 'z': lambda speed: self.toggle_zoom(speed), 'Key.enter': lambda speed: self.take_picture(speed) } self.key_listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release) self.key_listener.start() # self.key_listener.join() def process_frame(self, frame): """convert frame to cv2 image and show""" # Start timer (for calculating frame rate) t1 = cv2.getTickCount() image = cv2.cvtColor(numpy.array( frame.to_image()), cv2.COLOR_RGB2BGR) image = self.write_hud(image) if self.record: self.record_vid(frame) # xoff, yoff = self.tracker.track(image) xoff, yoff = 0,0 xLeftWrist, yLeftWrist =0,0 xNose, yNose =0,0 # print("CV xoff{}, yoff {}".format(xoff, yoff)) #posenet frame_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) frame_resized = cv2.resize(frame_rgb, (width, height)) input_data = np.expand_dims(frame_resized, axis=0) # Normalize pixel values if using a floating model (i.e. if model is non-quantized) if floating_model: input_data = (np.float32(input_data) - input_mean) / input_std # Perform the actual detection by running the model with the image as input interpreter.set_tensor(input_details[0]['index'],input_data) interpreter.invoke() heatmapscores = interpreter.get_tensor(output_details[0]['index'])[0] # Bounding box coordinates of detected objects offsets = interpreter.get_tensor(output_details[1]['index'])[0] # Class index of detected objects # define vectorized sigmoid sigmoid_v = np.vectorize(sigmoid) # 1 sigmoid sigmoheatmapscores = sigmoid_v(heatmapscores) # 2 argmax2d heatmapPositions,heatmapConfidence = argmax2d(sigmoheatmapscores) # 3 offsetVectors offsetVectors = get_offsetVector(heatmapPositions,offsets) # 4 keypointPositions outputStride = 32 keypointPositions = heatmapPositions * outputStride + offsetVectors # 5 draw keypoints for idx,el in enumerate(heatmapConfidence): if heatmapConfidence[idx][0] >= min_thresh: x = round((keypointPositions[idx][1]/width)*imW) y = round((keypointPositions[idx][0]/height)*imH) if 'right' in labels[idx]: cv2.circle(image,(int(x),int(y)), 5, (0,255,0), -1) elif 'left' in labels[idx]: cv2.circle(image,(int(x),int(y)), 5, (0,0,255), -1) elif 'nose' in labels[idx]: xNose, yNose = int(x),int(y) xoff, yoff = (x-int(960/2)),(int(720/2)-y) # print("NOSE xoff{}, yoff {}".format(xoff, yoff)) cv2.circle(image,(int(x),int(y)), 5, (255,0,0), -1) if 'leftWri' in labels[idx]: xLeftWrist, yLeftWrist = int(x),int(y) #posenet def draw_arrows(frame): """Show the direction vector output in the cv2 window""" #cv2.putText(frame,"Color:", (0, 35), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, thickness=2) cv2.arrowedLine(frame, (int(960/2), int(720/2)), (int(960/2 + xoff), int(720/2 - yoff)), (0, 0, 255), 1) return frame # image = self.tracker.draw_arrows(image) image = draw_arrows(image) # Calculate framerate t2 = cv2.getTickCount() time1 = (t2-t1)/freq frame_rate_calc= 1/time1 # Draw framerate in corner of frame cv2.putText(image, 'FPS: {0:.2f}'.format(frame_rate_calc), (imW-200,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,0), 1, cv2.LINE_AA) distance = 150 cmd = "" # print(yoff) # print("WRIST {}>>>> NOSE {}???? ".format(yLeftWrist,yNose),yLeftWrist>yNose) if self.tracking: # if yLeftWrist>yNose: # print("RECORDING",yLeftWrist) # cmd = "r" # lambda speed: self.toggle_recording(speed) if xoff < -distance and xoff>-960/2: cmd = "counter_clockwise" elif xoff > distance and xoff<960/2: cmd = "clockwise" elif yoff < -distance and yoff>-720/2: cmd = "down" elif yoff > distance and yoff<720/2: print("UPPPPPPPPPPPPPPP",yoff) cmd = "up" else: if self.track_cmd is not "": getattr(self.drone, self.track_cmd)(0) self.track_cmd = "" if cmd is not self.track_cmd: if cmd is not "": print("track command:", cmd) getattr(self.drone, cmd)(self.speed) self.track_cmd = cmd return image def write_hud(self, frame): """Draw drone info, tracking and record on frame""" stats = self.prev_flight_data.split('|') stats.append("Tracking:" + str(self.tracking)) if self.drone.zoom: stats.append("VID") else: stats.append("PIC") if self.record: diff = int(time.time() - self.start_time) mins, secs = divmod(diff, 60) stats.append("REC {:02d}:{:02d}".format(mins, secs)) for idx, stat in enumerate(stats): text = stat.lstrip() cv2.putText(frame, text, (0, 30 + (idx * 30)), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), lineType=30) return frame def toggle_recording(self, speed): """Handle recording keypress, creates output stream and file""" if speed == 0: return self.record = not self.record if self.record: datename = [os.getenv('HOME'), datetime.datetime.now().strftime(self.date_fmt)] self.out_name = '{}/Pictures/tello-{}.mp4'.format(*datename) print("Outputting video to:", self.out_name) self.out_file = av.open(self.out_name, 'w') self.start_time = time.time() self.out_stream = self.out_file.add_stream( 'mpeg4', self.vid_stream.rate) self.out_stream.pix_fmt = 'yuv420p' self.out_stream.width = self.vid_stream.width self.out_stream.height = self.vid_stream.height if not self.record: print("Video saved to ", self.out_name) self.out_file.close() self.out_stream = None def record_vid(self, frame): """ convert frames to packets and write to file """ new_frame = av.VideoFrame( width=frame.width, height=frame.height, format=frame.format.name) for i in range(len(frame.planes)): new_frame.planes[i].update(frame.planes[i]) pkt = None try: pkt = self.out_stream.encode(new_frame) except IOError as err: print("encoding failed: {0}".format(err)) if pkt is not None: try: self.out_file.mux(pkt) except IOError: print('mux failed: ' + str(pkt)) def take_picture(self, speed): """Tell drone to take picture, image sent to file handler""" if speed == 0: return self.drone.take_picture() def palm_land(self, speed): """Tell drone to land""" if speed == 0: return self.drone.palm_land() def toggle_tracking(self, speed): """ Handle tracking keypress""" if speed == 0: # handle key up event return self.tracking = not self.tracking print("tracking:", self.tracking) return def toggle_zoom(self, speed): """ In "video" mode the self.drone sends 1280x720 frames. In "photo" mode it sends 2592x1936 (952x720) frames. The video will always be centered in the window. In photo mode, if we keep the window at 1280x720 that gives us ~160px on each side for status information, which is ample. Video mode is harder because then we need to abandon the 16:9 display size if we want to put the HUD next to the video. """ if speed == 0: return self.drone.set_video_mode(not self.drone.zoom) def flight_data_handler(self, event, sender, data): """Listener to flight data from the drone.""" text = str(data) if self.prev_flight_data != text: self.prev_flight_data = text def handle_flight_received(self, event, sender, data): """Create a file in ~/Pictures/ to receive image from the drone""" path = '%s/Pictures/tello-%s.jpeg' % ( os.getenv('HOME'), datetime.datetime.now().strftime(self.date_fmt)) with open(path, 'wb') as out_file: out_file.write(data) print('Saved photo to %s' % path) if __name__ == '__main__': main()
[ "time.sleep", "cv2.imshow", "sys.exc_info", "av.open", "cv2.destroyAllWindows", "math.exp", "traceback.print_exception", "tracker.Tracker", "cv2.waitKey", "cv2.getTickFrequency", "numpy.float32", "cv2.putText", "cv2.cvtColor", "threading.Thread", "cv2.resize", "time.time", "numpy.vectorize", "pynput.keyboard.Listener", "av.VideoFrame", "os.getenv", "os.path.join", "os.getcwd", "datetime.datetime.now", "numpy.zeros", "cv2.getTickCount", "numpy.expand_dims", "tellopy.Tello", "tensorflow.lite.python.interpreter.Interpreter" ]
[((2062, 2073), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2071, 2073), False, 'import os\n'), ((2173, 2219), 'os.path.join', 'os.path.join', (['CWD_PATH', 'MODEL_NAME', 'GRAPH_NAME'], {}), '(CWD_PATH, MODEL_NAME, GRAPH_NAME)\n', (2185, 2219), False, 'import os\n'), ((2261, 2310), 'os.path.join', 'os.path.join', (['CWD_PATH', 'MODEL_NAME', 'LABELMAP_NAME'], {}), '(CWD_PATH, MODEL_NAME, LABELMAP_NAME)\n', (2273, 2310), False, 'import os\n'), ((3385, 3407), 'cv2.getTickFrequency', 'cv2.getTickFrequency', ([], {}), '()\n', (3405, 3407), False, 'import cv2\n'), ((1183, 1206), 'numpy.zeros', 'np.zeros', ([], {'shape': '(17, 2)'}), '(shape=(17, 2))\n', (1191, 1206), True, 'import numpy as np\n'), ((1224, 1247), 'numpy.zeros', 'np.zeros', ([], {'shape': '(17, 1)'}), '(shape=(17, 1))\n', (1232, 1247), True, 'import numpy as np\n'), ((1578, 1601), 'numpy.zeros', 'np.zeros', ([], {'shape': '(17, 2)'}), '(shape=(17, 2))\n', (1586, 1601), True, 'import numpy as np\n'), ((2956, 2992), 'tensorflow.lite.python.interpreter.Interpreter', 'Interpreter', ([], {'model_path': 'PATH_TO_CKPT'}), '(model_path=PATH_TO_CKPT)\n', (2967, 2992), False, 'from tensorflow.lite.python.interpreter import Interpreter\n'), ((4607, 4630), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (4628, 4630), False, 'import cv2\n'), ((5063, 5078), 'tellopy.Tello', 'tellopy.Tello', ([], {}), '()\n', (5076, 5078), False, 'import tellopy\n'), ((5440, 5451), 'time.time', 'time.time', ([], {}), '()\n', (5449, 5451), False, 'import time\n'), ((5938, 5981), 'tracker.Tracker', 'Tracker', (['(720)', '(960)', 'green_lower', 'green_upper'], {}), '(720, 960, green_lower, green_upper)\n', (5945, 5981), False, 'from tracker import Tracker\n'), ((10356, 10425), 'pynput.keyboard.Listener', 'keyboard.Listener', ([], {'on_press': 'self.on_press', 'on_release': 'self.on_release'}), '(on_press=self.on_press, on_release=self.on_release)\n', (10373, 10425), False, 'from pynput import keyboard\n'), ((10701, 10719), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (10717, 10719), False, 'import cv2\n'), ((11141, 11179), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (11153, 11179), False, 'import cv2\n'), ((11204, 11242), 'cv2.resize', 'cv2.resize', (['frame_rgb', '(width, height)'], {}), '(frame_rgb, (width, height))\n', (11214, 11242), False, 'import cv2\n'), ((11264, 11301), 'numpy.expand_dims', 'np.expand_dims', (['frame_resized'], {'axis': '(0)'}), '(frame_resized, axis=0)\n', (11278, 11301), True, 'import numpy as np\n'), ((11993, 12014), 'numpy.vectorize', 'np.vectorize', (['sigmoid'], {}), '(sigmoid)\n', (12005, 12014), True, 'import numpy as np\n'), ((13843, 13861), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (13859, 13861), False, 'import cv2\n'), ((17168, 17247), 'av.VideoFrame', 'av.VideoFrame', ([], {'width': 'frame.width', 'height': 'frame.height', 'format': 'frame.format.name'}), '(width=frame.width, height=frame.height, format=frame.format.name)\n', (17181, 17247), False, 'import av\n'), ((1043, 1055), 'math.exp', 'math.exp', (['(-x)'], {}), '(-x)\n', (1051, 1055), False, 'import math\n'), ((4451, 4465), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (4463, 4465), False, 'import sys\n'), ((4474, 4535), 'traceback.print_exception', 'traceback.print_exception', (['exc_type', 'exc_value', 'exc_traceback'], {}), '(exc_type, exc_value, exc_traceback)\n', (4499, 4535), False, 'import traceback\n'), ((15909, 16014), 'cv2.putText', 'cv2.putText', (['frame', 'text', '(0, 30 + idx * 30)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1.0)', '(255, 0, 0)'], {'lineType': '(30)'}), '(frame, text, (0, 30 + idx * 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0,\n (255, 0, 0), lineType=30)\n', (15920, 16014), False, 'import cv2\n'), ((16549, 16576), 'av.open', 'av.open', (['self.out_name', '"""w"""'], {}), "(self.out_name, 'w')\n", (16556, 16576), False, 'import av\n'), ((16607, 16618), 'time.time', 'time.time', ([], {}), '()\n', (16616, 16618), False, 'import time\n'), ((3888, 3935), 'threading.Thread', 'threading.Thread', ([], {'target': 'tellotrack.recv_thread'}), '(target=tellotrack.recv_thread)\n', (3904, 3935), False, 'import threading\n'), ((4011, 4027), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (4021, 4027), False, 'import time\n'), ((4158, 4187), 'cv2.imshow', 'cv2.imshow', (['"""Original"""', 'image'], {}), "('Original', image)\n", (4168, 4187), False, 'import cv2\n'), ((4270, 4284), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (4281, 4284), False, 'import cv2\n'), ((7056, 7072), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (7066, 7072), False, 'import time\n'), ((7154, 7168), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (7166, 7168), False, 'import sys\n'), ((7181, 7242), 'traceback.print_exception', 'traceback.print_exception', (['exc_type', 'exc_value', 'exc_traceback'], {}), '(exc_type, exc_value, exc_traceback)\n', (7206, 7242), False, 'import traceback\n'), ((16323, 16340), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (16332, 16340), False, 'import os\n'), ((19277, 19294), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (19286, 19294), False, 'import os\n'), ((11447, 11469), 'numpy.float32', 'np.float32', (['input_data'], {}), '(input_data)\n', (11457, 11469), True, 'import numpy as np\n'), ((15682, 15693), 'time.time', 'time.time', ([], {}), '()\n', (15691, 15693), False, 'import time\n'), ((16342, 16365), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (16363, 16365), False, 'import datetime\n'), ((19308, 19331), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (19329, 19331), False, 'import datetime\n')]
# Copyright (c) 2021 PaddlePaddle Authors. 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. from auto_scan_test import PassAutoScanTest, IgnoreReasons from program_config import TensorConfig, ProgramConfig, OpConfig import numpy as np import paddle.inference as paddle_infer from functools import partial from typing import Optional, List, Callable, Dict, Any, Set import unittest import hypothesis from hypothesis import given, settings, seed, example, assume, reproduce_failure import hypothesis.strategies as st class TestFcFusePass(PassAutoScanTest): """ x_var y_var(persistable) \ / mul bias_var(persistable) | mul_out_var bias_var(persistable) \ / elementwise_add """ def sample_predictor_configs(self, program_config): # cpu before_num_ops = len(program_config.ops) + 2 config = self.create_inference_config(use_gpu=False) yield config, ["fc"], (1e-5, 1e-5) # for gpu config = self.create_inference_config(use_gpu=True) yield config, ["fc"], (1e-5, 1e-5) # trt static_shape config = self.create_trt_inference_config() config.enable_tensorrt_engine( max_batch_size=8, workspace_size=102400, min_subgraph_size=0, precision_mode=paddle_infer.PrecisionType.Float32, use_static=False, use_calib_mode=False) yield config, ['fc'], (1e-5, 1e-5) def add_ignore_pass_case(self): # Here we put some skip rules to avoid known bugs def teller1(program_config, predictor_config): # shape of bias should be [1, mul_y_shape[-1]] or [mul_y_shape[-1]] x_shape = list(program_config.inputs["mul_x"].shape) y_shape = list(program_config.weights["mul_y"].shape) bias_shape = program_config.weights["bias"].shape bias_shape = list(program_config.weights["bias"].shape) if predictor_config.tensorrt_engine_enabled(): # TensorRT cann't handle all the situation of elementwise_add # disable it until this problem fixed predictor_config.exp_disable_tensorrt_ops(["elementwise_add"]) if bias_shape != [y_shape[-1]] and bias_shape != [1, y_shape[-1]]: return True return False def teller2(program_config, predictor_config): # TODO fuse has bug while axis != -1 axis = program_config.ops[1].attrs["axis"] if axis != -1 and axis != program_config.ops[0].attrs[ "x_num_col_dims"]: return True return False self.add_ignore_check_case( teller1, IgnoreReasons.PASS_ACCURACY_ERROR, "The pass output has diff while shape of bias is not [out_size] or [1, out_size].", ) self.add_ignore_check_case( teller2, IgnoreReasons.PASS_ACCURACY_ERROR, "The pass output has diff while axis of elementwise_add is not -1.", ) def is_program_valid(self, prog_config): add_x_rank = prog_config.ops[0].attrs["x_num_col_dims"] + 1 add_y_rank = len(prog_config.weights["bias"].shape) axis = prog_config.ops[1].attrs["axis"] if add_x_rank == add_y_rank: if axis != -1 or axis != 0: return False return True def sample_program_config(self, draw): # 1. Generate shape of input:X of mul x_shape = draw( st.lists(st.integers(min_value=1, max_value=4), min_size=2, max_size=4)) # 2. Generate attr:x_num_col_dims/y_num_col_dims of mul x_num_col_dims = draw( st.integers(min_value=1, max_value=len(x_shape) - 1)) y_num_col_dims = 1 # 3. Generate legal shape of input:Y of mul y_shape = draw( st.lists(st.integers(min_value=1, max_value=8), min_size=2, max_size=2)) y_shape[0] = int(np.prod(x_shape[x_num_col_dims:])) # 4. Generate legal attr:axis of elementwise_add mul_out_shape = x_shape[:x_num_col_dims] + y_shape[1:] axis = draw(st.integers(min_value=-1, max_value=x_num_col_dims)) # 5. Generate legal shape of input:Y of elementwise_add if axis >= 0: max_bias_rank = x_num_col_dims + 1 - axis bias_rank = draw(st.integers(min_value=1, max_value=max_bias_rank)) bias_shape = mul_out_shape[axis:axis + bias_rank] else: max_bias_rank = 1 bias_rank = draw( st.integers(min_value=1, max_value=len(mul_out_shape))) bias_shape = mul_out_shape[-1 * bias_rank:] # 6. Random choose if use broadcast for elementwise_add, e.g [3, 4] -> [1, 4] if draw(st.booleans()): broadcast_dims = draw(st.integers(min_value=1, max_value=bias_rank)) for i in range(0, broadcast_dims): bias_shape[i] = 1 # 7. Random choose if add a relu operator has_relu = draw(st.booleans()) # Now we have all the decided parameters to compose a program # shape of inputs/weights tensors: x_shape, y_shape, bias_shape... # parameters of operators: x_num_col_dims, y_num_col_dims, axis... # a random boolean value(has_relu) to decide if program include a relu op # Here we will compose a program # Still has some risks that the program is invalid or cause bug while running # Use function `is_program_valid` to filter the invalid programs before running # Use function `add_skip_pass_case` to ignore the programs even if they cause bug while runing mul_op = OpConfig( "mul", inputs={ "X": ["mul_x"], "Y": ["mul_y"] }, outputs={"Out": ["mul_out"]}, x_num_col_dims=x_num_col_dims, y_num_col_dims=y_num_col_dims, ) add_op = OpConfig( "elementwise_add", inputs={ "X": ["mul_out"], "Y": ["bias"] }, outputs={"Out": ["add_out"]}, axis=axis, ) ops = [mul_op, add_op] if has_relu: relu_op = OpConfig("relu", inputs={"X": ["add_out"]}, outputs={"Out": ["relu_out"]}) ops.append(relu_op) program_config = ProgramConfig( ops=ops, weights={ "mul_y": TensorConfig(shape=y_shape), "bias": TensorConfig(shape=bias_shape), }, inputs={ "mul_x": TensorConfig(shape=x_shape), }, outputs=ops[-1].outputs["Out"], ) return program_config def test(self): self.run_and_statis(quant=False, max_examples=500, passes=["fc_fuse_pass"]) if __name__ == "__main__": unittest.main()
[ "numpy.prod", "hypothesis.strategies.integers", "program_config.TensorConfig", "hypothesis.strategies.booleans", "unittest.main", "program_config.OpConfig" ]
[((7681, 7696), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7694, 7696), False, 'import unittest\n'), ((6363, 6516), 'program_config.OpConfig', 'OpConfig', (['"""mul"""'], {'inputs': "{'X': ['mul_x'], 'Y': ['mul_y']}", 'outputs': "{'Out': ['mul_out']}", 'x_num_col_dims': 'x_num_col_dims', 'y_num_col_dims': 'y_num_col_dims'}), "('mul', inputs={'X': ['mul_x'], 'Y': ['mul_y']}, outputs={'Out': [\n 'mul_out']}, x_num_col_dims=x_num_col_dims, y_num_col_dims=y_num_col_dims)\n", (6371, 6516), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((6646, 6760), 'program_config.OpConfig', 'OpConfig', (['"""elementwise_add"""'], {'inputs': "{'X': ['mul_out'], 'Y': ['bias']}", 'outputs': "{'Out': ['add_out']}", 'axis': 'axis'}), "('elementwise_add', inputs={'X': ['mul_out'], 'Y': ['bias']},\n outputs={'Out': ['add_out']}, axis=axis)\n", (6654, 6760), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((4643, 4676), 'numpy.prod', 'np.prod', (['x_shape[x_num_col_dims:]'], {}), '(x_shape[x_num_col_dims:])\n', (4650, 4676), True, 'import numpy as np\n'), ((4818, 4869), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(-1)', 'max_value': 'x_num_col_dims'}), '(min_value=-1, max_value=x_num_col_dims)\n', (4829, 4869), True, 'import hypothesis.strategies as st\n'), ((5457, 5470), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (5468, 5470), True, 'import hypothesis.strategies as st\n'), ((5709, 5722), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (5720, 5722), True, 'import hypothesis.strategies as st\n'), ((6936, 7010), 'program_config.OpConfig', 'OpConfig', (['"""relu"""'], {'inputs': "{'X': ['add_out']}", 'outputs': "{'Out': ['relu_out']}"}), "('relu', inputs={'X': ['add_out']}, outputs={'Out': ['relu_out']})\n", (6944, 7010), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((4121, 4158), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(4)'}), '(min_value=1, max_value=4)\n', (4132, 4158), True, 'import hypothesis.strategies as st\n'), ((4512, 4549), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(8)'}), '(min_value=1, max_value=8)\n', (4523, 4549), True, 'import hypothesis.strategies as st\n'), ((5040, 5089), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': 'max_bias_rank'}), '(min_value=1, max_value=max_bias_rank)\n', (5051, 5089), True, 'import hypothesis.strategies as st\n'), ((5507, 5552), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': 'bias_rank'}), '(min_value=1, max_value=bias_rank)\n', (5518, 5552), True, 'import hypothesis.strategies as st\n'), ((7213, 7240), 'program_config.TensorConfig', 'TensorConfig', ([], {'shape': 'y_shape'}), '(shape=y_shape)\n', (7225, 7240), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((7266, 7296), 'program_config.TensorConfig', 'TensorConfig', ([], {'shape': 'bias_shape'}), '(shape=bias_shape)\n', (7278, 7296), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((7359, 7386), 'program_config.TensorConfig', 'TensorConfig', ([], {'shape': 'x_shape'}), '(shape=x_shape)\n', (7371, 7386), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n')]
import cv2 from tkinter import Tk from tkinter.filedialog import askopenfilename import numpy as np import imutils import threading def main(): cap = cv2.VideoCapture(vid_path) status1, previous_frame = cap.read() total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) copy_frame = cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY) fgbg = cv2.createBackgroundSubtractorMOG2() hsv = np.zeros_like(previous_frame) hsv[...,1] = 255 t = 20 red = 30 check_red = 1 start = 0 radiuce_up_limit =60 radiuce_low_limit = 30 i = 0 while(i < total_frames - 1): ret, frame = cap.read() i = i + 1 frame1 = frame.copy() current_frame = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) current_frame = cv2.GaussianBlur(current_frame, (var_blur,var_blur), 0) # frame differening frame_diff = cv2.absdiff(current_frame,copy_frame) ret ,binary_image1 = cv2.threshold(frame_diff,3,255,cv2.THRESH_BINARY) # Background Subtraction binary_image3 = fgbg.apply(current_frame) # combination of two methods final_binary = cv2.bitwise_and(binary_image3,binary_image1) lab_val = 255 n_labels, img_labeled, lab_stats, _ = \ cv2.connectedComponentsWithStats(final_binary, connectivity=8, ltype=cv2.CV_32S) if check_red == 1: red = red +10 if red > radiuce_up_limit: check_red =0 else: red = red -10 if red == radiuce_low_limit: check_red =1 if lab_stats[1:, 4].size > 2: re = lab_stats[1:, 4].argsort()[-2:][::-1] + 1 largest_mask = np.zeros(final_binary.shape, dtype=np.uint8) largest_mask[img_labeled == re[0]] = lab_val cnts1 = cv2.findContours(largest_mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts1 = cnts1[0] if imutils.is_cv2() else cnts1[1] X1 = cnts1[0][0] cX1 = X1[0][0] cY1 = X1[0][1] cv2.circle(frame, (cX1, cY1), red, (0, 255, 255), 3) cv2.putText(frame,'Breathing',(10,40),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,255),1,cv2.LINE_AA) cv2.imshow('Frame',frame) else: t = t+1 if t > 40: if lab_stats[1:, 4].size > 0 and start == 1: t = 0 cv2.putText(frame,'Not Breathing',(10,40),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),1,cv2.LINE_AA) cv2.imshow('Frame',frame) else: cv2.circle(frame, (cX1, cY1), red, (0, 255, 255), 3) cv2.putText(frame,'Breathing',(10,40),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,255),1,cv2.LINE_AA) cv2.imshow('Frame',frame) previous_frame = current_frame k = cv2.waitKey(1) & 0xff if k == 27: break cap.release() cv2.destroyAllWindows() Tk().withdraw() vid_path = askopenfilename(filetypes =(("Video File", "*.mp4"),("Video File","*.avi"),("Video File", "*.flv"),("All Files","*.*")), title = "Choose a video.") no_of_threads = 1 var_blur = 3 thred = [] jobs = [] for i in range(0, no_of_threads): thred = threading.Thread(target=main) jobs.append(thred) for j in jobs: j.start() for j in jobs: j.join() # # #
[ "cv2.createBackgroundSubtractorMOG2", "imutils.is_cv2", "cv2.imshow", "cv2.destroyAllWindows", "cv2.threshold", "cv2.waitKey", "tkinter.filedialog.askopenfilename", "cv2.putText", "cv2.circle", "cv2.cvtColor", "cv2.GaussianBlur", "cv2.bitwise_and", "numpy.zeros", "cv2.connectedComponentsWithStats", "tkinter.Tk", "cv2.VideoCapture", "threading.Thread", "numpy.zeros_like", "cv2.absdiff" ]
[((3251, 3404), 'tkinter.filedialog.askopenfilename', 'askopenfilename', ([], {'filetypes': "(('Video File', '*.mp4'), ('Video File', '*.avi'), ('Video File', '*.flv'),\n ('All Files', '*.*'))", 'title': '"""Choose a video."""'}), "(filetypes=(('Video File', '*.mp4'), ('Video File', '*.avi'),\n ('Video File', '*.flv'), ('All Files', '*.*')), title='Choose a video.')\n", (3266, 3404), False, 'from tkinter.filedialog import askopenfilename\n'), ((174, 200), 'cv2.VideoCapture', 'cv2.VideoCapture', (['vid_path'], {}), '(vid_path)\n', (190, 200), False, 'import cv2\n'), ((322, 370), 'cv2.cvtColor', 'cv2.cvtColor', (['previous_frame', 'cv2.COLOR_BGR2GRAY'], {}), '(previous_frame, cv2.COLOR_BGR2GRAY)\n', (334, 370), False, 'import cv2\n'), ((382, 418), 'cv2.createBackgroundSubtractorMOG2', 'cv2.createBackgroundSubtractorMOG2', ([], {}), '()\n', (416, 418), False, 'import cv2\n'), ((429, 458), 'numpy.zeros_like', 'np.zeros_like', (['previous_frame'], {}), '(previous_frame)\n', (442, 458), True, 'import numpy as np\n'), ((3195, 3218), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3216, 3218), False, 'import cv2\n'), ((3523, 3552), 'threading.Thread', 'threading.Thread', ([], {'target': 'main'}), '(target=main)\n', (3539, 3552), False, 'import threading\n'), ((754, 794), 'cv2.cvtColor', 'cv2.cvtColor', (['frame1', 'cv2.COLOR_BGR2GRAY'], {}), '(frame1, cv2.COLOR_BGR2GRAY)\n', (766, 794), False, 'import cv2\n'), ((819, 875), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['current_frame', '(var_blur, var_blur)', '(0)'], {}), '(current_frame, (var_blur, var_blur), 0)\n', (835, 875), False, 'import cv2\n'), ((932, 970), 'cv2.absdiff', 'cv2.absdiff', (['current_frame', 'copy_frame'], {}), '(current_frame, copy_frame)\n', (943, 970), False, 'import cv2\n'), ((1008, 1060), 'cv2.threshold', 'cv2.threshold', (['frame_diff', '(3)', '(255)', 'cv2.THRESH_BINARY'], {}), '(frame_diff, 3, 255, cv2.THRESH_BINARY)\n', (1021, 1060), False, 'import cv2\n'), ((1211, 1256), 'cv2.bitwise_and', 'cv2.bitwise_and', (['binary_image3', 'binary_image1'], {}), '(binary_image3, binary_image1)\n', (1226, 1256), False, 'import cv2\n'), ((1351, 1436), 'cv2.connectedComponentsWithStats', 'cv2.connectedComponentsWithStats', (['final_binary'], {'connectivity': '(8)', 'ltype': 'cv2.CV_32S'}), '(final_binary, connectivity=8, ltype=cv2.CV_32S\n )\n', (1383, 1436), False, 'import cv2\n'), ((3224, 3228), 'tkinter.Tk', 'Tk', ([], {}), '()\n', (3226, 3228), False, 'from tkinter import Tk\n'), ((1910, 1954), 'numpy.zeros', 'np.zeros', (['final_binary.shape'], {'dtype': 'np.uint8'}), '(final_binary.shape, dtype=np.uint8)\n', (1918, 1954), True, 'import numpy as np\n'), ((2308, 2360), 'cv2.circle', 'cv2.circle', (['frame', '(cX1, cY1)', 'red', '(0, 255, 255)', '(3)'], {}), '(frame, (cX1, cY1), red, (0, 255, 255), 3)\n', (2318, 2360), False, 'import cv2\n'), ((2373, 2479), 'cv2.putText', 'cv2.putText', (['frame', '"""Breathing"""', '(10, 40)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 255, 255)', '(1)', 'cv2.LINE_AA'], {}), "(frame, 'Breathing', (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, \n 255, 255), 1, cv2.LINE_AA)\n", (2384, 2479), False, 'import cv2\n'), ((2477, 2503), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'frame'], {}), "('Frame', frame)\n", (2487, 2503), False, 'import cv2\n'), ((3113, 3127), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3124, 3127), False, 'import cv2\n'), ((2146, 2162), 'imutils.is_cv2', 'imutils.is_cv2', ([], {}), '()\n', (2160, 2162), False, 'import imutils\n'), ((2685, 2792), 'cv2.putText', 'cv2.putText', (['frame', '"""Not Breathing"""', '(10, 40)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 0, 255)', '(1)', 'cv2.LINE_AA'], {}), "(frame, 'Not Breathing', (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (0, 0, 255), 1, cv2.LINE_AA)\n", (2696, 2792), False, 'import cv2\n'), ((2795, 2821), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'frame'], {}), "('Frame', frame)\n", (2805, 2821), False, 'import cv2\n'), ((2855, 2907), 'cv2.circle', 'cv2.circle', (['frame', '(cX1, cY1)', 'red', '(0, 255, 255)', '(3)'], {}), '(frame, (cX1, cY1), red, (0, 255, 255), 3)\n', (2865, 2907), False, 'import cv2\n'), ((2924, 3030), 'cv2.putText', 'cv2.putText', (['frame', '"""Breathing"""', '(10, 40)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 255, 255)', '(1)', 'cv2.LINE_AA'], {}), "(frame, 'Breathing', (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, \n 255, 255), 1, cv2.LINE_AA)\n", (2935, 3030), False, 'import cv2\n'), ((3032, 3058), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'frame'], {}), "('Frame', frame)\n", (3042, 3058), False, 'import cv2\n')]
import numpy as np import scipy.stats as stats import scipy.special as spec import util class HMCParams: def __init__(self, tau, tau_g, L, eta, mass, r_clip, grad_clip): self.tau = tau self.tau_g = tau_g self.L = L self.eta = eta self.mass = mass self.r_clip = r_clip self.grad_clip = grad_clip class GradClipCounter: def __init__(self): self.clipped_grad = 0 self.grad_accesses = 0 def zcdp_iters(epsilon, delta, params, n, compute_less_grad=False): rho = (np.sqrt(epsilon - np.log(delta)) - np.sqrt(-np.log(delta)))**2 rho_l = 1 / (2 * params.tau**2 * n) rho_g = 1 / (2 * params.tau_g**2 * n) # print("rho_l: {}".format(rho_l)) # print("rho_g: {}".format(rho_g)) if compute_less_grad: iters = int((rho - rho_g) / (rho_l + params.L * rho_g)) else: iters = int(rho / (rho_l + (params.L + 1) * rho_g)) return iters def adp_delta(k, epsilon, params, n, compute_less_grad=False): tau_l = params.tau tau_g = params.tau_g L = params.L grad_evals = k * L + 1 if compute_less_grad else k * (L + 1) mu = k / (2 * tau_l**2 * n) + grad_evals / (2 * tau_g**2 * n) term1 = spec.erfc((epsilon - mu) / (2 * np.sqrt(mu))) term2 = np.exp(epsilon) * spec.erfc((epsilon + mu) / (2 * np.sqrt(mu))) return (0.5 * (term1 - term2)).sum() def adp_iters(epsilon, delta, params, n, compute_less_grad=False): low_iters = zcdp_iters(epsilon, delta, params, n, compute_less_grad) up_iters = max(low_iters, 1) while adp_delta(up_iters, epsilon, params, n, compute_less_grad) < delta: up_iters *= 2 while int(up_iters) - int(low_iters) > 1: new_iters = (low_iters + up_iters) / 2 new_delta = adp_delta(new_iters, epsilon, params, n, compute_less_grad) if new_delta > delta: up_iters = new_iters else: low_iters = new_iters if adp_delta(int(up_iters), epsilon, params, n, compute_less_grad) < delta: return int(up_iters) else: return int(low_iters) def hmc(problem, theta0, epsilon, delta, params, verbose=True, use_adp=True, compute_less_grad=False): data = problem.data n, data_dim = data.shape dim = theta0.size temp_scale = problem.temp_scale tau = params.tau tau_g = params.tau_g L = params.L eta = params.eta mass = params.mass r_clip = params.r_clip grad_clip = params.grad_clip if not use_adp: iters = zcdp_iters(epsilon, delta, params, n, compute_less_grad) else: iters = adp_iters(epsilon, delta, params, n, compute_less_grad) if verbose: print("Iterations: {}".format(iters)) sigma = tau * np.sqrt(n) chain = np.zeros((iters + 1, dim)) chain[0, :] = theta0 leapfrog_chain = np.zeros((iters * L, dim)) clipped_r = np.zeros(iters) clipped_grad_counter = GradClipCounter() accepts = 0 grad_noise_sigma = 2 * tau_g * np.sqrt(n) * grad_clip def grad_fun(theta): ll_grad, clips = problem.log_likelihood_grad_clipped(grad_clip, theta, data) clipped_grad_counter.clipped_grad += clips clipped_grad_counter.grad_accesses += 1 pri_grad = problem.log_prior_grad(theta) return temp_scale * (ll_grad + stats.norm.rvs(size=dim, scale=grad_noise_sigma)) + pri_grad if compute_less_grad: grad = grad_fun(theta0) llc = problem.log_likelihood_no_sum(theta0, data) for i in range(iters): current = chain[i, :] #TODO: this assumes diagonal M p = stats.norm.rvs(size=dim) * np.sqrt(mass) p_orig = p.copy() prop = current.copy() if compute_less_grad: grad_new = grad.copy() else: grad_new = grad_fun(current) for j in range(L): p += 0.5 * eta * (grad_new)# - 0.5 * grad_noise_sigma**2 * p / mass) prop += eta * p / mass leapfrog_chain[i * L + j] = prop grad_new = grad_fun(prop) p += 0.5 * eta * (grad_new)# - 0.5 * grad_noise_sigma**2 * p / mass) llp = problem.log_likelihood_no_sum(prop, data) r = llp - llc d = np.sqrt(np.sum((current - prop)**2)) clip = d * r_clip clipped_r[i] = np.sum(np.abs(r) > clip) r = np.clip(r, -clip, clip) lpp = problem.log_prior(prop) lpc = problem.log_prior(current) s = stats.norm.rvs(size=1, scale=sigma * d * 2 * r_clip) dp = 0.5 * np.sum(p_orig**2 / mass) - 0.5 * np.sum(p**2 / mass) dH = dp + temp_scale * (np.sum(r) + s) + lpp - lpc u = np.log(np.random.rand()) if u < dH - 0.5 * (temp_scale * sigma * d * 2 * r_clip)**2: chain[i + 1, :] = prop if compute_less_grad: grad = grad_new llc = llp accepts += 1 else: chain[i + 1, :] = current if verbose and (i + 1) % 100 == 0: print("Iteration: {}".format(i + 1)) if verbose: print("Gradient evals: {}".format(clipped_grad_counter.grad_accesses)) return util.MCMCResult( problem, chain, leapfrog_chain, iters, accepts, np.sum(clipped_r) / n / iters, np.sum(clipped_grad_counter.clipped_grad) / n / clipped_grad_counter.grad_accesses ) # return ( # chain, leapfrog_chain, accepts, clipped_r, iters, # clipped_grad_counter.clipped_grad, clipped_grad_counter.grad_accesses # )
[ "numpy.clip", "numpy.abs", "numpy.sqrt", "numpy.random.rand", "numpy.log", "scipy.stats.norm.rvs", "numpy.exp", "numpy.sum", "numpy.zeros" ]
[((2760, 2786), 'numpy.zeros', 'np.zeros', (['(iters + 1, dim)'], {}), '((iters + 1, dim))\n', (2768, 2786), True, 'import numpy as np\n'), ((2833, 2859), 'numpy.zeros', 'np.zeros', (['(iters * L, dim)'], {}), '((iters * L, dim))\n', (2841, 2859), True, 'import numpy as np\n'), ((2876, 2891), 'numpy.zeros', 'np.zeros', (['iters'], {}), '(iters)\n', (2884, 2891), True, 'import numpy as np\n'), ((1281, 1296), 'numpy.exp', 'np.exp', (['epsilon'], {}), '(epsilon)\n', (1287, 1296), True, 'import numpy as np\n'), ((2736, 2746), 'numpy.sqrt', 'np.sqrt', (['n'], {}), '(n)\n', (2743, 2746), True, 'import numpy as np\n'), ((4332, 4355), 'numpy.clip', 'np.clip', (['r', '(-clip)', 'clip'], {}), '(r, -clip, clip)\n', (4339, 4355), True, 'import numpy as np\n'), ((4449, 4501), 'scipy.stats.norm.rvs', 'stats.norm.rvs', ([], {'size': '(1)', 'scale': '(sigma * d * 2 * r_clip)'}), '(size=1, scale=sigma * d * 2 * r_clip)\n', (4463, 4501), True, 'import scipy.stats as stats\n'), ((2989, 2999), 'numpy.sqrt', 'np.sqrt', (['n'], {}), '(n)\n', (2996, 2999), True, 'import numpy as np\n'), ((3593, 3617), 'scipy.stats.norm.rvs', 'stats.norm.rvs', ([], {'size': 'dim'}), '(size=dim)\n', (3607, 3617), True, 'import scipy.stats as stats\n'), ((3620, 3633), 'numpy.sqrt', 'np.sqrt', (['mass'], {}), '(mass)\n', (3627, 3633), True, 'import numpy as np\n'), ((4217, 4246), 'numpy.sum', 'np.sum', (['((current - prop) ** 2)'], {}), '((current - prop) ** 2)\n', (4223, 4246), True, 'import numpy as np\n'), ((4652, 4668), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (4666, 4668), True, 'import numpy as np\n'), ((1255, 1266), 'numpy.sqrt', 'np.sqrt', (['mu'], {}), '(mu)\n', (1262, 1266), True, 'import numpy as np\n'), ((4302, 4311), 'numpy.abs', 'np.abs', (['r'], {}), '(r)\n', (4308, 4311), True, 'import numpy as np\n'), ((4521, 4547), 'numpy.sum', 'np.sum', (['(p_orig ** 2 / mass)'], {}), '(p_orig ** 2 / mass)\n', (4527, 4547), True, 'import numpy as np\n'), ((4554, 4575), 'numpy.sum', 'np.sum', (['(p ** 2 / mass)'], {}), '(p ** 2 / mass)\n', (4560, 4575), True, 'import numpy as np\n'), ((5212, 5229), 'numpy.sum', 'np.sum', (['clipped_r'], {}), '(clipped_r)\n', (5218, 5229), True, 'import numpy as np\n'), ((5251, 5292), 'numpy.sum', 'np.sum', (['clipped_grad_counter.clipped_grad'], {}), '(clipped_grad_counter.clipped_grad)\n', (5257, 5292), True, 'import numpy as np\n'), ((568, 581), 'numpy.log', 'np.log', (['delta'], {}), '(delta)\n', (574, 581), True, 'import numpy as np\n'), ((594, 607), 'numpy.log', 'np.log', (['delta'], {}), '(delta)\n', (600, 607), True, 'import numpy as np\n'), ((1331, 1342), 'numpy.sqrt', 'np.sqrt', (['mu'], {}), '(mu)\n', (1338, 1342), True, 'import numpy as np\n'), ((3311, 3359), 'scipy.stats.norm.rvs', 'stats.norm.rvs', ([], {'size': 'dim', 'scale': 'grad_noise_sigma'}), '(size=dim, scale=grad_noise_sigma)\n', (3325, 3359), True, 'import scipy.stats as stats\n'), ((4606, 4615), 'numpy.sum', 'np.sum', (['r'], {}), '(r)\n', (4612, 4615), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import numpy from simmate.toolkit import Structure from pymatgen.analysis.diffusion.neb.pathfinder import ( DistinctPathFinder, MigrationHop as PymatgenMigrationHop, IDPPSolver, ) from typing import List class MigrationImages(list): """ This class is just a list of structures for a diffusion pathway. It has utility methods to help create these structures but otherwise behaves exactly like a python list. Note, this class is primarily used to generate inputs for calculations. If you'd like more advanced features, you should represent your diffusion pathway as a MigrationHop instead.As a rule of thumb: Only use this class if you are manually creating your pathway from endpoint supercells or from a set of supercell images. All MigrationHop's can be converted to MigrationImages (using the `from_migration_hop` method); but not all MigrationImages can be converted to MigrationHops. """ def __init__(self, structures: List[Structure]): # This init function does nothing except apply typing -- specifically, # it says that it expects a list of structures. super().__init__(structures) def get_sum_structure(self, tolerance: float = 1e-3): """ Takes all structures and combines them into one. Atoms that are within the given tolerance are joined into a single site. This is primarily used to view a diffusing pathway within a single structure -- as well as how the host lattice changes during diffusion. If you are able to convert your pathway to a MigrationHop, the MigrationHop.write_path() method is much faster and cleaner than this method, so it should be preffered. Also, because there are many atoms that are overlapping here, the output structure may cause programs like VESTA to crash. #### Parameters - `tolerance`: the angle and distance tolerance to consider fractional coordinates as matching. Matching sites will be merged as 1 site in the final sum structure. """ # OPTIMIZE: this is very inefficient. It's much faster to visualize # structures with MigrationHop class because you know which atom is # moving. Here, we need to treat all atoms as moving. We can also # speed this up by only looking at diffusing species too. final_coords = [] final_species = [] for structure in self: # recall self is a list of structures for site in structure: is_new = True for coords in final_coords: if all( numpy.isclose( site.frac_coords, coords, rtol=tolerance, atol=tolerance, ) ): is_new = False break if is_new: final_coords.append(site.frac_coords) final_species.append(site.specie) structure = Structure( lattice=structure.lattice, species=final_species, coords=final_coords, ) return structure @staticmethod def get_nimages( pathway_length: float, min_image_step: float = 0.7, require_midpoint: bool = True, ): """ Gives the desirable number of images (not including start/end structures). This method helps generate a MigrationImages object, and typically is not called directly. The other classmethods of MigrationImages call this for you. #### Parameters - `pathway_length`: The length of the pathway. - `min_image_step`: The minimum step distance for the diffusing atom between images. The default is 0.7 Angstroms. For example, a path 2.8A long would require at least 4 images for this default. - `require_midpoint`: Whether there should be an image at the midpoint. In other words, whether the number of images should be odd. This is often important if you expect the transition state to be at the midpoint and you are not running CI-NEB. The default is True. Returns ------- - `nimages`: The number of images to use for this pathway. """ # At a minimum, we want to have images be 0.7 angstroms apart, and # with one additional image. nimages = pathway_length // min_image_step + 1 # We also want an odd number of images. This ensures we have an image # at exactly the midpoint, which is often necessary if we aren't # running CI-NEB. if require_midpoint and nimages % 2 == 0: nimages += 1 # This is a float but it makes more sense to have an integer return int(nimages) @classmethod def from_migration_hop( cls, migration_hop: PymatgenMigrationHop, vacancy_mode: bool = True, min_nsites: int = 80, max_nsites: int = 240, min_length: int = 10, **kwargs, ): """ Creates a MigrationImages object from a MigrationHop object #### Parameters - `migration_hop`: The MigrationHop object that should be converted. - `vacancy_mode`: Whether to use single-vacancy diffusion (True) or interstitial diffusion (False). The default is True. - `min_nsites`: The minimum number of sites to have in the supercell structure. The default is 80. - `max_nsites`: The maximum number of sites to have in the supercell structure. The default is 240. - `min_length`: The minimum length for each vector in the supercell structure. The default is 10 Angstroms. - `**kwargs`: Any arguments that are normally accepted by IDPPSolver """ # The third thing returned is the bulk_supercell which we don't need. start_supercell, end_supercell, _ = migration_hop.get_sc_structures( vac_mode=vacancy_mode, min_atoms=min_nsites, max_atoms=max_nsites, min_length=min_length, ) # calculate the number of images required nimages = cls.get_nimages(migration_hop.length) return cls.from_endpoints( start_supercell, end_supercell, nimages=nimages, **kwargs, ) @classmethod def from_endpoints( cls, structure_start: Structure, structure_end: Structure, nimages: int, **kwargs, ): """ Creates a MigrationImages object from start and end supercell structures. You do not need to specify the diffusing atom(s) as all sites are linearly interpolated and then relaxed by IDPP. #### Parameters - `structure_start`: The starting supercell of the diffusion pathway. - `structure_end`: The ending supercell of the diffusion pathway. - `nimages`: The number of desired images for the pathway. Note, if you know the pathway length of your path, you can use the `get_nimages` static method to get a logical number of images. - `**kwargs`: Any arguments that are normally accepted by IDPPSolver """ # Run IDPP relaxation on the images before returning them idpp_solver = IDPPSolver.from_endpoints( [structure_start, structure_end], nimages=nimages, **kwargs, ) images = idpp_solver.run() return cls(images) @classmethod def from_startend_sites( cls, structure: Structure, site_start: int, site_end: int, **kwargs, ): """ Creates a MigrationImages object from a bulk structure and start/end periodic sites of the diffusing atom. For example, this would allow a diffusion pathway that goes from a site at (0,0,0) to (1,1,1). Thus, symmetry and periodic boundry conditions are considered. Note, this method just creates a MigrationHop and then uses the `from_migration_hop` method to make a MigrationImages object. #### Parameters - `structure`: The bulk crystal structure (NOT the supercell). - `site_start`: The starting periodic site for this pathway. - `site_end`: The end periodic site for this pathway. - `**kwargs`: Any arguments that are normally accepted by `from_migration_hop`. """ # This information is all we need for a MigrationHop object pathway = PymatgenMigrationHop(site_start, site_end, structure) return cls.from_migration_hop(pathway, **kwargs) @classmethod def from_structure( cls, structure: Structure, migrating_specie: str, pathfinder_kwargs: dict = {}, **kwargs, ): """ Given a bulk crystal structure, this will find all symmetrically unique pathways and return them as list of MigrationImages objects. #### Parameters - `structure`: The bulk crystal structure (NOT the supercell). - `migrating_specie`: The identity of the diffusing ion (e.g. "Li" or "Li1+"). Note, only provide oxidation state if you are using an oxidation-state decorated structure. - `pathfinder_kwargs`: Any arguments that are normally accepted by DistinctPathFinder, but given as a dictionary. The default is {}. - `**kwargs`: Any arguments that are normally accepted by `from_migration_hop`. """ # convert to the LLL reduced primitive cell to make it as cubic as possible structure_lll = structure.get_sanitized_structure() # Use pymatgen to find all the symmetrically unique pathways. # NOTE: This only finds pathways up until the structure is percolating. # If you are interested in longer pathways, then this script needs to # be adjusted by passing additional kwargs pathfinder = DistinctPathFinder( structure_lll, migrating_specie=migrating_specie, **pathfinder_kwargs, ) pathways = pathfinder.get_paths() # Now go through each path and convert to a MigrationPath. We return # these as a list of paths. migration_paths = [] for pathway in pathways: migration_path = cls.from_migration_hop( migration_hop=pathway, **kwargs, ) migration_paths.append(migration_path) return migration_paths @classmethod def from_dynamic(cls, migration_images): """ This is an experimental feature. The code here is a repurposing of Structre.from_dynamic so consider making a general class for from_dynamic methods. """ is_from_past_calc = False # assume any list is in the MigrationHop format if there are more than # two structures (i.e. there is at least one midpoint image) if isinstance(migration_images, list) and len(migration_images) > 2: migration_images_cleaned = migration_images else: raise Exception("Unknown format provided for migration_images input.") migration_images_cleaned.is_from_past_calc = is_from_past_calc return migration_images_cleaned def as_dict(self): return [s.as_dict() for s in self]
[ "simmate.toolkit.Structure", "numpy.isclose", "pymatgen.analysis.diffusion.neb.pathfinder.MigrationHop", "pymatgen.analysis.diffusion.neb.pathfinder.IDPPSolver.from_endpoints", "pymatgen.analysis.diffusion.neb.pathfinder.DistinctPathFinder" ]
[((3195, 3280), 'simmate.toolkit.Structure', 'Structure', ([], {'lattice': 'structure.lattice', 'species': 'final_species', 'coords': 'final_coords'}), '(lattice=structure.lattice, species=final_species, coords=final_coords\n )\n', (3204, 3280), False, 'from simmate.toolkit import Structure\n'), ((7774, 7864), 'pymatgen.analysis.diffusion.neb.pathfinder.IDPPSolver.from_endpoints', 'IDPPSolver.from_endpoints', (['[structure_start, structure_end]'], {'nimages': 'nimages'}), '([structure_start, structure_end], nimages=nimages,\n **kwargs)\n', (7799, 7864), False, 'from pymatgen.analysis.diffusion.neb.pathfinder import DistinctPathFinder, MigrationHop as PymatgenMigrationHop, IDPPSolver\n'), ((9060, 9113), 'pymatgen.analysis.diffusion.neb.pathfinder.MigrationHop', 'PymatgenMigrationHop', (['site_start', 'site_end', 'structure'], {}), '(site_start, site_end, structure)\n', (9080, 9113), True, 'from pymatgen.analysis.diffusion.neb.pathfinder import DistinctPathFinder, MigrationHop as PymatgenMigrationHop, IDPPSolver\n'), ((10560, 10654), 'pymatgen.analysis.diffusion.neb.pathfinder.DistinctPathFinder', 'DistinctPathFinder', (['structure_lll'], {'migrating_specie': 'migrating_specie'}), '(structure_lll, migrating_specie=migrating_specie, **\n pathfinder_kwargs)\n', (10578, 10654), False, 'from pymatgen.analysis.diffusion.neb.pathfinder import DistinctPathFinder, MigrationHop as PymatgenMigrationHop, IDPPSolver\n'), ((2732, 2803), 'numpy.isclose', 'numpy.isclose', (['site.frac_coords', 'coords'], {'rtol': 'tolerance', 'atol': 'tolerance'}), '(site.frac_coords, coords, rtol=tolerance, atol=tolerance)\n', (2745, 2803), False, 'import numpy\n')]
# Copyright 2020 LMNT, 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. # ============================================================================== import numpy as np import os import torch import torch.nn as nn from torch.nn.parallel import DistributedDataParallel from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from wavegrad.dataset import from_path as dataset_from_path from wavegrad.model import WaveGrad def _nested_map(struct, map_fn): if isinstance(struct, tuple): return tuple(_nested_map(x, map_fn) for x in struct) if isinstance(struct, list): return [_nested_map(x, map_fn) for x in struct] if isinstance(struct, dict): return { k: _nested_map(v, map_fn) for k, v in struct.items() } return map_fn(struct) class WaveGradLearner: def __init__(self, model_dir, model, dataset, optimizer, params, *args, **kwargs): os.makedirs(model_dir, exist_ok=True) self.model_dir = model_dir self.model = model self.dataset = dataset self.optimizer = optimizer self.params = params self.autocast = torch.cuda.amp.autocast(enabled=kwargs.get('fp16', False)) self.scaler = torch.cuda.amp.GradScaler(enabled=kwargs.get('fp16', False)) self.step = 0 self.is_master = True beta = np.array(self.params.noise_schedule) noise_level = np.cumprod(1 - beta)**0.5 noise_level = np.concatenate([[1.0], noise_level], axis=0) self.noise_level = torch.tensor(noise_level.astype(np.float32)) self.loss_fn = nn.L1Loss() self.summary_writer = None def state_dict(self): if hasattr(self.model, 'module') and isinstance(self.model.module, nn.Module): model_state = self.model.module.state_dict() else: model_state = self.model.state_dict() return { 'step': self.step, 'model': { k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in model_state.items() }, 'optimizer': { k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in self.optimizer.state_dict().items() }, 'params': dict(self.params), 'scaler': self.scaler.state_dict(), } def load_state_dict(self, state_dict): if hasattr(self.model, 'module') and isinstance(self.model.module, nn.Module): self.model.module.load_state_dict(state_dict['model']) else: self.model.load_state_dict(state_dict['model']) self.optimizer.load_state_dict(state_dict['optimizer']) self.scaler.load_state_dict(state_dict['scaler']) self.step = state_dict['step'] def save_to_checkpoint(self, filename='weights'): save_basename = f'{filename}-{self.step}.pt' save_name = f'{self.model_dir}/{save_basename}' link_name = f'{self.model_dir}/{filename}.pt' torch.save(self.state_dict(), save_name) if os.name == 'nt': torch.save(self.state_dict(), link_name) else: if os.path.islink(link_name): os.unlink(link_name) os.symlink(save_basename, link_name) def restore_from_checkpoint(self, filename='weights'): try: checkpoint = torch.load(f'{self.model_dir}/{filename}.pt') self.load_state_dict(checkpoint) return True except FileNotFoundError: return False def train(self, max_steps=None): device = next(self.model.parameters()).device while True: for features in tqdm(self.dataset, desc=f'Epoch {self.step // len(self.dataset)}') if self.is_master else self.dataset: if max_steps is not None and self.step >= max_steps: return features = _nested_map(features, lambda x: x.to(device) if isinstance(x, torch.Tensor) else x) loss = self.train_step(features) if torch.isnan(loss).any(): raise RuntimeError(f'Detected NaN loss at step {self.step}.') if self.is_master: if self.step % 100 == 0: self._write_summary(self.step, features, loss) if self.step % len(self.dataset) == 0: self.save_to_checkpoint() self.step += 1 def train_step(self, features): for param in self.model.parameters(): param.grad = None audio = features['audio'] spectrogram = features['spectrogram'] N, T = audio.shape S = 1000 device = audio.device self.noise_level = self.noise_level.to(device) with self.autocast: s = torch.randint(1, S + 1, [N], device=audio.device) l_a, l_b = self.noise_level[s-1], self.noise_level[s] noise_scale = l_a + torch.rand(N, device=audio.device) * (l_b - l_a) noise_scale = noise_scale.unsqueeze(1) noise = torch.randn_like(audio) noisy_audio = noise_scale * audio + (1.0 - noise_scale**2)**0.5 * noise predicted = self.model(noisy_audio, spectrogram, noise_scale.squeeze(1)) loss = self.loss_fn(noise, predicted.squeeze(1)) self.scaler.scale(loss).backward() self.scaler.unscale_(self.optimizer) self.grad_norm = nn.utils.clip_grad_norm_(self.model.parameters(), self.params.max_grad_norm) self.scaler.step(self.optimizer) self.scaler.update() return loss def _write_summary(self, step, features, loss): writer = self.summary_writer or SummaryWriter(self.model_dir, purge_step=step) writer.add_audio('audio/reference', features['audio'][0], step, sample_rate=self.params.sample_rate) writer.add_scalar('train/loss', loss, step) writer.add_scalar('train/grad_norm', self.grad_norm, step) writer.flush() self.summary_writer = writer def _train_impl(replica_id, model, dataset, args, params): torch.backends.cudnn.benchmark = True opt = torch.optim.Adam(model.parameters(), lr=params.learning_rate) learner = WaveGradLearner(args.model_dir, model, dataset, opt, params, fp16=args.fp16) learner.is_master = (replica_id == 0) learner.restore_from_checkpoint() learner.train(max_steps=args.max_steps) def train(args, params): dataset = dataset_from_path(args.data_dirs, params) model = WaveGrad(params).cuda() _train_impl(0, model, dataset, args, params) def train_distributed(replica_id, replica_count, port, args, params): os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = str(port) torch.distributed.init_process_group('nccl', rank=replica_id, world_size=replica_count) device = torch.device('cuda', replica_id) torch.cuda.set_device(device) model = WaveGrad(params).to(device) model = DistributedDataParallel(model, device_ids=[replica_id]) _train_impl(replica_id, model, dataset_from_path(args.data_dirs, params, is_distributed=True), args, params)
[ "wavegrad.model.WaveGrad", "torch.nn.L1Loss", "numpy.array", "wavegrad.dataset.from_path", "os.path.islink", "torch.isnan", "torch.utils.tensorboard.SummaryWriter", "torch.randint", "os.unlink", "numpy.concatenate", "torch.nn.parallel.DistributedDataParallel", "torch.randn_like", "torch.cuda.set_device", "torch.device", "os.makedirs", "numpy.cumprod", "torch.load", "os.symlink", "torch.distributed.init_process_group", "torch.rand" ]
[((6383, 6424), 'wavegrad.dataset.from_path', 'dataset_from_path', (['args.data_dirs', 'params'], {}), '(args.data_dirs, params)\n', (6400, 6424), True, 'from wavegrad.dataset import from_path as dataset_from_path\n'), ((6662, 6754), 'torch.distributed.init_process_group', 'torch.distributed.init_process_group', (['"""nccl"""'], {'rank': 'replica_id', 'world_size': 'replica_count'}), "('nccl', rank=replica_id, world_size=\n replica_count)\n", (6698, 6754), False, 'import torch\n'), ((6762, 6794), 'torch.device', 'torch.device', (['"""cuda"""', 'replica_id'], {}), "('cuda', replica_id)\n", (6774, 6794), False, 'import torch\n'), ((6797, 6826), 'torch.cuda.set_device', 'torch.cuda.set_device', (['device'], {}), '(device)\n', (6818, 6826), False, 'import torch\n'), ((6875, 6930), 'torch.nn.parallel.DistributedDataParallel', 'DistributedDataParallel', (['model'], {'device_ids': '[replica_id]'}), '(model, device_ids=[replica_id])\n', (6898, 6930), False, 'from torch.nn.parallel import DistributedDataParallel\n'), ((1409, 1446), 'os.makedirs', 'os.makedirs', (['model_dir'], {'exist_ok': '(True)'}), '(model_dir, exist_ok=True)\n', (1420, 1446), False, 'import os\n'), ((1798, 1834), 'numpy.array', 'np.array', (['self.params.noise_schedule'], {}), '(self.params.noise_schedule)\n', (1806, 1834), True, 'import numpy as np\n'), ((1897, 1941), 'numpy.concatenate', 'np.concatenate', (['[[1.0], noise_level]'], {'axis': '(0)'}), '([[1.0], noise_level], axis=0)\n', (1911, 1941), True, 'import numpy as np\n'), ((2029, 2040), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (2038, 2040), True, 'import torch.nn as nn\n'), ((6964, 7026), 'wavegrad.dataset.from_path', 'dataset_from_path', (['args.data_dirs', 'params'], {'is_distributed': '(True)'}), '(args.data_dirs, params, is_distributed=True)\n', (6981, 7026), True, 'from wavegrad.dataset import from_path as dataset_from_path\n'), ((1853, 1873), 'numpy.cumprod', 'np.cumprod', (['(1 - beta)'], {}), '(1 - beta)\n', (1863, 1873), True, 'import numpy as np\n'), ((3376, 3401), 'os.path.islink', 'os.path.islink', (['link_name'], {}), '(link_name)\n', (3390, 3401), False, 'import os\n'), ((3438, 3474), 'os.symlink', 'os.symlink', (['save_basename', 'link_name'], {}), '(save_basename, link_name)\n', (3448, 3474), False, 'import os\n'), ((3561, 3606), 'torch.load', 'torch.load', (['f"""{self.model_dir}/{filename}.pt"""'], {}), "(f'{self.model_dir}/{filename}.pt')\n", (3571, 3606), False, 'import torch\n'), ((4825, 4874), 'torch.randint', 'torch.randint', (['(1)', '(S + 1)', '[N]'], {'device': 'audio.device'}), '(1, S + 1, [N], device=audio.device)\n', (4838, 4874), False, 'import torch\n'), ((5069, 5092), 'torch.randn_like', 'torch.randn_like', (['audio'], {}), '(audio)\n', (5085, 5092), False, 'import torch\n'), ((5650, 5696), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['self.model_dir'], {'purge_step': 'step'}), '(self.model_dir, purge_step=step)\n', (5663, 5696), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((6435, 6451), 'wavegrad.model.WaveGrad', 'WaveGrad', (['params'], {}), '(params)\n', (6443, 6451), False, 'from wavegrad.model import WaveGrad\n'), ((6837, 6853), 'wavegrad.model.WaveGrad', 'WaveGrad', (['params'], {}), '(params)\n', (6845, 6853), False, 'from wavegrad.model import WaveGrad\n'), ((3411, 3431), 'os.unlink', 'os.unlink', (['link_name'], {}), '(link_name)\n', (3420, 3431), False, 'import os\n'), ((4961, 4995), 'torch.rand', 'torch.rand', (['N'], {'device': 'audio.device'}), '(N, device=audio.device)\n', (4971, 4995), False, 'import torch\n'), ((4174, 4191), 'torch.isnan', 'torch.isnan', (['loss'], {}), '(loss)\n', (4185, 4191), False, 'import torch\n')]
# Import necessary packages here from typing import List import warnings from datetime import datetime import pandas as pd import numpy as np import matplotlib.dates as mdates from matplotlib import rc, pyplot as plt # ============================================================================ # ============================================================================ # Date: December 18, 2020 # Purpose: This file contains classes and functions necessary for # plotting. # Source Code Metadata __author__ = "<NAME>" __copyright__ = "Copyright 2020, Jon Webb Inc." __version__ = "1.0" # ============================================================================ # ============================================================================ def text_date_plot(dates: List[List[str]], y_data: List[List[float]], line_colors: List[str], line_style: List[str], line_weight: List[str], x_label: str, y_label: str, dat_labels: List[str], label_pos: str, y_scale: str = 'LIN', plot_name: str = 'NULL', save: bool = False, label_font_size: int = 18, tick_font_size: int = 18, style_name: str = 'default', title: str = 'NULL', title_font_size: int = 24) -> None: """ :param dates: A list of lists, where each inner list contains a list of dates as a text string in the format YYYY-MM-DD or YYYY/MM/DD :param y_data: A list of lists containing y-axis data corresponding to the list of lists in `dates` :param line_colors: A list of line colors ,one for each curve. Acceptable line color indicators can be found in documentation for matplotlib colors <https://matplotlib.org/3.1.0/gallery/color/named_colors.html>`_. :param line_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style <https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html>`_. :param line_weight: A list of line weights, one for each curve. :param x_label: The x-axis label :param y_label: The y-axis label :param dat_labels: A list of labels, one for each curve :param label_pos: The position of the label in the plot, examples might be ``upper left``, ``lower right``. :param y_scale: 'LOG' or 'LIN' for logarithmic or linear scale :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param save: True or False, defaulted to False :param label_font_size: The font size for plot labels, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return None: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single plots of one or multiple data sets as a function of date. This function assumes that the date string is in the format of a text string and not a Timestamp or datetime. This function also autonomusly determines the appropriate date display format. If you desire plots as a function of time you should use the ``text_time_plot`` function. The function can be used in the following manner; .. code-block:: python > # Use stock data for example > tickers = ['AAPL', 'WMT'] > data = yf.download(tickers, '2015-1-1')['Adj Close'] > # transform Timestamps to string > dates = list(data.index.strftime('%Y-%m-%d')) > date_list = [dates, dates] > y_list = [list(data[tickers[0]]), list(data[tickers[1]])] > colors = ['red', 'green'] > line_style = ['-', '-'] > weight = [1.0, 1.0] > text_date_plot(date_list, y_list, colors, line_style, weight, 'Date', '$', tickers, 'upper left') .. image:: date.eps :align: center """ # Adjust format for YYYY/MM/DD to YYYY-MM-DD outer_list = [] for i in range(len(dates)): inner_list = [] for j in range(len(dates[i])): year = dates[i][j][0:4] month = dates[i][j][5:7] day = dates[i][j][8:10] date_string = year + '-' + month + '-' + day inner_list.append(datetime.strptime(date_string, '%Y-%m-%d')) outer_list.append(inner_list) # Determine time difference between min and max point days = 0 for i in outer_list: delta = (max(i) - min(i)).days if delta > days: days = delta # Start plot fig, td_plot = plt.subplots() plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) if y_scale.upper() == 'LOG': td_plot.set_yscale('log') if days <= 15: myfmt = mdates.DateFormatter('%d') td_plot.xaxis.set_major_locator(mdates.DayLocator()) elif days <= 180: myfmt = mdates.DateFormatter('%b-%y') td_plot.xaxis.set_major_locator(mdates.MonthLocator()) else: myfmt = mdates.DateFormatter('%b-%y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(4)) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) td_plot.xaxis.set_major_formatter(myfmt) for i in range(len(outer_list)): td_plot.plot(outer_list[i], y_data[i], color=line_colors[i], label=dat_labels[i], linewidth=line_weight[i], linestyle=line_style[i]) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) # ---------------------------------------------------------------------------- def two_d_line_matplot(x_data: List[List[float]], y_data: List[List[float]], line_colors: List[str], line_style: List[str], line_weight: List[str], x_label: str, y_label: str, dat_labels: List[str], label_pos: str, x_scale: str = 'LIN', y_scale: str = 'LIN', plot_name: str = 'NULL', save: bool = False, label_font_size: int = 18, tick_font_size: int = 18, style_name: str = 'default', title: str = 'NULL', title_font_size: int = 24) -> None: """ :param x_data: A list of lists, where the inner lists contain data points for the x-axis :param y_data: A list of lists, where the inner lists contain data points for the y-axis :param line_colors: A list of line colors ,one for each curve. Acceptable line color indicators can be found in documentation for matplotlib colors <https://matplotlib.org/3.1.0/gallery/color/named_colors.html>`_. :param line_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style <https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html>`_. :param line_weight: A list of line weights, one for each curve. :param x_label: The label for the x-axis :param y_label: The label for the y-axis :param dat_labels: A list of labels, one for each curve :param label_pos: The position of the label in the plot, examples might be ``upper left``, ``lower right``. :param x_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param y_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param save: True or False, defaulted to False :param label_font_size: The font size for plot labels, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return None: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single plots of one or multiple data sets. This function will only produce line plots and not scatter plots or a combination of both. The function can be used in the following manner; .. code-block:: python > x_dat = np.linspace(0, 10, 15) > y1_dat = x_dat > y2_dat = x_dat ** 2.0 > y3_dat = x_dat ** 3.0 > x_list = [x_dat, x_dat, x_dat] > y_list = [y1_dat, y2_dat, y3_dat] > colors = ['red', 'blue', 'black'] > line_style = ['-', '-', '--'] > labels = ['linear', 'squared', 'cubed'] > weight = [1, 2, 3] > two_d_line_matplot(x_list, y_list, colors, line_style, weight, 'x-data', 'y-data', labels, 'upper left') .. image:: line_plot.eps :scale: 90% :align: center """ # Error checking and warnings if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if len(x_data) != len(y_data): warnings.warn('length of x list of lists is not the same as y list of lists, plot not printed') return if len(line_colors) != len(x_data): warnings.warn('line colors list not the same length as data lists, plot not printed') return if len(line_style) != len(x_data): warnings.warn('line_style list not the same length as data lists, plot not printed') return if len(line_weight) != len(x_data): warnings.warn('line_weight list not the same length as data lists, plot not printed') return if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(line_colors)): td_plot.plot(x_data[i], y_data[i], color=line_colors[i], label=dat_labels[i], linewidth=line_weight[i], linestyle=line_style[i]) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) # ---------------------------------------------------------------------------- def two_d_scatter_matplot(x_data: List[List[float]], y_data: List[List[float]], marker_colors: List[str], marker_style: List[str], x_label: str, y_label: str, dat_labels: List[str], label_pos: str, x_scale: str = 'LIN', y_scale: str = 'LIN', plot_name: str = 'NULL', save: bool = False, label_font_size: int = 18, tick_font_size: int = 18, style_name: str = 'default', title: str = 'NULL', title_font_size: int = 24) -> None: """ :param x_data: A list of lists, where the inner lists contain data points for the x-axis :param y_data: A list of lists, where the inner lists contain data points for the y-axis :param marker_colors: A list of line colors ,one for each curve. Acceptable line color indicators can be found in documentation for `matplotlib colors <https://matplotlib.org/3.1.0/gallery/color/named_colors.html>`_. :param marker_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style`_. :param x_label: The label for the x-axis :param y_label: The label for the y-axis :param dat_labels: A list of labels, one for each curve :param label_pos: The position of the label in the plot, examples might be ``upper left``, ``lower right`` :param x_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param y_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param save: True or False, defaulted to False :param label_font_size: The font size for plot labels, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return None: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single plots of one or multiple data sets. This function will only produce line plots and not scatter plots or a combination of both. The function can be used in the following manner; .. code-block:: python > x_dat = np.linspace(0, 10, 15) > y1_dat = x_dat > y2_dat = x_dat ** 2.0 > y3_dat = x_dat ** 3.0 > x_list = [x_dat, x_dat, x_dat] > y_list = [y1_dat, y2_dat, y3_dat] > colors = ['red', 'blue', 'black'] > line_style = ['-', '-', '--'] > labels = ['linear', 'squared', 'cubed'] > weight = [1, 2, 3] > two_d_scatter_matplot(x_list, y_list, colors, line_style, weight, 'x-data', 'y-data', labels, 'upper left') .. image:: scatter_plot.eps :align: center """ # Error checking and warnings if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if len(x_data) != len(y_data): warnings.warn('length of x list of lists is not the same as y list of lists, plot not printed') return if len(marker_colors) != len(x_data): warnings.warn('line colors list not the same length as data lists, plot not printed') return if len(marker_style) != len(x_data): warnings.warn('line_style list not the same length as data lists, plot not printed') return if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(marker_colors)): td_plot.plot(x_data[i], y_data[i], color=marker_colors[i], label=dat_labels[i], marker=marker_style[i], linestyle=' ') plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) # ---------------------------------------------------------------------------- def two_d_scatter_line_matplot(x_data: List[List[float]], y_data: List[List[float]], marker_colors: List[str], marker_style: List[str], line_style: List[str], line_weight: List[str], x_label: str, y_label: str, dat_labels: List[str], label_pos: str, x_scale: str = 'LIN', y_scale: str = 'LIN', plot_name: str = 'NULL', save: bool = False, label_font_size: int = 18, tick_font_size: int = 18, style_name: str = 'default', title: str = 'NULL', title_font_size: int = 24) -> None: """ :param x_data: A list of lists, where the inner lists contain data points for the x-axis :param y_data: A list of lists, where the inner lists contain data points for the y-axis :param marker_colors: A list of line colors ,one for each curve. Acceptable line color indicators can be found in documentation for `matplotlib colors <https://matplotlib.org/3.1.0/gallery/color/named_colors.html>`_. :param marker_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style`_. :param line_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style <https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html>`_. :param line_weight: A list of line weights, one for each curve. :param x_label: The label for the x-axis :param y_label: The label for the y-axis :param dat_labels: A list of labels, one for each curve :param label_pos: The position of the label in the plot, examples might be ``upper left``, ``lower right`` :param x_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param y_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param save: True or False, defaulted to False :param label_font_size: The font size for plot labels, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return None: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single plots of one or multiple data sets overlaid with line plots. This function will only produce line plots and not scatter plots or a combination of both. The function can be used in the following manner; .. code-block:: python > x_dat = np.linspace(0, 10, 15) > y1_dat = x_dat > y2_dat = x_dat ** 2.0 > y3_dat = x_dat ** 3.0 > x_list = [x_dat, x_dat, x_dat] > y_list = [y1_dat, y2_dat, y3_dat] > colors = ['red', 'blue', 'black'] > line_style = ['-', '-', '--'] > labels = ['linear', 'squared', 'cubed'] > weight = [1, 2, 3] > marker_style = ['^', 'o', 'd'] > two_d_scatter_line_matplot(x_list, y_list, colors, marker_style, line_style, weight, 'x-axis', 'y-axis', labels, 'upper left', save=True, plot_name=plt_name) .. image:: line_mark.eps :align: center """ # Error checking and warnings if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if len(x_data) != len(y_data): warnings.warn('length of x list of lists is not the same as y list of lists, plot not printed') return if len(marker_colors) != len(x_data): warnings.warn('line colors list not the same length as data lists, plot not printed') return if len(marker_style) != len(x_data): warnings.warn('line_style list not the same length as data lists, plot not printed') return if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(marker_colors)): td_plot.plot(x_data[i], y_data[i], color=marker_colors[i], label=dat_labels[i], marker=marker_style[i], linestyle=line_style[i], linewidth=line_weight[i]) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) # ---------------------------------------------------------------------------- def one_d_histogram_plot(data: List[List[float]], labels: List[List[str]], x_label: str, y_label: str, colors: List[str], edge_colors: List[str], shading: List[float], label_pos: str, num_bins: int = 50, tick_font_size: int = 18, label_font_size: str = 18, style_name: str = 'default', save: bool = False, plot_name: str = 'NULL', hist_type: str = 'bar', dens: bool = False, title: str = 'NULL', title_font_size: int = 24) -> None: """ :param data: A list of lists containing data for one or multiple distributions :param labels: A list of labels, one for each distribution :param x_label: The label for the x-axis :param y_label: The label for the y-axis :param colors: The fill colors for each ``bar`` plot. If a ``step`` plot is selected, this input is irrelevant, but data must still be passed to the function. :param edge_colors: The colors for the edge of each bar or step plot :param shading: The level of transparency for bar plot fill. a Value of 0 is invisible, 1 is the maximum color density :param label_pos: Where in the plot, the labels for each curve are to be placed. ``upper left`` or ``lower right`` are examples. :param num_bins: The number of bins to be plotted, defaulted to 50 :param tick_font_size: The size for each tick, defaulted to 18 :param label_font_size: The size for printed font, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param save: True or False, defaulted to False :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param hist_type: {``bar``, ``barstacked``, ``step``, ``stepfilled``} See `histogram <https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html>`_ for more information. :param dens: If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1 :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single phistogram plots or multiple overlaid plots. The function can be used in the following manner; .. code-block:: python > np.random.seed(19680801) > x = np.random.normal(15.0, 3.0, 1000) > y = np.random.normal(20.0, 3.0, 1000) > data = [x, y] > labels = ['one', 'two'] > colors = ['blue', 'green'] > edge_colors = ['black', 'black'] > alpha = [0.9, 0.2] > x_label = 'x-axis' > y_label = 'y-axis' > one_d_histogram_plot(data, labels, x_label, y_label, colors, edge_colors, alpha, 'upper left', num_bins=50, hist_type='step', dens=True) .. image:: hist1.eps :align: center The plot parameters can be changed to produce a normalized plot, only showing the histogram outline with the following code. .. code-block:: python > np.random.seed(19680801) > x = np.random.normal(15.0, 3.0, 1000) > y = np.random.normal(20.0, 3.0, 1000) > data = [x, y] > labels = ['one', 'two'] > colors = ['black', 'red'] > edge_colors = ['black', 'red'] > alpha = [1.0, 1.0] > x_label = 'x-axis' > y_label = 'y-axis' > one_d_histogram_plot(data, labels, x_label, y_label, colors, edge_colors, alpha, 'upper left', num_bins=50) .. image:: hist2.eps :align: center """ if len(labels) != len(data): warnings.warn("data list should be the same length as the labels list") if len(labels) != len(colors): warnings.warn("data list should be the same length as the colors list") if len(labels) != len(edge_colors): warnings.warn("labels list should be the same length as the edge_colors list") if len(labels) != len(shading): warnings.warn("labels list should be the same length as the shading list") plt.tight_layout() plt.gcf().subplots_adjust(bottom=0.15) plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) plt.xlabel(x_label, fontsize=label_font_size) plt.ylabel(y_label, fontsize=label_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) for i in range(len(labels)): plt.hist(data[i], bins=num_bins, color=colors[i], edgecolor=edge_colors[i], alpha=shading[i], label=labels[i], histtype=hist_type, density=dens) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # ================================================================================ # ================================================================================ class MatPlotDataFrame: """ :param df: Dataframe containing columnar data to be plotted This class will plot user specified data from a pandas dataframe """ def __init__(self, df: pd.DataFrame): self.df = df self.colors = ['lightgrey', 'deepskyblue', 'sandybrown', 'teal', 'limegreen', 'coral', 'hotpink', 'magenta', 'red', 'white', 'gold', 'darkgreen', 'turqoise', 'olive', 'orange', 'mediumvioletred', 'purple' , 'darkred'] self.styles = ['o' for i in range(len(self.colors))] # -------------------------------------------------------------------------------- def scatter_plot_parse_column(self, x_header: str, y_header: str, parsing_header: str, column_values: List[str], style_name: str='default', marker_colors: List[str]=['None'], marker_style: List[str]=['None'], fill_alpha: np.float32=0.7, edge_color: str='black', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey') -> None: """ :param x_header: The title of the dataframe column containing the x-axis data sets :param y_header: The title of the dataframe column containing the y-axis data sets :param parsing_header: The title of the dataframe column containing the values which will be used to parse the dataframe into one or multiple data sets :param column_values: The values contained in the parsing_header column that will be used to parse the data set into multiple data sets :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param marker_colors: A list of marker colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param marker_style: A list of marker styles, where each marker style corresponds to a data set. This parameter has a default list of 18 circle marker styles that the user can override. Marker styles can be found at :href `marker style<https://matplotlib.org/stable/api/markers_api.html>` :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param edge_color: The color of the line surrounding the marker :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will parse a dataframe column based on a user specified value or list of values, and plot the data in a user specified x and y axis column based on filter data. As an example, consider a dataframe with the following columnar data structure. .. code-block:: python > length = 20 > x = np.linspace(0, length, num=length) > linear = x > squared = x ** 2.0 > lin = np.repeat('linear', length) > sq = np.repeat('squared', length) > # Combine arrays into one > x = np.hstack((x, x)) > y = np.hstack((linear, squared)) > power = np.hstack((lin, sq)) > # Create dataframe > dictionary = {'x': x, 'y': y, 'power': power} > df = pd.DataFrame(dictionary) > # Plot data > obj = MatPlotDataFrame(df) > parsing_header = 'power' > column_values = ['linear', 'squared'] obj.scatter_plot_filter_column('x', 'y', parsing_header, column_values, marker_colors=['red', 'green'], marker_style=['o', '^'], label_pos='upper left') .. image:: mat_scatter_test1.eps :align: center """ df_list = [self.df[self.df[parsing_header] == col_val] for col_val in column_values] # Error checking if marker_colors[0] == 'None': marker_colors = self.colors if len(marker_colors) < len(column_values): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if marker_style[0] == 'None': marker_style = self.styles if len(marker_style) < len(column_values): msg1 = 'FATAL ERROR: The length of the marker stye list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(df_list)): td_plot.scatter(df_list[i][x_header], df_list[i][y_header], label=column_values[i], marker=marker_style[i], color=marker_colors[i], alpha=fill_alpha, edgecolors=edge_color, s=marker_size, linewidth=marker_edge_width) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def scatter_plot_columns(self, x_headers: List[str], y_headers: List[str], labels: List[str], style_name: str='default', marker_colors: List[str]=['None'], marker_style: List[str]=['None'], fill_alpha: np.float32=0.7, edge_color: str='black', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey'): """ :param x_headers: The title of the dataframe columns containing the x-axis data sets :param y_headers: The title of the dataframe columns containing the y-axis data sets :param labels: A list of the label names for each data set :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param marker_colors: A list of marker colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param marker_style: A list of marker styles, where each marker style corresponds to a data set. This parameter has a default list of 18 circle marker styles that the user can override. Marker styles can be found at :href `marker style<https://matplotlib.org/stable/api/markers_api.html>` :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param edge_color: The color of the line surrounding the marker :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will plot used defined dataframe columns for the x and y axis of a 2-d plot as a scatter plot. .. code-block:: python > length = 20 > x = np.linspace(0, 20, num=20) > linear = x > squared = x ** 2.0 > # create dataframe > dictionary = {'x': x, 'linear': linear, 'squared': squared} > df = pd.DataFrame(dictionary) > # plot data > obj = MatPlotDataFrame(df) > x_headers = ['x', 'x'] > y_headers = ['linear', 'squared'] > obj.scatter_plot_columns(x_headers, y_headers, y_headers, x_label='x-axis', y_label='y-axis', title='Test', style_name='default',marker_colors=['red', 'green'], fill_alpha=0.7, marker_style=['o', '^'], label_pos='upper left', grid=False, save=True, plot_name=plt_name) .. image:: mat_scatter_test2.eps :align: center """ # Error checking if marker_colors[0] == 'None': marker_colors = self.colors if len(x_headers) != len(y_headers): sys.exit('FATAL ERROR: x and y arrays must be the same size') if marker_style[0] == 'None': marker_style = self.styles if len(marker_style) < len(x_headers): msg1 = 'FATAL ERROR: The length of the marker stye list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(x_headers)): td_plot.scatter(self.df[x_headers[i]], self.df[y_headers[i]], label=labels[i], marker=marker_style[i], color=marker_colors[i], alpha=fill_alpha, edgecolors=edge_color, s=marker_size, linewidth=marker_edge_width) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def line_plot_parse_column(self, x_header: str, y_header: str, parsing_header: str, column_values: List[str], style_name: str='default', line_colors: List[str]=['None'], line_weight: np.float32=2.0, fill_alpha: np.float32=0.7, line_style: str='-', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey') -> None: """ :param x_header: The title of the dataframe column containing the x-axis data sets :param y_header: The title of the dataframe column containing the y-axis data sets :param parsing_header: The title of the dataframe column containing the values which will be used to parse the dataframe into one or multiple data sets :param column_values: The values contained in the parsing_header column that will be used to parse the data set into multiple data sets :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param line_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param line_weight: The weight corresponding to the line thickness, defaulted to 2.0 :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will parse a dataframe column based on a user specified value or list of values, and plot the data in a user specified x and y axis column based on filter data. As an example, consider a dataframe with the following columnar data structure. .. code-block:: python > length = 20 > x = np.linspace(0, length, num=length) > linear = x > squared = x ** 2.0 > lin = np.repeat('linear', length) > sq = np.repeat('squared', length) > # Combine arrays into one > x = np.hstack((x, x)) > y = np.hstack((linear, squared)) > power = np.hstack((lin, sq)) > # Create dataframe > dictionary = {'x': x, 'y': y, 'power': power} > df = pd.DataFrame(dictionary) > # Plot data > obj = MatPlotDataFrame(df) > parsing_header = 'power' > column_values = ['linear', 'squared'] obj.line_plot_filter_column('x', 'y', parsing_header, column_values, marker_colors=['red', 'green'], marker_style=['o', '^'], label_pos='upper left') .. image:: line_scatter_test1.eps :align: center """ df_list = [self.df[self.df[parsing_header] == col_val] for col_val in column_values] # Error checking if line_colors[0] == 'None': line_colors = self.colors if len(line_colors) < len(column_values): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(df_list)): td_plot.plot(df_list[i][x_header], df_list[i][y_header], label=column_values[i], linestyle=line_style, color=line_colors[i], linewidth=line_weight) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def line_plot_columns(self, x_headers: str, y_headers: str, labels: List[str], style_name: str='default', line_colors: List[str]=['None'], line_weight: np.float32=2.0, fill_alpha: np.float32=0.7, line_style: str='-', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey') -> None: """ :param x_headers: The title of the dataframe columns containing the x-axis data sets :param y_headers: The title of the dataframe columns containing the y-axis data sets :param labels: A list containing the name of each label :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param line_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param line_weight: The weight corresponding to the line thickness, defaulted to 2.0 :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will plot used defined dataframe columns for the x and y axis of a 2-d plot as a line plot. .. code-block:: python > length = 20 > x = np.linspace(0, 20, num=20) > linear = x > squared = x ** 2.0 > # create dataframe > dictionary = {'x': x, 'linear': linear, 'squared': squared} > df = pd.DataFrame(dictionary) > # plot data > obj = MatPlotDataFrame(df) > x_headers = ['x', 'x'] > y_headers = ['linear', 'squared'] > obj.line_plot_columns(x_headers, y_headers, y_headers, x_label='x-axis', y_label='y-axis', title='Test', style_name='default',marker_colors=['red', 'green'], fill_alpha=0.7, marker_style=['o', '^'], label_pos='upper left', grid=False, save=True, plot_name=plt_name) .. image:: line_scatter_test2.eps :align: center """ # Error checking if line_colors[0] == 'None': line_colors = self.colors if len(line_colors) < len(labels): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(x_headers)): td_plot.plot(self.df[x_headers[i]], self.df[y_headers[i]], label=labels[i], linestyle=line_style, color=line_colors[i], linewidth=line_weight) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def timedate_plot_parse_column(self, x_header: str, y_header: str, parsing_header: str, column_values: List[str], style_name: str='default', line_colors: List[str]=['None'], line_weight: np.float32=2.0, fill_alpha: np.float32=0.7, line_style: str='-', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey'): """ :param x_header: The title of the dataframe column containing the x-axis data sets. It is assumes that the x axis is the datetime axis for this plot. :param y_header: The title of the dataframe column containing the y-axis data sets :param parsing_header: The title of the dataframe column containing the values which will be used to parse the dataframe into one or multiple data sets :param column_values: The values contained in the parsing_header column that will be used to parse the data set into multiple data sets :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param line_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param line_weight: The weight corresponding to the line thickness, defaulted to 2.0 :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will parse a dataframe column based on a user specified value or list of values, and plot the data in a user specified x and y axis column based on filter data. As an example, consider a dataframe with the following columnar data structure. .. code-block:: python > length = 20 > x = np.linspace(0, length, num=length) > linear = x > squared = x ** 2.0 > lin = np.repeat('linear', length) > sq = np.repeat('squared', length) > # Combine arrays into one > x = np.hstack((x, x)) > y = np.hstack((linear, squared)) > power = np.hstack((lin, sq)) > # Create dataframe > dictionary = {'x': x, 'y': y, 'power': power} > df = pd.DataFrame(dictionary) > # Plot data > obj = MatPlotDataFrame(df) > parsing_header = 'power' > column_values = ['linear', 'squared'] obj.line_plot_filter_column('x', 'y', parsing_header, column_values, marker_colors=['red', 'green'], marker_style=['o', '^'], label_pos='upper left') .. image:: line_scatter_test1.eps :align: center """ max_date = self.df[x_header].max() min_date = self.df[x_header].min() diff = (max_date - min_date) / np.timedelta64(1, 'D') df_list = [self.df[self.df[parsing_header] == col_val] for col_val in column_values] df_list = [df.set_index(x_header) for df in df_list] # Error checking if line_colors[0] == 'None': line_colors = self.colors if len(line_colors) < len(column_values): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') if diff <= 2: myfmt = mdates.DateFormatter('%H') td_plot.xaxis.set_major_locator(plt.MaxNLocator(6)) elif diff <= 15: myfmt = mdates.DateFormatter('%b-%d') td_plot.xaxis.set_major_locator(plt.MaxNLocator(6)) elif diff <= 180: myfmt = mdates.DateFormatter('%b-%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) elif diff <= 2191: myfmt = mdates.DateFormatter('%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) else: myfmt = mdates.DateFormatter('%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) td_plot.xaxis.set_major_formatter(myfmt) for i in range(len(df_list)): td_plot.plot(df_list[i].index, df_list[i][y_header], label=column_values[i], linestyle=line_style, color=line_colors[i], linewidth=line_weight) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def timedate_plot_columns(self, x_headers: str, y_headers: str, labels: List[str], style_name: str='default', line_colors: List[str]=['None'], line_weight: np.float32=2.0, fill_alpha: np.float32=0.7, line_style: str='-', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey'): """ :param x_headers: The title of the dataframe column containing the x-axis data sets. It is assumes that the x axis is the datetime axis for this plot. :param y_headers: The title of the dataframe column containing the y-axis data sets :param labels: A list of the labels to use for each curve in the legend :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param line_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param line_weight: The weight corresponding to the line thickness, defaulted to 2.0 :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will parse a dataframe column based on a user specified value or list of values, and plot the data in a user specified x and y axis column based on filter data. As an example, consider a dataframe with the following columnar data structure. .. code-block:: python > length = 20 > x = np.linspace(0, length, num=length) > linear = x > squared = x ** 2.0 > lin = np.repeat('linear', length) > sq = np.repeat('squared', length) > # Combine arrays into one > x = np.hstack((x, x)) > y = np.hstack((linear, squared)) > power = np.hstack((lin, sq)) > # Create dataframe > dictionary = {'x': x, 'y': y, 'power': power} > df = pd.DataFrame(dictionary) > # Plot data > obj = MatPlotDataFrame(df) > parsing_header = 'power' > column_values = ['linear', 'squared'] obj.line_plot_filter_column('x', 'y', parsing_header, column_values, marker_colors=['red', 'green'], marker_style=['o', '^'], label_pos='upper left') .. image:: line_scatter_test1.eps :align: center """ diff = 0 for i in range(len(x_headers)): max_date = self.df[x_headers[i]].max() min_date = self.df[x_headers[i]].min() delta = (max_date - min_date) / np.timedelta64(1, 'D') if delta > diff: diff = delta # Error checking if line_colors[0] == 'None': line_colors = self.colors if len(line_colors) < len(x_headers): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') if diff <= 2: myfmt = mdates.DateFormatter('%H') td_plot.xaxis.set_major_locator(plt.MaxNLocator(6)) elif diff <= 15: myfmt = mdates.DateFormatter('%b-%d') td_plot.xaxis.set_major_locator(plt.MaxNLocator(6)) elif diff <= 180: myfmt = mdates.DateFormatter('%b-%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) elif diff <= 2191: myfmt = mdates.DateFormatter('%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) else: myfmt = mdates.DateFormatter('%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) td_plot.xaxis.set_major_formatter(myfmt) for i in range(len(x_headers)): td_plot.plot(self.df[x_headers[i]], self.df[y_headers[i]], label=labels[i], linestyle=line_style, color=line_colors[i], linewidth=line_weight) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def histogram_plot_parse_column(self, header: str, parsing_header: str, column_values: List[str], x_label: str='', y_label: str='', colors: List[str]=['None'], edge_colors: List[str]=['None'], shading: List[float]=['None'], label_pos: str='upper right', num_bins: int = 50, tick_font_size: int = 18, label_font_size: str = 18, style_name: str = 'default', save: bool = False, plot_name: str = 'NULL', hist_type: str = 'bar', dens: bool = False, title: str = 'NULL', title_font_size: int = 24) -> None: """ :param headers: A string representing the dataframe column that contains the data to be parsed and plotted :param parsing_header: A string representing the dataframe header that contains key phrases that will be used to filter the dataframe for specific data :param column_values: The key phrases in the dataframe column described by the `parsing_header` variable :param x_label: The title for the x axis. Defaulted to '' :param y_label: The title for the y axis. Defaulted to '' :param colors: A list containing the colors that will be used to represent each plot. :param edge_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>`_ :param shading: The density of the fill for each plot, defaulted to 0.7 :param label_pos: The position of the ledgend in the plot. Defaulted to 'upper_right' :param num_bins: The number of bins used to represent the histogram. Defaulted to 50 :param tick_font_size: The font size of the plot ticks. Defaulted to 18 :param label_font_size: The font size of plot labels. Defaulted to 18 :param style_name: The plot style, defaulted to 'default'. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. :param save: True if the plot is to be saved, False if the plot is only to be shown :param plot_name: The name of the plot, if it is to be saved :param hist_type: {``bar``, ``barstacked``, ``step``, ``stepfilled``} See `histogram <https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html>`_ for more information. :param dens: If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1 :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 .. code-block:: python > np.random.seed(19680801) > x = np.random.normal(15.0, 3.0, 1000) > y = np.random.normal(20.0, 3.0, 1000) > data = [x, y] > labels = ['one', 'two'] > one = np.repeat('one', len(x)) > two = np.repeat('two', len(x)) > x = np.hstack((x, y)) > y = np.hstack((one, two)) > dictionary = {'data': x, 'type': y} > df = pd.DataFrame(dictionary) > obj = MatPlotDataFrame(df) > obj.histogram_plot_parse_column('data', 'type', labels, x_label='x-axis', y_label='y-axis', shading=[0.9, 0.4], save=True, .. image:: hist2.eps :align: center """ if colors[0] == "None": colors = self.colors if edge_colors[0] == 'None': edge_colors = np.repeat('black', len(column_values)) if shading[0] == "None": shading = np.repeat(0.7, len(column_values)) df_list = [self.df[self.df[parsing_header] == col_val] for col_val in column_values] plt.tight_layout() plt.gcf().subplots_adjust(bottom=0.15) plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) plt.xlabel(x_label, fontsize=label_font_size) plt.ylabel(y_label, fontsize=label_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) for i in range(len(column_values)): plt.hist(df_list[i][header], bins=num_bins, color=colors[i], edgecolor=edge_colors[i], alpha=shading[i], label=column_values[i], histtype=hist_type, density=dens) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def histogram_plot_columns(self, x_headers: List[str], labels: List[str], x_label: str='', y_label: str='', colors: List[str]=['None'], edge_colors: List[str]=['None'], shading: List[float]=['None'], label_pos: str='upper right', num_bins: int = 50, tick_font_size: int = 18, label_font_size: str = 18, style_name: str = 'default', save: bool = False, plot_name: str = 'NULL', hist_type: str = 'bar', dens: bool = False, title: str = 'NULL', title_font_size: int = 24) -> None: """ :param x_headers: A list of strings representing the dataframe columns to be used for the x axis of a plot :param labels: A list of labels, each label corresponding to each histogram :param x_label: The title for the x axis. Defaulted to '' :param y_label: The title for the y axis. Defaulted to '' :param colors: A list containing the colors that will be used to represent each plot. :param edge_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>`_ :param shading: The density of the fill for each plot, defaulted to 0.7 :param label_pos: The position of the ledgend in the plot. Defaulted to 'upper_right' :param num_bins: The number of bins used to represent the histogram. Defaulted to 50 :param tick_font_size: The font size of the plot ticks. Defaulted to 18 :param label_font_size: The font size of plot labels. Defaulted to 18 :param style_name: The plot style, defaulted to 'default'. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. :param save: True if the plot is to be saved, False if the plot is only to be shown :param plot_name: The name of the plot, if it is to be saved :param hist_type: {``bar``, ``barstacked``, ``step``, ``stepfilled``} See `histogram <https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html>`_ for more information. :param dens: If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1 :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 .. code-block:: python > np.random.seed(19680801) > x = np.random.normal(15.0, 3.0, 1000) > y = np.random.normal(20.0, 3.0, 1000) > data = [x, y] > labels = ['one', 'two'] > one = np.repeat('one', len(x)) > two = np.repeat('two', len(x)) > x = np.hstack((x, y)) > y = np.hstack((one, two)) > dictionary = {'data': x, 'type': y} > df = pd.DataFrame(dictionary) > obj = MatPlotDataFrame(df) > obj.histogram_plot_parse_column('data', 'type', labels, x_label='x-axis', y_label='y-axis', shading=[0.9, 0.4], save=True, .. image:: hist2.eps :align: center """ if colors[0] == "None": colors = self.colors if edge_colors[0] == 'None': edge_colors = np.repeat('black', len(labels)) if shading[0] == "None": shading = np.repeat(0.7, len(labels)) plt.tight_layout() plt.gcf().subplots_adjust(bottom=0.15) plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) plt.xlabel(x_label, fontsize=label_font_size) plt.ylabel(y_label, fontsize=label_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) for i in range(len(x_headers)): plt.hist(self.df[x_headers[i]], bins=num_bins, color=colors[i], edgecolor=edge_colors[i], alpha=shading[i], label=labels[i], density=dens) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # ================================================================================ # ================================================================================ # eof # TODO Create histogram version of plots # TODO Repeat for Bokeh plots
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "matplotlib.rc", "matplotlib.dates.DayLocator", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.style.use", "matplotlib.pyplot.close", "warnings.warn", "matplotlib.pyplot.savefig", "matplotlib.pyplot.MaxNLocator", "matplotlib.dates.MonthLocator", "matplotlib.pyplot.gcf", "matplotlib.dates.DateFormatter", "numpy.timedelta64", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "matplotlib.pyplot.show", "datetime.datetime.strptime", "matplotlib.pyplot.rcParams.update", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.subplots" ]
[((5218, 5232), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5230, 5232), True, 'from matplotlib import rc, pyplot as plt\n'), ((5237, 5285), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (5256, 5285), True, 'from matplotlib import rc, pyplot as plt\n'), ((5290, 5315), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (5303, 5315), True, 'from matplotlib import rc, pyplot as plt\n'), ((5320, 5357), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (5322, 5357), False, 'from matplotlib import rc, pyplot as plt\n'), ((5362, 5399), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (5364, 5399), False, 'from matplotlib import rc, pyplot as plt\n'), ((6306, 6331), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (6316, 6331), True, 'from matplotlib import rc, pyplot as plt\n'), ((11101, 11149), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (11120, 11149), True, 'from matplotlib import rc, pyplot as plt\n'), ((11154, 11179), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (11167, 11179), True, 'from matplotlib import rc, pyplot as plt\n'), ((11199, 11213), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (11211, 11213), True, 'from matplotlib import rc, pyplot as plt\n'), ((11218, 11255), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (11220, 11255), False, 'from matplotlib import rc, pyplot as plt\n'), ((11260, 11297), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (11262, 11297), False, 'from matplotlib import rc, pyplot as plt\n'), ((11854, 11879), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (11864, 11879), True, 'from matplotlib import rc, pyplot as plt\n'), ((16347, 16395), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (16366, 16395), True, 'from matplotlib import rc, pyplot as plt\n'), ((16400, 16425), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (16413, 16425), True, 'from matplotlib import rc, pyplot as plt\n'), ((16445, 16459), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (16457, 16459), True, 'from matplotlib import rc, pyplot as plt\n'), ((16464, 16501), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (16466, 16501), False, 'from matplotlib import rc, pyplot as plt\n'), ((16506, 16543), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (16508, 16543), False, 'from matplotlib import rc, pyplot as plt\n'), ((17092, 17117), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (17102, 17117), True, 'from matplotlib import rc, pyplot as plt\n'), ((22170, 22218), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (22189, 22218), True, 'from matplotlib import rc, pyplot as plt\n'), ((22223, 22248), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (22236, 22248), True, 'from matplotlib import rc, pyplot as plt\n'), ((22268, 22282), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (22280, 22282), True, 'from matplotlib import rc, pyplot as plt\n'), ((22287, 22324), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (22289, 22324), False, 'from matplotlib import rc, pyplot as plt\n'), ((22329, 22366), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (22331, 22366), False, 'from matplotlib import rc, pyplot as plt\n'), ((22950, 22975), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (22960, 22975), True, 'from matplotlib import rc, pyplot as plt\n'), ((27969, 27987), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (27985, 27987), True, 'from matplotlib import rc, pyplot as plt\n'), ((28035, 28083), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (28054, 28083), True, 'from matplotlib import rc, pyplot as plt\n'), ((28088, 28113), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (28101, 28113), True, 'from matplotlib import rc, pyplot as plt\n'), ((28118, 28155), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (28120, 28155), False, 'from matplotlib import rc, pyplot as plt\n'), ((28160, 28197), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (28162, 28197), False, 'from matplotlib import rc, pyplot as plt\n'), ((28202, 28247), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {'fontsize': 'label_font_size'}), '(x_label, fontsize=label_font_size)\n', (28212, 28247), True, 'from matplotlib import rc, pyplot as plt\n'), ((28252, 28297), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {'fontsize': 'label_font_size'}), '(y_label, fontsize=label_font_size)\n', (28262, 28297), True, 'from matplotlib import rc, pyplot as plt\n'), ((28580, 28605), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (28590, 28605), True, 'from matplotlib import rc, pyplot as plt\n'), ((28687, 28698), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (28696, 28698), True, 'from matplotlib import rc, pyplot as plt\n'), ((5502, 5528), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%d"""'], {}), "('%d')\n", (5522, 5528), True, 'import matplotlib.dates as mdates\n'), ((6357, 6367), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6365, 6367), True, 'from matplotlib import rc, pyplot as plt\n'), ((6386, 6408), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (6397, 6408), True, 'from matplotlib import rc, pyplot as plt\n'), ((10207, 10269), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (10220, 10269), False, 'import warnings\n'), ((10313, 10418), 'warnings.warn', 'warnings.warn', (['"""length of x list of lists is not the same as y list of lists, plot not printed"""'], {}), "(\n 'length of x list of lists is not the same as y list of lists, plot not printed'\n )\n", (10326, 10418), False, 'import warnings\n'), ((10472, 10562), 'warnings.warn', 'warnings.warn', (['"""line colors list not the same length as data lists, plot not printed"""'], {}), "(\n 'line colors list not the same length as data lists, plot not printed')\n", (10485, 10562), False, 'import warnings\n'), ((10620, 10709), 'warnings.warn', 'warnings.warn', (['"""line_style list not the same length as data lists, plot not printed"""'], {}), "(\n 'line_style list not the same length as data lists, plot not printed')\n", (10633, 10709), False, 'import warnings\n'), ((10768, 10858), 'warnings.warn', 'warnings.warn', (['"""line_weight list not the same length as data lists, plot not printed"""'], {}), "(\n 'line_weight list not the same length as data lists, plot not printed')\n", (10781, 10858), False, 'import warnings\n'), ((10923, 10973), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (10936, 10973), False, 'import warnings\n'), ((11028, 11078), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (11041, 11078), False, 'import warnings\n'), ((11905, 11915), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11913, 11915), True, 'from matplotlib import rc, pyplot as plt\n'), ((11934, 11956), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (11945, 11956), True, 'from matplotlib import rc, pyplot as plt\n'), ((15598, 15660), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (15611, 15660), False, 'import warnings\n'), ((15704, 15809), 'warnings.warn', 'warnings.warn', (['"""length of x list of lists is not the same as y list of lists, plot not printed"""'], {}), "(\n 'length of x list of lists is not the same as y list of lists, plot not printed'\n )\n", (15717, 15809), False, 'import warnings\n'), ((15865, 15955), 'warnings.warn', 'warnings.warn', (['"""line colors list not the same length as data lists, plot not printed"""'], {}), "(\n 'line colors list not the same length as data lists, plot not printed')\n", (15878, 15955), False, 'import warnings\n'), ((16015, 16104), 'warnings.warn', 'warnings.warn', (['"""line_style list not the same length as data lists, plot not printed"""'], {}), "(\n 'line_style list not the same length as data lists, plot not printed')\n", (16028, 16104), False, 'import warnings\n'), ((16169, 16219), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (16182, 16219), False, 'import warnings\n'), ((16274, 16324), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (16287, 16324), False, 'import warnings\n'), ((17143, 17153), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (17151, 17153), True, 'from matplotlib import rc, pyplot as plt\n'), ((17172, 17194), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (17183, 17194), True, 'from matplotlib import rc, pyplot as plt\n'), ((21421, 21483), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (21434, 21483), False, 'import warnings\n'), ((21527, 21632), 'warnings.warn', 'warnings.warn', (['"""length of x list of lists is not the same as y list of lists, plot not printed"""'], {}), "(\n 'length of x list of lists is not the same as y list of lists, plot not printed'\n )\n", (21540, 21632), False, 'import warnings\n'), ((21688, 21778), 'warnings.warn', 'warnings.warn', (['"""line colors list not the same length as data lists, plot not printed"""'], {}), "(\n 'line colors list not the same length as data lists, plot not printed')\n", (21701, 21778), False, 'import warnings\n'), ((21838, 21927), 'warnings.warn', 'warnings.warn', (['"""line_style list not the same length as data lists, plot not printed"""'], {}), "(\n 'line_style list not the same length as data lists, plot not printed')\n", (21851, 21927), False, 'import warnings\n'), ((21992, 22042), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (22005, 22042), False, 'import warnings\n'), ((22097, 22147), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (22110, 22147), False, 'import warnings\n'), ((23001, 23011), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (23009, 23011), True, 'from matplotlib import rc, pyplot as plt\n'), ((23030, 23052), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (23041, 23052), True, 'from matplotlib import rc, pyplot as plt\n'), ((27531, 27602), 'warnings.warn', 'warnings.warn', (['"""data list should be the same length as the labels list"""'], {}), "('data list should be the same length as the labels list')\n", (27544, 27602), False, 'import warnings\n'), ((27646, 27717), 'warnings.warn', 'warnings.warn', (['"""data list should be the same length as the colors list"""'], {}), "('data list should be the same length as the colors list')\n", (27659, 27717), False, 'import warnings\n'), ((27766, 27844), 'warnings.warn', 'warnings.warn', (['"""labels list should be the same length as the edge_colors list"""'], {}), "('labels list should be the same length as the edge_colors list')\n", (27779, 27844), False, 'import warnings\n'), ((27889, 27963), 'warnings.warn', 'warnings.warn', (['"""labels list should be the same length as the shading list"""'], {}), "('labels list should be the same length as the shading list')\n", (27902, 27963), False, 'import warnings\n'), ((28330, 28372), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (28339, 28372), True, 'from matplotlib import rc, pyplot as plt\n'), ((28414, 28562), 'matplotlib.pyplot.hist', 'plt.hist', (['data[i]'], {'bins': 'num_bins', 'color': 'colors[i]', 'edgecolor': 'edge_colors[i]', 'alpha': 'shading[i]', 'label': 'labels[i]', 'histtype': 'hist_type', 'density': 'dens'}), '(data[i], bins=num_bins, color=colors[i], edgecolor=edge_colors[i],\n alpha=shading[i], label=labels[i], histtype=hist_type, density=dens)\n', (28422, 28562), True, 'from matplotlib import rc, pyplot as plt\n'), ((28631, 28641), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (28639, 28641), True, 'from matplotlib import rc, pyplot as plt\n'), ((28660, 28682), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (28671, 28682), True, 'from matplotlib import rc, pyplot as plt\n'), ((36372, 36420), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (36391, 36420), True, 'from matplotlib import rc, pyplot as plt\n'), ((36429, 36454), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (36442, 36454), True, 'from matplotlib import rc, pyplot as plt\n'), ((36478, 36492), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (36490, 36492), True, 'from matplotlib import rc, pyplot as plt\n'), ((36501, 36538), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (36503, 36538), False, 'from matplotlib import rc, pyplot as plt\n'), ((36547, 36584), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (36549, 36584), False, 'from matplotlib import rc, pyplot as plt\n'), ((37342, 37367), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (37352, 37367), True, 'from matplotlib import rc, pyplot as plt\n'), ((37547, 37558), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (37556, 37558), True, 'from matplotlib import rc, pyplot as plt\n'), ((43499, 43547), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (43518, 43547), True, 'from matplotlib import rc, pyplot as plt\n'), ((43556, 43581), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (43569, 43581), True, 'from matplotlib import rc, pyplot as plt\n'), ((43605, 43619), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (43617, 43619), True, 'from matplotlib import rc, pyplot as plt\n'), ((43628, 43665), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (43630, 43665), False, 'from matplotlib import rc, pyplot as plt\n'), ((43674, 43711), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (43676, 43711), False, 'from matplotlib import rc, pyplot as plt\n'), ((44469, 44494), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (44479, 44494), True, 'from matplotlib import rc, pyplot as plt\n'), ((44674, 44685), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (44683, 44685), True, 'from matplotlib import rc, pyplot as plt\n'), ((50791, 50839), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (50810, 50839), True, 'from matplotlib import rc, pyplot as plt\n'), ((50848, 50873), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (50861, 50873), True, 'from matplotlib import rc, pyplot as plt\n'), ((50897, 50911), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (50909, 50911), True, 'from matplotlib import rc, pyplot as plt\n'), ((50920, 50957), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (50922, 50957), False, 'from matplotlib import rc, pyplot as plt\n'), ((50966, 51003), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (50968, 51003), False, 'from matplotlib import rc, pyplot as plt\n'), ((51629, 51654), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (51639, 51654), True, 'from matplotlib import rc, pyplot as plt\n'), ((51834, 51845), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (51843, 51845), True, 'from matplotlib import rc, pyplot as plt\n'), ((57108, 57156), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (57127, 57156), True, 'from matplotlib import rc, pyplot as plt\n'), ((57165, 57190), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (57178, 57190), True, 'from matplotlib import rc, pyplot as plt\n'), ((57214, 57228), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (57226, 57228), True, 'from matplotlib import rc, pyplot as plt\n'), ((57237, 57274), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (57239, 57274), False, 'from matplotlib import rc, pyplot as plt\n'), ((57283, 57320), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (57285, 57320), False, 'from matplotlib import rc, pyplot as plt\n'), ((57944, 57969), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (57954, 57969), True, 'from matplotlib import rc, pyplot as plt\n'), ((58149, 58160), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (58158, 58160), True, 'from matplotlib import rc, pyplot as plt\n'), ((64598, 64646), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (64617, 64646), True, 'from matplotlib import rc, pyplot as plt\n'), ((64655, 64680), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (64668, 64680), True, 'from matplotlib import rc, pyplot as plt\n'), ((64704, 64718), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (64716, 64718), True, 'from matplotlib import rc, pyplot as plt\n'), ((64727, 64764), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (64729, 64764), False, 'from matplotlib import rc, pyplot as plt\n'), ((64773, 64810), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (64775, 64810), False, 'from matplotlib import rc, pyplot as plt\n'), ((66163, 66188), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (66173, 66188), True, 'from matplotlib import rc, pyplot as plt\n'), ((66368, 66379), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (66377, 66379), True, 'from matplotlib import rc, pyplot as plt\n'), ((72353, 72401), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (72372, 72401), True, 'from matplotlib import rc, pyplot as plt\n'), ((72410, 72435), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (72423, 72435), True, 'from matplotlib import rc, pyplot as plt\n'), ((72459, 72473), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (72471, 72473), True, 'from matplotlib import rc, pyplot as plt\n'), ((72482, 72519), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (72484, 72519), False, 'from matplotlib import rc, pyplot as plt\n'), ((72528, 72565), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (72530, 72565), False, 'from matplotlib import rc, pyplot as plt\n'), ((73921, 73946), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (73931, 73946), True, 'from matplotlib import rc, pyplot as plt\n'), ((74126, 74137), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (74135, 74137), True, 'from matplotlib import rc, pyplot as plt\n'), ((79108, 79126), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (79124, 79126), True, 'from matplotlib import rc, pyplot as plt\n'), ((79182, 79230), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (79201, 79230), True, 'from matplotlib import rc, pyplot as plt\n'), ((79239, 79264), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (79252, 79264), True, 'from matplotlib import rc, pyplot as plt\n'), ((79273, 79310), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (79275, 79310), False, 'from matplotlib import rc, pyplot as plt\n'), ((79319, 79356), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (79321, 79356), False, 'from matplotlib import rc, pyplot as plt\n'), ((79365, 79410), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {'fontsize': 'label_font_size'}), '(x_label, fontsize=label_font_size)\n', (79375, 79410), True, 'from matplotlib import rc, pyplot as plt\n'), ((79419, 79464), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {'fontsize': 'label_font_size'}), '(y_label, fontsize=label_font_size)\n', (79429, 79464), True, 'from matplotlib import rc, pyplot as plt\n'), ((79883, 79908), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (79893, 79908), True, 'from matplotlib import rc, pyplot as plt\n'), ((80010, 80021), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (80019, 80021), True, 'from matplotlib import rc, pyplot as plt\n'), ((84532, 84550), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (84548, 84550), True, 'from matplotlib import rc, pyplot as plt\n'), ((84606, 84654), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (84625, 84654), True, 'from matplotlib import rc, pyplot as plt\n'), ((84663, 84688), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (84676, 84688), True, 'from matplotlib import rc, pyplot as plt\n'), ((84697, 84734), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (84699, 84734), False, 'from matplotlib import rc, pyplot as plt\n'), ((84743, 84780), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (84745, 84780), False, 'from matplotlib import rc, pyplot as plt\n'), ((84789, 84834), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {'fontsize': 'label_font_size'}), '(x_label, fontsize=label_font_size)\n', (84799, 84834), True, 'from matplotlib import rc, pyplot as plt\n'), ((84843, 84888), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {'fontsize': 'label_font_size'}), '(y_label, fontsize=label_font_size)\n', (84853, 84888), True, 'from matplotlib import rc, pyplot as plt\n'), ((85303, 85328), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (85313, 85328), True, 'from matplotlib import rc, pyplot as plt\n'), ((85430, 85441), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (85439, 85441), True, 'from matplotlib import rc, pyplot as plt\n'), ((5569, 5588), 'matplotlib.dates.DayLocator', 'mdates.DayLocator', ([], {}), '()\n', (5586, 5588), True, 'import matplotlib.dates as mdates\n'), ((5628, 5657), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%y"""'], {}), "('%b-%y')\n", (5648, 5657), True, 'import matplotlib.dates as mdates\n'), ((5747, 5776), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%y"""'], {}), "('%b-%y')\n", (5767, 5776), True, 'import matplotlib.dates as mdates\n'), ((27992, 28001), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (27999, 28001), True, 'from matplotlib import rc, pyplot as plt\n'), ((36053, 36115), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (36066, 36115), False, 'import warnings\n'), ((36178, 36228), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (36191, 36228), False, 'import warnings\n'), ((36291, 36341), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (36304, 36341), False, 'import warnings\n'), ((37397, 37445), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (37405, 37445), True, 'from matplotlib import rc, pyplot as plt\n'), ((37479, 37489), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (37487, 37489), True, 'from matplotlib import rc, pyplot as plt\n'), ((37516, 37538), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (37527, 37538), True, 'from matplotlib import rc, pyplot as plt\n'), ((43180, 43242), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (43193, 43242), False, 'import warnings\n'), ((43305, 43355), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (43318, 43355), False, 'import warnings\n'), ((43418, 43468), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (43431, 43468), False, 'import warnings\n'), ((44524, 44572), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (44532, 44572), True, 'from matplotlib import rc, pyplot as plt\n'), ((44606, 44616), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (44614, 44616), True, 'from matplotlib import rc, pyplot as plt\n'), ((44643, 44665), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (44654, 44665), True, 'from matplotlib import rc, pyplot as plt\n'), ((50472, 50534), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (50485, 50534), False, 'import warnings\n'), ((50597, 50647), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (50610, 50647), False, 'import warnings\n'), ((50710, 50760), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (50723, 50760), False, 'import warnings\n'), ((51684, 51732), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (51692, 51732), True, 'from matplotlib import rc, pyplot as plt\n'), ((51766, 51776), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (51774, 51776), True, 'from matplotlib import rc, pyplot as plt\n'), ((51803, 51825), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (51814, 51825), True, 'from matplotlib import rc, pyplot as plt\n'), ((56789, 56851), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (56802, 56851), False, 'import warnings\n'), ((56914, 56964), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (56927, 56964), False, 'import warnings\n'), ((57027, 57077), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (57040, 57077), False, 'import warnings\n'), ((57999, 58047), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (58007, 58047), True, 'from matplotlib import rc, pyplot as plt\n'), ((58081, 58091), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (58089, 58091), True, 'from matplotlib import rc, pyplot as plt\n'), ((58118, 58140), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (58129, 58140), True, 'from matplotlib import rc, pyplot as plt\n'), ((63692, 63714), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""D"""'], {}), "(1, 'D')\n", (63706, 63714), True, 'import numpy as np\n'), ((64280, 64342), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (64293, 64342), False, 'import warnings\n'), ((64405, 64455), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (64418, 64455), False, 'import warnings\n'), ((64518, 64568), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (64531, 64568), False, 'import warnings\n'), ((65227, 65253), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%H"""'], {}), "('%H')\n", (65247, 65253), True, 'import matplotlib.dates as mdates\n'), ((66218, 66266), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (66226, 66266), True, 'from matplotlib import rc, pyplot as plt\n'), ((66300, 66310), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (66308, 66310), True, 'from matplotlib import rc, pyplot as plt\n'), ((66337, 66359), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (66348, 66359), True, 'from matplotlib import rc, pyplot as plt\n'), ((72035, 72097), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (72048, 72097), False, 'import warnings\n'), ((72160, 72210), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (72173, 72210), False, 'import warnings\n'), ((72273, 72323), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (72286, 72323), False, 'import warnings\n'), ((72982, 73008), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%H"""'], {}), "('%H')\n", (73002, 73008), True, 'import matplotlib.dates as mdates\n'), ((73976, 74024), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (73984, 74024), True, 'from matplotlib import rc, pyplot as plt\n'), ((74058, 74068), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (74066, 74068), True, 'from matplotlib import rc, pyplot as plt\n'), ((74095, 74117), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (74106, 74117), True, 'from matplotlib import rc, pyplot as plt\n'), ((79505, 79547), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (79514, 79547), True, 'from matplotlib import rc, pyplot as plt\n'), ((79592, 79634), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (79601, 79634), True, 'from matplotlib import rc, pyplot as plt\n'), ((79691, 79863), 'matplotlib.pyplot.hist', 'plt.hist', (['df_list[i][header]'], {'bins': 'num_bins', 'color': 'colors[i]', 'edgecolor': 'edge_colors[i]', 'alpha': 'shading[i]', 'label': 'column_values[i]', 'histtype': 'hist_type', 'density': 'dens'}), '(df_list[i][header], bins=num_bins, color=colors[i], edgecolor=\n edge_colors[i], alpha=shading[i], label=column_values[i], histtype=\n hist_type, density=dens)\n', (79699, 79863), True, 'from matplotlib import rc, pyplot as plt\n'), ((79942, 79952), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (79950, 79952), True, 'from matplotlib import rc, pyplot as plt\n'), ((79979, 80001), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (79990, 80001), True, 'from matplotlib import rc, pyplot as plt\n'), ((84929, 84971), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (84938, 84971), True, 'from matplotlib import rc, pyplot as plt\n'), ((85016, 85058), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (85025, 85058), True, 'from matplotlib import rc, pyplot as plt\n'), ((85112, 85255), 'matplotlib.pyplot.hist', 'plt.hist', (['self.df[x_headers[i]]'], {'bins': 'num_bins', 'color': 'colors[i]', 'edgecolor': 'edge_colors[i]', 'alpha': 'shading[i]', 'label': 'labels[i]', 'density': 'dens'}), '(self.df[x_headers[i]], bins=num_bins, color=colors[i], edgecolor=\n edge_colors[i], alpha=shading[i], label=labels[i], density=dens)\n', (85120, 85255), True, 'from matplotlib import rc, pyplot as plt\n'), ((85362, 85372), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (85370, 85372), True, 'from matplotlib import rc, pyplot as plt\n'), ((85399, 85421), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (85410, 85421), True, 'from matplotlib import rc, pyplot as plt\n'), ((4913, 4955), 'datetime.datetime.strptime', 'datetime.strptime', (['date_string', '"""%Y-%m-%d"""'], {}), "(date_string, '%Y-%m-%d')\n", (4930, 4955), False, 'from datetime import datetime\n'), ((5698, 5719), 'matplotlib.dates.MonthLocator', 'mdates.MonthLocator', ([], {}), '()\n', (5717, 5719), True, 'import matplotlib.dates as mdates\n'), ((5817, 5835), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(4)'], {}), '(4)\n', (5832, 5835), True, 'from matplotlib import rc, pyplot as plt\n'), ((65298, 65316), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(6)'], {}), '(6)\n', (65313, 65316), True, 'from matplotlib import rc, pyplot as plt\n'), ((65363, 65392), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%d"""'], {}), "('%b-%d')\n", (65383, 65392), True, 'import matplotlib.dates as mdates\n'), ((71567, 71589), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""D"""'], {}), "(1, 'D')\n", (71581, 71589), True, 'import numpy as np\n'), ((73053, 73071), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(6)'], {}), '(6)\n', (73068, 73071), True, 'from matplotlib import rc, pyplot as plt\n'), ((73118, 73147), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%d"""'], {}), "('%b-%d')\n", (73138, 73147), True, 'import matplotlib.dates as mdates\n'), ((79135, 79144), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (79142, 79144), True, 'from matplotlib import rc, pyplot as plt\n'), ((84559, 84568), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (84566, 84568), True, 'from matplotlib import rc, pyplot as plt\n'), ((65437, 65455), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(6)'], {}), '(6)\n', (65452, 65455), True, 'from matplotlib import rc, pyplot as plt\n'), ((65503, 65532), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%Y"""'], {}), "('%b-%Y')\n", (65523, 65532), True, 'import matplotlib.dates as mdates\n'), ((73192, 73210), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(6)'], {}), '(6)\n', (73207, 73210), True, 'from matplotlib import rc, pyplot as plt\n'), ((73258, 73287), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%Y"""'], {}), "('%b-%Y')\n", (73278, 73287), True, 'import matplotlib.dates as mdates\n'), ((65577, 65595), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (65592, 65595), True, 'from matplotlib import rc, pyplot as plt\n'), ((65644, 65670), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y"""'], {}), "('%Y')\n", (65664, 65670), True, 'import matplotlib.dates as mdates\n'), ((65769, 65795), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y"""'], {}), "('%Y')\n", (65789, 65795), True, 'import matplotlib.dates as mdates\n'), ((73332, 73350), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (73347, 73350), True, 'from matplotlib import rc, pyplot as plt\n'), ((73399, 73425), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y"""'], {}), "('%Y')\n", (73419, 73425), True, 'import matplotlib.dates as mdates\n'), ((73524, 73550), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y"""'], {}), "('%Y')\n", (73544, 73550), True, 'import matplotlib.dates as mdates\n'), ((65715, 65733), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (65730, 65733), True, 'from matplotlib import rc, pyplot as plt\n'), ((65840, 65858), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (65855, 65858), True, 'from matplotlib import rc, pyplot as plt\n'), ((73470, 73488), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (73485, 73488), True, 'from matplotlib import rc, pyplot as plt\n'), ((73595, 73613), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (73610, 73613), True, 'from matplotlib import rc, pyplot as plt\n')]
import tempfile from concurrent.futures import ProcessPoolExecutor, as_completed import numpy as np import pytest import zarr from dask.distributed import LocalCluster from swyft import Dataset, DirectoryStore, Prior, Simulator from swyft.store.simulator import SimulationStatus PARAMS = ["z1", "z2"] PRIOR = Prior.from_uv(lambda u: u * np.array([1 for _ in PARAMS]), len(PARAMS)) OUTPUT_SHAPE = (20, 20) SIM_SHAPES = {"x": OUTPUT_SHAPE} N_SIMULATIONS = 1000 BATCH_SIZE = 100 MAX_WORKERS = 4 # number of simultaneous processes acting on the store def model(_): """ Model with dummy parameters. Return random numbers in (0; 1]. """ return dict(x=-np.random.random(OUTPUT_SHAPE) + 1) @pytest.fixture(scope="function") def store(): simulator = Simulator(model, sim_shapes=SIM_SHAPES) with tempfile.TemporaryDirectory() as tmpdir: path = f"{tmpdir}/test_store" yield DirectoryStore(path=path, params=PARAMS, simulator=simulator) @pytest.fixture(scope="module") def cluster(): return LocalCluster(n_workers=2, threads_per_worker=1) def simulate(cluster, path="./cache", wait_for_results=True): """ Open store, sample simulation parameters and run the corresponding simulations. """ simulator = Simulator(model=model, sim_shapes=SIM_SHAPES, cluster=cluster) store = DirectoryStore(path=path, params=PARAMS, simulator=simulator) dataset = Dataset(N_SIMULATIONS, PRIOR, store=store) dataset.simulate(wait_for_results=wait_for_results, batch_size=BATCH_SIZE) return dataset.indices def read_from_store(path): """ Extract data from the Zarr Directory store """ z = zarr.open(f"{path}/samples/pars") x = zarr.open_group(f"{path}/samples/sims") s = zarr.open_array(f"{path}/samples/simulation_status") return z[:], {key: val[:] for key, val in x.items()}, s[:] def test_concurrent_runs_waiting_for_results(cluster, store): """ Run several processes that access the same store to sample parameters and to submit the corresponding simulations. The outcome of the simulations is waited for within the processes, so when they return all outcome should be written to the store. """ path = store._zarr_store.path with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor: futures = [] for i in range(MAX_WORKERS): # each process grows and sample the same cache future = executor.submit( simulate, cluster=cluster.scheduler_address, path=path, ) futures.append(future) for future in as_completed(futures): # processes are waiting for results, so all simulations should be finished status = store.get_simulation_status(future.result()) assert np.all(status == SimulationStatus.FINISHED) z, x, s = read_from_store(path) # check shape of the parameter array n_simulations, n_params = z.shape # the real number of samples can differ slightly from the required value assert n_simulations > 0.80 * N_SIMULATIONS and n_simulations < 1.20 * N_SIMULATIONS assert n_params == len(PARAMS) # check shape and values of the simulation array assert x.keys() == SIM_SHAPES.keys() for key, val in SIM_SHAPES.items(): assert x[key].shape == (n_simulations, *val) assert np.all(x[key][:] > 0.0) # all simulation output has been updated # check shape and values of the status array assert s.shape == (n_simulations,) assert np.all(s == SimulationStatus.FINISHED) # all simulations are done def test_concurrent_run_without_waiting_for_results(cluster, store): """ Run several processes that access the same store to sample parameters and to submit the corresponding simulations. The processes do not wait for the simulations to be done, so when they return some simulations should still be running. """ path = store._zarr_store.path with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor: futures = [] for i in range(MAX_WORKERS): # each process grows and sample the same cache future = executor.submit( simulate, cluster=cluster.scheduler_address, path=path, wait_for_results=False, ) futures.append(future) for future in as_completed(futures): # processes are not waiting for results, so some simulations should still be running status = store.get_simulation_status(future.result()) assert np.any(status == SimulationStatus.RUNNING) z, x, s = read_from_store(path) # check shape of the parameter array n_simulations, n_params = z.shape # the real number of samples can differ slightly from the required value assert n_simulations > 0.80 * N_SIMULATIONS and n_simulations < 1.20 * N_SIMULATIONS assert n_params == len(PARAMS) # check shape of the simulation array assert x.keys() == SIM_SHAPES.keys() for key, val in SIM_SHAPES.items(): assert x[key].shape == (n_simulations, *val) # check shape of the status array assert s.shape == (n_simulations,) # now explicitly wait for simulations store.wait_for_simulations(indices=np.arange(n_simulations)) z, x, s = read_from_store(path) for key, val in SIM_SHAPES.items(): assert np.all(x[key] > 0.0) # all simulation output has been updated assert np.all(s == SimulationStatus.FINISHED) # all simulations are done
[ "tempfile.TemporaryDirectory", "dask.distributed.LocalCluster", "numpy.random.random", "swyft.Simulator", "numpy.any", "swyft.Dataset", "concurrent.futures.as_completed", "numpy.array", "zarr.open", "swyft.DirectoryStore", "zarr.open_group", "pytest.fixture", "concurrent.futures.ProcessPoolExecutor", "numpy.all", "zarr.open_array", "numpy.arange" ]
[((700, 732), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (714, 732), False, 'import pytest\n'), ((969, 999), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (983, 999), False, 'import pytest\n'), ((762, 801), 'swyft.Simulator', 'Simulator', (['model'], {'sim_shapes': 'SIM_SHAPES'}), '(model, sim_shapes=SIM_SHAPES)\n', (771, 801), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((1026, 1073), 'dask.distributed.LocalCluster', 'LocalCluster', ([], {'n_workers': '(2)', 'threads_per_worker': '(1)'}), '(n_workers=2, threads_per_worker=1)\n', (1038, 1073), False, 'from dask.distributed import LocalCluster\n'), ((1258, 1320), 'swyft.Simulator', 'Simulator', ([], {'model': 'model', 'sim_shapes': 'SIM_SHAPES', 'cluster': 'cluster'}), '(model=model, sim_shapes=SIM_SHAPES, cluster=cluster)\n', (1267, 1320), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((1333, 1394), 'swyft.DirectoryStore', 'DirectoryStore', ([], {'path': 'path', 'params': 'PARAMS', 'simulator': 'simulator'}), '(path=path, params=PARAMS, simulator=simulator)\n', (1347, 1394), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((1409, 1451), 'swyft.Dataset', 'Dataset', (['N_SIMULATIONS', 'PRIOR'], {'store': 'store'}), '(N_SIMULATIONS, PRIOR, store=store)\n', (1416, 1451), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((1650, 1683), 'zarr.open', 'zarr.open', (['f"""{path}/samples/pars"""'], {}), "(f'{path}/samples/pars')\n", (1659, 1683), False, 'import zarr\n'), ((1692, 1731), 'zarr.open_group', 'zarr.open_group', (['f"""{path}/samples/sims"""'], {}), "(f'{path}/samples/sims')\n", (1707, 1731), False, 'import zarr\n'), ((1740, 1792), 'zarr.open_array', 'zarr.open_array', (['f"""{path}/samples/simulation_status"""'], {}), "(f'{path}/samples/simulation_status')\n", (1755, 1792), False, 'import zarr\n'), ((3556, 3594), 'numpy.all', 'np.all', (['(s == SimulationStatus.FINISHED)'], {}), '(s == SimulationStatus.FINISHED)\n', (3562, 3594), True, 'import numpy as np\n'), ((5530, 5568), 'numpy.all', 'np.all', (['(s == SimulationStatus.FINISHED)'], {}), '(s == SimulationStatus.FINISHED)\n', (5536, 5568), True, 'import numpy as np\n'), ((811, 840), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (838, 840), False, 'import tempfile\n'), ((2241, 2285), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': 'MAX_WORKERS'}), '(max_workers=MAX_WORKERS)\n', (2260, 2285), False, 'from concurrent.futures import ProcessPoolExecutor, as_completed\n'), ((2630, 2651), 'concurrent.futures.as_completed', 'as_completed', (['futures'], {}), '(futures)\n', (2642, 2651), False, 'from concurrent.futures import ProcessPoolExecutor, as_completed\n'), ((3390, 3413), 'numpy.all', 'np.all', (['(x[key][:] > 0.0)'], {}), '(x[key][:] > 0.0)\n', (3396, 3413), True, 'import numpy as np\n'), ((4005, 4049), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': 'MAX_WORKERS'}), '(max_workers=MAX_WORKERS)\n', (4024, 4049), False, 'from concurrent.futures import ProcessPoolExecutor, as_completed\n'), ((4434, 4455), 'concurrent.futures.as_completed', 'as_completed', (['futures'], {}), '(futures)\n', (4446, 4455), False, 'from concurrent.futures import ProcessPoolExecutor, as_completed\n'), ((5455, 5475), 'numpy.all', 'np.all', (['(x[key] > 0.0)'], {}), '(x[key] > 0.0)\n', (5461, 5475), True, 'import numpy as np\n'), ((340, 371), 'numpy.array', 'np.array', (['[(1) for _ in PARAMS]'], {}), '([(1) for _ in PARAMS])\n', (348, 371), True, 'import numpy as np\n'), ((904, 965), 'swyft.DirectoryStore', 'DirectoryStore', ([], {'path': 'path', 'params': 'PARAMS', 'simulator': 'simulator'}), '(path=path, params=PARAMS, simulator=simulator)\n', (918, 965), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((2825, 2868), 'numpy.all', 'np.all', (['(status == SimulationStatus.FINISHED)'], {}), '(status == SimulationStatus.FINISHED)\n', (2831, 2868), True, 'import numpy as np\n'), ((4639, 4681), 'numpy.any', 'np.any', (['(status == SimulationStatus.RUNNING)'], {}), '(status == SimulationStatus.RUNNING)\n', (4645, 4681), True, 'import numpy as np\n'), ((5337, 5361), 'numpy.arange', 'np.arange', (['n_simulations'], {}), '(n_simulations)\n', (5346, 5361), True, 'import numpy as np\n'), ((661, 691), 'numpy.random.random', 'np.random.random', (['OUTPUT_SHAPE'], {}), '(OUTPUT_SHAPE)\n', (677, 691), True, 'import numpy as np\n')]
# @Author: <NAME> # @Date: 2021-03-22 09:43:07 # @Last Modified by: <NAME> # @Last Modified time: 2021-11-08 15:09:29 #!/usr/bin/env python ## based on: detectron2.modeling.roi_heads.box_head ## based on: detectron2.modeling.roi_heads.fast_rcnn import torch from torch import nn import numpy as np import logging from typing import Dict, List, Tuple, Union from fvcore.nn import giou_loss, smooth_l1_loss import fvcore.nn.weight_init as weight_init from torch import nn from torch.nn import functional as F from detectron2.config import configurable, get_cfg from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.structures import Boxes, Instances from detectron2.utils.events import get_event_storage from detectron2.utils.registry import Registry ## these specific libraries are needed to alter the network architecture from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads, Res5ROIHeads from detectron2.modeling.roi_heads.box_head import ROI_BOX_HEAD_REGISTRY from detectron2.modeling.roi_heads.fast_rcnn import fast_rcnn_inference, _log_classification_stats from detectron2.modeling.roi_heads.mask_head import ROI_MASK_HEAD_REGISTRY, BaseMaskRCNNHead @ROI_BOX_HEAD_REGISTRY.register() class FastRCNNConvFCHeadDropout(nn.Sequential): """ A head with several 3x3 conv layers (each followed by norm & relu) and then several fc layers (each followed by relu). """ @configurable def __init__( self, input_shape: ShapeSpec, *, conv_dims: List[int], fc_dims: List[int], conv_norm="", dropout_probability: float = 0.5, ): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature. conv_dims (list[int]): the output dimensions of the conv layers fc_dims (list[int]): the output dimensions of the fc layers conv_norm (str or callable): normalization for the conv layers. See :func:`detectron2.layers.get_norm` for supported types. """ super().__init__() assert len(conv_dims) + len(fc_dims) > 0 self._output_size = (input_shape.channels, input_shape.height, input_shape.width) self.conv_norm_relus = [] for k, conv_dim in enumerate(conv_dims): conv = Conv2d( self._output_size[0], conv_dim, kernel_size=3, padding=1, bias=not conv_norm, norm=get_norm(conv_norm, conv_dim), activation=nn.ReLU(), ) self.add_module("conv{}".format(k + 1), conv) self.conv_norm_relus.append(conv) self._output_size = (conv_dim, self._output_size[1], self._output_size[2]) self.fcs = [] for k, fc_dim in enumerate(fc_dims): if k == 0: self.add_module("flatten", nn.Flatten()) dropout = nn.Dropout(p=dropout_probability) self.add_module("dropout{}".format(k + 1), dropout) fc = nn.Linear(int(np.prod(self._output_size)), fc_dim) self.add_module("fc{}".format(k + 1), fc) self.add_module("fc_relu{}".format(k + 1), nn.ReLU()) self.fcs.append(fc) self._output_size = fc_dim for layer in self.conv_norm_relus: weight_init.c2_msra_fill(layer) for layer in self.fcs: weight_init.c2_xavier_fill(layer) @classmethod def from_config(cls, cfg, input_shape): num_conv = cfg.MODEL.ROI_BOX_HEAD.NUM_CONV conv_dim = cfg.MODEL.ROI_BOX_HEAD.CONV_DIM num_fc = cfg.MODEL.ROI_BOX_HEAD.NUM_FC fc_dim = cfg.MODEL.ROI_BOX_HEAD.FC_DIM return { "input_shape": input_shape, "conv_dims": [conv_dim] * num_conv, "fc_dims": [fc_dim] * num_fc, "conv_norm": cfg.MODEL.ROI_BOX_HEAD.NORM, "dropout_probability": cfg.MODEL.ROI_BOX_HEAD.DROPOUT_PROBABILITY, } def forward(self, x): for layer in self: x = layer(x) return x @property @torch.jit.unused def output_shape(self): """ Returns: ShapeSpec: the output feature shape """ o = self._output_size if isinstance(o, int): return ShapeSpec(channels=o) else: return ShapeSpec(channels=o[0], height=o[1], width=o[2]) class FastRCNNOutputLayersDropout(nn.Module): """ Two linear layers for predicting Fast R-CNN outputs: 1. proposal-to-detection box regression deltas 2. classification scores """ @configurable def __init__( self, input_shape: ShapeSpec, *, box2box_transform, num_classes: int, test_score_thresh: float = 0.0, test_nms_thresh: float = 0.5, test_topk_per_image: int = 100, cls_agnostic_bbox_reg: bool = False, smooth_l1_beta: float = 0.0, box_reg_loss_type: str = "smooth_l1", loss_weight: Union[float, Dict[str, float]] = 1.0, softmaxes: bool = False, dropout_probability: float = 0.5, ): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature to this module box2box_transform (Box2BoxTransform or Box2BoxTransformRotated): num_classes (int): number of foreground classes test_score_thresh (float): threshold to filter predictions results. test_nms_thresh (float): NMS threshold for prediction results. test_topk_per_image (int): number of top predictions to produce per image. cls_agnostic_bbox_reg (bool): whether to use class agnostic for bbox regression smooth_l1_beta (float): transition point from L1 to L2 loss. Only used if `box_reg_loss_type` is "smooth_l1" box_reg_loss_type (str): Box regression loss type. One of: "smooth_l1", "giou" loss_weight (float|dict): weights to use for losses. Can be single float for weighting all losses, or a dict of individual weightings. Valid dict keys are: * "loss_cls": applied to classification loss * "loss_box_reg": applied to box regression loss """ super().__init__() if isinstance(input_shape, int): # some backward compatibility input_shape = ShapeSpec(channels=input_shape) self.num_classes = num_classes input_size = input_shape.channels * (input_shape.width or 1) * (input_shape.height or 1) # prediction layer for num_classes foreground classes and one background class (hence + 1) self.dropout1 = nn.Dropout(p=dropout_probability) self.cls_score = nn.Linear(input_size, num_classes + 1) num_bbox_reg_classes = 1 if cls_agnostic_bbox_reg else num_classes box_dim = len(box2box_transform.weights) self.dropout2 = nn.Dropout(p=dropout_probability) self.bbox_pred = nn.Linear(input_size, num_bbox_reg_classes * box_dim) nn.init.normal_(self.cls_score.weight, std=0.01) nn.init.normal_(self.bbox_pred.weight, std=0.001) for l in [self.cls_score, self.bbox_pred]: nn.init.constant_(l.bias, 0) self.box2box_transform = box2box_transform self.smooth_l1_beta = smooth_l1_beta self.test_score_thresh = test_score_thresh self.test_nms_thresh = test_nms_thresh self.test_topk_per_image = test_topk_per_image self.box_reg_loss_type = box_reg_loss_type if isinstance(loss_weight, float): loss_weight = {"loss_cls": loss_weight, "loss_box_reg": loss_weight} self.loss_weight = loss_weight self.softmaxes = softmaxes @classmethod def from_config(cls, cfg, input_shape): return { "input_shape": input_shape, "box2box_transform": Box2BoxTransform(weights=cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS), # fmt: off "num_classes" : cfg.MODEL.ROI_HEADS.NUM_CLASSES, "cls_agnostic_bbox_reg" : cfg.MODEL.ROI_BOX_HEAD.CLS_AGNOSTIC_BBOX_REG, "smooth_l1_beta" : cfg.MODEL.ROI_BOX_HEAD.SMOOTH_L1_BETA, "test_score_thresh" : cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST, "test_nms_thresh" : cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST, "test_topk_per_image" : cfg.TEST.DETECTIONS_PER_IMAGE, "box_reg_loss_type" : cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_LOSS_TYPE, "loss_weight" : {"loss_box_reg": cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_LOSS_WEIGHT}, "softmaxes" : cfg.MODEL.ROI_HEADS.SOFTMAXES, "dropout_probability" : cfg.MODEL.ROI_BOX_HEAD.DROPOUT_PROBABILITY, # fmt: on } def forward(self, x): """ Args: x: per-region features of shape (N, ...) for N bounding boxes to predict. Returns: (Tensor, Tensor): First tensor: shape (N,K+1), scores for each of the N box. Each row contains the scores for K object categories and 1 background class. Second tensor: bounding box regression deltas for each box. Shape is shape (N,Kx4), or (N,4) for class-agnostic regression. """ if x.dim() > 2: x = torch.flatten(x, start_dim=1) x = self.dropout1(x) scores = self.cls_score(x) x = self.dropout2(x) proposal_deltas = self.bbox_pred(x) return scores, proposal_deltas def losses(self, predictions, proposals): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The fields ``proposal_boxes``, ``gt_boxes``, ``gt_classes`` are expected. Returns: Dict[str, Tensor]: dict of losses """ scores, proposal_deltas = predictions # parse classification outputs gt_classes = ( cat([p.gt_classes for p in proposals], dim=0) if len(proposals) else torch.empty(0) ) _log_classification_stats(scores, gt_classes) # parse box regression outputs if len(proposals): proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) # Nx4 assert not proposal_boxes.requires_grad, "Proposals should not require gradients!" # If "gt_boxes" does not exist, the proposals must be all negative and # should not be included in regression loss computation. # Here we just use proposal_boxes as an arbitrary placeholder because its # value won't be used in self.box_reg_loss(). gt_boxes = cat( [(p.gt_boxes if p.has("gt_boxes") else p.proposal_boxes).tensor for p in proposals], dim=0, ) else: proposal_boxes = gt_boxes = torch.empty((0, 4), device=proposal_deltas.device) losses = { "loss_cls": cross_entropy(scores, gt_classes, reduction="mean"), "loss_box_reg": self.box_reg_loss( proposal_boxes, gt_boxes, proposal_deltas, gt_classes ), } return {k: v * self.loss_weight.get(k, 1.0) for k, v in losses.items()} def box_reg_loss(self, proposal_boxes, gt_boxes, pred_deltas, gt_classes): """ Args: All boxes are tensors with the same shape Rx(4 or 5). gt_classes is a long tensor of shape R, the gt class label of each proposal. R shall be the number of proposals. """ box_dim = proposal_boxes.shape[1] # 4 or 5 # Regression loss is only computed for foreground proposals (those matched to a GT) fg_inds = nonzero_tuple((gt_classes >= 0) & (gt_classes < self.num_classes))[0] if pred_deltas.shape[1] == box_dim: # cls-agnostic regression fg_pred_deltas = pred_deltas[fg_inds] else: fg_pred_deltas = pred_deltas.view(-1, self.num_classes, box_dim)[ fg_inds, gt_classes[fg_inds] ] if self.box_reg_loss_type == "smooth_l1": gt_pred_deltas = self.box2box_transform.get_deltas( proposal_boxes[fg_inds], gt_boxes[fg_inds], ) loss_box_reg = smooth_l1_loss( fg_pred_deltas, gt_pred_deltas, self.smooth_l1_beta, reduction="sum" ) elif self.box_reg_loss_type == "giou": fg_pred_boxes = self.box2box_transform.apply_deltas( fg_pred_deltas, proposal_boxes[fg_inds] ) loss_box_reg = giou_loss(fg_pred_boxes, gt_boxes[fg_inds], reduction="sum") else: raise ValueError(f"Invalid bbox reg loss type '{self.box_reg_loss_type}'") # The reg loss is normalized using the total number of regions (R), not the number # of foreground regions even though the box regression loss is only defined on # foreground regions. Why? Because doing so gives equal training influence to # each foreground example. To see how, consider two different minibatches: # (1) Contains a single foreground region # (2) Contains 100 foreground regions # If we normalize by the number of foreground regions, the single example in # minibatch (1) will be given 100 times as much influence as each foreground # example in minibatch (2). Normalizing by the total number of regions, R, # means that the single example in minibatch (1) and each of the 100 examples # in minibatch (2) are given equal influence. return loss_box_reg / max(gt_classes.numel(), 1.0) # return 0 if empty def inference(self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances]): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The ``proposal_boxes`` field is expected. Returns: list[Instances]: same as `fast_rcnn_inference`. list[Tensor]: same as `fast_rcnn_inference`. """ boxes = self.predict_boxes(predictions, proposals) scores = self.predict_probs(predictions, proposals) image_shapes = [x.image_size for x in proposals] return fast_rcnn_inference( boxes, scores, image_shapes, self.test_score_thresh, self.test_nms_thresh, self.test_topk_per_image, self.softmaxes, ) def predict_boxes_for_gt_classes(self, predictions, proposals): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The fields ``proposal_boxes``, ``gt_classes`` are expected. Returns: list[Tensor]: A list of Tensors of predicted boxes for GT classes in case of class-specific box head. Element i of the list has shape (Ri, B), where Ri is the number of proposals for image i and B is the box dimension (4 or 5) """ if not len(proposals): return [] scores, proposal_deltas = predictions proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) N, B = proposal_boxes.shape predict_boxes = self.box2box_transform.apply_deltas( proposal_deltas, proposal_boxes ) # Nx(KxB) K = predict_boxes.shape[1] // B if K > 1: gt_classes = torch.cat([p.gt_classes for p in proposals], dim=0) # Some proposals are ignored or have a background class. Their gt_classes # cannot be used as index. gt_classes = gt_classes.clamp_(0, K - 1) predict_boxes = predict_boxes.view(N, K, B)[ torch.arange(N, dtype=torch.long, device=predict_boxes.device), gt_classes ] num_prop_per_image = [len(p) for p in proposals] return predict_boxes.split(num_prop_per_image) def predict_boxes( self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances] ): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The ``proposal_boxes`` field is expected. Returns: list[Tensor]: A list of Tensors of predicted class-specific or class-agnostic boxes for each image. Element i has shape (Ri, K * B) or (Ri, B), where Ri is the number of proposals for image i and B is the box dimension (4 or 5) """ if not len(proposals): return [] _, proposal_deltas = predictions num_prop_per_image = [len(p) for p in proposals] proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) predict_boxes = self.box2box_transform.apply_deltas( proposal_deltas, proposal_boxes, ) # Nx(KxB) return predict_boxes.split(num_prop_per_image) def predict_probs( self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances] ): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. Returns: list[Tensor]: A list of Tensors of predicted class probabilities for each image. Element i has shape (Ri, K + 1), where Ri is the number of proposals for image i. """ scores, _ = predictions num_inst_per_image = [len(p) for p in proposals] probs = F.softmax(scores, dim=-1) return probs.split(num_inst_per_image, dim=0) @ROI_HEADS_REGISTRY.register() class Res5ROIHeadsDropout(Res5ROIHeads): def __init__(self, cfg, input_shape): super().__init__(cfg, input_shape, box_predictor=FastRCNNOutputLayersDropout(cfg, 2048)) @ROI_HEADS_REGISTRY.register() class StandardROIHeadsDropout(StandardROIHeads): def __init__(self, cfg, input_shape): super().__init__(cfg, input_shape, box_predictor=FastRCNNOutputLayersDropout(cfg, 1024)) @ROI_MASK_HEAD_REGISTRY.register() class MaskRCNNConvUpsampleHeadDropout(BaseMaskRCNNHead, nn.Sequential): """ A mask head with several conv layers, plus an upsample layer (with `ConvTranspose2d`). Predictions are made with a final 1x1 conv layer. """ @configurable def __init__(self, input_shape: ShapeSpec, *, num_classes, conv_dims, conv_norm="", dropout_probability: float = 0.5, **kwargs): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature num_classes (int): the number of foreground classes (i.e. background is not included). 1 if using class agnostic prediction. conv_dims (list[int]): a list of N>0 integers representing the output dimensions of N-1 conv layers and the last upsample layer. conv_norm (str or callable): normalization for the conv layers. See :func:`detectron2.layers.get_norm` for supported types. """ super().__init__(**kwargs) assert len(conv_dims) >= 1, "conv_dims have to be non-empty!" self.conv_norm_relus = [] cur_channels = input_shape.channels for k, conv_dim in enumerate(conv_dims[:-1]): conv = Conv2d( cur_channels, conv_dim, kernel_size=3, stride=1, padding=1, bias=not conv_norm, norm=get_norm(conv_norm, conv_dim), activation=nn.ReLU(), ) self.add_module("mask_fcn{}".format(k + 1), conv) self.conv_norm_relus.append(conv) cur_channels = conv_dim self.dropout1 = nn.Dropout(p=dropout_probability) self.deconv = ConvTranspose2d( cur_channels, conv_dims[-1], kernel_size=2, stride=2, padding=0 ) self.add_module("deconv_relu", nn.ReLU()) cur_channels = conv_dims[-1] self.dropout2 = nn.Dropout(p=dropout_probability) self.predictor = Conv2d(cur_channels, num_classes, kernel_size=1, stride=1, padding=0) for layer in self.conv_norm_relus + [self.deconv]: weight_init.c2_msra_fill(layer) # use normal distribution initialization for mask prediction layer nn.init.normal_(self.predictor.weight, std=0.001) if self.predictor.bias is not None: nn.init.constant_(self.predictor.bias, 0) @classmethod def from_config(cls, cfg, input_shape): ret = super().from_config(cfg, input_shape) conv_dim = cfg.MODEL.ROI_MASK_HEAD.CONV_DIM num_conv = cfg.MODEL.ROI_MASK_HEAD.NUM_CONV ret.update( conv_dims=[conv_dim] * (num_conv + 1), # +1 for ConvTranspose conv_norm=cfg.MODEL.ROI_MASK_HEAD.NORM, input_shape=input_shape, ) if cfg.MODEL.ROI_MASK_HEAD.CLS_AGNOSTIC_MASK: ret["num_classes"] = 1 else: ret["num_classes"] = cfg.MODEL.ROI_HEADS.NUM_CLASSES ret["dropout_probability"] = cfg.MODEL.ROI_MASK_HEAD.DROPOUT_PROBABILITY return ret def layers(self, x): for layer in self: x = layer(x) return x
[ "numpy.prod", "torch.nn.ReLU", "torch.nn.Dropout", "detectron2.modeling.roi_heads.fast_rcnn._log_classification_stats", "torch.nn.init.constant_", "detectron2.layers.cross_entropy", "fvcore.nn.smooth_l1_loss", "torch.nn.functional.softmax", "torch.arange", "detectron2.layers.ShapeSpec", "torch.nn.Flatten", "detectron2.layers.cat", "detectron2.modeling.roi_heads.fast_rcnn.fast_rcnn_inference", "detectron2.layers.ConvTranspose2d", "fvcore.nn.weight_init.c2_xavier_fill", "detectron2.modeling.box_regression.Box2BoxTransform", "fvcore.nn.weight_init.c2_msra_fill", "detectron2.modeling.roi_heads.mask_head.ROI_MASK_HEAD_REGISTRY.register", "detectron2.layers.Conv2d", "detectron2.layers.nonzero_tuple", "fvcore.nn.giou_loss", "detectron2.modeling.roi_heads.box_head.ROI_BOX_HEAD_REGISTRY.register", "torch.empty", "torch.nn.init.normal_", "torch.cat", "detectron2.modeling.roi_heads.ROI_HEADS_REGISTRY.register", "detectron2.layers.get_norm", "torch.nn.Linear", "torch.flatten" ]
[((1340, 1372), 'detectron2.modeling.roi_heads.box_head.ROI_BOX_HEAD_REGISTRY.register', 'ROI_BOX_HEAD_REGISTRY.register', ([], {}), '()\n', (1370, 1372), False, 'from detectron2.modeling.roi_heads.box_head import ROI_BOX_HEAD_REGISTRY\n'), ((18533, 18562), 'detectron2.modeling.roi_heads.ROI_HEADS_REGISTRY.register', 'ROI_HEADS_REGISTRY.register', ([], {}), '()\n', (18560, 18562), False, 'from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads, Res5ROIHeads\n'), ((18751, 18780), 'detectron2.modeling.roi_heads.ROI_HEADS_REGISTRY.register', 'ROI_HEADS_REGISTRY.register', ([], {}), '()\n', (18778, 18780), False, 'from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads, Res5ROIHeads\n'), ((18973, 19006), 'detectron2.modeling.roi_heads.mask_head.ROI_MASK_HEAD_REGISTRY.register', 'ROI_MASK_HEAD_REGISTRY.register', ([], {}), '()\n', (19004, 19006), False, 'from detectron2.modeling.roi_heads.mask_head import ROI_MASK_HEAD_REGISTRY, BaseMaskRCNNHead\n'), ((6937, 6970), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (6947, 6970), False, 'from torch import nn\n'), ((6996, 7034), 'torch.nn.Linear', 'nn.Linear', (['input_size', '(num_classes + 1)'], {}), '(input_size, num_classes + 1)\n', (7005, 7034), False, 'from torch import nn\n'), ((7183, 7216), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (7193, 7216), False, 'from torch import nn\n'), ((7242, 7295), 'torch.nn.Linear', 'nn.Linear', (['input_size', '(num_bbox_reg_classes * box_dim)'], {}), '(input_size, num_bbox_reg_classes * box_dim)\n', (7251, 7295), False, 'from torch import nn\n'), ((7305, 7353), 'torch.nn.init.normal_', 'nn.init.normal_', (['self.cls_score.weight'], {'std': '(0.01)'}), '(self.cls_score.weight, std=0.01)\n', (7320, 7353), False, 'from torch import nn\n'), ((7362, 7411), 'torch.nn.init.normal_', 'nn.init.normal_', (['self.bbox_pred.weight'], {'std': '(0.001)'}), '(self.bbox_pred.weight, std=0.001)\n', (7377, 7411), False, 'from torch import nn\n'), ((10471, 10516), 'detectron2.modeling.roi_heads.fast_rcnn._log_classification_stats', '_log_classification_stats', (['scores', 'gt_classes'], {}), '(scores, gt_classes)\n', (10496, 10516), False, 'from detectron2.modeling.roi_heads.fast_rcnn import fast_rcnn_inference, _log_classification_stats\n'), ((14819, 14959), 'detectron2.modeling.roi_heads.fast_rcnn.fast_rcnn_inference', 'fast_rcnn_inference', (['boxes', 'scores', 'image_shapes', 'self.test_score_thresh', 'self.test_nms_thresh', 'self.test_topk_per_image', 'self.softmaxes'], {}), '(boxes, scores, image_shapes, self.test_score_thresh,\n self.test_nms_thresh, self.test_topk_per_image, self.softmaxes)\n', (14838, 14959), False, 'from detectron2.modeling.roi_heads.fast_rcnn import fast_rcnn_inference, _log_classification_stats\n'), ((15838, 15894), 'detectron2.layers.cat', 'cat', (['[p.proposal_boxes.tensor for p in proposals]'], {'dim': '(0)'}), '([p.proposal_boxes.tensor for p in proposals], dim=0)\n', (15841, 15894), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((17519, 17575), 'detectron2.layers.cat', 'cat', (['[p.proposal_boxes.tensor for p in proposals]'], {'dim': '(0)'}), '([p.proposal_boxes.tensor for p in proposals], dim=0)\n', (17522, 17575), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((18449, 18474), 'torch.nn.functional.softmax', 'F.softmax', (['scores'], {'dim': '(-1)'}), '(scores, dim=-1)\n', (18458, 18474), True, 'from torch.nn import functional as F\n'), ((20731, 20764), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (20741, 20764), False, 'from torch import nn\n'), ((20788, 20873), 'detectron2.layers.ConvTranspose2d', 'ConvTranspose2d', (['cur_channels', 'conv_dims[-1]'], {'kernel_size': '(2)', 'stride': '(2)', 'padding': '(0)'}), '(cur_channels, conv_dims[-1], kernel_size=2, stride=2, padding=0\n )\n', (20803, 20873), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((21003, 21036), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (21013, 21036), False, 'from torch import nn\n'), ((21063, 21132), 'detectron2.layers.Conv2d', 'Conv2d', (['cur_channels', 'num_classes'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(cur_channels, num_classes, kernel_size=1, stride=1, padding=0)\n', (21069, 21132), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((21320, 21369), 'torch.nn.init.normal_', 'nn.init.normal_', (['self.predictor.weight'], {'std': '(0.001)'}), '(self.predictor.weight, std=0.001)\n', (21335, 21369), False, 'from torch import nn\n'), ((3098, 3131), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (3108, 3131), False, 'from torch import nn\n'), ((3511, 3542), 'fvcore.nn.weight_init.c2_msra_fill', 'weight_init.c2_msra_fill', (['layer'], {}), '(layer)\n', (3535, 3542), True, 'import fvcore.nn.weight_init as weight_init\n'), ((3586, 3619), 'fvcore.nn.weight_init.c2_xavier_fill', 'weight_init.c2_xavier_fill', (['layer'], {}), '(layer)\n', (3612, 3619), True, 'import fvcore.nn.weight_init as weight_init\n'), ((4498, 4519), 'detectron2.layers.ShapeSpec', 'ShapeSpec', ([], {'channels': 'o'}), '(channels=o)\n', (4507, 4519), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((4553, 4602), 'detectron2.layers.ShapeSpec', 'ShapeSpec', ([], {'channels': 'o[0]', 'height': 'o[1]', 'width': 'o[2]'}), '(channels=o[0], height=o[1], width=o[2])\n', (4562, 4602), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((6646, 6677), 'detectron2.layers.ShapeSpec', 'ShapeSpec', ([], {'channels': 'input_shape'}), '(channels=input_shape)\n', (6655, 6677), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((7475, 7503), 'torch.nn.init.constant_', 'nn.init.constant_', (['l.bias', '(0)'], {}), '(l.bias, 0)\n', (7492, 7503), False, 'from torch import nn\n'), ((8156, 8221), 'detectron2.modeling.box_regression.Box2BoxTransform', 'Box2BoxTransform', ([], {'weights': 'cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS'}), '(weights=cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS)\n', (8172, 8221), False, 'from detectron2.modeling.box_regression import Box2BoxTransform\n'), ((9612, 9641), 'torch.flatten', 'torch.flatten', (['x'], {'start_dim': '(1)'}), '(x, start_dim=1)\n', (9625, 9641), False, 'import torch\n'), ((10369, 10414), 'detectron2.layers.cat', 'cat', (['[p.gt_classes for p in proposals]'], {'dim': '(0)'}), '([p.gt_classes for p in proposals], dim=0)\n', (10372, 10414), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((10438, 10452), 'torch.empty', 'torch.empty', (['(0)'], {}), '(0)\n', (10449, 10452), False, 'import torch\n'), ((10613, 10669), 'detectron2.layers.cat', 'cat', (['[p.proposal_boxes.tensor for p in proposals]'], {'dim': '(0)'}), '([p.proposal_boxes.tensor for p in proposals], dim=0)\n', (10616, 10669), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((11288, 11338), 'torch.empty', 'torch.empty', (['(0, 4)'], {'device': 'proposal_deltas.device'}), '((0, 4), device=proposal_deltas.device)\n', (11299, 11338), False, 'import torch\n'), ((11383, 11434), 'detectron2.layers.cross_entropy', 'cross_entropy', (['scores', 'gt_classes'], {'reduction': '"""mean"""'}), "(scores, gt_classes, reduction='mean')\n", (11396, 11434), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((12141, 12207), 'detectron2.layers.nonzero_tuple', 'nonzero_tuple', (['((gt_classes >= 0) & (gt_classes < self.num_classes))'], {}), '((gt_classes >= 0) & (gt_classes < self.num_classes))\n', (12154, 12207), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((12715, 12803), 'fvcore.nn.smooth_l1_loss', 'smooth_l1_loss', (['fg_pred_deltas', 'gt_pred_deltas', 'self.smooth_l1_beta'], {'reduction': '"""sum"""'}), "(fg_pred_deltas, gt_pred_deltas, self.smooth_l1_beta,\n reduction='sum')\n", (12729, 12803), False, 'from fvcore.nn import giou_loss, smooth_l1_loss\n'), ((16141, 16192), 'torch.cat', 'torch.cat', (['[p.gt_classes for p in proposals]'], {'dim': '(0)'}), '([p.gt_classes for p in proposals], dim=0)\n', (16150, 16192), False, 'import torch\n'), ((20930, 20939), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (20937, 20939), False, 'from torch import nn\n'), ((21205, 21236), 'fvcore.nn.weight_init.c2_msra_fill', 'weight_init.c2_msra_fill', (['layer'], {}), '(layer)\n', (21229, 21236), True, 'import fvcore.nn.weight_init as weight_init\n'), ((21426, 21467), 'torch.nn.init.constant_', 'nn.init.constant_', (['self.predictor.bias', '(0)'], {}), '(self.predictor.bias, 0)\n', (21443, 21467), False, 'from torch import nn\n'), ((3373, 3382), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (3380, 3382), False, 'from torch import nn\n'), ((13039, 13099), 'fvcore.nn.giou_loss', 'giou_loss', (['fg_pred_boxes', 'gt_boxes[fg_inds]'], {'reduction': '"""sum"""'}), "(fg_pred_boxes, gt_boxes[fg_inds], reduction='sum')\n", (13048, 13099), False, 'from fvcore.nn import giou_loss, smooth_l1_loss\n'), ((2654, 2683), 'detectron2.layers.get_norm', 'get_norm', (['conv_norm', 'conv_dim'], {}), '(conv_norm, conv_dim)\n', (2662, 2683), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((2712, 2721), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (2719, 2721), False, 'from torch import nn\n'), ((3062, 3074), 'torch.nn.Flatten', 'nn.Flatten', ([], {}), '()\n', (3072, 3074), False, 'from torch import nn\n'), ((3227, 3253), 'numpy.prod', 'np.prod', (['self._output_size'], {}), '(self._output_size)\n', (3234, 3253), True, 'import numpy as np\n'), ((16445, 16507), 'torch.arange', 'torch.arange', (['N'], {'dtype': 'torch.long', 'device': 'predict_boxes.device'}), '(N, dtype=torch.long, device=predict_boxes.device)\n', (16457, 16507), False, 'import torch\n'), ((20479, 20508), 'detectron2.layers.get_norm', 'get_norm', (['conv_norm', 'conv_dim'], {}), '(conv_norm, conv_dim)\n', (20487, 20508), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((20537, 20546), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (20544, 20546), False, 'from torch import nn\n')]
#thomas feiring model import math import numpy as np import pandas as pd #enter the year for which you need prediction starting 2019 year=2019 number_of_days=365 day=0 df = pd.read_csv('groundtruth.csv') u=df['Mean'] X_t= u[0] sd=df['St dev'] print("Month,Year,Inflow") #lag -1 correlation lag=df['co relation'] np.random.seed(9001) for i in range(number_of_days): rn=np.random.normal(0,1,1)[0] z_t=(X_t-u[day])/sd[day] z_t1=lag[day]*z_t+rn*math.sqrt(1-lag[day]*lag[day]) X_t1=u[(day+1)%365]+z_t1*sd[(day+1)%365] print(day+1,",",year,",",X_t1) if(day==364): year=year+1 day=0 day=day+1 X_t=X_t1
[ "numpy.random.normal", "math.sqrt", "numpy.random.seed", "pandas.read_csv" ]
[((174, 204), 'pandas.read_csv', 'pd.read_csv', (['"""groundtruth.csv"""'], {}), "('groundtruth.csv')\n", (185, 204), True, 'import pandas as pd\n'), ((313, 333), 'numpy.random.seed', 'np.random.seed', (['(9001)'], {}), '(9001)\n', (327, 333), True, 'import numpy as np\n'), ((373, 398), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(1)'], {}), '(0, 1, 1)\n', (389, 398), True, 'import numpy as np\n'), ((454, 488), 'math.sqrt', 'math.sqrt', (['(1 - lag[day] * lag[day])'], {}), '(1 - lag[day] * lag[day])\n', (463, 488), False, 'import math\n')]