code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
# -------------------------------------------------------- # Pytorch FPN implementation # Licensed under The MIT License [see LICENSE for details] # Written by <NAME>, based on code from faster R-CNN # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import scipy.io as sio import _init_paths import os import sys import numpy as np import argparse import pprint import time import cv2 import pickle import torch from torch.autograd import Variable import torch.nn as nn import torch.optim as optim from roi_data_layer.roidb import combined_roidb from roi_data_layer.roibatchLoader import roibatchLoader from model.utils.config import cfg, cfg_from_file, cfg_from_list, get_output_dir from model.rpn.bbox_transform import clip_boxes from model.nms.nms_wrapper import nms, soft_nms from model.rpn.bbox_transform import bbox_transform_inv from model.utils.net_utils import vis_detections from model.fpn.resnet import resnet from scipy import io import pdb try: xrange # Python 2 except NameError: xrange = range # Python 3 def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('exp_name', type=str, default=None, help='experiment name') parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default='cfgs/res101.yml', type=str) parser.add_argument('--net', dest='net', help='vgg16, res50, res101, res152', default='res101', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) parser.add_argument('--load_dir', dest='load_dir', help='directory to load models', default="weights", type=str) parser.add_argument('--cuda', dest='cuda', help='whether use CUDA', action='store_true') parser.add_argument('--ls', dest='large_scale', help='whether use large imag scale', action='store_true') parser.add_argument('--mGPUs', dest='mGPUs', help='whether use multiple GPUs', action='store_true') parser.add_argument('--cag', dest='class_agnostic', help='whether perform class_agnostic bbox regression', action='store_true') parser.add_argument('--parallel_type', dest='parallel_type', help='which part of model to parallel, 0: all, 1: model before roi pooling', default=0, type=int) parser.add_argument('--checksession', dest='checksession', help='checksession to load model', default=1, type=int) parser.add_argument('--checkepoch', dest='checkepoch', help='checkepoch to load network', default=1, type=int) parser.add_argument('--checkpoint', dest='checkpoint', help='checkpoint to load network', default=10021, type=int) parser.add_argument('--bs', dest='batch_size', help='batch_size', default=1, type=int) parser.add_argument('--vis', dest='vis', help='visualization mode', action='store_true') parser.add_argument('--soft_nms', help='whether use soft_nms', action='store_true') args = parser.parse_args() return args lr = cfg.TRAIN.LEARNING_RATE momentum = cfg.TRAIN.MOMENTUM weight_decay = cfg.TRAIN.WEIGHT_DECAY if __name__ == '__main__': args = parse_args() print('Called with args:') print(args) if torch.cuda.is_available() and not args.cuda: print("WARNING: You have a CUDA device, so you should probably run with --cuda") if args.dataset == "pascal_voc": args.imdb_name = "voc_2007_trainval" args.imdbval_name = "voc_2007_test" args.set_cfgs = ['ANCHOR_SCALES', '[8, 16, 32]', 'ANCHOR_RATIOS', '[0.5,1,2]'] elif args.dataset == "pascal_voc_0712": args.imdb_name = "voc_0712_trainval" args.imdbval_name = "voc_0712_test" args.set_cfgs = ['ANCHOR_SCALES', '[8, 16, 32]', 'ANCHOR_RATIOS', '[0.5,1,2]'] elif args.dataset == "coco": args.imdb_name = "coco_2014_train+coco_2014_valminusminival" args.imdbval_name = "coco_2014_minival" args.set_cfgs = ['ANCHOR_SCALES', '[4, 8, 16, 32]', 'ANCHOR_RATIOS', '[0.5,1,2]'] elif args.dataset == "imagenet": args.imdb_name = "imagenet_train" args.imdbval_name = "imagenet_val" args.set_cfgs = ['ANCHOR_SCALES', '[8, 16, 32]', 'ANCHOR_RATIOS', '[0.5,1,2]'] elif args.dataset == "vg": args.imdb_name = "vg_train" args.imdbval_name = "vg_val" args.set_cfgs = ['ANCHOR_SCALES', '[4, 8, 16, 32]', 'ANCHOR_RATIOS', '[0.5,1,2]'] elif args.dataset == "vgbig": args.imdb_name = "vg_train_big" args.imdbval_name = "vg_val_big" args.set_cfgs = ['ANCHOR_SCALES', '[4, 8, 16, 32]', 'ANCHOR_RATIOS', '[0.5,1,2]'] elif args.dataset == "kitti": args.imdb_name = "kittivoc_train" args.imdbval_name = "kittivoc_val" args.set_cfgs = ['ANCHOR_SCALES', '[2, 4, 8, 16, 32]', 'ANCHOR_RATIOS', '[0.5,1,2]'] args.cfg_file = "cfgs/{}.yml".format(args.net) if args.cfg_file is not None: cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) print('Using config:') pprint.pprint(cfg) np.random.seed(cfg.RNG_SEED) cfg.TRAIN.USE_FLIPPED = False imdb, roidb, ratio_list, ratio_index = combined_roidb(args.imdbval_name, False) imdb.competition_mode(on=True) print('{:d} roidb entries'.format(len(roidb))) if args.exp_name is not None: input_dir = args.load_dir + "/" + args.net + "/" + args.dataset + '/' + args.exp_name else: input_dir = args.load_dir + "/" + args.net + "/" + args.dataset if not os.path.exists(input_dir): raise Exception('There is no input directory for loading network from ' + input_dir) load_name = os.path.join(input_dir, 'fpn_{}_{}_{}.pth'.format(args.checksession, args.checkepoch, args.checkpoint)) # initilize the network here. if args.net == 'vgg16': fpn = vgg16(imdb.classes, pretrained=False, class_agnostic=args.class_agnostic) elif args.net == 'res101': fpn = resnet(imdb.classes, 101, pretrained=False, class_agnostic=args.class_agnostic) elif args.net == 'res50': fpn = resnet(imdb.classes, 50, pretrained=False, class_agnostic=args.class_agnostic) elif args.net == 'res152': fpn = resnet(imdb.classes, 152, pretrained=False, class_agnostic=args.class_agnostic) else: print("network is not defined") pdb.set_trace() fpn.create_architecture() print("load checkpoint %s" % (load_name)) checkpoint = torch.load(load_name) fpn.load_state_dict(checkpoint['model'],strict=False) if 'pooling_mode' in checkpoint.keys(): cfg.POOLING_MODE = checkpoint['pooling_mode'] print('load model successfully!') im_data = torch.FloatTensor(1) im_info = torch.FloatTensor(1) num_boxes = torch.LongTensor(1) gt_boxes = torch.FloatTensor(1) # ship to cuda if args.cuda: im_data = im_data.cuda() im_info = im_info.cuda() num_boxes = num_boxes.cuda() gt_boxes = gt_boxes.cuda() # make variable im_data = Variable(im_data, volatile=True) im_info = Variable(im_info, volatile=True) num_boxes = Variable(num_boxes, volatile=True) gt_boxes = Variable(gt_boxes, volatile=True) if args.cuda: cfg.CUDA = True if args.cuda: fpn.cuda() start = time.time() max_per_image = 100 vis = args.vis if vis: thresh = 0.05 #thresh = 0.975 #thresh = 0.3 else: thresh = 0.0 save_name = 'faster_rcnn_10' num_images = len(imdb.image_index) all_boxes = [[[] for _ in xrange(num_images)] for _ in xrange(imdb.num_classes)] output_dir = get_output_dir(imdb, save_name) dataset = roibatchLoader(roidb, ratio_list, ratio_index, args.batch_size, \ imdb.num_classes, training=False, normalize=False) dataloader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=4, pin_memory=True) data_iter = iter(dataloader) _t = {'im_detect': time.time(), 'misc': time.time()} det_file = os.path.join(output_dir, 'detections.pkl') fpn.eval() # matlab_score = [] # matlab_uncer_cls = [] # matlab_uncer_loc = [] empty_array = np.transpose(np.array([[], [], [], [], []]), (1, 0)) score_list = [] uncer_list = [] for i in range(num_images): data = data_iter.next() im_data.data.resize_(data[0].size()).copy_(data[0]) im_info.data.resize_(data[1].size()).copy_(data[1]) gt_boxes.data.resize_(data[2].size()).copy_(data[2]) num_boxes.data.resize_(data[3].size()).copy_(data[3]) # mean1s = [] # mean2s = [] # # mean1b = [] # mean2b = [] # var1s = [] # var1b = [] det_tic = time.time() # for ii in range(1): rois, cls_prob, cls_score, bbox_pred, \ _, _, _, _, _, uncer_cls = fpn(im_data, im_info, gt_boxes, num_boxes, th=0.0) # mean1s.append(cls_score ** 2) # mean2s.append(cls_score) # mean1b.append(bbox_pred **2) # mean2b.append(bbox_pred) # ## mean1s_ = torch.stack(mean1s, dim=0).mean(dim=0) # mean2s_ = torch.stack(mean2s, dim=0).mean(dim=0) # # mean1b_ = torch.stack(mean1b, dim=0).mean(dim=0) # mean2b_ = torch.stack(mean2b, dim=0).mean(dim=0) # # var1 = mean1s_ - (mean2s_ ** 2) # var1_norm = var1 #/ var1.max() # # var2 = mean1b_ - (mean2b_ ** 2) # var2_norm = var2 #/ var2.max() # var2_norm = torch.squeeze(var2_norm,0) #rois, cls_prob, cls_score, bbox_pred, \ #_, _, _, _, _ = fpn(im_data, im_info, gt_boxes, num_boxes, th=0) scores = cls_prob.data boxes = rois.data[:, :, 1:5] if cfg.TEST.BBOX_REG: # Apply bounding-box regression deltas box_deltas = bbox_pred.data if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED: # Optionally normalize targets by a precomputed mean and stdev if args.class_agnostic: box_deltas = box_deltas.view(-1, 4) * torch.FloatTensor(cfg.TRAIN.BBOX_NORMALIZE_STDS).cuda() \ + torch.FloatTensor(cfg.TRAIN.BBOX_NORMALIZE_MEANS).cuda() box_deltas = box_deltas.view(1, -1, 4) else: box_deltas = box_deltas.view(-1, 4) * torch.FloatTensor(cfg.TRAIN.BBOX_NORMALIZE_STDS).cuda() \ + torch.FloatTensor(cfg.TRAIN.BBOX_NORMALIZE_MEANS).cuda() box_deltas = box_deltas.view(1, -1, 4 * len(imdb.classes)) pred_boxes = bbox_transform_inv(boxes, box_deltas, 1) pred_boxes = clip_boxes(pred_boxes, im_info.data, 1) else: # Simply repeat the boxes, once for each class pred_boxes = boxes pred_boxes /= data[1][0][2]#.cuda() scores = scores.squeeze() pred_boxes = pred_boxes.squeeze() det_toc = time.time() detect_time = det_toc - det_tic misc_tic = time.time() if vis: im = cv2.imread(imdb.image_path_at(i)) im2show = np.copy(im) for j in xrange(1, imdb.num_classes): inds = torch.nonzero(scores[:, j] > thresh).view(-1) # if there is det if inds.numel() > 0: cls_scores = scores[:, j][inds] _, order = torch.sort(cls_scores, 0, True) if args.class_agnostic: cls_boxes = pred_boxes[inds, :] else: cls_boxes = pred_boxes[inds][:, j * 4:(j + 1) * 4] cls_dets = torch.cat((cls_boxes, cls_scores.unsqueeze(1)), 1) cls_dets = cls_dets[order] uncertainty_cls = uncer_cls[inds] uncertainty_cls = uncertainty_cls[order] # var_norm_cls = var1_norm[inds] # var_norm_loc = var2_norm[inds] # # var_norm_cls = var_norm_cls[order] # var_norm_loc = var_norm_loc[order] if args.soft_nms: np_dets = cls_dets.cpu().numpy().astype(np.float32) keep = soft_nms(np_dets, cfg.TEST.SOFT_NMS_METHOD) # np_dets will be changed in soft_nms keep = torch.from_numpy(keep).type_as(cls_dets).int() cls_dets = torch.from_numpy(np_dets).type_as(cls_dets) else: keep = nms(cls_dets, cfg.TEST.NMS) cls_dets = cls_dets[keep.view(-1).long()] uncertainty_cls = uncertainty_cls[keep.view(-1).long()] # for jjj in range(cls_dets.size(0)): # # score_list.append(cls_dets.cpu().numpy()[jjj]) # uncer_list.append(uncertainty_cls.data.cpu().numpy()[jjj]) # var_norm_cls = var_norm_cls[keep.view(-1).long()] # var_norm_loc = var_norm_loc[keep.view(-1).long()] # matlab_score = np.concatenate([matlab_score, cls_dets[:,-1].cpu().numpy()], axis=0) # matlab_uncer_cls = np.concatenate([matlab_uncer_cls, var_norm_cls[:,-1].data.cpu().numpy()], axis=0) # matlab_uncer_loc = np.concatenate([matlab_uncer_loc, var_norm_loc[:,-1].data.cpu().numpy()], axis=0) # sio.savemat('np_struct_arr.mat', {'matlab_score': matlab_score, 'matlab_uncer_cls': matlab_uncer_cls, 'matlab_uncer_loc': matlab_uncer_loc}) # assert 1==0 # print (matlab_score.shape, matlab_uncer_cls.shape, matlab_uncer_loc.shape) if vis: im2show = vis_detections(im2show, imdb.classes[j], cls_dets.cpu().numpy(), uncertainty_cls.data.cpu().numpy(), j, 0.3) all_boxes[j][i] = cls_dets.cpu().numpy() else: all_boxes[j][i] = empty_array # Limit to max_per_image detections *over all classes* if max_per_image > 0: image_scores = np.hstack([all_boxes[j][i][:, -1] for j in xrange(1, imdb.num_classes)]) if len(image_scores) > max_per_image: image_thresh = np.sort(image_scores)[-max_per_image] for j in xrange(1, imdb.num_classes): keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0] all_boxes[j][i] = all_boxes[j][i][keep, :] misc_toc = time.time() nms_time = misc_toc - misc_tic sys.stdout.write('im_detect: {:d}/{:d} {:.3f}s {:.3f}s \r' \ .format(i + 1, num_images, detect_time, nms_time)) sys.stdout.flush() # if vis: # cv2.imwrite('./tmp/' + str(i) + '.png', im2show) # assert 1==0 #pdb.set_trace() # cv2.imshow('test', im2show) # cv2.waitKey(0) # sio.savemat('np_struct_arr.mat', {'matlab_score': matlab_score, 'matlab_uncer_cls': matlab_uncer_cls, 'matlab_uncer_loc': matlab_uncer_loc}) # if i == 700: # break # io.savemat('./matfile/score.mat', {'score': np.array(score_list)}) # io.savemat('./matfile/uncer.mat', {'fpn_uncer': np.array(uncer_list)}) with open(det_file, 'wb') as f: pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL) print('Evaluating detections') results = [] # overthresh = 0.5 imdb.evaluate_detections(all_boxes, output_dir)#, overthresh) #results.append(recall_val) # print('Overthresh: ', overthresh) # results = [] # overthresh = np.arange(0.5, 1.0, 0.05) # for t in overthresh: # recall_val = imdb.evaluate_detections(all_boxes, output_dir, t) # results.append(recall_val) # print('Overthresh: ', overthresh) # print('Recall: ', results) # print('mean : ', sum(results) / len(results)) # print('Evaluating detections') # imdb.evaluate_detections(all_boxes, output_dir) end = time.time() print("test time: %0.4fs" % (end - start))
[ "torch.LongTensor", "model.fpn.resnet.resnet", "torch.from_numpy", "numpy.array", "torch.cuda.is_available", "model.utils.config.cfg_from_file", "pprint.pprint", "model.utils.config.cfg_from_list", "os.path.exists", "argparse.ArgumentParser", "numpy.where", "numpy.sort", "numpy.random.seed",...
[((1227, 1292), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train a Fast R-CNN network"""'}), "(description='Train a Fast R-CNN network')\n", (1250, 1292), False, 'import argparse\n'), ((6001, 6019), 'pprint.pprint', 'pprint.pprint', (['cfg'], {}), '(cfg)\n', (6014, 6019), False, 'import pprint\n'), ((6024, 6052), 'numpy.random.seed', 'np.random.seed', (['cfg.RNG_SEED'], {}), '(cfg.RNG_SEED)\n', (6038, 6052), True, 'import numpy as np\n'), ((6131, 6171), 'roi_data_layer.roidb.combined_roidb', 'combined_roidb', (['args.imdbval_name', '(False)'], {}), '(args.imdbval_name, False)\n', (6145, 6171), False, 'from roi_data_layer.roidb import combined_roidb\n'), ((7443, 7464), 'torch.load', 'torch.load', (['load_name'], {}), '(load_name)\n', (7453, 7464), False, 'import torch\n'), ((7674, 7694), 'torch.FloatTensor', 'torch.FloatTensor', (['(1)'], {}), '(1)\n', (7691, 7694), False, 'import torch\n'), ((7709, 7729), 'torch.FloatTensor', 'torch.FloatTensor', (['(1)'], {}), '(1)\n', (7726, 7729), False, 'import torch\n'), ((7746, 7765), 'torch.LongTensor', 'torch.LongTensor', (['(1)'], {}), '(1)\n', (7762, 7765), False, 'import torch\n'), ((7781, 7801), 'torch.FloatTensor', 'torch.FloatTensor', (['(1)'], {}), '(1)\n', (7798, 7801), False, 'import torch\n'), ((8013, 8045), 'torch.autograd.Variable', 'Variable', (['im_data'], {'volatile': '(True)'}), '(im_data, volatile=True)\n', (8021, 8045), False, 'from torch.autograd import Variable\n'), ((8060, 8092), 'torch.autograd.Variable', 'Variable', (['im_info'], {'volatile': '(True)'}), '(im_info, volatile=True)\n', (8068, 8092), False, 'from torch.autograd import Variable\n'), ((8109, 8143), 'torch.autograd.Variable', 'Variable', (['num_boxes'], {'volatile': '(True)'}), '(num_boxes, volatile=True)\n', (8117, 8143), False, 'from torch.autograd import Variable\n'), ((8159, 8192), 'torch.autograd.Variable', 'Variable', (['gt_boxes'], {'volatile': '(True)'}), '(gt_boxes, volatile=True)\n', (8167, 8192), False, 'from torch.autograd import Variable\n'), ((8287, 8298), 'time.time', 'time.time', ([], {}), '()\n', (8296, 8298), False, 'import time\n'), ((8648, 8679), 'model.utils.config.get_output_dir', 'get_output_dir', (['imdb', 'save_name'], {}), '(imdb, save_name)\n', (8662, 8679), False, 'from model.utils.config import cfg, cfg_from_file, cfg_from_list, get_output_dir\n'), ((8694, 8813), 'roi_data_layer.roibatchLoader.roibatchLoader', 'roibatchLoader', (['roidb', 'ratio_list', 'ratio_index', 'args.batch_size', 'imdb.num_classes'], {'training': '(False)', 'normalize': '(False)'}), '(roidb, ratio_list, ratio_index, args.batch_size, imdb.\n num_classes, training=False, normalize=False)\n', (8708, 8813), False, 'from roi_data_layer.roibatchLoader import roibatchLoader\n'), ((8857, 8973), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(4)', 'pin_memory': '(True)'}), '(dataset, batch_size=args.batch_size, shuffle=\n False, num_workers=4, pin_memory=True)\n', (8884, 8973), False, 'import torch\n'), ((9166, 9208), 'os.path.join', 'os.path.join', (['output_dir', '"""detections.pkl"""'], {}), "(output_dir, 'detections.pkl')\n", (9178, 9208), False, 'import os\n'), ((17083, 17094), 'time.time', 'time.time', ([], {}), '()\n', (17092, 17094), False, 'import time\n'), ((4145, 4170), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4168, 4170), False, 'import torch\n'), ((5869, 5897), 'model.utils.config.cfg_from_file', 'cfg_from_file', (['args.cfg_file'], {}), '(args.cfg_file)\n', (5882, 5897), False, 'from model.utils.config import cfg, cfg_from_file, cfg_from_list, get_output_dir\n'), ((5940, 5968), 'model.utils.config.cfg_from_list', 'cfg_from_list', (['args.set_cfgs'], {}), '(args.set_cfgs)\n', (5953, 5968), False, 'from model.utils.config import cfg, cfg_from_file, cfg_from_list, get_output_dir\n'), ((6481, 6506), 'os.path.exists', 'os.path.exists', (['input_dir'], {}), '(input_dir)\n', (6495, 6506), False, 'import os\n'), ((9117, 9128), 'time.time', 'time.time', ([], {}), '()\n', (9126, 9128), False, 'import time\n'), ((9138, 9149), 'time.time', 'time.time', ([], {}), '()\n', (9147, 9149), False, 'import time\n'), ((9334, 9364), 'numpy.array', 'np.array', (['[[], [], [], [], []]'], {}), '([[], [], [], [], []])\n', (9342, 9364), True, 'import numpy as np\n'), ((9867, 9878), 'time.time', 'time.time', ([], {}), '()\n', (9876, 9878), False, 'import time\n'), ((12102, 12113), 'time.time', 'time.time', ([], {}), '()\n', (12111, 12113), False, 'import time\n'), ((12173, 12184), 'time.time', 'time.time', ([], {}), '()\n', (12182, 12184), False, 'import time\n'), ((15578, 15589), 'time.time', 'time.time', ([], {}), '()\n', (15587, 15589), False, 'import time\n'), ((15785, 15803), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (15801, 15803), False, 'import sys\n'), ((16396, 16446), 'pickle.dump', 'pickle.dump', (['all_boxes', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(all_boxes, f, pickle.HIGHEST_PROTOCOL)\n', (16407, 16446), False, 'import pickle\n'), ((6946, 7025), 'model.fpn.resnet.resnet', 'resnet', (['imdb.classes', '(101)'], {'pretrained': '(False)', 'class_agnostic': 'args.class_agnostic'}), '(imdb.classes, 101, pretrained=False, class_agnostic=args.class_agnostic)\n', (6952, 7025), False, 'from model.fpn.resnet import resnet\n'), ((11752, 11792), 'model.rpn.bbox_transform.bbox_transform_inv', 'bbox_transform_inv', (['boxes', 'box_deltas', '(1)'], {}), '(boxes, box_deltas, 1)\n', (11770, 11792), False, 'from model.rpn.bbox_transform import bbox_transform_inv\n'), ((11818, 11857), 'model.rpn.bbox_transform.clip_boxes', 'clip_boxes', (['pred_boxes', 'im_info.data', '(1)'], {}), '(pred_boxes, im_info.data, 1)\n', (11828, 11857), False, 'from model.rpn.bbox_transform import clip_boxes\n'), ((12274, 12285), 'numpy.copy', 'np.copy', (['im'], {}), '(im)\n', (12281, 12285), True, 'import numpy as np\n'), ((7070, 7148), 'model.fpn.resnet.resnet', 'resnet', (['imdb.classes', '(50)'], {'pretrained': '(False)', 'class_agnostic': 'args.class_agnostic'}), '(imdb.classes, 50, pretrained=False, class_agnostic=args.class_agnostic)\n', (7076, 7148), False, 'from model.fpn.resnet import resnet\n'), ((12535, 12566), 'torch.sort', 'torch.sort', (['cls_scores', '(0)', '(True)'], {}), '(cls_scores, 0, True)\n', (12545, 12566), False, 'import torch\n'), ((7194, 7273), 'model.fpn.resnet.resnet', 'resnet', (['imdb.classes', '(152)'], {'pretrained': '(False)', 'class_agnostic': 'args.class_agnostic'}), '(imdb.classes, 152, pretrained=False, class_agnostic=args.class_agnostic)\n', (7200, 7273), False, 'from model.fpn.resnet import resnet\n'), ((7332, 7347), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (7345, 7347), False, 'import pdb\n'), ((12351, 12387), 'torch.nonzero', 'torch.nonzero', (['(scores[:, j] > thresh)'], {}), '(scores[:, j] > thresh)\n', (12364, 12387), False, 'import torch\n'), ((13318, 13361), 'model.nms.nms_wrapper.soft_nms', 'soft_nms', (['np_dets', 'cfg.TEST.SOFT_NMS_METHOD'], {}), '(np_dets, cfg.TEST.SOFT_NMS_METHOD)\n', (13326, 13361), False, 'from model.nms.nms_wrapper import nms, soft_nms\n'), ((13599, 13626), 'model.nms.nms_wrapper.nms', 'nms', (['cls_dets', 'cfg.TEST.NMS'], {}), '(cls_dets, cfg.TEST.NMS)\n', (13602, 13626), False, 'from model.nms.nms_wrapper import nms, soft_nms\n'), ((15324, 15345), 'numpy.sort', 'np.sort', (['image_scores'], {}), '(image_scores)\n', (15331, 15345), True, 'import numpy as np\n'), ((15443, 15491), 'numpy.where', 'np.where', (['(all_boxes[j][i][:, -1] >= image_thresh)'], {}), '(all_boxes[j][i][:, -1] >= image_thresh)\n', (15451, 15491), True, 'import numpy as np\n'), ((13506, 13531), 'torch.from_numpy', 'torch.from_numpy', (['np_dets'], {}), '(np_dets)\n', (13522, 13531), False, 'import torch\n'), ((11301, 11350), 'torch.FloatTensor', 'torch.FloatTensor', (['cfg.TRAIN.BBOX_NORMALIZE_MEANS'], {}), '(cfg.TRAIN.BBOX_NORMALIZE_MEANS)\n', (11318, 11350), False, 'import torch\n'), ((11590, 11639), 'torch.FloatTensor', 'torch.FloatTensor', (['cfg.TRAIN.BBOX_NORMALIZE_MEANS'], {}), '(cfg.TRAIN.BBOX_NORMALIZE_MEANS)\n', (11607, 11639), False, 'import torch\n'), ((11208, 11256), 'torch.FloatTensor', 'torch.FloatTensor', (['cfg.TRAIN.BBOX_NORMALIZE_STDS'], {}), '(cfg.TRAIN.BBOX_NORMALIZE_STDS)\n', (11225, 11256), False, 'import torch\n'), ((11497, 11545), 'torch.FloatTensor', 'torch.FloatTensor', (['cfg.TRAIN.BBOX_NORMALIZE_STDS'], {}), '(cfg.TRAIN.BBOX_NORMALIZE_STDS)\n', (11514, 11545), False, 'import torch\n'), ((13428, 13450), 'torch.from_numpy', 'torch.from_numpy', (['keep'], {}), '(keep)\n', (13444, 13450), False, 'import torch\n')]
import json import logging import os import time import cv2 import numpy as np import torch import inference from inference.vision.classification_and_detection.python.coco import Coco from inference.vision.classification_and_detection.python.coco import log class CocoMod(Coco): def __init__(self, data_path, image_list, name, use_cache=0, image_size=None, image_format="NHWC", pre_process=None, count=None, cache_dir=None,use_label_map=False): self.image_size = image_size self.image_list = [] self.label_list = [] self.image_ids = [] self.image_sizes = [] self.count = count self.use_cache = use_cache self.data_path = data_path self.pre_process = pre_process self.use_label_map=use_label_map if not cache_dir: cache_dir = os.getcwd() self.cache_dir = os.path.join(cache_dir, "preprocessed", name, image_format) # input images are in HWC self.need_transpose = True if image_format == "NCHW" else False not_found = 0 empty_80catageories = 0 self.annotation_file = image_list if self.use_label_map: # for pytorch label_map = {} with open(self.annotation_file) as fin: annotations = json.load(fin) for cnt, cat in enumerate(annotations["categories"]): label_map[cat["id"]] = cnt + 1 if self.use_cache: os.makedirs(self.cache_dir, exist_ok=True) start = time.time() images = {} with open(image_list, "r") as f: coco = json.load(f) for i in coco["images"]: images[i["id"]] = {"file_name": i["file_name"], "height": i["height"], "width": i["width"], "bbox": [], "category": []} for a in coco["annotations"]: i = images.get(a["image_id"]) if i is None: continue catagory_ids = label_map[a.get("category_id")] if self.use_label_map else a.get("category_id") i["category"].append(catagory_ids) i["bbox"].append(a.get("bbox")) for image_id, img in images.items(): #image_name = os.path.join("val2017", img["file_name"]) image_name = os.path.join(img["file_name"]) src = os.path.join(data_path, image_name) if not os.path.exists(src): # if the image does not exists ignore it not_found += 1 continue if len(img["category"])==0 and self.use_label_map: #if an image doesn't have any of the 81 categories in it empty_80catageories += 1 #should be 48 images - thus the validation sert has 4952 images continue if self.use_cache: os.makedirs(os.path.dirname(os.path.join(self.cache_dir, image_name)), exist_ok=True) dst = os.path.join(self.cache_dir, image_name) if self.use_cache and not os.path.exists(dst + ".npy"): # cache a preprocessed version of the image img_org = cv2.imread(src) processed = self.pre_process(img_org, need_transpose=self.need_transpose, dims=self.image_size) np.save(dst, processed) self.image_ids.append(image_id) self.image_list.append(image_name) self.image_sizes.append((img["height"], img["width"])) self.label_list.append((img["category"], img["bbox"])) # limit the dataset if requested if self.count and len(self.image_list) >= self.count: break time_taken = time.time() - start if not self.image_list: log.error("no images in image list found") raise ValueError("no images in image list found") if not_found > 0: log.info("reduced image list, %d images not found", not_found) if empty_80catageories > 0: log.info("reduced image list, %d images without any of the 80 categories", empty_80catageories) log.info("loaded {} images, cache={}, took={:.1f}sec".format( len(self.image_list), use_cache, time_taken)) self.label_list = np.array(self.label_list) def get_item(self, nr): """Get image by number in the list.""" if self.use_cache: dst = os.path.join(self.cache_dir, self.image_list[nr]) img = np.load(dst + ".npy") return img, self.label_list[nr] else: src = self.get_item_loc(nr) img_org = cv2.imread(src) processed = self.pre_process(img_org, need_transpose=self.need_transpose, dims=self.image_size) processed = torch.Tensor(processed).unsqueeze(0) return processed, self.label_list[nr] def get_samples(self, id_list): data = [self.image_list_inmemory[id] for id in id_list] labels = self.label_list[id_list] return data, labels
[ "os.path.exists", "cv2.imread", "os.makedirs", "inference.vision.classification_and_detection.python.coco.log.info", "os.path.join", "torch.Tensor", "os.getcwd", "numpy.array", "json.load", "inference.vision.classification_and_detection.python.coco.log.error", "time.time", "numpy.save", "num...
[((886, 945), 'os.path.join', 'os.path.join', (['cache_dir', '"""preprocessed"""', 'name', 'image_format'], {}), "(cache_dir, 'preprocessed', name, image_format)\n", (898, 945), False, 'import os\n'), ((1541, 1552), 'time.time', 'time.time', ([], {}), '()\n', (1550, 1552), False, 'import time\n'), ((4373, 4398), 'numpy.array', 'np.array', (['self.label_list'], {}), '(self.label_list)\n', (4381, 4398), True, 'import numpy as np\n'), ((849, 860), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (858, 860), False, 'import os\n'), ((1482, 1524), 'os.makedirs', 'os.makedirs', (['self.cache_dir'], {'exist_ok': '(True)'}), '(self.cache_dir, exist_ok=True)\n', (1493, 1524), False, 'import os\n'), ((1633, 1645), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1642, 1645), False, 'import json\n'), ((2402, 2432), 'os.path.join', 'os.path.join', (["img['file_name']"], {}), "(img['file_name'])\n", (2414, 2432), False, 'import os\n'), ((2451, 2486), 'os.path.join', 'os.path.join', (['data_path', 'image_name'], {}), '(data_path, image_name)\n', (2463, 2486), False, 'import os\n'), ((3063, 3103), 'os.path.join', 'os.path.join', (['self.cache_dir', 'image_name'], {}), '(self.cache_dir, image_name)\n', (3075, 3103), False, 'import os\n'), ((3805, 3816), 'time.time', 'time.time', ([], {}), '()\n', (3814, 3816), False, 'import time\n'), ((3869, 3911), 'inference.vision.classification_and_detection.python.coco.log.error', 'log.error', (['"""no images in image list found"""'], {}), "('no images in image list found')\n", (3878, 3911), False, 'from inference.vision.classification_and_detection.python.coco import log\n'), ((4012, 4074), 'inference.vision.classification_and_detection.python.coco.log.info', 'log.info', (['"""reduced image list, %d images not found"""', 'not_found'], {}), "('reduced image list, %d images not found', not_found)\n", (4020, 4074), False, 'from inference.vision.classification_and_detection.python.coco import log\n'), ((4123, 4222), 'inference.vision.classification_and_detection.python.coco.log.info', 'log.info', (['"""reduced image list, %d images without any of the 80 categories"""', 'empty_80catageories'], {}), "('reduced image list, %d images without any of the 80 categories',\n empty_80catageories)\n", (4131, 4222), False, 'from inference.vision.classification_and_detection.python.coco import log\n'), ((4520, 4569), 'os.path.join', 'os.path.join', (['self.cache_dir', 'self.image_list[nr]'], {}), '(self.cache_dir, self.image_list[nr])\n', (4532, 4569), False, 'import os\n'), ((4588, 4609), 'numpy.load', 'np.load', (["(dst + '.npy')"], {}), "(dst + '.npy')\n", (4595, 4609), True, 'import numpy as np\n'), ((4730, 4745), 'cv2.imread', 'cv2.imread', (['src'], {}), '(src)\n', (4740, 4745), False, 'import cv2\n'), ((1315, 1329), 'json.load', 'json.load', (['fin'], {}), '(fin)\n', (1324, 1329), False, 'import json\n'), ((2506, 2525), 'os.path.exists', 'os.path.exists', (['src'], {}), '(src)\n', (2520, 2525), False, 'import os\n'), ((3258, 3273), 'cv2.imread', 'cv2.imread', (['src'], {}), '(src)\n', (3268, 3273), False, 'import cv2\n'), ((3402, 3425), 'numpy.save', 'np.save', (['dst', 'processed'], {}), '(dst, processed)\n', (3409, 3425), True, 'import numpy as np\n'), ((3142, 3170), 'os.path.exists', 'os.path.exists', (["(dst + '.npy')"], {}), "(dst + '.npy')\n", (3156, 3170), False, 'import os\n'), ((4878, 4901), 'torch.Tensor', 'torch.Tensor', (['processed'], {}), '(processed)\n', (4890, 4901), False, 'import torch\n'), ((2987, 3027), 'os.path.join', 'os.path.join', (['self.cache_dir', 'image_name'], {}), '(self.cache_dir, image_name)\n', (2999, 3027), False, 'import os\n')]
""" Please see https://computationalmindset.com/en/neural-networks/ordinary-differential-equation-solvers.html#ode1 for details """ import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_probability as tfp ode_fn = lambda t, x: tf.math.sin(t) + tf.constant(3.) * tf.math.cos(tf.constant(2.) * t) - x an_sol = lambda t : (1./2.) * np.sin(t) - (1./2.) * np.cos(t) + \ (3./5.) * np.cos(2.*t) + (6./5.) * np.sin(2.*t) - \ (1./10.) * np.exp(-t) t_begin=0. t_end=10. t_nsamples=100 t_space = np.linspace(t_begin, t_end, t_nsamples) t_init = tf.constant(t_begin) x_init = tf.constant(0.) x_an_sol = an_sol(t_space) num_sol = tfp.math.ode.BDF().solve(ode_fn, t_init, x_init, solution_times=tfp.math.ode.ChosenBySolver(tf.constant(t_end)) ) plt.figure() plt.plot(t_space, x_an_sol, '--', linewidth=2, label='analytical') plt.plot(num_sol.times, num_sol.states, linewidth=1, label='numerical') plt.title('ODE 1st order IVP solved by TFP with BDF') plt.xlabel('t') plt.ylabel('x') plt.legend() plt.show()
[ "matplotlib.pyplot.ylabel", "tensorflow_probability.math.ode.BDF", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "tensorflow.math.sin", "numpy.exp", "numpy.linspace", "matplotlib.pyplot.figure", "tensorflow.constant", "numpy.cos", "numpy.sin", "matplotlib.pyplot.title", "matplotlib.p...
[((569, 608), 'numpy.linspace', 'np.linspace', (['t_begin', 't_end', 't_nsamples'], {}), '(t_begin, t_end, t_nsamples)\n', (580, 608), True, 'import numpy as np\n'), ((618, 638), 'tensorflow.constant', 'tf.constant', (['t_begin'], {}), '(t_begin)\n', (629, 638), True, 'import tensorflow as tf\n'), ((648, 664), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), '(0.0)\n', (659, 664), True, 'import tensorflow as tf\n'), ((819, 831), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (829, 831), True, 'import matplotlib.pyplot as plt\n'), ((832, 898), 'matplotlib.pyplot.plot', 'plt.plot', (['t_space', 'x_an_sol', '"""--"""'], {'linewidth': '(2)', 'label': '"""analytical"""'}), "(t_space, x_an_sol, '--', linewidth=2, label='analytical')\n", (840, 898), True, 'import matplotlib.pyplot as plt\n'), ((899, 970), 'matplotlib.pyplot.plot', 'plt.plot', (['num_sol.times', 'num_sol.states'], {'linewidth': '(1)', 'label': '"""numerical"""'}), "(num_sol.times, num_sol.states, linewidth=1, label='numerical')\n", (907, 970), True, 'import matplotlib.pyplot as plt\n'), ((971, 1024), 'matplotlib.pyplot.title', 'plt.title', (['"""ODE 1st order IVP solved by TFP with BDF"""'], {}), "('ODE 1st order IVP solved by TFP with BDF')\n", (980, 1024), True, 'import matplotlib.pyplot as plt\n'), ((1025, 1040), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""t"""'], {}), "('t')\n", (1035, 1040), True, 'import matplotlib.pyplot as plt\n'), ((1041, 1056), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""x"""'], {}), "('x')\n", (1051, 1056), True, 'import matplotlib.pyplot as plt\n'), ((1057, 1069), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1067, 1069), True, 'import matplotlib.pyplot as plt\n'), ((1070, 1080), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1078, 1080), True, 'import matplotlib.pyplot as plt\n'), ((703, 721), 'tensorflow_probability.math.ode.BDF', 'tfp.math.ode.BDF', ([], {}), '()\n', (719, 721), True, 'import tensorflow_probability as tfp\n'), ((269, 283), 'tensorflow.math.sin', 'tf.math.sin', (['t'], {}), '(t)\n', (280, 283), True, 'import tensorflow as tf\n'), ((511, 521), 'numpy.exp', 'np.exp', (['(-t)'], {}), '(-t)\n', (517, 521), True, 'import numpy as np\n'), ((796, 814), 'tensorflow.constant', 'tf.constant', (['t_end'], {}), '(t_end)\n', (807, 814), True, 'import tensorflow as tf\n'), ((286, 302), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (297, 302), True, 'import tensorflow as tf\n'), ((463, 478), 'numpy.sin', 'np.sin', (['(2.0 * t)'], {}), '(2.0 * t)\n', (469, 478), True, 'import numpy as np\n'), ((438, 453), 'numpy.cos', 'np.cos', (['(2.0 * t)'], {}), '(2.0 * t)\n', (444, 453), True, 'import numpy as np\n'), ((316, 332), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (327, 332), True, 'import tensorflow as tf\n'), ((372, 381), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (378, 381), True, 'import numpy as np\n'), ((394, 403), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (400, 403), True, 'import numpy as np\n')]
import numpy as np import cv2 black_image = np.zeros((300,300,3), dtype='uint8') red = (0, 0, 255) black_image = cv2.line(black_image, (0, 0), (300, 300), red, 3) cv2.imshow('Red line', black_image) cv2.waitKey(0) green = (0, 255, 0) black_image = cv2.rectangle(black_image, (10, 10), (50, 50), green, -1) cv2.imshow('Green square', black_image) cv2.waitKey(0) height, width, num_channels = black_image.shape blue = (255, 0, 0) black_image = cv2.circle(black_image, (width // 2, height // 2), 25, blue, 5) cv2.imshow('Blue circle', black_image) cv2.waitKey(0)
[ "cv2.rectangle", "cv2.line", "cv2.imshow", "numpy.zeros", "cv2.circle", "cv2.waitKey" ]
[((44, 82), 'numpy.zeros', 'np.zeros', (['(300, 300, 3)'], {'dtype': '"""uint8"""'}), "((300, 300, 3), dtype='uint8')\n", (52, 82), True, 'import numpy as np\n'), ((114, 163), 'cv2.line', 'cv2.line', (['black_image', '(0, 0)', '(300, 300)', 'red', '(3)'], {}), '(black_image, (0, 0), (300, 300), red, 3)\n', (122, 163), False, 'import cv2\n'), ((165, 200), 'cv2.imshow', 'cv2.imshow', (['"""Red line"""', 'black_image'], {}), "('Red line', black_image)\n", (175, 200), False, 'import cv2\n'), ((201, 215), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (212, 215), False, 'import cv2\n'), ((251, 308), 'cv2.rectangle', 'cv2.rectangle', (['black_image', '(10, 10)', '(50, 50)', 'green', '(-1)'], {}), '(black_image, (10, 10), (50, 50), green, -1)\n', (264, 308), False, 'import cv2\n'), ((309, 348), 'cv2.imshow', 'cv2.imshow', (['"""Green square"""', 'black_image'], {}), "('Green square', black_image)\n", (319, 348), False, 'import cv2\n'), ((349, 363), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (360, 363), False, 'import cv2\n'), ((446, 509), 'cv2.circle', 'cv2.circle', (['black_image', '(width // 2, height // 2)', '(25)', 'blue', '(5)'], {}), '(black_image, (width // 2, height // 2), 25, blue, 5)\n', (456, 509), False, 'import cv2\n'), ((510, 548), 'cv2.imshow', 'cv2.imshow', (['"""Blue circle"""', 'black_image'], {}), "('Blue circle', black_image)\n", (520, 548), False, 'import cv2\n'), ((549, 563), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (560, 563), False, 'import cv2\n')]
# -*- encoding: utf-8 -*- # # anasysfile.py # # Copyright 2017 <NAME> <<EMAIL>> # # This program is the property of Anasys Instruments, and may not be # redistributed or modified without explict permission of the author. from xml.dom import minidom #Unfortunately required as ElementTree won't pretty format xml import xml.etree.ElementTree as ET #for parsing XML import base64 import struct import numpy as np import re import collections import decimal as DC class AnasysElement(object): # class AnasysElement(collections.abc.Mapping): """Blank object for storing xml data""" def __init__(self, parent_obj=None, etree=None): self._parent_obj = parent_obj self._attributes = [] #list of dicts of tags:attributes, where applicable if not hasattr(self, '_iterable_write'): self._iterable_write = {} #just in case if not hasattr(self, '_special_write'): self._special_write = {} #just in case if not hasattr(self, '_special_read'): self._special_read = {} #just in case if not hasattr(self, '_skip_on_write'): self._skip_on_write = [] #just in case if etree is not None: self._etree_to_anasys(etree) #really just parses the hell outta this tree def __dir__(self): """Returns a list of user-accessible attributes""" vars_and_funcs = [x for x in object.__dir__(self) if x[0]!='_'] return vars_and_funcs def __getitem__(self, key): """Class attributes can be called by subscription, e.g. Foo['bar']""" items = dir(self) if key in items: return getattr(self, key) else: raise KeyError def __iter__(self): """Makes object iterable. Returns all user-accessible, non-method, attributes""" for obj in dir(self): if not callable(self[obj]): yield self[obj] def _get_iterator(self, obj): """For use with _anasys_to_etree. Returns a dict to iterate over, or None""" #If obj is a dict, return its items if type(obj) == dict: return obj#.items() #If obj is derived from AnasysElement, return its user-accessible attributes that aren't in _skip_on_write elif isinstance(obj, AnasysElement): return {k: obj[k] for k in obj.__dict__.keys() if k[0] != '_' and k not in obj._skip_on_write} #If it's something else, return None. _anasys_to_etree will test for this condition else: return None def _object_to_text(self, obj): """Takes an object, returns it to text to append to an etree object""" if isinstance(obj, np.ndarray): return self._encode_bs64(obj) else: return str(obj) def _anasys_to_etree(self, obj, name="APlaceholder"): """Return object and all sub objects as an etree object for writing""" # Create new element for appending tags to obj_items = self._get_iterator(obj) #Test object list for None, indicating it's time to return some text if obj_items is None: txt = self._object_to_text(obj) rtn = ET.Element(name) rtn.text = txt return rtn #Odd case where there's no text and nothing to return if obj_items == {}: return ET.Element(name) #If it's made it this far, it's time to loop through obj_items elem = ET.Element(name) # pdb.set_trace() for k, v in obj_items.items(): #If element was once an xml attribute, make it so again try: #Too lazy to deal with the fact dicts won't have this attribute if k in obj._attributes: elem.set(k, v) continue except: #If axz's had unique tag names I wouldn't have to do this pass #Iterable conversions if k in obj._iterable_write.keys(): obj._iterable_to_etree(elem, k, v) #Special return values elif k in obj._special_write.keys(): if callable(obj._special_write[k]): obj._special_write[k](elem, k, v) else: obj._special_write[k] else: rr = self._anasys_to_etree(v, k) #Create subelement k, with a value determined by recursion elem.append(rr) return elem def _attr_to_children(self, et_elem): """Convert element attributes of given etree object to child elements""" for attr in et_elem.items(): ET.SubElement(et_elem, attr[0]) et_elem.find(attr[0]).text = attr[1] def _etree_to_anasys(self, element, parent_obj=None): """Iterates through element tree object and adds atrtibutes to HeightMap Object""" #If element has attributes, make them children before continuing self._attr_to_children(element) # If element is a key in _special_read, set special return value if element.tag in self._special_read.keys(): return self._special_read[element.tag](element) #If element is a key in _base_64_tags, return decoded data if '64' in element.tag: return self._decode_bs64(element.text) #If element has no children, return either it's text or {} if list(element) == []: if element.text: #Default return value for an element with text return element.text else: #Default return value for an empty tree leaf/XML tag return "" #If element has children, return an object with its children else: if parent_obj == None: #Top level case, we want to add to self, rather than blank object element_obj = self else: #Default case, create blank object to add attributes to element_obj = AnasysElement()#parent_obj=self) #store the etree tag name for later use element_obj._name = element.tag #Update _attributes of given element element_obj._attributes.extend(element.keys()) #Loop over each child and add attributes for child in element: #Get recursion return value - either text, {} or AnasysElement() instance rr = element_obj._etree_to_anasys(child, element) #Set element_obj.child_tag = rr setattr(element_obj, child.tag, rr) #Return the object containing all children and attributes return element_obj def _check_key(self, key, _dict, copy=1): """Check if key is in dict. If it is, increment key until key is unique, and return""" if key not in _dict: return key num_list = re.findall('\s\((\d+)\)', key) if num_list != [] and key[-1] == ')': copy = int(num_list[-1]) index = key.find(' ({})'.format(copy)) if index != -1: key = key[:index] + ' ({})'.format(copy+1) return self._check_key(key, _dict, copy+1) else: key += ' ({})'.format(copy) return self._check_key(key, _dict, copy) def _decode_bs64(self, data): """Returns base64 data decoded in a numpy array""" decoded_bytes = base64.b64decode(data.encode()) fmt = 'f'*int((len(decoded_bytes)/4)) structured_data = struct.unpack(fmt, decoded_bytes) decoded_array = np.array(structured_data) return decoded_array def _encode_bs64(self, np_array): """Returns numpy array encoded as base64 string""" tup = tuple(np_array.flatten()) fmt = 'f'*np_array.size structured_data = struct.pack(fmt, *tup) encoded_string = base64.b64encode(structured_data).decode() return encoded_string def _serial_tags_to_nparray(self, parent_tag): """Return floats listed consecutively (e.g., background tables) as numpy array""" np_array = [] for child_tag in list(parent_tag): np_array.append(DC.Decimal(child_tag.text)) parent_tag.remove(child_tag) np_array = np.array(np_array) return np_array def _nparray_to_serial_tags(self, elem, nom, np_array): """Takes a numpy array returns an etree object and of consecutive <double>float</double> tags""" root = ET.Element(nom) flat = np_array.flatten() for x in flat: el = ET.SubElement(root, 'Double') el.text=str(x) elem.append(root) def write(self, filename): """Writes the current object to file""" xml = self._anasys_to_etree(self, 'Document') #ElementTree annoyingly only remembers namespaces that are used so next line is necessary xml.set("xmlns", "www.anasysinstruments.com") #Can't see any reason to add unused namespaces other than default, as Analysis Studio won't complain, #but minidom will if one is duplicated (can't easily get around this lame default behavior in etree) with open(filename, 'wb') as f: xmlstr = minidom.parseString(ET.tostring(xml)).toprettyxml(indent=" ", encoding='UTF-16') f.write(xmlstr) def _etree_to_dict(self, etree, key_tag): """ Converts an ET element to a dict containing its children as AnasysElements. e.g., <parent> <obj1> <key>A</key> </obj1> <obj2> <key>B</key> </obj2> ... </parent> becomes: parent = {'A': obj1, 'B': obj2, ...} Arguments: self = calling object (will be an instance of or derived from AnasysElement) etree = element tree object to be converted key_tag = object element to be used as key (e.g., Label, Name, ID, etc.) """ return_dict = {} for child in etree: new_obj = AnasysElement(etree=child) key = new_obj[key_tag] key = self._check_key(key, return_dict) return_dict[key] = new_obj return return_dict def _etree_to_list(self, etree): """ Converts an ET element to a list containing its children as AnasysElements. e.g., <parent> <obj1/> <obj2/> ... </parent> becomes: parent = [obj1, obj2, ...] Arguments: self = calling object (will be an instance of or derived from AnasysElement) etree = element tree object to be converted """ return_list = [] for child in etree: new_obj = AnasysElement(etree=child) return_list.append(new_obj) return return_list def _iterable_to_etree(self, parent_elem, iterable_elem_name, iterable_obj): """ Converts a named dict or list of Anasys Elements to an Element Tree object representation of the object e.g., parent.var = {'ID1': obj1, 'ID2': obj2, ...} or parent.var = [obj1, obj2, ...] becomes: <parent> <var> <obj1>...</obj1> <obj2>...</obj2> ... </var> </parent> Arguments: self = calling object (will be an instance of or derived from AnasysElement) parent_elem = the parent etree object to append to iterable_elem_name = the name of the dict or list variable (will become etree element name) iterable_obj = the dict or list itself """ parent_etree = ET.SubElement(parent_elem, iterable_elem_name) if type(iterable_obj) == dict: for child in iterable_obj.values(): new_elem = child._anasys_to_etree(child, name=child._name) parent_etree.append(new_elem) else: for child in iterable_obj: new_elem = child._anasys_to_etree(child, name=child._name) parent_etree.append(new_elem)
[ "xml.etree.ElementTree.tostring", "base64.b64encode", "struct.pack", "numpy.array", "xml.etree.ElementTree.Element", "struct.unpack", "xml.etree.ElementTree.SubElement", "re.findall", "decimal.Decimal" ]
[((3463, 3479), 'xml.etree.ElementTree.Element', 'ET.Element', (['name'], {}), '(name)\n', (3473, 3479), True, 'import xml.etree.ElementTree as ET\n'), ((6921, 6955), 're.findall', 're.findall', (['"""\\\\s\\\\((\\\\d+)\\\\)"""', 'key'], {}), "('\\\\s\\\\((\\\\d+)\\\\)', key)\n", (6931, 6955), False, 'import re\n'), ((7545, 7578), 'struct.unpack', 'struct.unpack', (['fmt', 'decoded_bytes'], {}), '(fmt, decoded_bytes)\n', (7558, 7578), False, 'import struct\n'), ((7603, 7628), 'numpy.array', 'np.array', (['structured_data'], {}), '(structured_data)\n', (7611, 7628), True, 'import numpy as np\n'), ((7854, 7876), 'struct.pack', 'struct.pack', (['fmt', '*tup'], {}), '(fmt, *tup)\n', (7865, 7876), False, 'import struct\n'), ((8298, 8316), 'numpy.array', 'np.array', (['np_array'], {}), '(np_array)\n', (8306, 8316), True, 'import numpy as np\n'), ((8522, 8537), 'xml.etree.ElementTree.Element', 'ET.Element', (['nom'], {}), '(nom)\n', (8532, 8537), True, 'import xml.etree.ElementTree as ET\n'), ((11865, 11911), 'xml.etree.ElementTree.SubElement', 'ET.SubElement', (['parent_elem', 'iterable_elem_name'], {}), '(parent_elem, iterable_elem_name)\n', (11878, 11911), True, 'import xml.etree.ElementTree as ET\n'), ((3184, 3200), 'xml.etree.ElementTree.Element', 'ET.Element', (['name'], {}), '(name)\n', (3194, 3200), True, 'import xml.etree.ElementTree as ET\n'), ((3360, 3376), 'xml.etree.ElementTree.Element', 'ET.Element', (['name'], {}), '(name)\n', (3370, 3376), True, 'import xml.etree.ElementTree as ET\n'), ((4652, 4683), 'xml.etree.ElementTree.SubElement', 'ET.SubElement', (['et_elem', 'attr[0]'], {}), '(et_elem, attr[0])\n', (4665, 4683), True, 'import xml.etree.ElementTree as ET\n'), ((8612, 8641), 'xml.etree.ElementTree.SubElement', 'ET.SubElement', (['root', '"""Double"""'], {}), "(root, 'Double')\n", (8625, 8641), True, 'import xml.etree.ElementTree as ET\n'), ((7902, 7935), 'base64.b64encode', 'base64.b64encode', (['structured_data'], {}), '(structured_data)\n', (7918, 7935), False, 'import base64\n'), ((8210, 8236), 'decimal.Decimal', 'DC.Decimal', (['child_tag.text'], {}), '(child_tag.text)\n', (8220, 8236), True, 'import decimal as DC\n'), ((9281, 9297), 'xml.etree.ElementTree.tostring', 'ET.tostring', (['xml'], {}), '(xml)\n', (9292, 9297), True, 'import xml.etree.ElementTree as ET\n')]
from chainer.training import extensions import chainer.serializers as S import chainer import os import json from chainer.training.triggers import IntervalTrigger from collections import defaultdict import numpy as np class Trainer(object): def __init__(self, folder, chain, train, test, batchsize=500, resume=True, gpu=0, nepoch=1, reports=[]): self.reports = reports self.nepoch = nepoch self.folder = folder self.chain = chain self.gpu = gpu if self.gpu >= 0: chainer.cuda.get_device(gpu).use() chain.to_gpu(gpu) self.eval_chain = eval_chain = chain.copy() self.chain.test = False self.eval_chain.test = True self.testset = test if not os.path.exists(folder): os.makedirs(folder) train_iter = chainer.iterators.SerialIterator(train, batchsize, shuffle=True) test_iter = chainer.iterators.SerialIterator(test, batchsize, repeat=False, shuffle=False) updater = chainer.training.StandardUpdater(train_iter, chain.optimizer, device=gpu) trainer = chainer.training.Trainer(updater, (nepoch, 'epoch'), out=folder) # trainer.extend(TrainingModeSwitch(chain)) # trainer.extend(extensions.dump_graph('main/loss')) trainer.extend(extensions.Evaluator(test_iter, eval_chain, device=gpu), trigger=(1, 'epoch')) trainer.extend(extensions.snapshot_object( chain, 'chain_snapshot_epoch_{.updater.epoch:06}'), trigger=(1, 'epoch')) trainer.extend(extensions.snapshot( filename='snapshot_epoch_{.updater.epoch:06}'), trigger=(1, 'epoch')) trainer.extend(extensions.LogReport(trigger=(1, 'epoch')), trigger=(1, 'iteration')) trainer.extend(extensions.PrintReport( ['epoch', 'main/loss', 'validation/main/loss', 'main/accuracy', 'validation/main/accuracy', 'elapsed_time']), trigger=IntervalTrigger(1, 'epoch')) self.trainer = trainer if resume: # if resumeFrom is not None: # trainerFile = os.path.join(resumeFrom[0],'snapshot_epoch_{:06}'.format(resumeFrom[1])) # S.load_npz(trainerFile, trainer) i = 1 trainerFile = os.path.join(folder, 'snapshot_epoch_{:06}'.format(i)) while i <= nepoch and os.path.isfile(trainerFile): i = i + 1 trainerFile = os.path.join(folder, 'snapshot_epoch_{:06}'.format(i)) i = i - 1 trainerFile = os.path.join(folder, 'snapshot_epoch_{:06}'.format(i)) if i >= 0 and os.path.isfile(trainerFile): S.load_npz(trainerFile, trainer) def run(self): if self.gpu >= 0: chainer.cuda.get_device(self.gpu).use() self.chain.to_gpu(self.gpu) self.chain.test = False self.eval_chain.test = True self.trainer.run() # ext = self.trainer.get_extension('validation')() # test_accuracy = ext['validation/main/accuracy'] # test_loss = ext['validation/main/loss'] # acc = test_accuracy.tolist() # loss = test_loss.tolist() if self.gpu >= 0: self.chain.to_cpu() return # return self.evaluate() # return acc,loss def evaluate(self): test_iter = chainer.iterators.SerialIterator(self.testset, 1, repeat=False, shuffle=False) self.chain.train = False self.chain.test = True if self.gpu >= 0: self.chain.to_gpu(self.gpu) result = extensions.Evaluator(test_iter, self.chain, device=self.gpu)() if self.gpu >= 0: self.chain.to_cpu() # for k,v in result.iteritems(): # if k in ["main/numsamples", "main/accuracy", "main/branch0exit", "main/branch1exit", "main/branch2exit"]: # print k, "\t\t\t", v return result def save_model(self): trainer = self.trainer chain = self.chain trainer.extend(extensions.snapshot_object(chain, 'so_epoch_{.updater.epoch:06}'), trigger=(1,'epoch')) trainer.extend(extensions.snapshot(filename='s_epoch_{.updater.epoch:06}'), trigger=(1,'epoch')) # Deprecated def get_result(self, key): # this only returns the lastest log ext = self.trainer.get_extension('validation')() return ext.get('{}'.format(key), np.array(None)).tolist() def get_log_result(self, key, reduce_fn=np.mean): folder = self.folder nepoch = self.nepoch with open(os.path.join(folder, 'log'), 'r') as f: log = json.load(f) epochMap = defaultdict(list) for v in log: if v.get(key, None) is not None: epochMap[int(v["epoch"])].append(v[key]) epochs = sorted(epochMap.keys()) values = [] for epoch in epochs: values.append(reduce_fn(epochMap[epoch])) return values[:nepoch]
[ "os.path.exists", "chainer.training.extensions.PrintReport", "os.makedirs", "chainer.training.extensions.snapshot_object", "chainer.iterators.SerialIterator", "chainer.training.extensions.LogReport", "chainer.training.Trainer", "chainer.training.StandardUpdater", "os.path.join", "chainer.cuda.get_...
[((837, 901), 'chainer.iterators.SerialIterator', 'chainer.iterators.SerialIterator', (['train', 'batchsize'], {'shuffle': '(True)'}), '(train, batchsize, shuffle=True)\n', (869, 901), False, 'import chainer\n'), ((922, 1000), 'chainer.iterators.SerialIterator', 'chainer.iterators.SerialIterator', (['test', 'batchsize'], {'repeat': '(False)', 'shuffle': '(False)'}), '(test, batchsize, repeat=False, shuffle=False)\n', (954, 1000), False, 'import chainer\n'), ((1073, 1146), 'chainer.training.StandardUpdater', 'chainer.training.StandardUpdater', (['train_iter', 'chain.optimizer'], {'device': 'gpu'}), '(train_iter, chain.optimizer, device=gpu)\n', (1105, 1146), False, 'import chainer\n'), ((1165, 1229), 'chainer.training.Trainer', 'chainer.training.Trainer', (['updater', "(nepoch, 'epoch')"], {'out': 'folder'}), "(updater, (nepoch, 'epoch'), out=folder)\n", (1189, 1229), False, 'import chainer\n'), ((3401, 3479), 'chainer.iterators.SerialIterator', 'chainer.iterators.SerialIterator', (['self.testset', '(1)'], {'repeat': '(False)', 'shuffle': '(False)'}), '(self.testset, 1, repeat=False, shuffle=False)\n', (3433, 3479), False, 'import chainer\n'), ((4760, 4777), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (4771, 4777), False, 'from collections import defaultdict\n'), ((759, 781), 'os.path.exists', 'os.path.exists', (['folder'], {}), '(folder)\n', (773, 781), False, 'import os\n'), ((795, 814), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (806, 814), False, 'import os\n'), ((1366, 1421), 'chainer.training.extensions.Evaluator', 'extensions.Evaluator', (['test_iter', 'eval_chain'], {'device': 'gpu'}), '(test_iter, eval_chain, device=gpu)\n', (1386, 1421), False, 'from chainer.training import extensions\n'), ((1468, 1545), 'chainer.training.extensions.snapshot_object', 'extensions.snapshot_object', (['chain', '"""chain_snapshot_epoch_{.updater.epoch:06}"""'], {}), "(chain, 'chain_snapshot_epoch_{.updater.epoch:06}')\n", (1494, 1545), False, 'from chainer.training import extensions\n'), ((1605, 1671), 'chainer.training.extensions.snapshot', 'extensions.snapshot', ([], {'filename': '"""snapshot_epoch_{.updater.epoch:06}"""'}), "(filename='snapshot_epoch_{.updater.epoch:06}')\n", (1624, 1671), False, 'from chainer.training import extensions\n'), ((1731, 1773), 'chainer.training.extensions.LogReport', 'extensions.LogReport', ([], {'trigger': "(1, 'epoch')"}), "(trigger=(1, 'epoch'))\n", (1751, 1773), False, 'from chainer.training import extensions\n'), ((1824, 1959), 'chainer.training.extensions.PrintReport', 'extensions.PrintReport', (["['epoch', 'main/loss', 'validation/main/loss', 'main/accuracy',\n 'validation/main/accuracy', 'elapsed_time']"], {}), "(['epoch', 'main/loss', 'validation/main/loss',\n 'main/accuracy', 'validation/main/accuracy', 'elapsed_time'])\n", (1846, 1959), False, 'from chainer.training import extensions\n'), ((3680, 3740), 'chainer.training.extensions.Evaluator', 'extensions.Evaluator', (['test_iter', 'self.chain'], {'device': 'self.gpu'}), '(test_iter, self.chain, device=self.gpu)\n', (3700, 3740), False, 'from chainer.training import extensions\n'), ((4129, 4194), 'chainer.training.extensions.snapshot_object', 'extensions.snapshot_object', (['chain', '"""so_epoch_{.updater.epoch:06}"""'], {}), "(chain, 'so_epoch_{.updater.epoch:06}')\n", (4155, 4194), False, 'from chainer.training import extensions\n'), ((4240, 4299), 'chainer.training.extensions.snapshot', 'extensions.snapshot', ([], {'filename': '"""s_epoch_{.updater.epoch:06}"""'}), "(filename='s_epoch_{.updater.epoch:06}')\n", (4259, 4299), False, 'from chainer.training import extensions\n'), ((4727, 4739), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4736, 4739), False, 'import json\n'), ((1991, 2018), 'chainer.training.triggers.IntervalTrigger', 'IntervalTrigger', (['(1)', '"""epoch"""'], {}), "(1, 'epoch')\n", (2006, 2018), False, 'from chainer.training.triggers import IntervalTrigger\n'), ((2400, 2427), 'os.path.isfile', 'os.path.isfile', (['trainerFile'], {}), '(trainerFile)\n', (2414, 2427), False, 'import os\n'), ((2669, 2696), 'os.path.isfile', 'os.path.isfile', (['trainerFile'], {}), '(trainerFile)\n', (2683, 2696), False, 'import os\n'), ((2714, 2746), 'chainer.serializers.load_npz', 'S.load_npz', (['trainerFile', 'trainer'], {}), '(trainerFile, trainer)\n', (2724, 2746), True, 'import chainer.serializers as S\n'), ((4669, 4696), 'os.path.join', 'os.path.join', (['folder', '"""log"""'], {}), "(folder, 'log')\n", (4681, 4696), False, 'import os\n'), ((530, 558), 'chainer.cuda.get_device', 'chainer.cuda.get_device', (['gpu'], {}), '(gpu)\n', (553, 558), False, 'import chainer\n'), ((2805, 2838), 'chainer.cuda.get_device', 'chainer.cuda.get_device', (['self.gpu'], {}), '(self.gpu)\n', (2828, 2838), False, 'import chainer\n'), ((4513, 4527), 'numpy.array', 'np.array', (['None'], {}), '(None)\n', (4521, 4527), True, 'import numpy as np\n')]
from six.moves import StringIO from numpy import zeros, unique, searchsorted, array from pyNastran.bdf.field_writer_8 import set_blank_if_default from pyNastran.bdf.field_writer_8 import print_card_8 from pyNastran.bdf.bdf_interface.assign_type import (integer, string_or_blank) from pyNastran.dev.bdf_vectorized.cards.elements.property import Property class PLSOLID(Property): type = 'PLSOLID' def __init__(self, model): """ Defines the PLSOLID object. Parameters ---------- model : BDF the BDF object """ Property.__init__(self, model) def allocate(self, ncards): self.n = ncards #float_fmt = self.model.float_fmt #: Property ID self.property_id = zeros(ncards, dtype='int32') #: Material ID self.material_id = zeros(ncards, dtype='int32') #: Location of stress and strain output self.stress_strain = zeros(ncards, dtype='|S4') def add_card(self, card, comment=''): i = self.i self.property_id[i] = integer(card, 1, 'pid') self.material_id[i] = integer(card, 2, 'mid') stress_strain = string_or_blank(card, 3, 'str', 'GRID') if stress_strain not in ('GRID', 'GAUS'): msg = 'STR="%s" doesnt have a valid stress/strain ' \ 'output value set; valid=["GRID", "GAUS"]\n' \ % stress_strain #raise RuntimeError(msg) self.stress_strain[i] = stress_strain assert len(card) <= 4, 'len(PLSOLID card) = %i\ncard=%s' % (len(card), card) self.i += 1 def build(self): if self.n: i = self.property_id.argsort() self.property_id = self.property_id[i] self.material_id = self.material_id[i] self.stress_strain = self.stress_strain[i] unique_pids = unique(self.property_id) if len(unique_pids) != len(self.property_id): raise RuntimeError('There are duplicate PLSOLID IDs...') else: self.property_id = array([], dtype='int32') self.material_id = array([], dtype='int32') def update(self, maps): """ maps = { 'property' : pid_map, 'material' : mid_map, } """ if self.n: nid_map = maps['node'] pid_map = maps['property'] mid_map = maps['material'] for i, pid, mids in enumerate(zip(self.property_id, self.material_ids)): self.property_id[i] = pid_map[pid] #def get_density_by_property_id(self, property_id=None): #if property_id is None: #property_id = self.property_id #elif isinstance(property_id, int): #property_id = array([property_id], dtype='int32') #property_id = asarray(property_id) #n = len(property_id) #rho = zeros(n, dtype='float64') #upid = unique(property_id) #for i, pid in enumerate(upid): ## get the location of pid id in global props #j = where(pid == self.property_id)[0] ## get the location of pid in the local props #k = where(pid == property_id)[0] #if len(j) == 0: #msg = 'pid=%s was not found in %s' % (upid, self.property_id) #raise ValueError(msg) #mid = self.material_id[j[0]] #rhoi = self.model.materials.get_density_by_material_id([mid]) ##print('pid=%s rho[%s]=%s' % (pid, k, rhoi)) #rho[k] = rhoi #if rho.min() == 0.0: #msg = 'property_id = %s\n' % property_id #msg += 'i = %s\n' % i #msg += 'rho = %s\n' % rho #msg += 'rhoj = %s' % rhoi #raise ValueError(msg) #assert rho.shape == (n, ), rho.shape #self.model.log.debug('rho = %s' % rho) #return rho def write_card(self, bdf_file, size=8, property_id=None): if self.n: #print("PSOLID.property_id =", self.property_id) for (pid, mid, stress) in zip( self.property_id, self.material_id, self.stress_strain): if eid in self._comments: bdf_file.write(self._comments[eid]) stress_strain = set_blank_if_default(stress_strain, 'GRID') card = ['PLSOLID', pid, mid, stress_strain] bdf_file.write(print_card_8(card)) def __getitem__(self, property_id): i = searchsorted(self.property_id, property_id) return self.slice_by_index(i) def slice_by_index(self, i): i = self._validate_slice(i) obj = PLSOLID(self.model) obj.n = len(i) #obj._comments = obj._comments[i] #obj.comments = obj.comments[i] obj.property_id = self.property_id[i] obj.material_id = self.material_id[i] obj.stress_strain = self.stress_strain[i, :] return obj def __repr__(self): f = StringIO() f.write('<PLSOLID object> n=%s\n' % self.n) self.write_card(f) return f.getvalue()
[ "numpy.unique", "numpy.searchsorted", "pyNastran.bdf.field_writer_8.set_blank_if_default", "numpy.array", "numpy.zeros", "pyNastran.bdf.bdf_interface.assign_type.string_or_blank", "pyNastran.dev.bdf_vectorized.cards.elements.property.Property.__init__", "six.moves.StringIO", "pyNastran.bdf.bdf_inter...
[((591, 621), 'pyNastran.dev.bdf_vectorized.cards.elements.property.Property.__init__', 'Property.__init__', (['self', 'model'], {}), '(self, model)\n', (608, 621), False, 'from pyNastran.dev.bdf_vectorized.cards.elements.property import Property\n'), ((771, 799), 'numpy.zeros', 'zeros', (['ncards'], {'dtype': '"""int32"""'}), "(ncards, dtype='int32')\n", (776, 799), False, 'from numpy import zeros, unique, searchsorted, array\n'), ((850, 878), 'numpy.zeros', 'zeros', (['ncards'], {'dtype': '"""int32"""'}), "(ncards, dtype='int32')\n", (855, 878), False, 'from numpy import zeros, unique, searchsorted, array\n'), ((956, 982), 'numpy.zeros', 'zeros', (['ncards'], {'dtype': '"""|S4"""'}), "(ncards, dtype='|S4')\n", (961, 982), False, 'from numpy import zeros, unique, searchsorted, array\n'), ((1075, 1098), 'pyNastran.bdf.bdf_interface.assign_type.integer', 'integer', (['card', '(1)', '"""pid"""'], {}), "(card, 1, 'pid')\n", (1082, 1098), False, 'from pyNastran.bdf.bdf_interface.assign_type import integer, string_or_blank\n'), ((1129, 1152), 'pyNastran.bdf.bdf_interface.assign_type.integer', 'integer', (['card', '(2)', '"""mid"""'], {}), "(card, 2, 'mid')\n", (1136, 1152), False, 'from pyNastran.bdf.bdf_interface.assign_type import integer, string_or_blank\n'), ((1177, 1216), 'pyNastran.bdf.bdf_interface.assign_type.string_or_blank', 'string_or_blank', (['card', '(3)', '"""str"""', '"""GRID"""'], {}), "(card, 3, 'str', 'GRID')\n", (1192, 1216), False, 'from pyNastran.bdf.bdf_interface.assign_type import integer, string_or_blank\n'), ((4533, 4576), 'numpy.searchsorted', 'searchsorted', (['self.property_id', 'property_id'], {}), '(self.property_id, property_id)\n', (4545, 4576), False, 'from numpy import zeros, unique, searchsorted, array\n'), ((5025, 5035), 'six.moves.StringIO', 'StringIO', ([], {}), '()\n', (5033, 5035), False, 'from six.moves import StringIO\n'), ((1888, 1912), 'numpy.unique', 'unique', (['self.property_id'], {}), '(self.property_id)\n', (1894, 1912), False, 'from numpy import zeros, unique, searchsorted, array\n'), ((2089, 2113), 'numpy.array', 'array', (['[]'], {'dtype': '"""int32"""'}), "([], dtype='int32')\n", (2094, 2113), False, 'from numpy import zeros, unique, searchsorted, array\n'), ((2145, 2169), 'numpy.array', 'array', (['[]'], {'dtype': '"""int32"""'}), "([], dtype='int32')\n", (2150, 2169), False, 'from numpy import zeros, unique, searchsorted, array\n'), ((4325, 4368), 'pyNastran.bdf.field_writer_8.set_blank_if_default', 'set_blank_if_default', (['stress_strain', '"""GRID"""'], {}), "(stress_strain, 'GRID')\n", (4345, 4368), False, 'from pyNastran.bdf.field_writer_8 import set_blank_if_default\n'), ((4460, 4478), 'pyNastran.bdf.field_writer_8.print_card_8', 'print_card_8', (['card'], {}), '(card)\n', (4472, 4478), False, 'from pyNastran.bdf.field_writer_8 import print_card_8\n')]
#import os #import subprocess #import sys import numpy as np from cereal import car from common.kalman.simple_kalman import KF1D from selfdrive.config import Conversions as CV from selfdrive.can.parser import CANParser from selfdrive.car.modules.UIBT_module import UIButtons,UIButton from selfdrive.car.modules.UIEV_module import UIEvents from selfdrive.car.gm.values import DBC, CAR, parse_gear_shifter, \ CruiseButtons, is_eps_status_ok, \ STEER_THRESHOLD, SUPERCRUISE_CARS import selfdrive.kegman_conf as kegman def get_powertrain_can_parser(CP, canbus): # this function generates lists for signal, messages and initial values signals = [ # sig_name, sig_address, default ("BrakePedalPosition", "EBCMBrakePedalPosition", 0), ("FrontLeftDoor", "BCMDoorBeltStatus", 0), ("FrontRightDoor", "BCMDoorBeltStatus", 0), ("RearLeftDoor", "BCMDoorBeltStatus", 0), ("RearRightDoor", "BCMDoorBeltStatus", 0), ("LeftSeatBelt", "BCMDoorBeltStatus", 0), ("RightSeatBelt", "BCMDoorBeltStatus", 0), ("TurnSignals", "BCMTurnSignals", 0), ("AcceleratorPedal", "AcceleratorPedal", 0), ("ACCButtons", "ASCMSteeringButton", CruiseButtons.UNPRESS), ("LKAButton", "ASCMSteeringButton", 0), ("SteeringWheelAngle", "PSCMSteeringAngle", 0), ("FLWheelSpd", "EBCMWheelSpdFront", 0), ("FRWheelSpd", "EBCMWheelSpdFront", 0), ("RLWheelSpd", "EBCMWheelSpdRear", 0), ("RRWheelSpd", "EBCMWheelSpdRear", 0), ("PRNDL", "ECMPRDNL", 0), ("LKADriverAppldTrq", "PSCMStatus", 0), ("LKATorqueDeliveredStatus", "PSCMStatus", 0), ("DistanceButton", "ASCMSteeringButton", 0), ] if CP.carFingerprint == CAR.VOLT: signals += [ ("RegenPaddle", "EBCMRegenPaddle", 0), ] if CP.carFingerprint in SUPERCRUISE_CARS: signals += [ ("ACCCmdActive", "ASCMActiveCruiseControlStatus", 0) ] else: signals += [ ("TractionControlOn", "ESPStatus", 0), ("EPBClosed", "EPBStatus", 0), ("CruiseMainOn", "ECMEngineStatus", 0), ("CruiseState", "AcceleratorPedal2", 0), ] return CANParser(DBC[CP.carFingerprint]['pt'], signals, [], canbus.powertrain) def get_chassis_can_parser(CP, canbus): # this function generates lists for signal, messages and initial values signals = [ # sig_name, sig_address, default ("FrictionBrakePressure", "EBCMFrictionBrakeStatus", 0), ] return CANParser(DBC[CP.carFingerprint]['chassis'], signals, [], canbus.chassis) class CarState(object): def __init__(self, CP, canbus): self.CP = CP # initialize can parser self.gasMode = int(kegman.conf['lastGasMode']) self.gasLabels = ["dynamic","sport","eco"] self.alcaLabels = ["MadMax","Normal","Wifey","off"] steerRatio = CP.steerRatio self.alcaMode = int(kegman.conf['lastALCAMode']) # default to last ALCAmode on startup self.car_fingerprint = CP.carFingerprint self.cruise_buttons = CruiseButtons.UNPRESS self.prev_distance_button = 0 self.distance_button = 0 self.left_blinker_on = False self.prev_left_blinker_on = False self.right_blinker_on = False self.prev_right_blinker_on = False self.follow_level = int(kegman.conf['lastTrMode']) self.prev_lka_button = 0 self.lka_button = 0 self.lkMode = True self.frictionBrakesActive = False # ALCA PARAMS self.blind_spot_on = bool(0) # max REAL delta angle for correction vs actuator self.CL_MAX_ANGLE_DELTA_BP = [10., 32., 44.] self.CL_MAX_ANGLE_DELTA = [2.0, 1., 0.5] # adjustment factor for merging steer angle to actuator; should be over 4; the higher the smoother self.CL_ADJUST_FACTOR_BP = [10., 44.] self.CL_ADJUST_FACTOR = [16. , 8.] # reenrey angle when to let go self.CL_REENTRY_ANGLE_BP = [10., 44.] self.CL_REENTRY_ANGLE = [5. , 5.] # a jump in angle above the CL_LANE_DETECT_FACTOR means we crossed the line self.CL_LANE_DETECT_BP = [10., 44.] self.CL_LANE_DETECT_FACTOR = [1.5, 2.5] self.CL_LANE_PASS_BP = [10., 20., 44.] self.CL_LANE_PASS_TIME = [40.,10., 4.] # change lane delta angles and other params self.CL_MAXD_BP = [10., 32., 55.] self.CL_MAXD_A = [.358 * 15.7 / steerRatio, 0.084 * 15.7 / steerRatio, 0.040 * 15.7 / steerRatio] #delta angle based on speed; needs fine tune, based on Tesla steer ratio of 16.75 self.CL_MIN_V = 8.9 # do not turn if speed less than x m/2; 20 mph = 8.9 m/s # do not turn if actuator wants more than x deg for going straight; this should be interp based on speed self.CL_MAX_A_BP = [10., 44.] self.CL_MAX_A = [10., 10.] # define limits for angle change every 0.1 s # we need to force correction above 10 deg but less than 20 # anything more means we are going to steep or not enough in a turn self.CL_MAX_ACTUATOR_DELTA = 2. self.CL_MIN_ACTUATOR_DELTA = 0. self.CL_CORRECTION_FACTOR = [1.,1.1,1.2] self.CL_CORRECTION_FACTOR_BP = [10., 32., 44.] #duration after we cross the line until we release is a factor of speed self.CL_TIMEA_BP = [10., 32., 44.] self.CL_TIMEA_T = [0.7 ,0.30, 0.30] #duration to wait (in seconds) with blinkers on before starting to turn self.CL_WAIT_BEFORE_START = 1 #END OF ALCA PARAMS self.CP = CP #BB UIEvents self.UE = UIEvents(self) #BB variable for custom buttons self.cstm_btns = UIButtons(self,"Gm","gm") #BB pid holder for ALCA self.pid = None #BB custom message counter self.custom_alert_counter = -1 #set to 100 for 1 second display; carcontroller will take down to zero # vEgo kalman filter dt = 0.01 self.v_ego_kf = KF1D(x0=[[0.], [0.]], A=[[1., dt], [0., 1.]], C=[1., 0.], K=[[0.12287673], [0.29666309]]) self.v_ego = 0. #BB init ui buttons def init_ui_buttons(self): btns = [] btns.append(UIButton("sound", "SND", 0, "", 0)) btns.append(UIButton("alca", "ALC", 0, self.alcaLabels[self.alcaMode], 1)) btns.append(UIButton("stop","",1,"SNG",2)) btns.append(UIButton("","",0,"",3)) btns.append(UIButton("gas","GAS",1,self.gasLabels[self.gasMode],4)) btns.append(UIButton("lka","LKA",1,"",5)) return btns #BB update ui buttons def update_ui_buttons(self,id,btn_status): if self.cstm_btns.btns[id].btn_status > 0: if (id == 1) and (btn_status == 0) and self.cstm_btns.btns[id].btn_name=="alca": if self.cstm_btns.btns[id].btn_label2 == self.alcaLabels[self.alcaMode]: self.alcaMode = (self.alcaMode + 1 ) % 4 kegman.save({'lastALCAMode': int(self.alcaMode)}) # write last distance bar setting to file else: self.alcaMode = 0 kegman.save({'lastALCAMode': int(self.alcaMode)}) # write last distance bar setting to file self.cstm_btns.btns[id].btn_label2 = self.alcaLabels[self.alcaMode] self.cstm_btns.hasChanges = True if self.alcaMode == 3: self.cstm_btns.set_button_status("alca", 0) elif (id == 4) and (btn_status == 0) and self.cstm_btns.btns[id].btn_name=="gas": if self.cstm_btns.btns[id].btn_label2 == self.gasLabels[self.gasMode]: self.gasMode = (self.gasMode + 1 ) % 3 kegman.save({'lastGasMode': int(self.gasMode)}) # write last GasMode setting to file else: self.gasMode = 0 kegman.save({'lastGasMode': int(self.gasMode)}) # write last GasMode setting to file self.cstm_btns.btns[id].btn_label2 = self.gasLabels[self.gasMode] self.cstm_btns.hasChanges = True else: self.cstm_btns.btns[id].btn_status = btn_status * self.cstm_btns.btns[id].btn_status else: self.cstm_btns.btns[id].btn_status = btn_status if (id == 1) and self.cstm_btns.btns[id].btn_name=="alca": self.alcaMode = (self.alcaMode + 1 ) % 4 kegman.save({'lastALCAMode': int(self.alcaMode)}) # write last distance bar setting to file self.cstm_btns.btns[id].btn_label2 = self.alcaLabels[self.alcaMode] self.cstm_btns.hasChanges = True def update(self, pt_cp, ch_cp): self.can_valid = pt_cp.can_valid self.prev_cruise_buttons = self.cruise_buttons self.cruise_buttons = pt_cp.vl["ASCMSteeringButton"]['ACCButtons'] self.prev_distance_button = self.distance_button self.distance_button = pt_cp.vl["ASCMSteeringButton"]["DistanceButton"] self.v_wheel_fl = pt_cp.vl["EBCMWheelSpdFront"]['FLWheelSpd'] * CV.KPH_TO_MS self.v_wheel_fr = pt_cp.vl["EBCMWheelSpdFront"]['FRWheelSpd'] * CV.KPH_TO_MS self.v_wheel_rl = pt_cp.vl["EBCMWheelSpdRear"]['RLWheelSpd'] * CV.KPH_TO_MS self.v_wheel_rr = pt_cp.vl["EBCMWheelSpdRear"]['RRWheelSpd'] * CV.KPH_TO_MS v_wheel = float(np.mean([self.v_wheel_fl, self.v_wheel_fr, self.v_wheel_rl, self.v_wheel_rr])) if abs(v_wheel - self.v_ego) > 2.0: # Prevent large accelerations when car starts at non zero speed self.v_ego_kf.x = [[v_wheel], [0.0]] self.v_ego_raw = v_wheel v_ego_x = self.v_ego_kf.update(v_wheel) self.v_ego = float(v_ego_x[0]) self.a_ego = float(v_ego_x[1]) self.prev_lka_button = self.lka_button self.lka_button = pt_cp.vl["ASCMSteeringButton"]['LKAButton'] self.standstill = self.v_ego_raw < 0.01 self.angle_steers = pt_cp.vl["PSCMSteeringAngle"]['SteeringWheelAngle'] self.gear_shifter = parse_gear_shifter(pt_cp.vl["ECMPRDNL"]['PRNDL']) self.user_brake = pt_cp.vl["EBCMBrakePedalPosition"]['BrakePedalPosition'] self.pedal_gas = pt_cp.vl["AcceleratorPedal"]['AcceleratorPedal'] self.user_gas_pressed = self.pedal_gas > 0 self.steer_torque_driver = pt_cp.vl["PSCMStatus"]['LKADriverAppldTrq'] self.steer_override = abs(self.steer_torque_driver) > STEER_THRESHOLD # 0 - inactive, 1 - active, 2 - temporary limited, 3 - failed self.lkas_status = pt_cp.vl["PSCMStatus"]['LKATorqueDeliveredStatus'] self.steer_not_allowed = not is_eps_status_ok(self.lkas_status, self.car_fingerprint) # 1 - open, 0 - closed self.door_all_closed = (pt_cp.vl["BCMDoorBeltStatus"]['FrontLeftDoor'] == 0 and pt_cp.vl["BCMDoorBeltStatus"]['FrontRightDoor'] == 0 and pt_cp.vl["BCMDoorBeltStatus"]['RearLeftDoor'] == 0 and pt_cp.vl["BCMDoorBeltStatus"]['RearRightDoor'] == 0) # 1 - latched self.seatbelt = pt_cp.vl["BCMDoorBeltStatus"]['LeftSeatBelt'] == 1 self.steer_error = False self.brake_error = False self.can_valid = True self.prev_left_blinker_on = self.left_blinker_on self.prev_right_blinker_on = self.right_blinker_on self.left_blinker_on = pt_cp.vl["BCMTurnSignals"]['TurnSignals'] == 1 self.right_blinker_on = pt_cp.vl["BCMTurnSignals"]['TurnSignals'] == 2 if self.cstm_btns.get_button_status("lka") == 0: self.lane_departure_toggle_on = False else: if self.alcaMode == 3 and (self.left_blinker_on or self.right_blinker_on): self.lane_departure_toggle_on = False else: self.lane_departure_toggle_on = True if self.car_fingerprint in SUPERCRUISE_CARS: self.park_brake = False self.main_on = False self.acc_active = pt_cp.vl["ASCMActiveCruiseControlStatus"]['ACCCmdActive'] self.esp_disabled = False self.regen_pressed = False self.pcm_acc_status = int(self.acc_active) else: self.park_brake = pt_cp.vl["EPBStatus"]['EPBClosed'] self.main_on = pt_cp.vl["ECMEngineStatus"]['CruiseMainOn'] self.acc_active = False self.esp_disabled = pt_cp.vl["ESPStatus"]['TractionControlOn'] != 1 self.pcm_acc_status = pt_cp.vl["AcceleratorPedal2"]['CruiseState'] if self.car_fingerprint == CAR.VOLT: self.regen_pressed = bool(pt_cp.vl["EBCMRegenPaddle"]['RegenPaddle']) else: self.regen_pressed = False # Brake pedal's potentiometer returns near-zero reading # even when pedal is not pressed. if self.user_brake < 10: self.user_brake = 0 # Regen braking is braking self.brake_pressed = self.user_brake > 10 or self.regen_pressed self.gear_shifter_valid = self.gear_shifter == car.CarState.GearShifter.drive # Update Friction Brakes from Chassis Canbus self.frictionBrakesActive = bool(ch_cp.vl["EBCMFrictionBrakeStatus"]["FrictionBrakePressure"] != 0) def get_follow_level(self): return self.follow_level
[ "selfdrive.can.parser.CANParser", "numpy.mean", "common.kalman.simple_kalman.KF1D", "selfdrive.car.modules.UIBT_module.UIButtons", "selfdrive.car.gm.values.parse_gear_shifter", "selfdrive.car.modules.UIEV_module.UIEvents", "selfdrive.car.gm.values.is_eps_status_ok", "selfdrive.car.modules.UIBT_module....
[((2145, 2216), 'selfdrive.can.parser.CANParser', 'CANParser', (["DBC[CP.carFingerprint]['pt']", 'signals', '[]', 'canbus.powertrain'], {}), "(DBC[CP.carFingerprint]['pt'], signals, [], canbus.powertrain)\n", (2154, 2216), False, 'from selfdrive.can.parser import CANParser\n'), ((2462, 2535), 'selfdrive.can.parser.CANParser', 'CANParser', (["DBC[CP.carFingerprint]['chassis']", 'signals', '[]', 'canbus.chassis'], {}), "(DBC[CP.carFingerprint]['chassis'], signals, [], canbus.chassis)\n", (2471, 2535), False, 'from selfdrive.can.parser import CANParser\n'), ((5370, 5384), 'selfdrive.car.modules.UIEV_module.UIEvents', 'UIEvents', (['self'], {}), '(self)\n', (5378, 5384), False, 'from selfdrive.car.modules.UIEV_module import UIEvents\n'), ((5447, 5474), 'selfdrive.car.modules.UIBT_module.UIButtons', 'UIButtons', (['self', '"""Gm"""', '"""gm"""'], {}), "(self, 'Gm', 'gm')\n", (5456, 5474), False, 'from selfdrive.car.modules.UIBT_module import UIButtons, UIButton\n'), ((5732, 5833), 'common.kalman.simple_kalman.KF1D', 'KF1D', ([], {'x0': '[[0.0], [0.0]]', 'A': '[[1.0, dt], [0.0, 1.0]]', 'C': '[1.0, 0.0]', 'K': '[[0.12287673], [0.29666309]]'}), '(x0=[[0.0], [0.0]], A=[[1.0, dt], [0.0, 1.0]], C=[1.0, 0.0], K=[[\n 0.12287673], [0.29666309]])\n', (5736, 5833), False, 'from common.kalman.simple_kalman import KF1D\n'), ((9532, 9581), 'selfdrive.car.gm.values.parse_gear_shifter', 'parse_gear_shifter', (["pt_cp.vl['ECMPRDNL']['PRNDL']"], {}), "(pt_cp.vl['ECMPRDNL']['PRNDL'])\n", (9550, 9581), False, 'from selfdrive.car.gm.values import DBC, CAR, parse_gear_shifter, CruiseButtons, is_eps_status_ok, STEER_THRESHOLD, SUPERCRUISE_CARS\n'), ((6000, 6034), 'selfdrive.car.modules.UIBT_module.UIButton', 'UIButton', (['"""sound"""', '"""SND"""', '(0)', '""""""', '(0)'], {}), "('sound', 'SND', 0, '', 0)\n", (6008, 6034), False, 'from selfdrive.car.modules.UIBT_module import UIButtons, UIButton\n'), ((6052, 6113), 'selfdrive.car.modules.UIBT_module.UIButton', 'UIButton', (['"""alca"""', '"""ALC"""', '(0)', 'self.alcaLabels[self.alcaMode]', '(1)'], {}), "('alca', 'ALC', 0, self.alcaLabels[self.alcaMode], 1)\n", (6060, 6113), False, 'from selfdrive.car.modules.UIBT_module import UIButtons, UIButton\n'), ((6131, 6164), 'selfdrive.car.modules.UIBT_module.UIButton', 'UIButton', (['"""stop"""', '""""""', '(1)', '"""SNG"""', '(2)'], {}), "('stop', '', 1, 'SNG', 2)\n", (6139, 6164), False, 'from selfdrive.car.modules.UIBT_module import UIButtons, UIButton\n'), ((6178, 6204), 'selfdrive.car.modules.UIBT_module.UIButton', 'UIButton', (['""""""', '""""""', '(0)', '""""""', '(3)'], {}), "('', '', 0, '', 3)\n", (6186, 6204), False, 'from selfdrive.car.modules.UIBT_module import UIButtons, UIButton\n'), ((6218, 6276), 'selfdrive.car.modules.UIBT_module.UIButton', 'UIButton', (['"""gas"""', '"""GAS"""', '(1)', 'self.gasLabels[self.gasMode]', '(4)'], {}), "('gas', 'GAS', 1, self.gasLabels[self.gasMode], 4)\n", (6226, 6276), False, 'from selfdrive.car.modules.UIBT_module import UIButtons, UIButton\n'), ((6290, 6322), 'selfdrive.car.modules.UIBT_module.UIButton', 'UIButton', (['"""lka"""', '"""LKA"""', '(1)', '""""""', '(5)'], {}), "('lka', 'LKA', 1, '', 5)\n", (6298, 6322), False, 'from selfdrive.car.modules.UIBT_module import UIButtons, UIButton\n'), ((8900, 8977), 'numpy.mean', 'np.mean', (['[self.v_wheel_fl, self.v_wheel_fr, self.v_wheel_rl, self.v_wheel_rr]'], {}), '([self.v_wheel_fl, self.v_wheel_fr, self.v_wheel_rl, self.v_wheel_rr])\n', (8907, 8977), True, 'import numpy as np\n'), ((10103, 10159), 'selfdrive.car.gm.values.is_eps_status_ok', 'is_eps_status_ok', (['self.lkas_status', 'self.car_fingerprint'], {}), '(self.lkas_status, self.car_fingerprint)\n', (10119, 10159), False, 'from selfdrive.car.gm.values import DBC, CAR, parse_gear_shifter, CruiseButtons, is_eps_status_ok, STEER_THRESHOLD, SUPERCRUISE_CARS\n')]
# ********************************************************************************* # REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this list # of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, this # list of conditions and the following disclaimer in the documentation and/or other # materials provided with the distribution. # # Neither the name of the copyright holder nor the names of its contributors may be # used to endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. # ********************************************************************************* import csv import numpy as np import os from .sscapi import PySSC """ Generic NREL powercurves for different scales of turbines as defined in SAM as - NREL 2000kW Distributed Large Turbine Reference - NREL 250kW Distributed Midsize Turbine Reference - NREL 100kW Distributed Commercial Turbine Reference - NREL 2.5kW Distributed Residential Turbine Reference """ wind_turbine_powercurve_lookup = {'large': [0, 0, 0, 70.119, 166.208, 324.625, 560.952, 890.771, 1329.664, 1893.213, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000], 'medium': [0, 0, 0, 8.764875, 20.776, 40.578125, 70.119, 111.346375, 166.208, 236.651625, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250], 'commercial': [0, 0, 0, 3.50595, 8.3104, 16.23125, 28.0476, 44.53855, 66.4832, 94.66065, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], 'residential': [0, 0, 0, 0.070542773, 0.1672125, 0.326586914, 0.564342188, 0.896154492, 1.3377, 1.904654883, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 0, 0, 0, 0, 0, 0, 0]} """ Corresponding size in kW for generic reference turbines sizes """ system_capacity_lookup = {'large': 2000, 'medium': 250, 'commercial': 100, 'residential': 2.5} """ Corresponding rotor diameter in meters for generic reference turbines sizes """ rotor_diameter_lookup = {'large': 55, 'medium': 21.9, 'commercial': 13.8, 'residential': 1.85} """ Corresponding string interval name given a float time step in hours """ time_step_hour_to_minute_interval_lookup = { round(float(1), 2): '60', round(float(0.5), 2): '30', round(float(0.25), 2): '15', round(float(5/60), 2): '5', round(float(1/60), 2): '1'} """ Allowed hub heights in meters for the Wind Toolkit """ allowed_hub_height_meters = [10, 40, 60, 80, 100, 120, 140, 160, 200] """ Given a dictionary of heights and filenames, combine into one resource file Parameters ---------- file_resource_heights: dict Dictionary with key as height in meters, value as absolute path to resource file, eg {40: '/local/workspace/39.9_-105.2_windtoolkit_2012_60_min_40m.srw', 60: '/local/workspace/39.9_-105.2_windtoolkit_2012_60_min_60m.srw'} file_combined: string The filename to combine the resource data into, eg: '/local/workspace/39.9_-105.2_windtoolkit_2012_60_min_40m_60m.srw """ def combine_wind_files(file_resource_heights, file_combined): data = [None] * 2 for height, f in file_resource_heights.items(): if os.path.isfile(f): with open(f) as file_in: csv_reader = csv.reader(file_in, delimiter=',') line = 0 for row in csv_reader: if line < 2: data[line] = row else: if line >= len(data): data.append(row) else: data[line] += row line += 1 with open(file_combined, 'w') as fo: writer = csv.writer(fo) writer.writerows(data) return os.path.isfile(file_combined) class WindSAMSDK: """ Class to manage interaction with the SAM wind model through the softwawre development kit (SDK) User can interact with class with resource data in the following ways: 1. Pass in vectors of temperature, pressure, wind speed, wind direction 2. Pass in a resource file directly: file_resource_full 3. Utilize the wind toolkit API, which will download required data if none passed in Attributes ---------- wind_turbine_speeds: list The speeds corresponding to all turbine power curves elevation: float Site elevation in meters latitude: float Site latitude longitude: float Site longitude year: int The year of resource data size_class: string The size class of the turbine hub_height_meters: float The desired turbine height time_steps_per_hour: float The time interval, eg. 1 is hourly, 0.5 half hour file_resource_full: string Absolute path of filename (.srw file) with all heights necessary """ wind_turbine_speeds = [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] def __init__(self, path_inputs=None, hub_height_meters=None, latitude=None, longitude=None, elevation=0, # not actually used in SDK year=2012, size_class='commercial', temperature_celsius=None, pressure_atmospheres=None, wind_meters_per_sec=None, wind_direction_degrees=None, time_steps_per_hour=1, file_resource_full=None, **kwargs ): """ Parameters ---------- path_inputs: string Path to folder where resource data should download hub_height_meters: float The desired turbine height elevation: float Site elevation in meters latitude: float Site latitude longitude: float Site longitude year: int The year of resource data size_class: string The size class of the turbine temperature_celsius: list If passing in data directly, the list of temperatures at the hub height pressure_atmospheres: list If passing in data directly, the list of pressures at the hub height wind_meters_per_sec: list If passing in data directly, the list of wind speeds at the hub height wind_direction_degrees: list If passing in data directly, the list of directions at the hub height time_steps_per_hour: float The time interval, eg. 1 is hourly, 0.5 half hour file_resource_full: string Absolute path of filename (.srw file) with all heights necessary """ self.elevation = elevation self.latitude = latitude self.longitude = longitude self.year = year self.size_class = size_class self.hub_height_meters = hub_height_meters self.time_steps_per_hour = time_steps_per_hour self.interval = time_step_hour_to_minute_interval_lookup[round(float(time_steps_per_hour), 2)] self.use_input_data = False if file_resource_full is not None: self.file_resource_full = file_resource_full self.file_downloaded = os.path.isfile(self.file_resource_full) # If data vectors have been passed in if None not in [temperature_celsius, pressure_atmospheres, wind_direction_degrees, wind_meters_per_sec]: self.temperature_celsius = temperature_celsius self.pressure_atmospheres = pressure_atmospheres self.wind_direction_degrees = wind_direction_degrees self.wind_meters_per_sec = wind_meters_per_sec self.use_input_data = True # If we need to download the resource data elif file_resource_full is None or not self.file_downloaded: # TODO: check input_files for previously downloaded wind resource file from reo.src.wind_resource import get_wind_resource_developer_api # evaluate hub height, determine what heights of resource data are required heights = [hub_height_meters] if hub_height_meters not in allowed_hub_height_meters: height_low = allowed_hub_height_meters[0] height_high = allowed_hub_height_meters[-1] for h in allowed_hub_height_meters: if h < hub_height_meters: height_low = h elif h > hub_height_meters: height_high = h break heights[0] = height_low heights.append(height_high) # if there is no resource file passed in, create one if file_resource_full is None: file_resource_base = os.path.join(path_inputs, str(latitude) + "_" + str(longitude) + "_windtoolkit_" + str( year) + "_" + str(self.interval) + "min") file_resource_full = file_resource_base # Regardless of whether file passed in, create the intermediate files required to download file_resource_heights = {} for h in heights: file_resource_heights[h] = file_resource_base + '_' + str(h) + 'm.srw' file_resource_full += "_" + str(h) + 'm' file_resource_full += ".srw" for height, f in file_resource_heights.items(): success = get_wind_resource_developer_api( filename=f, year=self.year, latitude=self.latitude, longitude=self.longitude, hub_height_meters=height) if not success: raise ValueError('Unable to download wind data') # combine into one file to pass to SAM if len(heights) > 1: self.file_downloaded = combine_wind_files(file_resource_heights, file_resource_full, path_inputs) self.file_resource_full = file_resource_full self.wind_turbine_powercurve = wind_turbine_powercurve_lookup[size_class] self.system_capacity = system_capacity_lookup[size_class] self.rotor_diameter = rotor_diameter_lookup[size_class] self.ssc = [] self.data = [] self.module = [] self.wind_resource = [] self.make_ssc() def make_ssc(self): """ Function to set up the SAM run through the SAM Simulation Core """ ssc = PySSC() ssc.module_exec_set_print(0) data = ssc.data_create() module = ssc.module_create('windpower') # must setup wind resource in its own ssc data structure wind_resource = [] if self.use_input_data: wind_resource = ssc.data_create() ssc.data_set_number(wind_resource, 'latitude', self.latitude) ssc.data_set_number(wind_resource, 'longitude', self.longitude) ssc.data_set_number(wind_resource, 'elevation', self.elevation) ssc.data_set_number(wind_resource, 'year', self.year) heights = [self.hub_height_meters, self.hub_height_meters, self.hub_height_meters, self.hub_height_meters] ssc.data_set_array(wind_resource, 'heights', heights) fields = [1, 2, 3, 4] ssc.data_set_array(wind_resource, 'fields', fields) data_matrix = np.matrix([self.temperature_celsius, self.pressure_atmospheres, self.wind_meters_per_sec, self.wind_direction_degrees]) data_matrix = data_matrix.transpose() data_matrix = data_matrix.tolist() ssc.data_set_matrix(wind_resource, 'data', data_matrix) ssc.data_set_table(data, 'wind_resource_data', wind_resource) else: ssc.data_set_string(data, 'wind_resource_filename', self.file_resource_full) ssc.data_set_number(data, 'wind_resource_shear', 0.14000000059604645) ssc.data_set_number(data, 'wind_resource_turbulence_coeff', 0.10000000149011612) ssc.data_set_number(data, 'system_capacity', self.system_capacity) ssc.data_set_number(data, 'wind_resource_model_choice', 0) ssc.data_set_number(data, 'weibull_reference_height', 50) ssc.data_set_number(data, 'weibull_k_factor', 2) ssc.data_set_number(data, 'weibull_wind_speed', 7.25) ssc.data_set_number(data, 'wind_turbine_rotor_diameter', self.rotor_diameter) ssc.data_set_array(data, 'wind_turbine_powercurve_windspeeds', self.wind_turbine_speeds) ssc.data_set_array(data, 'wind_turbine_powercurve_powerout', self.wind_turbine_powercurve) ssc.data_set_number(data, 'wind_turbine_hub_ht', self.hub_height_meters) ssc.data_set_number(data, 'wind_turbine_max_cp', 0.44999998807907104) wind_farm_xCoordinates = [0] ssc.data_set_array(data, 'wind_farm_xCoordinates', wind_farm_xCoordinates) wind_farm_yCoordinates = [0] ssc.data_set_array(data, 'wind_farm_yCoordinates', wind_farm_yCoordinates) ssc.data_set_number(data, 'wind_farm_losses_percent', 0) ssc.data_set_number(data, 'wind_farm_wake_model', 0) ssc.data_set_number(data, 'adjust:constant', 0) self.ssc = ssc self.data = data self.module = module self.wind_resource = wind_resource def wind_prod_factor(self): """ Retrieve the wind production factor, a time series unit representation of wind power production """ if self.ssc.module_exec(self.module, self.data) == 0: print ('windpower simulation error') idx = 1 msg = self.ssc.module_log(self.module, 0) while msg is not None: print (' : ' + msg) msg = self.ssc.module_log(self.module, idx) idx = idx + 1 self.ssc.module_free(self.module) # the system_power output from SAMSDK is of same length as input (i.e. 35040 series for 4 times steps/hour) system_power = self.ssc.data_get_array(self.data, 'gen') prod_factor_original = [power/self.system_capacity for power in system_power] self.ssc.data_free(self.data) if self.use_input_data: self.ssc.data_free(self.wind_resource) # subhourly (i.e 15 minute data) if self.time_steps_per_hour >= 1: timesteps = [] timesteps_base = range(0, 8760) for ts_b in timesteps_base: for step in range(0, self.time_steps_per_hour): timesteps.append(ts_b) # downscaled run (i.e 288 steps per year) else: timesteps = range(0, 8760, int(1 / self.time_steps_per_hour)) prod_factor = [] for hour in timesteps: #prod_factor.append(round(prod_factor_original[hour]/self.time_steps_per_hour, 3)) prod_factor.append(prod_factor_original[hour]) return prod_factor_original
[ "reo.src.wind_resource.get_wind_resource_developer_api", "csv.writer", "os.path.isfile", "numpy.matrix", "csv.reader" ]
[((5480, 5509), 'os.path.isfile', 'os.path.isfile', (['file_combined'], {}), '(file_combined)\n', (5494, 5509), False, 'import os\n'), ((4882, 4899), 'os.path.isfile', 'os.path.isfile', (['f'], {}), '(f)\n', (4896, 4899), False, 'import os\n'), ((5422, 5436), 'csv.writer', 'csv.writer', (['fo'], {}), '(fo)\n', (5432, 5436), False, 'import csv\n'), ((9044, 9083), 'os.path.isfile', 'os.path.isfile', (['self.file_resource_full'], {}), '(self.file_resource_full)\n', (9058, 9083), False, 'import os\n'), ((13344, 13468), 'numpy.matrix', 'np.matrix', (['[self.temperature_celsius, self.pressure_atmospheres, self.\n wind_meters_per_sec, self.wind_direction_degrees]'], {}), '([self.temperature_celsius, self.pressure_atmospheres, self.\n wind_meters_per_sec, self.wind_direction_degrees])\n', (13353, 13468), True, 'import numpy as np\n'), ((4967, 5001), 'csv.reader', 'csv.reader', (['file_in'], {'delimiter': '""","""'}), "(file_in, delimiter=',')\n", (4977, 5001), False, 'import csv\n'), ((11345, 11485), 'reo.src.wind_resource.get_wind_resource_developer_api', 'get_wind_resource_developer_api', ([], {'filename': 'f', 'year': 'self.year', 'latitude': 'self.latitude', 'longitude': 'self.longitude', 'hub_height_meters': 'height'}), '(filename=f, year=self.year, latitude=self.\n latitude, longitude=self.longitude, hub_height_meters=height)\n', (11376, 11485), False, 'from reo.src.wind_resource import get_wind_resource_developer_api\n')]
from __future__ import division import glob import numpy as NP from functools import reduce import numpy.ma as MA import progressbar as PGB import h5py import healpy as HP import warnings import copy import astropy.cosmology as CP from astropy.time import Time, TimeDelta from astropy.io import fits from astropy import units as U from astropy import constants as FCNST from scipy import interpolate from astroutils import DSP_modules as DSP from astroutils import constants as CNST from astroutils import nonmathops as NMO from astroutils import mathops as OPS from astroutils import lookup_operations as LKP import prisim from prisim import interferometry as RI from prisim import primary_beams as PB from prisim import delay_spectrum as DS try: from pyuvdata import UVBeam except ImportError: uvbeam_module_found = False else: uvbeam_module_found = True prisim_path = prisim.__path__[0]+'/' cosmoPlanck15 = CP.Planck15 # Planck 2015 cosmology cosmo100 = cosmoPlanck15.clone(name='Modified Planck 2015 cosmology with h=1.0', H0=100.0) # Modified Planck 2015 cosmology with h=1.0, H= 100 km/s/Mpc ################################################################################ def write_PRISim_bispectrum_phase_to_npz(infile_prefix, outfile_prefix, triads=None, bltriplet=None, hdf5file_prefix=None, infmt='npz', datakey='noisy', blltol=0.1): """ ---------------------------------------------------------------------------- Write closure phases computed in a PRISim simulation to a NPZ file with appropriate format for further analysis. Inputs: infile_prefix [string] HDF5 file or NPZ file created by a PRISim simulation or its replication respectively. If infmt is specified as 'hdf5', then hdf5file_prefix will be ignored and all the observing info will be read from here. If infmt is specified as 'npz', then hdf5file_prefix needs to be specified in order to read the observing parameters. triads [list or numpy array or None] Antenna triads given as a list of 3-element lists or a ntriads x 3 array. Each element in the inner list is an antenna label. They will be converted to strings internally. If set to None, then all triads determined by bltriplet will be used. If specified, then inputs in blltol and bltriplet will be ignored. bltriplet [numpy array or None] 3x3 numpy array containing the 3 baseline vectors. The first axis denotes the three baselines, the second axis denotes the East, North, Up coordinates of the baseline vector. Units are in m. Will be used only if triads is set to None. outfile_prefix [string] Prefix of the NPZ file. It will be appended by '_noiseless', '_noisy', and '_noise' and further by extension '.npz' infmt [string] Format of the input file containing visibilities. Accepted values are 'npz' (default), and 'hdf5'. If infmt is specified as 'npz', then hdf5file_prefix also needs to be specified for reading the observing parameters datakey [string] Specifies which -- 'noiseless', 'noisy' (default), or 'noise' -- visibilities are to be written to the output. If set to None, and infmt is 'hdf5', then all three sets of visibilities are written. The datakey string will also be added as a suffix in the output file. blltol [scalar] Baseline length tolerance (in m) for matching baseline vectors in triads. It must be a scalar. Default = 0.1 m. Will be used only if triads is set to None and bltriplet is to be used. ---------------------------------------------------------------------------- """ if not isinstance(infile_prefix, str): raise TypeError('Input infile_prefix must be a string') if not isinstance(outfile_prefix, str): raise TypeError('Input outfile_prefix must be a string') if (triads is None) and (bltriplet is None): raise ValueError('One of triads or bltriplet must be set') if triads is None: if not isinstance(bltriplet, NP.ndarray): raise TypeError('Input bltriplet must be a numpy array') if not isinstance(blltol, (int,float)): raise TypeError('Input blltol must be a scalar') if bltriplet.ndim != 2: raise ValueError('Input bltriplet must be a 2D numpy array') if bltriplet.shape[0] != 3: raise ValueError('Input bltriplet must contain three baseline vectors') if bltriplet.shape[1] != 3: raise ValueError('Input bltriplet must contain baseline vectors along three corrdinates in the ENU frame') else: if not isinstance(triads, (list, NP.ndarray)): raise TypeError('Input triads must be a list or numpy array') triads = NP.asarray(triads).astype(str) if not isinstance(infmt, str): raise TypeError('Input infmt must be a string') if infmt.lower() not in ['npz', 'hdf5']: raise ValueError('Input file format must be npz or hdf5') if infmt.lower() == 'npz': if not isinstance(hdf5file_prefix, str): raise TypeError('If infmt is npz, then hdf5file_prefix needs to be specified for observing parameters information') if datakey is None: datakey = ['noisy'] if isinstance(datakey, str): datakey = [datakey] elif not isinstance(datakey, list): raise TypeError('Input datakey must be a list') for dkey in datakey: if dkey.lower() not in ['noiseless', 'noisy', 'noise']: raise ValueError('Invalid input found in datakey') if infmt.lower() == 'hdf5': fullfnames_with_extension = glob.glob(infile_prefix + '*' + infmt.lower()) fullfnames_without_extension = [fname.split('.hdf5')[0] for fname in fullfnames_with_extension] else: fullfnames_without_extension = [infile_prefix] if len(fullfnames_without_extension) == 0: raise IOError('No input files found with pattern {0}'.format(infile_prefix)) try: if infmt.lower() == 'hdf5': simvis = RI.InterferometerArray(None, None, None, init_file=fullfnames_without_extension[0]) else: simvis = RI.InterferometerArray(None, None, None, init_file=hdf5file_prefix) except: raise IOError('Input PRISim file does not contain a valid PRISim output') latitude = simvis.latitude longitude = simvis.longitude location = ('{0:.5f}d'.format(longitude), '{0:.5f}d'.format(latitude)) last = simvis.lst / 15.0 / 24.0 # from degrees to fraction of day last = last.reshape(-1,1) daydata = NP.asarray(simvis.timestamp[0]).ravel() if infmt.lower() == 'npz': simvisinfo = NP.load(fullfnames_without_extension[0]+'.'+infmt.lower()) skyvis = simvisinfo['noiseless'][0,...] vis = simvisinfo['noisy'] noise = simvisinfo['noise'] n_realize = vis.shape[0] else: n_realize = len(fullfnames_without_extension) cpdata = {} outfile = {} for fileind in range(n_realize): if infmt.lower() == 'npz': simvis.vis_freq = vis[fileind,...] simvis.vis_noise_freq = noise[fileind,...] else: simvis = RI.InterferometerArray(None, None, None, init_file=fullfnames_without_extension[fileind]) if fileind == 0: if triads is None: triads, bltriplets = simvis.getThreePointCombinations(unique=False) # triads = NP.asarray(prisim_BSP_info['antenna_triplets']).reshape(-1,3) # bltriplets = NP.asarray(prisim_BSP_info['baseline_triplets']) triads = NP.asarray(triads).reshape(-1,3) bltriplets = NP.asarray(bltriplets) blinds = [] matchinfo = LKP.find_NN(bltriplet, bltriplets.reshape(-1,3), distance_ULIM=blltol) revind = [] for blnum in NP.arange(bltriplet.shape[0]): if len(matchinfo[0][blnum]) == 0: revind += [blnum] if len(revind) > 0: flip_factor = NP.ones(3, dtype=NP.float) flip_factor[NP.array(revind)] = -1 rev_bltriplet = bltriplet * flip_factor.reshape(-1,1) matchinfo = LKP.find_NN(rev_bltriplet, bltriplets.reshape(-1,3), distance_ULIM=blltol) for blnum in NP.arange(bltriplet.shape[0]): if len(matchinfo[0][blnum]) == 0: raise ValueError('Some baselines in the triplet are not found in the model triads') triadinds = [] for blnum in NP.arange(bltriplet.shape[0]): triadind, blind = NP.unravel_index(NP.asarray(matchinfo[0][blnum]), (bltriplets.shape[0], bltriplets.shape[1])) triadinds += [triadind] triadind_intersection = NP.intersect1d(triadinds[0], NP.intersect1d(triadinds[1], triadinds[2])) if triadind_intersection.size == 0: raise ValueError('Specified triad not found in the PRISim model. Try other permutations of the baseline vectors and/or reverse individual baseline vectors in the triad before giving up.') triads = triads[triadind_intersection,:] selected_bltriplets = bltriplets[triadind_intersection,:,:].reshape(-1,3,3) prisim_BSP_info = simvis.getClosurePhase(antenna_triplets=triads.tolist(), delay_filter_info=None, specsmooth_info=None, spectral_window_info=None, unique=False) if fileind == 0: triads = NP.asarray(prisim_BSP_info['antenna_triplets']).reshape(-1,3) # Re-establish the triads returned after the first iteration (to accunt for any order flips) for outkey in datakey: if fileind == 0: outfile[outkey] = outfile_prefix + '_{0}.npz'.format(outkey) if outkey == 'noiseless': if fileind == 0: # cpdata = prisim_BSP_info['closure_phase_skyvis'][triadind_intersection,:,:][NP.newaxis,...] cpdata[outkey] = prisim_BSP_info['closure_phase_skyvis'][NP.newaxis,...] else: # cpdata = NP.concatenate((cpdata, prisim_BSP_info['closure_phase_skyvis'][triadind_intersection,:,:][NP.newaxis,...]), axis=0) cpdata[outkey] = NP.concatenate((cpdata[outkey], prisim_BSP_info['closure_phase_skyvis'][NP.newaxis,...]), axis=0) if outkey == 'noisy': if fileind == 0: # cpdata = prisim_BSP_info['closure_phase_vis'][triadind_intersection,:,:][NP.newaxis,...] cpdata[outkey] = prisim_BSP_info['closure_phase_vis'][NP.newaxis,...] else: # cpdata = NP.concatenate((cpdata, prisim_BSP_info['closure_phase_vis'][triadind_intersection,:,:][NP.newaxis,...]), axis=0) cpdata[outkey] = NP.concatenate((cpdata[outkey], prisim_BSP_info['closure_phase_vis'][NP.newaxis,...]), axis=0) if outkey == 'noise': if fileind == 0: # cpdata = prisim_BSP_info['closure_phase_noise'][triadind_intersection,:,:] cpdata[outkey] = prisim_BSP_info['closure_phase_noise'][NP.newaxis,:,:] else: # cpdata = NP.concatenate((cpdata, prisim_BSP_info['closure_phase_noise'][triadind_intersection,:,:][NP.newaxis,...]), axis=0) cpdata[outkey] = NP.concatenate((cpdata[outkey], prisim_BSP_info['closure_phase_noise'][NP.newaxis,...]), axis=0) for outkey in datakey: cpdata[outkey] = NP.rollaxis(cpdata[outkey], 3, start=0) flagsdata = NP.zeros(cpdata[outkey].shape, dtype=NP.bool) NP.savez_compressed(outfile[outkey], closures=cpdata[outkey], flags=flagsdata, triads=triads, last=last+NP.zeros((1,n_realize)), days=daydata+NP.arange(n_realize)) ################################################################################ def loadnpz(npzfile, longitude=0.0, latitude=0.0, lst_format='fracday'): """ ---------------------------------------------------------------------------- Read an input NPZ file containing closure phase data output from CASA and return a dictionary Inputs: npzfile [string] Input NPZ file including full path containing closure phase data. It must have the following files/keys inside: 'closures' [numpy array] Closure phase (radians). It is of shape (nlst,ndays,ntriads,nchan) 'triads' [numpy array] Array of triad tuples, of shape (ntriads,3) 'flags' [numpy array] Array of flags (boolean), of shape (nlst,ndays,ntriads,nchan) 'last' [numpy array] Array of LST for each day (CASA units which is MJD+6713). Shape is (nlst,ndays) 'days' [numpy array] Array of days, shape is (ndays,) 'averaged_closures' [numpy array] optional array of closure phases averaged across days. Shape is (nlst,ntriads,nchan) 'std_dev_lst' [numpy array] optional array of standard deviation of closure phases across days. Shape is (nlst,ntriads,nchan) 'std_dev_triads' [numpy array] optional array of standard deviation of closure phases across triads. Shape is (nlst,ndays,nchan) latitude [scalar int or float] Latitude of site (in degrees). Default=0.0 deg. longitude [scalar int or float] Longitude of site (in degrees). Default=0.0 deg. lst_format [string] Specifies the format/units in which the 'last' key is to be interpreted. If set to 'hourangle', the LST is in units of hour angle. If set to 'fracday', the fractional portion of the 'last' value is the LST in units of days. Output: cpinfo [dictionary] Contains one top level keys, namely, 'raw' Under key 'raw' which holds a dictionary, the subkeys include 'cphase' (nlst,ndays,ntriads,nchan), 'triads' (ntriads,3), 'lst' (nlst,ndays), and 'flags' (nlst,ndays,ntriads,nchan), and some other optional keys ---------------------------------------------------------------------------- """ npzdata = NP.load(npzfile) cpdata = npzdata['closures'] triadsdata = npzdata['triads'] flagsdata = npzdata['flags'] location = ('{0:.5f}d'.format(longitude), '{0:.5f}d'.format(latitude)) daydata = Time(npzdata['days'].astype(NP.float64), scale='utc', format='jd', location=location) # lstdata = Time(npzdata['last'].astype(NP.float64) - 6713.0, scale='utc', format='mjd', location=('+21.4278d', '-30.7224d')).sidereal_time('apparent') # Subtract 6713 based on CASA convention to obtain MJD if lst_format.lower() == 'hourangle': lstHA = npzdata['last'] lstday = daydata.reshape(1,-1) + TimeDelta(NP.zeros(lstHA.shape[0]).reshape(-1,1)*U.s) elif lst_format.lower() == 'fracday': lstfrac, lstint = NP.modf(npzdata['last']) lstday = Time(lstint.astype(NP.float64) - 6713.0, scale='utc', format='mjd', location=location) # Subtract 6713 based on CASA convention to obtain MJD lstHA = lstfrac * 24.0 # in hours else: raise ValueError('Input lst_format invalid') cp = cpdata.astype(NP.float64) flags = flagsdata.astype(NP.bool) cpinfo = {} datapool = ['raw'] for dpool in datapool: cpinfo[dpool] = {} if dpool == 'raw': qtys = ['cphase', 'triads', 'flags', 'lst', 'lst-day', 'days', 'dayavg', 'std_triads', 'std_lst'] for qty in qtys: if qty == 'cphase': cpinfo[dpool][qty] = NP.copy(cp) elif qty == 'triads': cpinfo[dpool][qty] = NP.copy(triadsdata) elif qty == 'flags': cpinfo[dpool][qty] = NP.copy(flags) elif qty == 'lst': cpinfo[dpool][qty] = NP.copy(lstHA) elif qty == 'lst-day': cpinfo[dpool][qty] = NP.copy(lstday.jd) elif qty == 'days': cpinfo[dpool][qty] = NP.copy(daydata.jd) elif qty == 'dayavg': if 'averaged_closures' in npzdata: cpinfo[dpool][qty] = NP.copy(cp_dayavg) elif qty == 'std_triads': if 'std_dev_triad' in npzdata: cpinfo[dpool][qty] = NP.copy(cp_std_triads) elif qty == 'std_lst': if 'std_dev_lst' in npzdata: cpinfo[dpool][qty] = NP.copy(cp_std_lst) return cpinfo ################################################################################ def npz2hdf5(npzfile, hdf5file, longitude=0.0, latitude=0.0, lst_format='fracday'): """ ---------------------------------------------------------------------------- Read an input NPZ file containing closure phase data output from CASA and save it to HDF5 format Inputs: npzfile [string] Input NPZ file including full path containing closure phase data. It must have the following files/keys inside: 'closures' [numpy array] Closure phase (radians). It is of shape (nlst,ndays,ntriads,nchan) 'triads' [numpy array] Array of triad tuples, of shape (ntriads,3) 'flags' [numpy array] Array of flags (boolean), of shape (nlst,ndays,ntriads,nchan) 'last' [numpy array] Array of LST for each day (CASA units ehich is MJD+6713). Shape is (nlst,ndays) 'days' [numpy array] Array of days, shape is (ndays,) 'averaged_closures' [numpy array] optional array of closure phases averaged across days. Shape is (nlst,ntriads,nchan) 'std_dev_lst' [numpy array] optional array of standard deviation of closure phases across days. Shape is (nlst,ntriads,nchan) 'std_dev_triads' [numpy array] optional array of standard deviation of closure phases across triads. Shape is (nlst,ndays,nchan) hdf5file [string] Output HDF5 file including full path. latitude [scalar int or float] Latitude of site (in degrees). Default=0.0 deg. longitude [scalar int or float] Longitude of site (in degrees). Default=0.0 deg. lst_format [string] Specifies the format/units in which the 'last' key is to be interpreted. If set to 'hourangle', the LST is in units of hour angle. If set to 'fracday', the fractional portion of the 'last' value is the LST in units of days. ---------------------------------------------------------------------------- """ npzdata = NP.load(npzfile) cpdata = npzdata['closures'] triadsdata = npzdata['triads'] flagsdata = npzdata['flags'] location = ('{0:.5f}d'.format(longitude), '{0:.5f}d'.format(latitude)) daydata = Time(npzdata['days'].astype(NP.float64), scale='utc', format='jd', location=location) # lstdata = Time(npzdata['last'].astype(NP.float64) - 6713.0, scale='utc', format='mjd', location=('+21.4278d', '-30.7224d')).sidereal_time('apparent') # Subtract 6713 based on CASA convention to obtain MJD if lst_format.lower() == 'hourangle': lstHA = npzdata['last'] lstday = daydata.reshape(1,-1) + TimeDelta(NP.zeros(lstHA.shape[0]).reshape(-1,1)*U.s) elif lst_format.lower() == 'fracday': lstfrac, lstint = NP.modf(npzdata['last']) lstday = Time(lstint.astype(NP.float64) - 6713.0, scale='utc', format='mjd', location=location) # Subtract 6713 based on CASA convention to obtain MJD lstHA = lstfrac * 24.0 # in hours else: raise ValueError('Input lst_format invalid') cp = cpdata.astype(NP.float64) flags = flagsdata.astype(NP.bool) if 'averaged_closures' in npzdata: day_avg_cpdata = npzdata['averaged_closures'] cp_dayavg = day_avg_cpdata.astype(NP.float64) if 'std_dev_triad' in npzdata: std_triads_cpdata = npzdata['std_dev_triad'] cp_std_triads = std_triads_cpdata.astype(NP.float64) if 'std_dev_lst' in npzdata: std_lst_cpdata = npzdata['std_dev_lst'] cp_std_lst = std_lst_cpdata.astype(NP.float64) with h5py.File(hdf5file, 'w') as fobj: datapool = ['raw'] for dpool in datapool: if dpool == 'raw': qtys = ['cphase', 'triads', 'flags', 'lst', 'lst-day', 'days', 'dayavg', 'std_triads', 'std_lst'] for qty in qtys: data = None if qty == 'cphase': data = NP.copy(cp) elif qty == 'triads': data = NP.copy(triadsdata) elif qty == 'flags': data = NP.copy(flags) elif qty == 'lst': data = NP.copy(lstHA) elif qty == 'lst-day': data = NP.copy(lstday.jd) elif qty == 'days': data = NP.copy(daydata.jd) elif qty == 'dayavg': if 'averaged_closures' in npzdata: data = NP.copy(cp_dayavg) elif qty == 'std_triads': if 'std_dev_triad' in npzdata: data = NP.copy(cp_std_triads) elif qty == 'std_lst': if 'std_dev_lst' in npzdata: data = NP.copy(cp_std_lst) if data is not None: dset = fobj.create_dataset('{0}/{1}'.format(dpool, qty), data=data, compression='gzip', compression_opts=9) ################################################################################ def save_CPhase_cross_power_spectrum(xcpdps, outfile): """ ---------------------------------------------------------------------------- Save cross-power spectrum information in a dictionary to a HDF5 file Inputs: xcpdps [dictionary] This dictionary is essentially an output of the member function compute_power_spectrum() of class ClosurePhaseDelaySpectrum. It has the following key-value structure: 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndays,) array), 'day_ind' ((ndays,) array), 'dday' ((ndays,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,) 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains one or more of the following keys named 'whole', 'submodel', 'residual', and 'errinfo' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided bu avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum outfile [string] Full path to the external HDF5 file where the cross- power spectrum information provided in xcpdps will be saved ---------------------------------------------------------------------------- """ if not isinstance(xcpdps, dict): raise TypeError('Input xcpdps must be a dictionary') with h5py.File(outfile, 'w') as fileobj: hdrgrp = fileobj.create_group('header') hdrkeys = ['triads', 'triads_ind', 'lst', 'lst_ind', 'dlst', 'days', 'day_ind', 'dday'] for key in hdrkeys: dset = hdrgrp.create_dataset(key, data=xcpdps[key]) sampling = ['oversampled', 'resampled'] sampling_keys = ['z', 'kprll', 'lags', 'freq_center', 'bw_eff', 'shape', 'freq_wts', 'lag_corr_length'] dpool_keys = ['whole', 'submodel', 'residual', 'errinfo'] for smplng in sampling: if smplng in xcpdps: smplgrp = fileobj.create_group(smplng) for key in sampling_keys: dset = smplgrp.create_dataset(key, data=xcpdps[smplng][key]) for dpool in dpool_keys: if dpool in xcpdps[smplng]: dpoolgrp = smplgrp.create_group(dpool) keys = ['diagoffsets', 'diagweights', 'axesmap', 'nsamples_incoh', 'nsamples_coh'] for key in keys: if key in xcpdps[smplng][dpool]: if isinstance(xcpdps[smplng][dpool][key], dict): subgrp = dpoolgrp.create_group(key) for subkey in xcpdps[smplng][dpool][key]: dset = subgrp.create_dataset(str(subkey), data=xcpdps[smplng][dpool][key][subkey]) else: dset = dpoolgrp.create_dataset(key, data=xcpdps[smplng][dpool][key]) for stat in ['mean', 'median']: if stat in xcpdps[smplng][dpool]: if isinstance(xcpdps[smplng][dpool][stat], list): for ii in range(len(xcpdps[smplng][dpool][stat])): dset = dpoolgrp.create_dataset(stat+'/diagcomb_{0}'.format(ii), data=xcpdps[smplng][dpool][stat][ii].si.value) dset.attrs['units'] = str(xcpdps[smplng][dpool][stat][ii].si.unit) else: dset = dpoolgrp.create_dataset(stat, data=xcpdps[smplng][dpool][stat].si.value) dset.attrs['units'] = str(xcpdps[smplng][dpool][stat].si.unit) ################################################################################ def read_CPhase_cross_power_spectrum(infile): """ ---------------------------------------------------------------------------- Read information about cross power spectrum from an external HDF5 file into a dictionary. This is the counterpart to save_CPhase_corss_power_spectrum() Input: infile [string] Full path to the external HDF5 file that contains info about cross-power spectrum. Output: xcpdps [dictionary] This dictionary has structure the same as output of the member function compute_power_spectrum() of class ClosurePhaseDelaySpectrum. It has the following key-value structure: 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndays,) array), 'day_ind' ((ndays,) array), 'dday' ((ndays,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,) 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains one or more of the following keys named 'whole', 'submodel', 'residual', and 'errinfo' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided bu avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum outfile [string] Full path to the external HDF5 file where the cross- power spectrum information provided in xcpdps will be saved ---------------------------------------------------------------------------- """ if not isinstance(infile, str): raise TypeError('Input infile must be a string') xcpdps = {} with h5py.File(infile, 'r') as fileobj: hdrgrp = fileobj['header'] hdrkeys = ['triads', 'triads_ind', 'lst', 'lst_ind', 'dlst', 'days', 'day_ind', 'dday'] for key in hdrkeys: xcpdps[key] = hdrgrp[key].value sampling = ['oversampled', 'resampled'] sampling_keys = ['z', 'kprll', 'lags', 'freq_center', 'bw_eff', 'shape', 'freq_wts', 'lag_corr_length'] dpool_keys = ['whole', 'submodel', 'residual', 'errinfo'] for smplng in sampling: if smplng in fileobj: smplgrp = fileobj[smplng] xcpdps[smplng] = {} for key in sampling_keys: xcpdps[smplng][key] = smplgrp[key].value for dpool in dpool_keys: if dpool in smplgrp: xcpdps[smplng][dpool] = {} dpoolgrp = smplgrp[dpool] keys = ['diagoffsets', 'diagweights', 'axesmap', 'nsamples_incoh', 'nsamples_coh'] for key in keys: if key in dpoolgrp: if isinstance(dpoolgrp[key], h5py.Group): xcpdps[smplng][dpool][key] = {} for subkey in dpoolgrp[key]: xcpdps[smplng][dpool][key][int(subkey)] = dpoolgrp[key][subkey].value elif isinstance(dpoolgrp[key], h5py.Dataset): xcpdps[smplng][dpool][key] = dpoolgrp[key].value else: raise TypeError('Invalid h5py data type encountered') for stat in ['mean', 'median']: if stat in dpoolgrp: if isinstance(dpoolgrp[stat], h5py.Dataset): valunits = dpoolgrp[stat].attrs['units'] xcpdps[smplng][dpool][stat] = dpoolgrp[stat].value * U.Unit(valunits) elif isinstance(dpoolgrp[stat], h5py.Group): xcpdps[smplng][dpool][stat] = [] for diagcomb_ind in range(len(dpoolgrp[stat].keys())): if 'diagcomb_{0}'.format(diagcomb_ind) in dpoolgrp[stat]: valunits = dpoolgrp[stat]['diagcomb_{0}'.format(diagcomb_ind)].attrs['units'] xcpdps[smplng][dpool][stat] += [dpoolgrp[stat]['diagcomb_{0}'.format(diagcomb_ind)].value * U.Unit(valunits)] return xcpdps ################################################################################ def incoherent_cross_power_spectrum_average(xcpdps, excpdps=None, diagoffsets=None): """ ---------------------------------------------------------------------------- Perform incoherent averaging of cross power spectrum along specified axes Inputs: xcpdps [dictionary or list of dictionaries] If provided as a list of dictionaries, each dictionary consists of cross power spectral information coming possible from different sources, and they will be averaged be averaged incoherently. If a single dictionary is provided instead of a list of dictionaries, the said averaging does not take place. Each dictionary is essentially an output of the member function compute_power_spectrum() of class ClosurePhaseDelaySpectrum. It has the following key-value structure: 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndays,) array), 'day_ind' ((ndays,) array), 'dday' ((ndays,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,) 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains 3 keys named 'whole', 'submodel', and 'residual' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided bu avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum excpdps [dictionary or list of dictionaries] If provided as a list of dictionaries, each dictionary consists of cross power spectral information of subsample differences coming possible from different sources, and they will be averaged be averaged incoherently. This is optional. If not set (default=None), no incoherent averaging happens. If a single dictionary is provided instead of a list of dictionaries, the said averaging does not take place. Each dictionary is essentially an output of the member function compute_power_spectrum_uncertainty() of class ClosurePhaseDelaySpectrum. It has the following key-value structure: 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndaycomb,) array), 'day_ind' ((ndaycomb,) array), 'dday' ((ndaycomb,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,) 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains a key named 'errinfo' which is a dictionary. It contains information about power spectrum uncertainties obtained from subsample differences. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum uncertainties incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['errinfo']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum uncertainties incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['errinfo']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum diagoffsets [NoneType or dictionary or list of dictionaries] This info is used for incoherent averaging along specified diagonals along specified axes. This incoherent averaging is performed after incoherently averaging multiple cross-power spectra (if any). If set to None, this incoherent averaging is not performed. Many combinations of axes and diagonals can be specified as individual dictionaries in a list. If only one dictionary is specified, then it assumed that only one combination of axes and diagonals is requested. If a list of dictionaries is given, each dictionary in the list specifies a different combination for incoherent averaging. Each dictionary should have the following key-value pairs. The key is the axis number (allowed values are 1, 2, 3) that denote the axis type (1=LST, 2=Days, 3=Triads to be averaged), and the value under they keys is a list or numpy array of diagonals to be averaged incoherently. These axes-diagonal combinations apply to both the inputs xcpdps and excpdps, except axis=2 does not apply to excpdps (since it is made of subsample differences already) and will be skipped. Outputs: A tuple consisting of two dictionaries. The first dictionary contains the incoherent averaging of xcpdps as specified by the inputs, while the second consists of incoherent of excpdps as specified by the inputs. The structure of these dictionaries are practically the same as the dictionary inputs xcpdps and excpdps respectively. The only differences in dictionary structure are: * Under key ['oversampled'/'resampled']['whole'/'submodel'/'residual' /'effinfo']['mean'/'median'] is a list of numpy arrays, where each array in the list corresponds to the dictionary in the list in input diagoffsets that defines the axes-diagonal combination. ---------------------------------------------------------------------------- """ if isinstance(xcpdps, dict): xcpdps = [xcpdps] if not isinstance(xcpdps, list): raise TypeError('Invalid data type provided for input xcpdps') if excpdps is not None: if isinstance(excpdps, dict): excpdps = [excpdps] if not isinstance(excpdps, list): raise TypeError('Invalid data type provided for input excpdps') if len(xcpdps) != len(excpdps): raise ValueError('Inputs xcpdps and excpdps found to have unequal number of values') out_xcpdps = {'triads': xcpdps[0]['triads'], 'triads_ind': xcpdps[0]['triads_ind'], 'lst': xcpdps[0]['lst'], 'lst_ind': xcpdps[0]['lst_ind'], 'dlst': xcpdps[0]['dlst'], 'days': xcpdps[0]['days'], 'day_ind': xcpdps[0]['day_ind'], 'dday': xcpdps[0]['dday']} out_excpdps = None if excpdps is not None: out_excpdps = {'triads': excpdps[0]['triads'], 'triads_ind': excpdps[0]['triads_ind'], 'lst': excpdps[0]['lst'], 'lst_ind': excpdps[0]['lst_ind'], 'dlst': excpdps[0]['dlst'], 'days': excpdps[0]['days'], 'day_ind': excpdps[0]['day_ind'], 'dday': excpdps[0]['dday']} for smplng in ['oversampled', 'resampled']: if smplng in xcpdps[0]: out_xcpdps[smplng] = {'z': xcpdps[0][smplng]['z'], 'kprll': xcpdps[0][smplng]['kprll'], 'lags': xcpdps[0][smplng]['lags'], 'freq_center': xcpdps[0][smplng]['freq_center'], 'bw_eff': xcpdps[0][smplng]['bw_eff'], 'shape': xcpdps[0][smplng]['shape'], 'freq_wts': xcpdps[0][smplng]['freq_wts'], 'lag_corr_length': xcpdps[0][smplng]['lag_corr_length']} if excpdps is not None: out_excpdps[smplng] = {'z': excpdps[0][smplng]['z'], 'kprll': excpdps[0][smplng]['kprll'], 'lags': excpdps[0][smplng]['lags'], 'freq_center': excpdps[0][smplng]['freq_center'], 'bw_eff': excpdps[0][smplng]['bw_eff'], 'shape': excpdps[0][smplng]['shape'], 'freq_wts': excpdps[0][smplng]['freq_wts'], 'lag_corr_length': excpdps[0][smplng]['lag_corr_length']} for dpool in ['whole', 'submodel', 'residual']: if dpool in xcpdps[0][smplng]: out_xcpdps[smplng][dpool] = {'diagoffsets': xcpdps[0][smplng][dpool]['diagoffsets'], 'axesmap': xcpdps[0][smplng][dpool]['axesmap']} for stat in ['mean', 'median']: if stat in xcpdps[0][smplng][dpool]: out_xcpdps[smplng][dpool][stat] = {} arr = [] diagweights = [] for i in range(len(xcpdps)): arr += [xcpdps[i][smplng][dpool][stat].si.value] arr_units = xcpdps[i][smplng][dpool][stat].si.unit if isinstance(xcpdps[i][smplng][dpool]['diagweights'], dict): diagwts = 1.0 diagwts_shape = NP.ones(xcpdps[i][smplng][dpool][stat].ndim, dtype=NP.int) for ax in xcpdps[i][smplng][dpool]['diagweights']: tmp_shape = NP.copy(diagwts_shape) tmp_shape[xcpdps[i][smplng][dpool]['axesmap'][ax]] = xcpdps[i][smplng][dpool]['diagweights'][ax].size diagwts = diagwts * xcpdps[i][smplng][dpool]['diagweights'][ax].reshape(tuple(tmp_shape)) elif isinstance(xcpdps[i][smplng][dpool]['diagweights'], NP.ndarray): diagwts = NP.copy(xcpdps[i][smplng][dpool]['diagweights']) else: raise TypeError('Diagonal weights in input must be a dictionary or a numpy array') diagweights += [diagwts] diagweights = NP.asarray(diagweights) arr = NP.asarray(arr) arr = NP.nansum(arr * diagweights, axis=0) / NP.nansum(diagweights, axis=0) * arr_units diagweights = NP.nansum(diagweights, axis=0) out_xcpdps[smplng][dpool][stat] = arr out_xcpdps[smplng][dpool]['diagweights'] = diagweights for dpool in ['errinfo']: if dpool in excpdps[0][smplng]: out_excpdps[smplng][dpool] = {'diagoffsets': excpdps[0][smplng][dpool]['diagoffsets'], 'axesmap': excpdps[0][smplng][dpool]['axesmap']} for stat in ['mean', 'median']: if stat in excpdps[0][smplng][dpool]: out_excpdps[smplng][dpool][stat] = {} arr = [] diagweights = [] for i in range(len(excpdps)): arr += [excpdps[i][smplng][dpool][stat].si.value] arr_units = excpdps[i][smplng][dpool][stat].si.unit if isinstance(excpdps[i][smplng][dpool]['diagweights'], dict): diagwts = 1.0 diagwts_shape = NP.ones(excpdps[i][smplng][dpool][stat].ndim, dtype=NP.int) for ax in excpdps[i][smplng][dpool]['diagweights']: tmp_shape = NP.copy(diagwts_shape) tmp_shape[excpdps[i][smplng][dpool]['axesmap'][ax]] = excpdps[i][smplng][dpool]['diagweights'][ax].size diagwts = diagwts * excpdps[i][smplng][dpool]['diagweights'][ax].reshape(tuple(tmp_shape)) elif isinstance(excpdps[i][smplng][dpool]['diagweights'], NP.ndarray): diagwts = NP.copy(excpdps[i][smplng][dpool]['diagweights']) else: raise TypeError('Diagonal weights in input must be a dictionary or a numpy array') diagweights += [diagwts] diagweights = NP.asarray(diagweights) arr = NP.asarray(arr) arr = NP.nansum(arr * diagweights, axis=0) / NP.nansum(diagweights, axis=0) * arr_units diagweights = NP.nansum(diagweights, axis=0) out_excpdps[smplng][dpool][stat] = arr out_excpdps[smplng][dpool]['diagweights'] = diagweights if diagoffsets is not None: if isinstance(diagoffsets, dict): diagoffsets = [diagoffsets] if not isinstance(diagoffsets, list): raise TypeError('Input diagoffsets must be a list of dictionaries') for ind in range(len(diagoffsets)): for ax in diagoffsets[ind]: if not isinstance(diagoffsets[ind][ax], (list, NP.ndarray)): raise TypeError('Values in input dictionary diagoffsets must be a list or numpy array') diagoffsets[ind][ax] = NP.asarray(diagoffsets[ind][ax]) for smplng in ['oversampled', 'resampled']: if smplng in out_xcpdps: for dpool in ['whole', 'submodel', 'residual']: if dpool in out_xcpdps[smplng]: masks = [] for ind in range(len(diagoffsets)): mask_ones = NP.ones(out_xcpdps[smplng][dpool]['diagweights'].shape, dtype=NP.bool) mask_agg = None for ax in diagoffsets[ind]: mltdim_slice = [slice(None)] * mask_ones.ndim mltdim_slice[out_xcpdps[smplng][dpool]['axesmap'][ax].squeeze()] = NP.where(NP.isin(out_xcpdps[smplng][dpool]['diagoffsets'][ax], diagoffsets[ind][ax]))[0] mask_tmp = NP.copy(mask_ones) mask_tmp[tuple(mltdim_slice)] = False if mask_agg is None: mask_agg = NP.copy(mask_tmp) else: mask_agg = NP.logical_or(mask_agg, mask_tmp) masks += [NP.copy(mask_agg)] diagwts = NP.copy(out_xcpdps[smplng][dpool]['diagweights']) out_xcpdps[smplng][dpool]['diagweights'] = [] for stat in ['mean', 'median']: if stat in out_xcpdps[smplng][dpool]: arr = NP.copy(out_xcpdps[smplng][dpool][stat].si.value) arr_units = out_xcpdps[smplng][dpool][stat].si.unit out_xcpdps[smplng][dpool][stat] = [] for ind in range(len(diagoffsets)): masked_diagwts = MA.array(diagwts, mask=masks[ind]) axes_to_avg = tuple([out_xcpdps[smplng][dpool]['axesmap'][ax][0] for ax in diagoffsets[ind]]) out_xcpdps[smplng][dpool][stat] += [MA.sum(arr * masked_diagwts, axis=axes_to_avg, keepdims=True) / MA.sum(masked_diagwts, axis=axes_to_avg, keepdims=True) * arr_units] if len(out_xcpdps[smplng][dpool]['diagweights']) < len(diagoffsets): out_xcpdps[smplng][dpool]['diagweights'] += [MA.sum(masked_diagwts, axis=axes_to_avg, keepdims=True)] if excpdps is not None: for smplng in ['oversampled', 'resampled']: if smplng in out_excpdps: for dpool in ['errinfo']: if dpool in out_excpdps[smplng]: masks = [] for ind in range(len(diagoffsets)): mask_ones = NP.ones(out_excpdps[smplng][dpool]['diagweights'].shape, dtype=NP.bool) mask_agg = None for ax in diagoffsets[ind]: if ax != 2: mltdim_slice = [slice(None)] * mask_ones.ndim mltdim_slice[out_excpdps[smplng][dpool]['axesmap'][ax].squeeze()] = NP.where(NP.isin(out_excpdps[smplng][dpool]['diagoffsets'][ax], diagoffsets[ind][ax]))[0] mask_tmp = NP.copy(mask_ones) mask_tmp[tuple(mltdim_slice)] = False if mask_agg is None: mask_agg = NP.copy(mask_tmp) else: mask_agg = NP.logical_or(mask_agg, mask_tmp) masks += [NP.copy(mask_agg)] diagwts = NP.copy(out_excpdps[smplng][dpool]['diagweights']) out_excpdps[smplng][dpool]['diagweights'] = [] for stat in ['mean', 'median']: if stat in out_excpdps[smplng][dpool]: arr = NP.copy(out_excpdps[smplng][dpool][stat].si.value) arr_units = out_excpdps[smplng][dpool][stat].si.unit out_excpdps[smplng][dpool][stat] = [] for ind in range(len(diagoffsets)): masked_diagwts = MA.array(diagwts, mask=masks[ind]) axes_to_avg = tuple([out_excpdps[smplng][dpool]['axesmap'][ax][0] for ax in diagoffsets[ind] if ax!=2]) out_excpdps[smplng][dpool][stat] += [MA.sum(arr * masked_diagwts, axis=axes_to_avg, keepdims=True) / MA.sum(masked_diagwts, axis=axes_to_avg, keepdims=True) * arr_units] if len(out_excpdps[smplng][dpool]['diagweights']) < len(diagoffsets): out_excpdps[smplng][dpool]['diagweights'] += [MA.sum(masked_diagwts, axis=axes_to_avg, keepdims=True)] return (out_xcpdps, out_excpdps) ################################################################################ def incoherent_kbin_averaging(xcpdps, kbins=None, num_kbins=None, kbintype='log'): """ ---------------------------------------------------------------------------- Averages the power spectrum incoherently by binning in bins of k. Returns the power spectrum in units of both standard power spectrum and \Delta^2 Inputs: xcpdps [dictionary] A dictionary that contains the incoherent averaged power spectrum along LST and/or triads axes. This dictionary is essentially the one(s) returned as the output of the function incoherent_cross_power_spectrum_average() kbins [NoneType, list or numpy array] Bins in k. If set to None (default), it will be determined automatically based on the inputs in num_kbins, and kbintype. If num_kbins is None and kbintype='linear', the negative and positive values of k are folded into a one-sided power spectrum. In this case, the bins will approximately have the same resolution as the k-values in the input power spectrum for all the spectral windows. num_kbins [NoneType or integer] Number of k-bins. Used only if kbins is set to None. If kbintype is set to 'linear', the negative and positive values of k are folded into a one-sided power spectrum. In this case, the bins will approximately have the same resolution as the k-values in the input power spectrum for all the spectral windows. kbintype [string] Specifies the type of binning, used only if kbins is set to None. Accepted values are 'linear' and 'log' for linear and logarithmic bins respectively. Outputs: Dictionary containing the power spectrum information. At the top level, it contains keys specifying the sampling to be 'oversampled' or 'resampled'. Under each of these keys is another dictionary containing the following keys: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,). 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains 3 keys named 'whole', 'submodel', and 'residual' or one key named 'errinfo' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. 'errinfo' contains power spectrum information about the subsample differences. There is also another dictionary under key 'kbininfo' that contains information about k-bins. These dictionaries contain the following keys and values: 'whole'/'submodel'/'residual'/'errinfo' [dictionary] It contains the following keys and values: 'mean' [dictionary] Delay power spectrum information under the 'mean' statistic incoherently obtained by averaging the input power spectrum in bins of k. It contains output power spectrum expressed as two quantities each of which is a dictionary with the following key-value pairs: 'PS' [list of numpy arrays] Standard power spectrum in units of 'K2 Mpc3'. Each numpy array in the list maps to a specific combination of axes and axis diagonals chosen for incoherent averaging in earlier processing such as in the function incoherent_cross_power_spectrum_average(). The numpy array has a shape similar to the input power spectrum, but that last axis (k-axis) will have a different size that depends on the k-bins that were used in the incoherent averaging along that axis. 'Del2' [list of numpy arrays] power spectrum in Delta^2 units of 'K2'. Each numpy array in the list maps to a specific combination of axes and axis diagonals chosen for incoherent averaging in earlier processing such as in the function incoherent_cross_power_spectrum_average(). The numpy array has a shape similar to the input power spectrum, but that last axis (k-axis) will have a different size that depends on the k-bins that were used in the incoherent averaging along that axis. 'median' [dictionary] Delay power spectrum information under the 'median' statistic incoherently obtained by averaging the input power spectrum in bins of k. It contains output power spectrum expressed as two quantities each of which is a dictionary with the following key-value pairs: 'PS' [list of numpy arrays] Standard power spectrum in units of 'K2 Mpc3'. Each numpy array in the list maps to a specific combination of axes and axis diagonals chosen for incoherent averaging in earlier processing such as in the function incoherent_cross_power_spectrum_average(). The numpy array has a shape similar to the input power spectrum, but that last axis (k-axis) will have a different size that depends on the k-bins that were used in the incoherent averaging along that axis. 'Del2' [list of numpy arrays] power spectrum in Delta^2 units of 'K2'. Each numpy array in the list maps to a specific combination of axes and axis diagonals chosen for incoherent averaging in earlier processing such as in the function incoherent_cross_power_spectrum_average(). The numpy array has a shape similar to the input power spectrum, but that last axis (k-axis) will have a different size that depends on the k-bins that were used in the incoherent averaging along that axis. 'kbininfo' [dictionary] Contains the k-bin information. It contains the following key-value pairs: 'counts' [list] List of numpy arrays where each numpy array in the stores the counts in the determined k-bins. Each numpy array in the list corresponds to a spectral window (redshift subband). The shape of each numpy array is (nkbins,) 'kbin_edges' [list] List of numpy arrays where each numpy array contains the k-bin edges. Each array in the list corresponds to a spectral window (redshift subband). The shape of each array is (nkbins+1,). 'kbinnum' [list] List of numpy arrays containing the bin number under which the k value falls. Each array in the list corresponds to a spectral window (redshift subband). The shape of each array is (nlags,). 'ri' [list] List of numpy arrays containing the reverse indices for each k-bin. Each array in the list corresponds to a spectral window (redshift subband). The shape of each array is (nlags+nkbins+1,). 'whole'/'submodel'/'residual' or 'errinfo' [dictionary] k-bin info estimated for the different datapools under different stats and PS definitions. It has the keys 'mean' and 'median' for the mean and median statistic respectively. Each of them contain a dictionary with the following key-value pairs: 'PS' [list] List of numpy arrays where each numpy array contains a standard power spectrum typically in units of 'K2 Mpc3'. Its shape is the same as input power spectrum except the k-axis which now has nkbins number of elements. 'Del2' [list] List of numpy arrays where each numpy array contains a Delta^2 power spectrum typically in units of 'K2'. Its shape is the same as input power spectrum except the k-axis which now has nkbins number of elements. ---------------------------------------------------------------------------- """ if not isinstance(xcpdps, dict): raise TypeError('Input xcpdps must be a dictionary') if kbins is not None: if not isinstance(kbins, (list,NP.ndarray)): raise TypeError('Input kbins must be a list or numpy array') else: if not isinstance(kbintype, str): raise TypeError('Input kbintype must be a string') if kbintype.lower() not in ['linear', 'log']: raise ValueError('Input kbintype must be set to "linear" or "log"') if kbintype.lower() == 'log': if num_kbins is None: num_kbins = 10 psinfo = {} keys = ['triads', 'triads_ind', 'lst', 'lst_ind', 'dlst', 'days', 'day_ind', 'dday'] for key in keys: psinfo[key] = xcpdps[key] sampling = ['oversampled', 'resampled'] sampling_keys = ['z', 'freq_center', 'bw_eff', 'shape', 'freq_wts', 'lag_corr_length'] dpool_keys = ['whole', 'submodel', 'residual', 'errinfo'] for smplng in sampling: if smplng in xcpdps: psinfo[smplng] = {} for key in sampling_keys: psinfo[smplng][key] = xcpdps[smplng][key] kprll = xcpdps[smplng]['kprll'] lags = xcpdps[smplng]['lags'] eps = 1e-10 if kbins is None: dkprll = NP.max(NP.mean(NP.diff(kprll, axis=-1), axis=-1)) if kbintype.lower() == 'linear': bins_kprll = NP.linspace(eps, NP.abs(kprll).max()+eps, num=kprll.shape[1]/2+1, endpoint=True) else: bins_kprll = NP.geomspace(eps, NP.abs(kprll).max()+eps, num=num_kbins+1, endpoint=True) bins_kprll = NP.insert(bins_kprll, 0, -eps) else: bins_kprll = NP.asarray(kbins) num_kbins = bins_kprll.size - 1 psinfo[smplng]['kbininfo'] = {'counts': [], 'kbin_edges': [], 'kbinnum': [], 'ri': []} for spw in range(kprll.shape[0]): counts, kbin_edges, kbinnum, ri = OPS.binned_statistic(NP.abs(kprll[spw,:]), statistic='count', bins=bins_kprll) counts = counts.astype(NP.int) psinfo[smplng]['kbininfo']['counts'] += [NP.copy(counts)] psinfo[smplng]['kbininfo']['kbin_edges'] += [kbin_edges / U.Mpc] psinfo[smplng]['kbininfo']['kbinnum'] += [NP.copy(kbinnum)] psinfo[smplng]['kbininfo']['ri'] += [NP.copy(ri)] for dpool in dpool_keys: if dpool in xcpdps[smplng]: psinfo[smplng][dpool] = {} psinfo[smplng]['kbininfo'][dpool] = {} keys = ['diagoffsets', 'diagweights', 'axesmap'] for key in keys: psinfo[smplng][dpool][key] = xcpdps[smplng][dpool][key] for stat in ['mean', 'median']: if stat in xcpdps[smplng][dpool]: psinfo[smplng][dpool][stat] = {'PS': [], 'Del2': []} psinfo[smplng]['kbininfo'][dpool][stat] = [] for combi in range(len(xcpdps[smplng][dpool][stat])): outshape = NP.asarray(xcpdps[smplng][dpool][stat][combi].shape) outshape[-1] = num_kbins tmp_dps = NP.full(tuple(outshape), NP.nan, dtype=NP.complex) * U.Unit(xcpdps[smplng][dpool][stat][combi].unit) tmp_Del2 = NP.full(tuple(outshape), NP.nan, dtype=NP.complex) * U.Unit(xcpdps[smplng][dpool][stat][combi].unit / U.Mpc**3) tmp_kprll = NP.full(tuple(outshape), NP.nan, dtype=NP.float) / U.Mpc for spw in range(kprll.shape[0]): counts = NP.copy(psinfo[smplng]['kbininfo']['counts'][spw]) ri = NP.copy(psinfo[smplng]['kbininfo']['ri'][spw]) print('Processing datapool={0}, stat={1}, LST-Day-Triad combination={2:0d}, spw={3:0d}...'.format(dpool, stat, combi, spw)) progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} k-bins '.format(num_kbins), PGB.ETA()], maxval=num_kbins).start() for binnum in range(num_kbins): if counts[binnum] > 0: ind_kbin = ri[ri[binnum]:ri[binnum+1]] tmp_dps[spw,...,binnum] = NP.nanmean(NP.take(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1), axis=-1) k_shape = NP.ones(NP.take(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1).ndim, dtype=NP.int) k_shape[-1] = -1 tmp_Del2[spw,...,binnum] = NP.nanmean(NP.abs(kprll[spw,ind_kbin].reshape(tuple(k_shape))/U.Mpc)**3 * NP.take(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1), axis=-1) / (2*NP.pi**2) tmp_kprll[spw,...,binnum] = NP.nansum(NP.abs(kprll[spw,ind_kbin].reshape(tuple(k_shape))/U.Mpc) * NP.abs(NP.take(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1)), axis=-1) / NP.nansum(NP.abs(NP.take(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1)), axis=-1) progress.update(binnum+1) progress.finish() psinfo[smplng][dpool][stat]['PS'] += [copy.deepcopy(tmp_dps)] psinfo[smplng][dpool][stat]['Del2'] += [copy.deepcopy(tmp_Del2)] psinfo[smplng]['kbininfo'][dpool][stat] += [copy.deepcopy(tmp_kprll)] return psinfo ################################################################################ class ClosurePhase(object): """ ---------------------------------------------------------------------------- Class to hold and operate on Closure Phase information. It has the following attributes and member functions. Attributes: extfile [string] Full path to external file containing information of ClosurePhase instance. The file is in HDF5 format cpinfo [dictionary] Contains the following top level keys, namely, 'raw', 'processed', and 'errinfo' Under key 'raw' which holds a dictionary, the subkeys include 'cphase' (nlst,ndays,ntriads,nchan), 'triads' (ntriads,3), 'lst' (nlst,ndays), and 'flags' (nlst,ndays,ntriads,nchan). Under the 'processed' key are more subkeys, namely, 'native', 'prelim', and optionally 'submodel' and 'residual' each holding a dictionary. Under 'native' dictionary, the subsubkeys for further dictionaries are 'cphase' (masked array: (nlst,ndays,ntriads,nchan)), 'eicp' (complex masked array: (nlst,ndays,ntriads,nchan)), and 'wts' (masked array: (nlst,ndays,ntriads,nchan)). Under 'prelim' dictionary, the subsubkeys for further dictionaries are 'tbins' (numpy array of tbin centers after smoothing), 'dtbins' (numpy array of tbin intervals), 'wts' (masked array: (ntbins,ndays,ntriads,nchan)), 'eicp' and 'cphase'. The dictionaries under 'eicp' are indexed by keys 'mean' (complex masked array: (ntbins,ndays,ntriads,nchan)), and 'median' (complex masked array: (ntbins,ndays,ntriads,nchan)). The dictionaries under 'cphase' are indexed by keys 'mean' (masked array: (ntbins,ndays,ntriads,nchan)), 'median' (masked array: (ntbins,ndays,ntriads,nchan)), 'rms' (masked array: (ntbins,ndays,ntriads,nchan)), and 'mad' (masked array: (ntbins,ndays,ntriads,nchan)). The last one denotes Median Absolute Deviation. Under 'submodel' dictionary, the subsubkeys for further dictionaries are 'cphase' (masked array: (nlst,ndays,ntriads,nchan)), and 'eicp' (complex masked array: (nlst,ndays,ntriads,nchan)). Under 'residual' dictionary, the subsubkeys for further dictionaries are 'cphase' and 'eicp'. These are dictionaries too. The dictionaries under 'eicp' are indexed by keys 'mean' (complex masked array: (ntbins,ndays,ntriads,nchan)), and 'median' (complex masked array: (ntbins,ndays,ntriads,nchan)). The dictionaries under 'cphase' are indexed by keys 'mean' (masked array: (ntbins,ndays,ntriads,nchan)), and 'median' (masked array: (ntbins,ndays,ntriads,nchan)). Under key 'errinfo', it contains the following keys and values: 'list_of_pair_of_pairs' List of pair of pairs for which differences of complex exponentials have been computed, where the elements are bins of days. The number of elements in the list is ncomb. And each element is a smaller (4-element) list of pair of pairs 'eicp_diff' Difference of complex exponentials between pairs of day bins. This will be used in evaluating noise properties in power spectrum. It is a dictionary with two keys '0' and '1' where each contains the difference from a pair of subsamples. Each of these keys contains a numpy array of shape (nlstbins,ncomb,2,ntriads,nchan) 'wts' Weights in difference of complex exponentials obtained by sum of squares of weights that are associated with the pair that was used in the differencing. It is a dictionary with two keys '0' and '1' where each contains the weights associated It is of shape (nlstbins,ncomb,2,ntriads,nchan) Member functions: __init__() Initialize an instance of class ClosurePhase expicp() Compute and return complex exponential of the closure phase as a masked array smooth_in_tbins() Smooth the complex exponentials of closure phases in LST bins. Both mean and median smoothing is produced. subtract() Subtract complex exponential of the bispectrum phase from the current instance and updates the cpinfo attribute subsample_differencing() Create subsamples and differences between subsamples to evaluate noise properties from the data set. save() Save contents of attribute cpinfo in external HDF5 file ---------------------------------------------------------------------------- """ def __init__(self, infile, freqs, infmt='npz'): """ ------------------------------------------------------------------------ Initialize an instance of class ClosurePhase Inputs: infile [string] Input file including full path. It could be a NPZ with raw data, or a HDF5 file that could contain raw or processed data. The input file format is specified in the input infmt. If it is a NPZ file, it must contain the following keys/files: 'closures' [numpy array] Closure phase (radians). It is of shape (nlst,ndays,ntriads,nchan) 'triads' [numpy array] Array of triad tuples, of shape (ntriads,3) 'flags' [numpy array] Array of flags (boolean), of shape (nlst,ndays,ntriads,nchan) 'last' [numpy array] Array of LST for each day (CASA units which is MJD+6713). Shape is (nlst,ndays) 'days' [numpy array] Array of days, shape is (ndays,) 'averaged_closures' [numpy array] optional array of closure phases averaged across days. Shape is (nlst,ntriads,nchan) 'std_dev_lst' [numpy array] optional array of standard deviation of closure phases across days. Shape is (nlst,ntriads,nchan) 'std_dev_triads' [numpy array] optional array of standard deviation of closure phases across triads. Shape is (nlst,ndays,nchan) freqs [numpy array] Frequencies (in Hz) in the input. Size is nchan. infmt [string] Input file format. Accepted values are 'npz' (default) and 'hdf5'. ------------------------------------------------------------------------ """ if not isinstance(infile, str): raise TypeError('Input infile must be a string') if not isinstance(freqs, NP.ndarray): raise TypeError('Input freqs must be a numpy array') freqs = freqs.ravel() if not isinstance(infmt, str): raise TypeError('Input infmt must be a string') if infmt.lower() not in ['npz', 'hdf5']: raise ValueError('Input infmt must be "npz" or "hdf5"') if infmt.lower() == 'npz': infilesplit = infile.split('.npz') infile_noext = infilesplit[0] self.cpinfo = loadnpz(infile) # npz2hdf5(infile, infile_noext+'.hdf5') self.extfile = infile_noext + '.hdf5' else: # if not isinstance(infile, h5py.File): # raise TypeError('Input infile is not a valid HDF5 file') self.extfile = infile self.cpinfo = NMO.load_dict_from_hdf5(self.extfile) if freqs.size != self.cpinfo['raw']['cphase'].shape[-1]: raise ValueError('Input frequencies do not match with dimensions of the closure phase data') self.f = freqs self.df = freqs[1] - freqs[0] force_expicp = False if 'processed' not in self.cpinfo: force_expicp = True else: if 'native' not in self.cpinfo['processed']: force_expicp = True self.expicp(force_action=force_expicp) if 'prelim' not in self.cpinfo['processed']: self.cpinfo['processed']['prelim'] = {} self.cpinfo['errinfo'] = {} ############################################################################ def expicp(self, force_action=False): """ ------------------------------------------------------------------------ Compute the complex exponential of the closure phase as a masked array Inputs: force_action [boolean] If set to False (default), the complex exponential is computed only if it has not been done so already. Otherwise the computation is forced. ------------------------------------------------------------------------ """ if 'processed' not in self.cpinfo: self.cpinfo['processed'] = {} force_action = True if 'native' not in self.cpinfo['processed']: self.cpinfo['processed']['native'] = {} force_action = True if 'cphase' not in self.cpinfo['processed']['native']: self.cpinfo['processed']['native']['cphase'] = MA.array(self.cpinfo['raw']['cphase'].astype(NP.float64), mask=self.cpinfo['raw']['flags']) force_action = True if not force_action: if 'eicp' not in self.cpinfo['processed']['native']: self.cpinfo['processed']['native']['eicp'] = NP.exp(1j * self.cpinfo['processed']['native']['cphase']) self.cpinfo['processed']['native']['wts'] = MA.array(NP.logical_not(self.cpinfo['raw']['flags']).astype(NP.float), mask=self.cpinfo['raw']['flags']) else: self.cpinfo['processed']['native']['eicp'] = NP.exp(1j * self.cpinfo['processed']['native']['cphase']) self.cpinfo['processed']['native']['wts'] = MA.array(NP.logical_not(self.cpinfo['raw']['flags']).astype(NP.float), mask=self.cpinfo['raw']['flags']) ############################################################################ def smooth_in_tbins(self, daybinsize=None, ndaybins=None, lstbinsize=None): """ ------------------------------------------------------------------------ Smooth the complex exponentials of closure phases in time bins. Both mean and median smoothing is produced. Inputs: daybinsize [Nonetype or scalar] Day bin size (in days) over which mean and median are estimated across different days for a fixed LST bin. If set to None, it will look for value in input ndaybins. If both are None, no smoothing is performed. Only one of daybinsize or ndaybins must be set to non-None value. ndaybins [NoneType or integer] Number of bins along day axis. Only if daybinsize is set to None. It produces bins that roughly consist of equal number of days in each bin regardless of how much the days in each bin are separated from each other. If both are None, no smoothing is performed. Only one of daybinsize or ndaybins must be set to non-None value. lstbinsize [NoneType or scalar] LST bin size (in seconds) over which mean and median are estimated across the LST. If set to None, no smoothing is performed ------------------------------------------------------------------------ """ if (ndaybins is not None) and (daybinsize is not None): raise ValueError('Only one of daybinsize or ndaybins should be set') if (daybinsize is not None) or (ndaybins is not None): if daybinsize is not None: if not isinstance(daybinsize, (int,float)): raise TypeError('Input daybinsize must be a scalar') dres = NP.diff(self.cpinfo['raw']['days']).min() # in days dextent = self.cpinfo['raw']['days'].max() - self.cpinfo['raw']['days'].min() + dres # in days if daybinsize > dres: daybinsize = NP.clip(daybinsize, dres, dextent) eps = 1e-10 daybins = NP.arange(self.cpinfo['raw']['days'].min(), self.cpinfo['raw']['days'].max() + dres + eps, daybinsize) ndaybins = daybins.size daybins = NP.concatenate((daybins, [daybins[-1]+daybinsize+eps])) if ndaybins > 1: daybinintervals = daybins[1:] - daybins[:-1] daybincenters = daybins[:-1] + 0.5 * daybinintervals else: daybinintervals = NP.asarray(daybinsize).reshape(-1) daybincenters = daybins[0] + 0.5 * daybinintervals counts, daybin_edges, daybinnum, ri = OPS.binned_statistic(self.cpinfo['raw']['days'], statistic='count', bins=daybins) counts = counts.astype(NP.int) # if 'prelim' not in self.cpinfo['processed']: # self.cpinfo['processed']['prelim'] = {} # self.cpinfo['processed']['prelim']['eicp'] = {} # self.cpinfo['processed']['prelim']['cphase'] = {} # self.cpinfo['processed']['prelim']['daybins'] = daybincenters # self.cpinfo['processed']['prelim']['diff_dbins'] = daybinintervals wts_daybins = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3])) eicp_dmean = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3]), dtype=NP.complex128) eicp_dmedian = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3]), dtype=NP.complex128) cp_drms = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3])) cp_dmad = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3])) for binnum in xrange(counts.size): ind_daybin = ri[ri[binnum]:ri[binnum+1]] wts_daybins[:,binnum,:,:] = NP.sum(self.cpinfo['processed']['native']['wts'][:,ind_daybin,:,:].data, axis=1) eicp_dmean[:,binnum,:,:] = NP.exp(1j*NP.angle(MA.mean(self.cpinfo['processed']['native']['eicp'][:,ind_daybin,:,:], axis=1))) eicp_dmedian[:,binnum,:,:] = NP.exp(1j*NP.angle(MA.median(self.cpinfo['processed']['native']['eicp'][:,ind_daybin,:,:].real, axis=1) + 1j * MA.median(self.cpinfo['processed']['native']['eicp'][:,ind_daybin,:,:].imag, axis=1))) cp_drms[:,binnum,:,:] = MA.std(self.cpinfo['processed']['native']['cphase'][:,ind_daybin,:,:], axis=1).data cp_dmad[:,binnum,:,:] = MA.median(NP.abs(self.cpinfo['processed']['native']['cphase'][:,ind_daybin,:,:] - NP.angle(eicp_dmedian[:,binnum,:,:][:,NP.newaxis,:,:])), axis=1).data # mask = wts_daybins <= 0.0 # self.cpinfo['processed']['prelim']['wts'] = MA.array(wts_daybins, mask=mask) # self.cpinfo['processed']['prelim']['eicp']['mean'] = MA.array(eicp_dmean, mask=mask) # self.cpinfo['processed']['prelim']['eicp']['median'] = MA.array(eicp_dmedian, mask=mask) # self.cpinfo['processed']['prelim']['cphase']['mean'] = MA.array(NP.angle(eicp_dmean), mask=mask) # self.cpinfo['processed']['prelim']['cphase']['median'] = MA.array(NP.angle(eicp_dmedian), mask=mask) # self.cpinfo['processed']['prelim']['cphase']['rms'] = MA.array(cp_drms, mask=mask) # self.cpinfo['processed']['prelim']['cphase']['mad'] = MA.array(cp_dmad, mask=mask) else: if not isinstance(ndaybins, int): raise TypeError('Input ndaybins must be an integer') if ndaybins <= 0: raise ValueError('Input ndaybins must be positive') days_split = NP.array_split(self.cpinfo['raw']['days'], ndaybins) daybincenters = NP.asarray([NP.mean(days) for days in days_split]) daybinintervals = NP.asarray([days.max()-days.min() for days in days_split]) counts = NP.asarray([days.size for days in days_split]) wts_split = NP.array_split(self.cpinfo['processed']['native']['wts'].data, ndaybins, axis=1) # mask_split = NP.array_split(self.cpinfo['processed']['native']['wts'].mask, ndaybins, axis=1) wts_daybins = NP.asarray([NP.sum(wtsitem, axis=1) for wtsitem in wts_split]) # ndaybins x nlst x ntriads x nchan wts_daybins = NP.moveaxis(wts_daybins, 0, 1) # nlst x ndaybins x ntriads x nchan mask_split = NP.array_split(self.cpinfo['processed']['native']['eicp'].mask, ndaybins, axis=1) eicp_split = NP.array_split(self.cpinfo['processed']['native']['eicp'].data, ndaybins, axis=1) eicp_dmean = MA.array([MA.mean(MA.array(eicp_split[i], mask=mask_split[i]), axis=1) for i in range(daybincenters.size)]) # ndaybins x nlst x ntriads x nchan eicp_dmean = NP.exp(1j * NP.angle(eicp_dmean)) eicp_dmean = NP.moveaxis(eicp_dmean, 0, 1) # nlst x ndaybins x ntriads x nchan eicp_dmedian = MA.array([MA.median(MA.array(eicp_split[i].real, mask=mask_split[i]), axis=1) + 1j * MA.median(MA.array(eicp_split[i].imag, mask=mask_split[i]), axis=1) for i in range(daybincenters.size)]) # ndaybins x nlst x ntriads x nchan eicp_dmedian = NP.exp(1j * NP.angle(eicp_dmedian)) eicp_dmedian = NP.moveaxis(eicp_dmedian, 0, 1) # nlst x ndaybins x ntriads x nchan cp_split = NP.array_split(self.cpinfo['processed']['native']['cphase'].data, ndaybins, axis=1) cp_drms = NP.array([MA.std(MA.array(cp_split[i], mask=mask_split[i]), axis=1).data for i in range(daybincenters.size)]) # ndaybins x nlst x ntriads x nchan cp_drms = NP.moveaxis(cp_drms, 0, 1) # nlst x ndaybins x ntriads x nchan cp_dmad = NP.array([MA.median(NP.abs(cp_split[i] - NP.angle(eicp_dmedian[:,[i],:,:])), axis=1).data for i in range(daybincenters.size)]) # ndaybins x nlst x ntriads x nchan cp_dmad = NP.moveaxis(cp_dmad, 0, 1) # nlst x ndaybins x ntriads x nchan if 'prelim' not in self.cpinfo['processed']: self.cpinfo['processed']['prelim'] = {} self.cpinfo['processed']['prelim']['eicp'] = {} self.cpinfo['processed']['prelim']['cphase'] = {} self.cpinfo['processed']['prelim']['daybins'] = daybincenters self.cpinfo['processed']['prelim']['diff_dbins'] = daybinintervals mask = wts_daybins <= 0.0 self.cpinfo['processed']['prelim']['wts'] = MA.array(wts_daybins, mask=mask) self.cpinfo['processed']['prelim']['eicp']['mean'] = MA.array(eicp_dmean, mask=mask) self.cpinfo['processed']['prelim']['eicp']['median'] = MA.array(eicp_dmedian, mask=mask) self.cpinfo['processed']['prelim']['cphase']['mean'] = MA.array(NP.angle(eicp_dmean), mask=mask) self.cpinfo['processed']['prelim']['cphase']['median'] = MA.array(NP.angle(eicp_dmedian), mask=mask) self.cpinfo['processed']['prelim']['cphase']['rms'] = MA.array(cp_drms, mask=mask) self.cpinfo['processed']['prelim']['cphase']['mad'] = MA.array(cp_dmad, mask=mask) rawlst = NP.degrees(NP.unwrap(NP.radians(self.cpinfo['raw']['lst'] * 15.0), discont=NP.pi, axis=0)) / 15.0 # in hours but unwrapped to have no discontinuities if NP.any(rawlst > 24.0): rawlst -= 24.0 if rawlst.shape[0] > 1: # LST bin only if there are multiple LST if lstbinsize is not None: if not isinstance(lstbinsize, (int,float)): raise TypeError('Input lstbinsize must be a scalar') lstbinsize = lstbinsize / 3.6e3 # in hours tres = NP.diff(rawlst[:,0]).min() # in hours textent = rawlst[:,0].max() - rawlst[:,0].min() + tres # in hours eps = 1e-10 if 'prelim' not in self.cpinfo['processed']: self.cpinfo['processed']['prelim'] = {} no_change_in_lstbins = False if lstbinsize > tres: lstbinsize = NP.clip(lstbinsize, tres, textent) lstbins = NP.arange(rawlst[:,0].min(), rawlst[:,0].max() + tres + eps, lstbinsize) nlstbins = lstbins.size lstbins = NP.concatenate((lstbins, [lstbins[-1]+lstbinsize+eps])) if nlstbins > 1: lstbinintervals = lstbins[1:] - lstbins[:-1] lstbincenters = lstbins[:-1] + 0.5 * lstbinintervals else: lstbinintervals = NP.asarray(lstbinsize).reshape(-1) lstbincenters = lstbins[0] + 0.5 * lstbinintervals self.cpinfo['processed']['prelim']['lstbins'] = lstbincenters self.cpinfo['processed']['prelim']['dlstbins'] = lstbinintervals no_change_in_lstbins = False else: # Perform no binning and keep the current LST resolution, data and weights warnings.warn('LST bin size found to be smaller than the LST resolution in the data. No LST binning/averaging will be performed.') lstbinsize = tres lstbins = NP.arange(rawlst[:,0].min(), rawlst[:,0].max() + lstbinsize + eps, lstbinsize) nlstbins = lstbins.size - 1 if nlstbins > 1: lstbinintervals = lstbins[1:] - lstbins[:-1] else: lstbinintervals = NP.asarray(lstbinsize).reshape(-1) self.cpinfo['processed']['prelim']['dlstbins'] = lstbinintervals self.cpinfo['processed']['prelim']['lstbins'] = lstbins[:-1] # Ensure that the LST bins are inside the min/max envelope to # error-free interpolation later self.cpinfo['processed']['prelim']['lstbins'][0] += eps self.cpinfo['processed']['prelim']['lstbins'][-1] -= eps no_change_in_lstbins = True counts, lstbin_edges, lstbinnum, ri = OPS.binned_statistic(rawlst[:,0], statistic='count', bins=lstbins) counts = counts.astype(NP.int) if 'wts' not in self.cpinfo['processed']['prelim']: outshape = (counts.size, self.cpinfo['processed']['native']['eicp'].shape[1], self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3]) else: outshape = (counts.size, self.cpinfo['processed']['prelim']['wts'].shape[1], self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3]) wts_lstbins = NP.zeros(outshape) eicp_tmean = NP.zeros(outshape, dtype=NP.complex128) eicp_tmedian = NP.zeros(outshape, dtype=NP.complex128) cp_trms = NP.zeros(outshape) cp_tmad = NP.zeros(outshape) for binnum in xrange(counts.size): if no_change_in_lstbins: ind_lstbin = [binnum] else: ind_lstbin = ri[ri[binnum]:ri[binnum+1]] if 'wts' not in self.cpinfo['processed']['prelim']: indict = self.cpinfo['processed']['native'] else: indict = self.cpinfo['processed']['prelim'] wts_lstbins[binnum,:,:,:] = NP.sum(indict['wts'][ind_lstbin,:,:,:].data, axis=0) if 'wts' not in self.cpinfo['processed']['prelim']: eicp_tmean[binnum,:,:,:] = NP.exp(1j*NP.angle(MA.mean(indict['eicp'][ind_lstbin,:,:,:], axis=0))) eicp_tmedian[binnum,:,:,:] = NP.exp(1j*NP.angle(MA.median(indict['eicp'][ind_lstbin,:,:,:].real, axis=0) + 1j * MA.median(self.cpinfo['processed']['native']['eicp'][ind_lstbin,:,:,:].imag, axis=0))) cp_trms[binnum,:,:,:] = MA.std(indict['cphase'][ind_lstbin,:,:,:], axis=0).data cp_tmad[binnum,:,:,:] = MA.median(NP.abs(indict['cphase'][ind_lstbin,:,:,:] - NP.angle(eicp_tmedian[binnum,:,:,:][NP.newaxis,:,:,:])), axis=0).data else: eicp_tmean[binnum,:,:,:] = NP.exp(1j*NP.angle(MA.mean(NP.exp(1j*indict['cphase']['mean'][ind_lstbin,:,:,:]), axis=0))) eicp_tmedian[binnum,:,:,:] = NP.exp(1j*NP.angle(MA.median(NP.cos(indict['cphase']['median'][ind_lstbin,:,:,:]), axis=0) + 1j * MA.median(NP.sin(indict['cphase']['median'][ind_lstbin,:,:,:]), axis=0))) cp_trms[binnum,:,:,:] = MA.std(indict['cphase']['mean'][ind_lstbin,:,:,:], axis=0).data cp_tmad[binnum,:,:,:] = MA.median(NP.abs(indict['cphase']['median'][ind_lstbin,:,:,:] - NP.angle(eicp_tmedian[binnum,:,:,:][NP.newaxis,:,:,:])), axis=0).data mask = wts_lstbins <= 0.0 self.cpinfo['processed']['prelim']['wts'] = MA.array(wts_lstbins, mask=mask) if 'eicp' not in self.cpinfo['processed']['prelim']: self.cpinfo['processed']['prelim']['eicp'] = {} if 'cphase' not in self.cpinfo['processed']['prelim']: self.cpinfo['processed']['prelim']['cphase'] = {} self.cpinfo['processed']['prelim']['eicp']['mean'] = MA.array(eicp_tmean, mask=mask) self.cpinfo['processed']['prelim']['eicp']['median'] = MA.array(eicp_tmedian, mask=mask) self.cpinfo['processed']['prelim']['cphase']['mean'] = MA.array(NP.angle(eicp_tmean), mask=mask) self.cpinfo['processed']['prelim']['cphase']['median'] = MA.array(NP.angle(eicp_tmedian), mask=mask) self.cpinfo['processed']['prelim']['cphase']['rms'] = MA.array(cp_trms, mask=mask) self.cpinfo['processed']['prelim']['cphase']['mad'] = MA.array(cp_tmad, mask=mask) # else: # # Perform no binning and keep the current LST resolution, data and weights # warnings.warn('LST bin size found to be smaller than the LST resolution in the data. No LST binning/averaging will be performed.') # lstbinsize = tres # lstbins = NP.arange(rawlst[:,0].min(), rawlst[:,0].max() + lstbinsize + eps, lstbinsize) # nlstbins = lstbins.size - 1 # if nlstbins > 1: # lstbinintervals = lstbins[1:] - lstbins[:-1] # lstbincenters = lstbins[:-1] + 0.5 * lstbinintervals # else: # lstbinintervals = NP.asarray(lstbinsize).reshape(-1) # lstbincenters = lstbins[0] + 0.5 * lstbinintervals # if 'prelim' not in self.cpinfo['processed']: # self.cpinfo['processed']['prelim'] = {} # self.cpinfo['processed']['prelim']['lstbins'] = lstbincenters # self.cpinfo['processed']['prelim']['dlstbins'] = lstbinintervals if (rawlst.shape[0] <= 1) or (lstbinsize is None): nlstbins = rawlst.shape[0] lstbins = NP.mean(rawlst, axis=1) if 'prelim' not in self.cpinfo['processed']: self.cpinfo['processed']['prelim'] = {} self.cpinfo['processed']['prelim']['lstbins'] = lstbins if lstbinsize is not None: self.cpinfo['processed']['prelim']['dlstbins'] = NP.asarray(lstbinsize).reshape(-1) else: self.cpinfo['processed']['prelim']['dlstbins'] = NP.zeros(1) ############################################################################ def subtract(self, cphase): """ ------------------------------------------------------------------------ Subtract complex exponential of the bispectrum phase from the current instance and updates the cpinfo attribute Inputs: cphase [masked array] Bispectrum phase array as a maked array. It must be of same size as freqs along the axis specified in input axis. Action: Updates 'submodel' and 'residual' keys under attribute cpinfo under key 'processed' ------------------------------------------------------------------------ """ if not isinstance(cphase, NP.ndarray): raise TypeError('Input cphase must be a numpy array') if not isinstance(cphase, MA.MaskedArray): cphase = MA.array(cphase, mask=NP.isnan(cphase)) if not OPS.is_broadcastable(cphase.shape, self.cpinfo['processed']['prelim']['cphase']['median'].shape): raise ValueError('Input cphase has shape incompatible with that in instance attribute') else: minshape = tuple(NP.ones(self.cpinfo['processed']['prelim']['cphase']['median'].ndim - cphase.ndim, dtype=NP.int)) + cphase.shape cphase = cphase.reshape(minshape) # cphase = NP.broadcast_to(cphase, minshape) eicp = NP.exp(1j*cphase) self.cpinfo['processed']['submodel'] = {} self.cpinfo['processed']['submodel']['cphase'] = cphase self.cpinfo['processed']['submodel']['eicp'] = eicp self.cpinfo['processed']['residual'] = {'eicp': {}, 'cphase': {}} for key in ['mean', 'median']: eicpdiff = self.cpinfo['processed']['prelim']['eicp'][key] - eicp eicpratio = self.cpinfo['processed']['prelim']['eicp'][key] / eicp self.cpinfo['processed']['residual']['eicp'][key] = eicpdiff self.cpinfo['processed']['residual']['cphase'][key] = MA.array(NP.angle(eicpratio.data), mask=self.cpinfo['processed']['residual']['eicp'][key].mask) ############################################################################ def subsample_differencing(self, daybinsize=None, ndaybins=4, lstbinsize=None): """ ------------------------------------------------------------------------ Create subsamples and differences between subsamples to evaluate noise properties from the data set. Inputs: daybinsize [Nonetype or scalar] Day bin size (in days) over which mean and median are estimated across different days for a fixed LST bin. If set to None, it will look for value in input ndaybins. If both are None, no smoothing is performed. Only one of daybinsize or ndaybins must be set to non-None value. Must yield greater than or equal to 4 bins ndaybins [NoneType or integer] Number of bins along day axis. Only if daybinsize is set to None. It produces bins that roughly consist of equal number of days in each bin regardless of how much the days in each bin are separated from each other. If both are None, no smoothing is performed. Only one of daybinsize or ndaybins must be set to non-None value. If set, it must be set to greater than or equal to 4 lstbinsize [NoneType or scalar] LST bin size (in seconds) over which mean and median are estimated across the LST. If set to None, no smoothing is performed ------------------------------------------------------------------------ """ if (ndaybins is not None) and (daybinsize is not None): raise ValueError('Only one of daybinsize or ndaybins should be set') if (daybinsize is not None) or (ndaybins is not None): if daybinsize is not None: if not isinstance(daybinsize, (int,float)): raise TypeError('Input daybinsize must be a scalar') dres = NP.diff(self.cpinfo['raw']['days']).min() # in days dextent = self.cpinfo['raw']['days'].max() - self.cpinfo['raw']['days'].min() + dres # in days if daybinsize > dres: daybinsize = NP.clip(daybinsize, dres, dextent) eps = 1e-10 daybins = NP.arange(self.cpinfo['raw']['days'].min(), self.cpinfo['raw']['days'].max() + dres + eps, daybinsize) ndaybins = daybins.size daybins = NP.concatenate((daybins, [daybins[-1]+daybinsize+eps])) if ndaybins >= 4: daybinintervals = daybins[1:] - daybins[:-1] daybincenters = daybins[:-1] + 0.5 * daybinintervals else: raise ValueError('Could not find at least 4 bins along repeating days. Adjust binning interval.') counts, daybin_edges, daybinnum, ri = OPS.binned_statistic(self.cpinfo['raw']['days'], statistic='count', bins=daybins) counts = counts.astype(NP.int) wts_daybins = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3])) eicp_dmean = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3]), dtype=NP.complex128) eicp_dmedian = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3]), dtype=NP.complex128) cp_drms = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3])) cp_dmad = NP.zeros((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3])) for binnum in xrange(counts.size): ind_daybin = ri[ri[binnum]:ri[binnum+1]] wts_daybins[:,binnum,:,:] = NP.sum(self.cpinfo['processed']['native']['wts'][:,ind_daybin,:,:].data, axis=1) eicp_dmean[:,binnum,:,:] = NP.exp(1j*NP.angle(MA.mean(self.cpinfo['processed']['native']['eicp'][:,ind_daybin,:,:], axis=1))) eicp_dmedian[:,binnum,:,:] = NP.exp(1j*NP.angle(MA.median(self.cpinfo['processed']['native']['eicp'][:,ind_daybin,:,:].real, axis=1) + 1j * MA.median(self.cpinfo['processed']['native']['eicp'][:,ind_daybin,:,:].imag, axis=1))) cp_drms[:,binnum,:,:] = MA.std(self.cpinfo['processed']['native']['cphase'][:,ind_daybin,:,:], axis=1).data cp_dmad[:,binnum,:,:] = MA.median(NP.abs(self.cpinfo['processed']['native']['cphase'][:,ind_daybin,:,:] - NP.angle(eicp_dmedian[:,binnum,:,:][:,NP.newaxis,:,:])), axis=1).data else: if not isinstance(ndaybins, int): raise TypeError('Input ndaybins must be an integer') if ndaybins < 4: raise ValueError('Input ndaybins must be greater than or equal to 4') days_split = NP.array_split(self.cpinfo['raw']['days'], ndaybins) daybincenters = NP.asarray([NP.mean(days) for days in days_split]) daybinintervals = NP.asarray([days.max()-days.min() for days in days_split]) counts = NP.asarray([days.size for days in days_split]) wts_split = NP.array_split(self.cpinfo['processed']['native']['wts'].data, ndaybins, axis=1) # mask_split = NP.array_split(self.cpinfo['processed']['native']['wts'].mask, ndaybins, axis=1) wts_daybins = NP.asarray([NP.sum(wtsitem, axis=1) for wtsitem in wts_split]) # ndaybins x nlst x ntriads x nchan wts_daybins = NP.moveaxis(wts_daybins, 0, 1) # nlst x ndaybins x ntriads x nchan mask_split = NP.array_split(self.cpinfo['processed']['native']['eicp'].mask, ndaybins, axis=1) eicp_split = NP.array_split(self.cpinfo['processed']['native']['eicp'].data, ndaybins, axis=1) eicp_dmean = MA.array([MA.mean(MA.array(eicp_split[i], mask=mask_split[i]), axis=1) for i in range(daybincenters.size)]) # ndaybins x nlst x ntriads x nchan eicp_dmean = NP.exp(1j * NP.angle(eicp_dmean)) eicp_dmean = NP.moveaxis(eicp_dmean, 0, 1) # nlst x ndaybins x ntriads x nchan eicp_dmedian = MA.array([MA.median(MA.array(eicp_split[i].real, mask=mask_split[i]), axis=1) + 1j * MA.median(MA.array(eicp_split[i].imag, mask=mask_split[i]), axis=1) for i in range(daybincenters.size)]) # ndaybins x nlst x ntriads x nchan eicp_dmedian = NP.exp(1j * NP.angle(eicp_dmedian)) eicp_dmedian = NP.moveaxis(eicp_dmedian, 0, 1) # nlst x ndaybins x ntriads x nchan cp_split = NP.array_split(self.cpinfo['processed']['native']['cphase'].data, ndaybins, axis=1) cp_drms = NP.array([MA.std(MA.array(cp_split[i], mask=mask_split[i]), axis=1).data for i in range(daybincenters.size)]) # ndaybins x nlst x ntriads x nchan cp_drms = NP.moveaxis(cp_drms, 0, 1) # nlst x ndaybins x ntriads x nchan cp_dmad = NP.array([MA.median(NP.abs(cp_split[i] - NP.angle(eicp_dmedian[:,[i],:,:])), axis=1).data for i in range(daybincenters.size)]) # ndaybins x nlst x ntriads x nchan cp_dmad = NP.moveaxis(cp_dmad, 0, 1) # nlst x ndaybins x ntriads x nchan mask = wts_daybins <= 0.0 wts_daybins = MA.array(wts_daybins, mask=mask) cp_dmean = MA.array(NP.angle(eicp_dmean), mask=mask) cp_dmedian = MA.array(NP.angle(eicp_dmedian), mask=mask) self.cpinfo['errinfo']['daybins'] = daybincenters self.cpinfo['errinfo']['diff_dbins'] = daybinintervals self.cpinfo['errinfo']['wts'] = {'{0}'.format(ind): None for ind in range(2)} self.cpinfo['errinfo']['eicp_diff'] = {'{0}'.format(ind): {} for ind in range(2)} rawlst = NP.degrees(NP.unwrap(NP.radians(self.cpinfo['raw']['lst'] * 15.0), discont=NP.pi, axis=0)) / 15.0 # in hours but unwrapped to have no discontinuities if NP.any(rawlst > 24.0): rawlst -= 24.0 if rawlst.shape[0] > 1: # LST bin only if there are multiple LST if lstbinsize is not None: if not isinstance(lstbinsize, (int,float)): raise TypeError('Input lstbinsize must be a scalar') lstbinsize = lstbinsize / 3.6e3 # in hours tres = NP.diff(rawlst[:,0]).min() # in hours textent = rawlst[:,0].max() - rawlst[:,0].min() + tres # in hours eps = 1e-10 no_change_in_lstbins = False if lstbinsize > tres: lstbinsize = NP.clip(lstbinsize, tres, textent) lstbins = NP.arange(rawlst[:,0].min(), rawlst[:,0].max() + tres + eps, lstbinsize) nlstbins = lstbins.size lstbins = NP.concatenate((lstbins, [lstbins[-1]+lstbinsize+eps])) if nlstbins > 1: lstbinintervals = lstbins[1:] - lstbins[:-1] lstbincenters = lstbins[:-1] + 0.5 * lstbinintervals else: lstbinintervals = NP.asarray(lstbinsize).reshape(-1) lstbincenters = lstbins[0] + 0.5 * lstbinintervals self.cpinfo['errinfo']['lstbins'] = lstbincenters self.cpinfo['errinfo']['dlstbins'] = lstbinintervals no_change_in_lstbins = False else: # Perform no binning and keep the current LST resolution warnings.warn('LST bin size found to be smaller than the LST resolution in the data. No LST binning/averaging will be performed.') lstbinsize = tres lstbins = NP.arange(rawlst[:,0].min(), rawlst[:,0].max() + lstbinsize + eps, lstbinsize) nlstbins = lstbins.size - 1 if nlstbins > 1: lstbinintervals = lstbins[1:] - lstbins[:-1] else: lstbinintervals = NP.asarray(lstbinsize).reshape(-1) self.cpinfo['errinfo']['dlstbins'] = lstbinintervals self.cpinfo['errinfo']['lstbins'] = lstbins[:-1] # Ensure that the LST bins are inside the min/max envelope to # error-free interpolation later self.cpinfo['errinfo']['lstbins'][0] += eps self.cpinfo['errinfo']['lstbins'][-1] -= eps no_change_in_lstbins = True counts, lstbin_edges, lstbinnum, ri = OPS.binned_statistic(rawlst[:,0], statistic='count', bins=lstbins) counts = counts.astype(NP.int) outshape = (counts.size, wts_daybins.shape[1], self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3]) wts_lstbins = NP.zeros(outshape) eicp_tmean = NP.zeros(outshape, dtype=NP.complex128) eicp_tmedian = NP.zeros(outshape, dtype=NP.complex128) cp_trms = NP.zeros(outshape) cp_tmad = NP.zeros(outshape) for binnum in xrange(counts.size): if no_change_in_lstbins: ind_lstbin = [binnum] else: ind_lstbin = ri[ri[binnum]:ri[binnum+1]] wts_lstbins[binnum,:,:,:] = NP.sum(wts_daybins[ind_lstbin,:,:,:].data, axis=0) eicp_tmean[binnum,:,:,:] = NP.exp(1j*NP.angle(MA.mean(NP.exp(1j*cp_dmean[ind_lstbin,:,:,:]), axis=0))) eicp_tmedian[binnum,:,:,:] = NP.exp(1j*NP.angle(MA.median(NP.cos(cp_dmedian[ind_lstbin,:,:,:]), axis=0) + 1j * MA.median(NP.sin(cp_dmedian[ind_lstbin,:,:,:]), axis=0))) mask = wts_lstbins <= 0.0 wts_lstbins = MA.array(wts_lstbins, mask=mask) eicp_tmean = MA.array(eicp_tmean, mask=mask) eicp_tmedian = MA.array(eicp_tmedian, mask=mask) else: wts_lstbins = MA.copy(wts_daybins) mask = wts_lstbins.mask eicp_tmean = MA.array(NP.exp(1j*NP.angle(NP.exp(1j*cp_dmean))), mask=mask) eicp_tmedian = MA.array(NP.exp(1j*NP.angle(NP.cos(cp_dmedian) + 1j * NP.sin(cp_dmedian))), mask=mask) if (rawlst.shape[0] <= 1) or (lstbinsize is None): nlstbins = rawlst.shape[0] lstbins = NP.mean(rawlst, axis=1) self.cpinfo['errinfo']['lstbins'] = lstbins if lstbinsize is not None: self.cpinfo['errinfo']['dlstbins'] = NP.asarray(lstbinsize).reshape(-1) else: self.cpinfo['errinfo']['dlstbins'] = NP.zeros(1) ncomb = NP.sum(NP.asarray([(ndaybins-i-1)*(ndaybins-i-2)*(ndaybins-i-3)/2 for i in range(ndaybins-3)])).astype(int) diff_outshape = (nlstbins, ncomb, self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed']['native']['eicp'].shape[3]) for diffind in range(2): self.cpinfo['errinfo']['eicp_diff']['{0}'.format(diffind)]['mean'] = MA.empty(diff_outshape, dtype=NP.complex) self.cpinfo['errinfo']['eicp_diff']['{0}'.format(diffind)]['median'] = MA.empty(diff_outshape, dtype=NP.complex) self.cpinfo['errinfo']['wts']['{0}'.format(diffind)] = MA.empty(diff_outshape, dtype=NP.float) ind = -1 self.cpinfo['errinfo']['list_of_pair_of_pairs'] = [] list_of_pair_of_pairs = [] for i in range(ndaybins-1): for j in range(i+1,ndaybins): for k in range(ndaybins-1): if (k != i) and (k != j): for m in range(k+1,ndaybins): if (m != i) and (m != j): pair_of_pairs = [set([i,j]), set([k,m])] if (pair_of_pairs not in list_of_pair_of_pairs) and (pair_of_pairs[::-1] not in list_of_pair_of_pairs): ind += 1 list_of_pair_of_pairs += [copy.deepcopy(pair_of_pairs)] self.cpinfo['errinfo']['list_of_pair_of_pairs'] += [[i,j,k,m]] for stat in ['mean', 'median']: if stat == 'mean': self.cpinfo['errinfo']['eicp_diff']['0'][stat][:,ind,:,:] = MA.array(0.5 * (eicp_tmean[:,j,:,:].data - eicp_tmean[:,i,:,:].data), mask=NP.logical_or(eicp_tmean[:,j,:,:].mask, eicp_tmean[:,i,:,:].mask)) self.cpinfo['errinfo']['eicp_diff']['1'][stat][:,ind,:,:] = MA.array(0.5 * (eicp_tmean[:,m,:,:].data - eicp_tmean[:,k,:,:].data), mask=NP.logical_or(eicp_tmean[:,m,:,:].mask, eicp_tmean[:,k,:,:].mask)) self.cpinfo['errinfo']['wts']['0'][:,ind,:,:] = MA.array(NP.sqrt(wts_lstbins[:,j,:,:].data**2 + wts_lstbins[:,i,:,:].data**2), mask=NP.logical_or(wts_lstbins[:,j,:,:].mask, wts_lstbins[:,i,:,:].mask)) self.cpinfo['errinfo']['wts']['1'][:,ind,:,:] = MA.array(NP.sqrt(wts_lstbins[:,m,:,:].data**2 + wts_lstbins[:,k,:,:].data**2), mask=NP.logical_or(wts_lstbins[:,m,:,:].mask, wts_lstbins[:,k,:,:].mask)) # self.cpinfo['errinfo']['eicp_diff']['0'][stat][:,ind,:,:] = 0.5 * (eicp_tmean[:,j,:,:] - eicp_tmean[:,i,:,:]) # self.cpinfo['errinfo']['eicp_diff']['1'][stat][:,ind,:,:] = 0.5 * (eicp_tmean[:,m,:,:] - eicp_tmean[:,k,:,:]) # self.cpinfo['errinfo']['wts']['0'][:,ind,:,:] = NP.sqrt(wts_lstbins[:,j,:,:]**2 + wts_lstbins[:,i,:,:]**2) # self.cpinfo['errinfo']['wts']['1'][:,ind,:,:] = NP.sqrt(wts_lstbins[:,m,:,:]**2 + wts_lstbins[:,k,:,:]**2) else: self.cpinfo['errinfo']['eicp_diff']['0'][stat][:,ind,:,:] = MA.array(0.5 * (eicp_tmedian[:,j,:,:].data - eicp_tmedian[:,i,:,:].data), mask=NP.logical_or(eicp_tmedian[:,j,:,:].mask, eicp_tmedian[:,i,:,:].mask)) self.cpinfo['errinfo']['eicp_diff']['1'][stat][:,ind,:,:] = MA.array(0.5 * (eicp_tmedian[:,m,:,:].data - eicp_tmedian[:,k,:,:].data), mask=NP.logical_or(eicp_tmedian[:,m,:,:].mask, eicp_tmedian[:,k,:,:].mask)) # self.cpinfo['errinfo']['eicp_diff']['0'][stat][:,ind,:,:] = 0.5 * (eicp_tmedian[:,j,:,:] - eicp_tmedian[:,i,:,:]) # self.cpinfo['errinfo']['eicp_diff']['1'][stat][:,ind,:,:] = 0.5 * (eicp_tmedian[:,m,:,:] - eicp_tmedian[:,k,:,:]) mask0 = self.cpinfo['errinfo']['wts']['0'] <= 0.0 mask1 = self.cpinfo['errinfo']['wts']['1'] <= 0.0 self.cpinfo['errinfo']['eicp_diff']['0'][stat] = MA.array(self.cpinfo['errinfo']['eicp_diff']['0'][stat], mask=mask0) self.cpinfo['errinfo']['eicp_diff']['1'][stat] = MA.array(self.cpinfo['errinfo']['eicp_diff']['1'][stat], mask=mask1) self.cpinfo['errinfo']['wts']['0'] = MA.array(self.cpinfo['errinfo']['wts']['0'], mask=mask0) self.cpinfo['errinfo']['wts']['1'] = MA.array(self.cpinfo['errinfo']['wts']['1'], mask=mask1) ############################################################################ def save(self, outfile=None): """ ------------------------------------------------------------------------ Save contents of attribute cpinfo in external HDF5 file Inputs: outfile [NoneType or string] Output file (HDF5) to save contents to. If set to None (default), it will be saved in the file pointed to by the extfile attribute of class ClosurePhase ------------------------------------------------------------------------ """ if outfile is None: outfile = self.extfile NMO.save_dict_to_hdf5(self.cpinfo, outfile, compressinfo={'compress_fmt': 'gzip', 'compress_opts': 9}) ################################################################################ class ClosurePhaseDelaySpectrum(object): """ ---------------------------------------------------------------------------- Class to hold and operate on Closure Phase information. It has the following attributes and member functions. Attributes: cPhase [instance of class ClosurePhase] Instance of class ClosurePhase f [numpy array] Frequencies (in Hz) in closure phase spectra df [float] Frequency resolution (in Hz) in closure phase spectra cPhaseDS [dictionary] Possibly oversampled Closure Phase Delay Spectrum information. cPhaseDS_resampled [dictionary] Resampled Closure Phase Delay Spectrum information. Member functions: __init__() Initialize instance of class ClosurePhaseDelaySpectrum FT() Fourier transform of complex closure phase spectra mapping from frequency axis to delay axis. subset() Return triad and time indices to select a subset of processed data compute_power_spectrum() Compute power spectrum of closure phase data. It is in units of Mpc/h. rescale_power_spectrum() Rescale power spectrum to dimensional quantity by converting the ratio given visibility amplitude information average_rescaled_power_spectrum() Average the rescaled power spectrum with physical units along certain axes with inverse variance or regular averaging beam3Dvol() Compute three-dimensional volume of the antenna power pattern along two transverse axes and one LOS axis. ---------------------------------------------------------------------------- """ def __init__(self, cPhase): """ ------------------------------------------------------------------------ Initialize instance of class ClosurePhaseDelaySpectrum Inputs: cPhase [class ClosurePhase] Instance of class ClosurePhase ------------------------------------------------------------------------ """ if not isinstance(cPhase, ClosurePhase): raise TypeError('Input cPhase must be an instance of class ClosurePhase') self.cPhase = cPhase self.f = self.cPhase.f self.df = self.cPhase.df self.cPhaseDS = None self.cPhaseDS_resampled = None ############################################################################ def FT(self, bw_eff, freq_center=None, shape=None, fftpow=None, pad=None, datapool='prelim', visscaleinfo=None, method='fft', resample=True, apply_flags=True): """ ------------------------------------------------------------------------ Fourier transform of complex closure phase spectra mapping from frequency axis to delay axis. Inputs: bw_eff [scalar or numpy array] effective bandwidths (in Hz) on the selected frequency windows for subband delay transform of closure phases. If a scalar value is provided, the same will be applied to all frequency windows freq_center [scalar, list or numpy array] frequency centers (in Hz) of the selected frequency windows for subband delay transform of closure phases. The value can be a scalar, list or numpy array. If a scalar is provided, the same will be applied to all frequency windows. Default=None uses the center frequency from the class attribute named channels shape [string] frequency window shape for subband delay transform of closure phases. Accepted values for the string are 'rect' or 'RECT' (for rectangular), 'bnw' and 'BNW' (for Blackman-Nuttall), and 'bhw' or 'BHW' (for Blackman-Harris). Default=None sets it to 'rect' (rectangular window) fftpow [scalar] the power to which the FFT of the window will be raised. The value must be a positive scalar. Default = 1.0 pad [scalar] padding fraction relative to the number of frequency channels for closure phases. Value must be a non-negative scalar. For e.g., a pad of 1.0 pads the frequency axis with zeros of the same width as the number of channels. After the delay transform, the transformed closure phases are downsampled by a factor of 1+pad. If a negative value is specified, delay transform will be performed with no padding. Default=None sets to padding factor to 1.0 datapool [string] Specifies which data set is to be Fourier transformed visscaleinfo [dictionary] Dictionary containing reference visibilities based on which the closure phases will be scaled to units of visibilities. It contains the following keys and values: 'vis' [numpy array or instance of class InterferometerArray] Reference visibilities from the baselines that form the triad. It can be an instance of class RI.InterferometerArray or a numpy array. If an instance of class InterferometerArray, the baseline triplet must be set in key 'bltriplet' and value in key 'lst' will be ignored. If the value under this key 'vis' is set to a numpy array, it must be of shape (nbl=3, nlst_vis, nchan). In this case the value under key 'bltriplet' will be ignored. The nearest LST will be looked up and applied after smoothing along LST based on the smoothing parameter 'smooth' 'bltriplet' [Numpy array] Will be used in searching for matches to these three baseline vectors if the value under key 'vis' is set to an instance of class InterferometerArray. However, if value under key 'vis' is a numpy array, this key 'bltriplet' will be ignored. 'lst' [numpy array] Reference LST (in hours). It is of shape (nlst_vis,). It will be used only if value under key 'vis' is a numpy array, otherwise it will be ignored and read from the instance of class InterferometerArray passed under key 'vis'. If the specified LST range does not cover the data LST range, those LST will contain NaN in the delay spectrum 'smoothinfo' [dictionary] Dictionary specifying smoothing and/or interpolation parameters. It has the following keys and values: 'op_type' [string] Specifies the interpolating operation. Must be specified (no default). Accepted values are 'interp1d' (scipy.interpolate), 'median' (skimage.filters), 'tophat' (astropy.convolution) and 'gaussian' (astropy.convolution) 'interp_kind' [string (optional)] Specifies the interpolation kind (if 'op_type' is set to 'interp1d'). For accepted values, see scipy.interpolate.interp1d() 'window_size' [integer (optional)] Specifies the size of the interpolating/smoothing kernel. Only applies when 'op_type' is set to 'median', 'tophat' or 'gaussian' The kernel is a tophat function when 'op_type' is set to 'median' or 'tophat'. If refers to FWHM when 'op_type' is set to 'gaussian' resample [boolean] If set to True (default), resample the delay spectrum axis to independent samples along delay axis. If set to False, return the results as is even if they may be be oversampled and not all samples may be independent method [string] Specifies the Fourier transform method to be used. Accepted values are 'fft' (default) for FFT and 'nufft' for non-uniform FFT apply_flags [boolean] If set to True (default), weights determined from flags will be applied. If False, no weights from flagging will be applied, and thus even flagged data will be included Outputs: A dictionary that contains the oversampled (if resample=False) or resampled (if resample=True) delay spectrum information. It has the following keys and values: 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the window function applied. Accepted values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'npad' [scalar] Numbber of zero-padded channels before performing the subband delay transform. 'lags' [numpy array] lags of the subband delay spectra after padding in frequency during the transform. It is of size nlags=nchan+npad if resample=True, where npad is the number of frequency channels padded specified under the key 'npad'. If resample=False, nlags = number of delays after resampling only independent delays. The lags roughly correspond to k_parallel. 'lag_kernel' [numpy array] delay transform of the frequency weights under the key 'freq_wts'. It is of size n_win x nlst x ndays x ntriads x nlags. nlags=nchan+npad if resample=True, where npad is the number of frequency channels padded specified under the key 'npad'. If resample=False, nlags = number of delays after resampling only independent delays. 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff 'whole' [dictionary] Delay spectrum results corresponding to bispectrum phase in 'prelim' key of attribute cpinfo. Contains the following keys and values: 'dspec' [dictionary] Contains the following keys and values: 'twts' [numpy array] Weights from time-based flags that went into time-averaging. Shape=(nlst,ndays,ntriads,nchan) 'mean' [numpy array] Delay spectrum of closure phases based on their mean across time intervals. Shape=(nspw,nlst,ndays,ntriads,nlags) 'median' [numpy array] Delay spectrum of closure phases based on their median across time intervals. Shape=(nspw,nlst,ndays,ntriads,nlags) 'submodel' [dictionary] Delay spectrum results corresponding to bispectrum phase in 'submodel' key of attribute cpinfo. Contains the following keys and values: 'dspec' [numpy array] Delay spectrum of closure phases Shape=(nspw,nlst,ndays,ntriads,nlags) 'residual' [dictionary] Delay spectrum results corresponding to bispectrum phase in 'residual' key of attribute cpinfo after subtracting 'submodel' bispectrum phase from that of 'prelim'. It contains the following keys and values: 'dspec' [dictionary] Contains the following keys and values: 'twts' [numpy array] Weights from time-based flags that went into time-averaging. Shape=(nlst,ndays,ntriads,nchan) 'mean' [numpy array] Delay spectrum of closure phases based on their mean across time intervals. Shape=(nspw,nlst,ndays,ntriads,nlags) 'median' [numpy array] Delay spectrum of closure phases based on their median across time intervals. Shape=(nspw,nlst,ndays,ntriads,nlags) 'errinfo' [dictionary] It has two keys 'dspec0' and 'dspec1' each of which are dictionaries with the following keys and values: 'twts' [numpy array] Weights for the subsample difference. It is of shape (nlst, ndays, ntriads, nchan) 'mean' [numpy array] Delay spectrum of the subsample difference obtained by using the mean statistic. It is of shape (nspw, nlst, ndays, ntriads, nlags) 'median' [numpy array] Delay spectrum of the subsample difference obtained by using the median statistic. It is of shape (nspw, nlst, ndays, ntriads, nlags) ------------------------------------------------------------------------ """ try: bw_eff except NameError: raise NameError('Effective bandwidth must be specified') else: if not isinstance(bw_eff, (int, float, list, NP.ndarray)): raise TypeError('Value of effective bandwidth must be a scalar, list or numpy array') bw_eff = NP.asarray(bw_eff).reshape(-1) if NP.any(bw_eff <= 0.0): raise ValueError('All values in effective bandwidth must be strictly positive') if freq_center is None: freq_center = NP.asarray(self.f[self.f.size/2]).reshape(-1) elif isinstance(freq_center, (int, float, list, NP.ndarray)): freq_center = NP.asarray(freq_center).reshape(-1) if NP.any((freq_center <= self.f.min()) | (freq_center >= self.f.max())): raise ValueError('Value(s) of frequency center(s) must lie strictly inside the observing band') else: raise TypeError('Values(s) of frequency center must be scalar, list or numpy array') if (bw_eff.size == 1) and (freq_center.size > 1): bw_eff = NP.repeat(bw_eff, freq_center.size) elif (bw_eff.size > 1) and (freq_center.size == 1): freq_center = NP.repeat(freq_center, bw_eff.size) elif bw_eff.size != freq_center.size: raise ValueError('Effective bandwidth(s) and frequency center(s) must have same number of elements') if shape is not None: if not isinstance(shape, str): raise TypeError('Window shape must be a string') if shape not in ['rect', 'bhw', 'bnw', 'RECT', 'BHW', 'BNW']: raise ValueError('Invalid value for window shape specified.') else: shape = 'rect' if fftpow is None: fftpow = 1.0 else: if not isinstance(fftpow, (int, float)): raise TypeError('Power to raise window FFT by must be a scalar value.') if fftpow < 0.0: raise ValueError('Power for raising FFT of window by must be positive.') if pad is None: pad = 1.0 else: if not isinstance(pad, (int, float)): raise TypeError('pad fraction must be a scalar value.') if pad < 0.0: pad = 0.0 if verbose: print('\tPad fraction found to be negative. Resetting to 0.0 (no padding will be applied).') if not isinstance(datapool, str): raise TypeError('Input datapool must be a string') if datapool.lower() not in ['prelim']: raise ValueError('Specified datapool not supported') if visscaleinfo is not None: if not isinstance(visscaleinfo, dict): raise TypeError('Input visscaleinfo must be a dictionary') if 'vis' not in visscaleinfo: raise KeyError('Input visscaleinfo does not contain key "vis"') if not isinstance(visscaleinfo['vis'], RI.InterferometerArray): if 'lst' not in visscaleinfo: raise KeyError('Input visscaleinfo does not contain key "lst"') lst_vis = visscaleinfo['lst'] * 15.0 if not isinstance(visscaleinfo['vis'], (NP.ndarray,MA.MaskedArray)): raise TypeError('Input visibilities must be a numpy or a masked array') if not isinstance(visscaleinfo['vis'], MA.MaskedArray): visscaleinfo['vis'] = MA.array(visscaleinfo['vis'], mask=NP.isnan(visscaleinfo['vis'])) vistriad = MA.copy(visscaleinfo['vis']) else: if 'bltriplet' not in visscaleinfo: raise KeyError('Input dictionary visscaleinfo does not contain key "bltriplet"') blind, blrefind, dbl = LKP.find_1NN(visscaleinfo['vis'].baselines, visscaleinfo['bltriplet'], distance_ULIM=0.2, remove_oob=True) if blrefind.size != 3: blind_missing = NP.setdiff1d(NP.arange(3), blind, assume_unique=True) blind_next, blrefind_next, dbl_next = LKP.find_1NN(visscaleinfo['vis'].baselines, -1*visscaleinfo['bltriplet'][blind_missing,:], distance_ULIM=0.2, remove_oob=True) if blind_next.size + blind.size != 3: raise ValueError('Exactly three baselines were not found in the reference baselines') else: blind = NP.append(blind, blind_missing[blind_next]) blrefind = NP.append(blrefind, blrefind_next) else: blind_missing = [] vistriad = NP.transpose(visscaleinfo['vis'].skyvis_freq[blrefind,:,:], (0,2,1)) if len(blind_missing) > 0: vistriad[-blrefind_next.size:,:,:] = vistriad[-blrefind_next.size:,:,:].conj() vistriad = MA.array(vistriad, mask=NP.isnan(vistriad)) lst_vis = visscaleinfo['vis'].lst viswts = MA.array(NP.ones_like(vistriad.data), mask=vistriad.mask, dtype=NP.float) lst_out = self.cPhase.cpinfo['processed']['prelim']['lstbins'] * 15.0 if lst_vis.size == 1: # Apply the visibility scaling from one reference LST to all LST vis_ref = vistriad * NP.ones(lst_out.size).reshape(1,-1,1) wts_ref = viswts * NP.ones(lst_out.size).reshape(1,-1,1) else: vis_ref, wts_ref = OPS.interpolate_masked_array_1D(vistriad, viswts, 1, visscaleinfo['smoothinfo'], inploc=lst_vis, outloc=lst_out) if not isinstance(method, str): raise TypeError('Input method must be a string') if method.lower() not in ['fft', 'nufft']: raise ValueError('Specified FFT method not supported') if not isinstance(apply_flags, bool): raise TypeError('Input apply_flags must be boolean') flagwts = 1.0 visscale = 1.0 if datapool.lower() == 'prelim': if method.lower() == 'fft': freq_wts = NP.empty((bw_eff.size, self.f.size), dtype=NP.float_) # nspw x nchan frac_width = DSP.window_N2width(n_window=None, shape=shape, fftpow=fftpow, area_normalize=False, power_normalize=True) window_loss_factor = 1 / frac_width n_window = NP.round(window_loss_factor * bw_eff / self.df).astype(NP.int) ind_freq_center, ind_channels, dfrequency = LKP.find_1NN(self.f.reshape(-1,1), freq_center.reshape(-1,1), distance_ULIM=0.51*self.df, remove_oob=True) sortind = NP.argsort(ind_channels) ind_freq_center = ind_freq_center[sortind] ind_channels = ind_channels[sortind] dfrequency = dfrequency[sortind] n_window = n_window[sortind] for i,ind_chan in enumerate(ind_channels): window = NP.sqrt(frac_width * n_window[i]) * DSP.window_fftpow(n_window[i], shape=shape, fftpow=fftpow, centering=True, peak=None, area_normalize=False, power_normalize=True) window_chans = self.f[ind_chan] + self.df * (NP.arange(n_window[i]) - int(n_window[i]/2)) ind_window_chans, ind_chans, dfreq = LKP.find_1NN(self.f.reshape(-1,1), window_chans.reshape(-1,1), distance_ULIM=0.51*self.df, remove_oob=True) sind = NP.argsort(ind_window_chans) ind_window_chans = ind_window_chans[sind] ind_chans = ind_chans[sind] dfreq = dfreq[sind] window = window[ind_window_chans] window = NP.pad(window, ((ind_chans.min(), self.f.size-1-ind_chans.max())), mode='constant', constant_values=((0.0,0.0))) freq_wts[i,:] = window npad = int(self.f.size * pad) lags = DSP.spectral_axis(self.f.size + npad, delx=self.df, use_real=False, shift=True) result = {'freq_center': freq_center, 'shape': shape, 'freq_wts': freq_wts, 'bw_eff': bw_eff, 'fftpow': fftpow, 'npad': npad, 'lags': lags, 'lag_corr_length': self.f.size / NP.sum(freq_wts, axis=-1), 'whole': {'dspec': {'twts': self.cPhase.cpinfo['processed'][datapool]['wts']}}, 'residual': {'dspec': {'twts': self.cPhase.cpinfo['processed'][datapool]['wts']}}, 'errinfo': {'dspec0': {'twts': self.cPhase.cpinfo['errinfo']['wts']['0']}, 'dspec1': {'twts': self.cPhase.cpinfo['errinfo']['wts']['1']}}, 'submodel': {}} if visscaleinfo is not None: visscale = NP.nansum(NP.transpose(vis_ref[NP.newaxis,NP.newaxis,:,:,:], axes=(0,3,1,2,4)) * freq_wts[:,NP.newaxis,NP.newaxis,NP.newaxis,:], axis=-1, keepdims=True) / NP.nansum(freq_wts[:,NP.newaxis,NP.newaxis,NP.newaxis,:], axis=-1, keepdims=True) # nspw x nlst x (ndays=1) x (nbl=3) x (nchan=1) visscale = NP.sqrt(1.0/NP.nansum(1/NP.abs(visscale)**2, axis=-2, keepdims=True)) # nspw x nlst x (ndays=1) x (ntriads=1) x (nchan=1) for dpool in ['errinfo', 'prelim', 'submodel', 'residual']: if dpool.lower() == 'errinfo': for diffind in range(2): if apply_flags: flagwts = NP.copy(self.cPhase.cpinfo['errinfo']['wts']['{0}'.format(diffind)].data) flagwts = flagwts[NP.newaxis,...] # nlst x ndays x ntriads x nchan --> (nspw=1) x nlst x ndays x ntriads x nchan flagwts = 1.0 * flagwts / NP.mean(flagwts, axis=-1, keepdims=True) # (nspw=1) x nlst x ndays x ntriads x nchan for stat in self.cPhase.cpinfo[dpool]['eicp_diff']['{0}'.format(diffind)]: eicp = NP.copy(self.cPhase.cpinfo[dpool]['eicp_diff']['{0}'.format(diffind)][stat].data) # Minimum shape as stored # eicp = NP.copy(self.cPhase.cpinfo[dpool]['eicp_diff']['{0}'.format(diffind)][stat].filled(0.0)) # Minimum shape as stored eicp = NP.broadcast_to(eicp, self.cPhase.cpinfo[dpool]['eicp_diff']['{0}'.format(diffind)][stat].shape) # Broadcast to final shape eicp = eicp[NP.newaxis,...] # nlst x ndayscomb x ntriads x nchan --> (nspw=1) x nlst x ndayscomb x ntriads x nchan ndim_padtuple = [(0,0)]*(eicp.ndim-1) + [(0,npad)] # [(0,0), (0,0), (0,0), (0,0), (0,npad)] result[dpool]['dspec{0}'.format(diffind)][stat] = DSP.FT1D(NP.pad(eicp*flagwts*freq_wts[:,NP.newaxis,NP.newaxis,NP.newaxis,:]*visscale.filled(NP.nan), ndim_padtuple, mode='constant'), ax=-1, inverse=True, use_real=False, shift=True) * (npad + self.f.size) * self.df else: if dpool in self.cPhase.cpinfo['processed']: if apply_flags: flagwts = NP.copy(self.cPhase.cpinfo['processed'][datapool]['wts'].data) flagwts = flagwts[NP.newaxis,...] # nlst x ndays x ntriads x nchan --> (nspw=1) x nlst x ndays x ntriads x nchan flagwts = 1.0 * flagwts / NP.mean(flagwts, axis=-1, keepdims=True) # (nspw=1) x nlst x ndays x ntriads x nchan if dpool == 'submodel': eicp = NP.copy(self.cPhase.cpinfo['processed'][dpool]['eicp'].data) # Minimum shape as stored # eicp = NP.copy(self.cPhase.cpinfo['processed'][dpool]['eicp'].filled(1.0)) # Minimum shape as stored eicp = NP.broadcast_to(eicp, self.cPhase.cpinfo['processed'][datapool]['eicp']['mean'].shape) # Broadcast to final shape eicp = eicp[NP.newaxis,...] # nlst x ndays x ntriads x nchan --> (nspw=1) x nlst x ndays x ntriads x nchan ndim_padtuple = [(0,0)]*(eicp.ndim-1) + [(0,npad)] # [(0,0), (0,0), (0,0), (0,0), (0,npad)] result[dpool]['dspec'] = DSP.FT1D(NP.pad(eicp*flagwts*freq_wts[:,NP.newaxis,NP.newaxis,NP.newaxis,:]*visscale.filled(NP.nan), ndim_padtuple, mode='constant'), ax=-1, inverse=True, use_real=False, shift=True) * (npad + self.f.size) * self.df else: for key in self.cPhase.cpinfo['processed'][dpool]['eicp']: eicp = NP.copy(self.cPhase.cpinfo['processed'][dpool]['eicp'][key].data) # eicp = NP.copy(self.cPhase.cpinfo['processed'][dpool]['eicp'][key].filled(1.0)) eicp = eicp[NP.newaxis,...] # nlst x ndays x ntriads x nchan --> (nspw=1) x nlst x ndays x ntriads x nchan ndim_padtuple = [(0,0)]*(eicp.ndim-1) + [(0,npad)] # [(0,0), (0,0), (0,0), (0,0), (0,npad)] if dpool == 'prelim': result['whole']['dspec'][key] = DSP.FT1D(NP.pad(eicp*flagwts*freq_wts[:,NP.newaxis,NP.newaxis,NP.newaxis,:]*visscale.filled(NP.nan), ndim_padtuple, mode='constant'), ax=-1, inverse=True, use_real=False, shift=True) * (npad + self.f.size) * self.df else: result[dpool]['dspec'][key] = DSP.FT1D(NP.pad(eicp*flagwts*freq_wts[:,NP.newaxis,NP.newaxis,NP.newaxis,:]*visscale.filled(NP.nan), ndim_padtuple, mode='constant'), ax=-1, inverse=True, use_real=False, shift=True) * (npad + self.f.size) * self.df result['lag_kernel'] = DSP.FT1D(NP.pad(flagwts*freq_wts[:,NP.newaxis,NP.newaxis,NP.newaxis,:], ndim_padtuple, mode='constant'), ax=-1, inverse=True, use_real=False, shift=True) * (npad + self.f.size) * self.df self.cPhaseDS = result if resample: result_resampled = copy.deepcopy(result) downsample_factor = NP.min((self.f.size + npad) * self.df / bw_eff) result_resampled['lags'] = DSP.downsampler(result_resampled['lags'], downsample_factor, axis=-1, method='interp', kind='linear') result_resampled['lag_kernel'] = DSP.downsampler(result_resampled['lag_kernel'], downsample_factor, axis=-1, method='interp', kind='linear') for dpool in ['errinfo', 'prelim', 'submodel', 'residual']: if dpool.lower() == 'errinfo': for diffind in self.cPhase.cpinfo[dpool]['eicp_diff']: for key in self.cPhase.cpinfo[dpool]['eicp_diff'][diffind]: result_resampled[dpool]['dspec'+diffind][key] = DSP.downsampler(result_resampled[dpool]['dspec'+diffind][key], downsample_factor, axis=-1, method='FFT') if dpool in self.cPhase.cpinfo['processed']: if dpool == 'submodel': result_resampled[dpool]['dspec'] = DSP.downsampler(result_resampled[dpool]['dspec'], downsample_factor, axis=-1, method='FFT') else: for key in self.cPhase.cpinfo['processed'][datapool]['eicp']: if dpool == 'prelim': result_resampled['whole']['dspec'][key] = DSP.downsampler(result_resampled['whole']['dspec'][key], downsample_factor, axis=-1, method='FFT') else: result_resampled[dpool]['dspec'][key] = DSP.downsampler(result_resampled[dpool]['dspec'][key], downsample_factor, axis=-1, method='FFT') self.cPhaseDS_resampled = result_resampled return result_resampled else: return result ############################################################################ def subset(self, selection=None): """ ------------------------------------------------------------------------ Return triad and time indices to select a subset of processed data Inputs: selection [NoneType or dictionary] Selection parameters based on which triad, LST, and day indices will be returned. If set to None (default), all triad, LST, and day indices will be returned. Otherwise it must be a dictionary with the following keys and values: 'triads' [NoneType or list of 3-element tuples] If set to None (default), indices of all triads are returned. Otherwise, the specific triads must be specified such as [(1,2,3), (1,2,4), ...] and their indices will be returned 'lst' [NoneType, list or numpy array] If set to None (default), indices of all LST are returned. Otherwise must be a list or numpy array containing indices to LST. 'days' [NoneType, list or numpy array] If set to None (default), indices of all days are returned. Otherwise must be a list or numpy array containing indices to days. Outputs: Tuple (triad_ind, lst_ind, day_ind, day_ind_eicpdiff) containing the triad, LST, day, and day-pair (for subsample differences) indices, each as a numpy array ------------------------------------------------------------------------ """ if selection is None: selsection = {} else: if not isinstance(selection, dict): raise TypeError('Input selection must be a dictionary') triads = map(tuple, self.cPhase.cpinfo['raw']['triads']) if 'triads' not in selection: selection['triads'] = triads if selection['triads'] is None: selection['triads'] = triads triad_ind = [triads.index(triad) for triad in selection['triads']] triad_ind = NP.asarray(triad_ind) lst_ind = None if 'lst' not in selection: if 'prelim' in self.cPhase.cpinfo['processed']: lst_ind = NP.arange(self.cPhase.cpinfo['processed']['prelim']['wts'].shape[0]) else: if selection['lst'] is None: if 'prelim' in self.cPhase.cpinfo['processed']: lst_ind = NP.arange(self.cPhase.cpinfo['processed']['prelim']['wts'].shape[0]) elif isinstance(selection['lst'], (list,NP.ndarray)): if 'prelim' in self.cPhase.cpinfo['processed']: lst_ind = selection['lst'] if NP.any(NP.logical_or(lst_ind < 0, lst_ind >= self.cPhase.cpinfo['processed']['prelim']['wts'].shape[0])): raise ValueError('Input processed lst indices out of bounds') else: raise TypeError('Wrong type for processed lst indices') if lst_ind is None: raise ValueError('LST index selection could not be performed') day_ind = None day_ind_eicpdiff = None if 'days' not in selection: if 'prelim' in self.cPhase.cpinfo['processed']: day_ind = NP.arange(self.cPhase.cpinfo['processed']['prelim']['wts'].shape[1]) if 'errinfo' in self.cPhase.cpinfo: day_ind_eicpdiff = NP.arange(len(self.cPhase.cpinfo['errinfo']['list_of_pair_of_pairs'])) else: if selection['days'] is None: if 'prelim' in self.cPhase.cpinfo['processed']: day_ind = NP.arange(self.cPhase.cpinfo['processed']['prelim']['wts'].shape[1]) if 'errinfo' in self.cPhase.cpinfo: day_ind_eicpdiff = NP.arange(len(self.cPhase.cpinfo['errinfo']['list_of_pair_of_pairs'])) elif isinstance(selection['days'], (list,NP.ndarray)): if 'prelim' in self.cPhase.cpinfo['processed']: day_ind = selection['days'] if NP.any(NP.logical_or(day_ind < 0, day_ind >= self.cPhase.cpinfo['processed']['prelim']['wts'].shape[1])): raise ValueError('Input processed day indices out of bounds') if 'errinfo' in self.cPhase.cpinfo: day_ind_eicpdiff = [i for i,item in enumerate(self.cPhase.cpinfo['errinfo']['list_of_pair_of_pairs']) if len(set(item)-set(selection['days']))==0] else: raise TypeError('Wrong type for processed day indices') if day_ind is None: raise ValueError('Day index selection could not be performed') return (triad_ind, lst_ind, day_ind, day_ind_eicpdiff) ############################################################################ def compute_power_spectrum(self, cpds=None, selection=None, autoinfo=None, xinfo=None, cosmo=cosmo100, units='K', beamparms=None): """ ------------------------------------------------------------------------ Compute power spectrum of closure phase data. It is in units of Mpc/h Inputs: cpds [dictionary] A dictionary that contains the 'oversampled' (if resample=False) and/or 'resampled' (if resample=True) delay spectrum information. If it is not specified the attributes cPhaseDS['processed'] and cPhaseDS_resampled['processed'] are used. Under each of these keys, it holds a dictionary that has the following keys and values: 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the window function applied. Accepted values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'npad' [scalar] Numbber of zero-padded channels before performing the subband delay transform. 'lags' [numpy array] lags of the subband delay spectra after padding in frequency during the transform. It is of size nlags. The lags roughly correspond to k_parallel. 'lag_kernel' [numpy array] delay transform of the frequency weights under the key 'freq_wts'. It is of size n_bl x n_win x nlags x n_t. 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff 'processed' [dictionary] Contains the following keys and values: 'dspec' [dictionary] Contains the following keys and values: 'twts' [numpy array] Weights from time-based flags that went into time-averaging. Shape=(ntriads,npol,nchan,nt) 'mean' [numpy array] Delay spectrum of closure phases based on their mean across time intervals. Shape=(nspw,npol,nt,ntriads,nlags) 'median' [numpy array] Delay spectrum of closure phases based on their median across time intervals. Shape=(nspw,npol,nt,ntriads,nlags) selection [NoneType or dictionary] Selection parameters based on which triad, LST, and day indices will be returned. If set to None (default), all triad, LST, and day indices will be returned. Otherwise it must be a dictionary with the following keys and values: 'triads' [NoneType or list of 3-element tuples] If set to None (default), indices of all triads are returned. Otherwise, the specific triads must be specified such as [(1,2,3), (1,2,4), ...] and their indices will be returned 'lst' [NoneType, list or numpy array] If set to None (default), indices of all LST are returned. Otherwise must be a list or numpy array containing indices to LST. 'days' [NoneType, list or numpy array] If set to None (default), indices of all days are returned. Otherwise must be a list or numpy array containing indices to days. autoinfo [NoneType or dictionary] Specifies parameters for processing before power spectrum in auto or cross modes. If set to None, a dictionary will be created with the default values as described below. The dictionary must have the following keys and values: 'axes' [NoneType/int/list/tuple/numpy array] Axes that will be averaged coherently before squaring (for auto) or cross-multiplying (for cross) power spectrum. If set to None (default), no axes are averaged coherently. If set to int, list, tuple or numpy array, those axes will be averaged coherently after applying the weights specified under key 'wts' along those axes. 1=lst, 2=days, 3=triads. 'wts' [NoneType/list/numpy array] If not provided (equivalent to setting it to None) or set to None (default), it is set to a one element list which is a one element numpy array of unity. Otherwise, it must be a list of same number of elements as in key 'axes' and each of these must be a numpy broadcast compatible array corresponding to each of the axis specified in 'axes' xinfo [NoneType or dictionary] Specifies parameters for processing cross power spectrum. If set to None, a dictionary will be created with the default values as described below. The dictionary must have the following keys and values: 'axes' [NoneType/int/list/tuple/numpy array] Axes over which power spectrum will be computed incoherently by cross- multiplication. If set to None (default), no cross- power spectrum is computed. If set to int, list, tuple or numpy array, cross-power over those axes will be computed incoherently by cross-multiplication. The cross-spectrum over these axes will be computed after applying the pre- and post- cross-multiplication weights specified in key 'wts'. 1=lst, 2=days, 3=triads. 'collapse_axes' [list] The axes that will be collpased after the cross-power matrix is produced by cross-multiplication. If this key is not set, it will be initialized to an empty list (default), in which case none of the axes is collapsed and the full cross-power matrix will be output. it must be a subset of values under key 'axes'. This will reduce it from a square matrix along that axis to collapsed values along each of the leading diagonals. 1=lst, 2=days, 3=triads. 'dlst' [scalar] LST interval (in mins) or difference between LST pairs which will be determined and used for cross-power spectrum. Will only apply if values under 'axes' contains the LST axis(=1). 'dlst_range' [scalar, numpy array, or NoneType] Specifies the LST difference(s) in minutes that are to be used in the computation of cross-power spectra. If a scalar, only the diagonal consisting of pairs with that LST difference will be computed. If a numpy array, those diagonals consisting of pairs with that LST difference will be computed. If set to None (default), the main diagonal (LST difference of 0) and the first off-main diagonal (LST difference of 1 unit) corresponding to pairs with 0 and 1 unit LST difference are computed. Applies only if key 'axes' contains LST axis (=1). 'avgcov' [boolean] It specifies if the collapse of square covariance matrix is to be collapsed further to a single number after applying 'postX' weights. If not set or set to False (default), this late stage collapse will not be performed. Otherwise, it will be averaged in a weighted average sense where the 'postX' weights would have already been applied during the collapsing operation 'wts' [NoneType or Dictionary] If not set, a default dictionary (see default values below) will be created. It must have the follwoing keys and values: 'preX' [list of numpy arrays] It contains pre-cross- multiplication weights. It is a list where each element in the list is a numpy array, and the number of elements in the list must match the number of entries in key 'axes'. If 'axes' is set None, 'preX' may be set to a list with one element which is a numpy array of ones. The number of elements in each of the numpy arrays must be numpy broadcastable into the number of elements along that axis in the delay spectrum. 'preXnorm' [boolean] If False (default), no normalization is done after the application of weights. If set to True, the delay spectrum will be normalized by the sum of the weights. 'postX' [list of numpy arrays] It contains post-cross- multiplication weights. It is a list where each element in the list is a numpy array, and the number of elements in the list must match the number of entries in key 'axes'. If 'axes' is set None, 'preX' may be set to a list with one element which is a numpy array of ones. The number of elements in each of the numpy arrays must be numpy broadcastable into the number of elements along that axis in the delay spectrum. 'preXnorm' [boolean] If False (default), no normalization is done after the application of 'preX' weights. If set to True, the delay spectrum will be normalized by the sum of the weights. 'postXnorm' [boolean] If False (default), no normalization is done after the application of postX weights. If set to True, the delay cross power spectrum will be normalized by the sum of the weights. cosmo [instance of cosmology class from astropy] An instance of class FLRW or default_cosmology of astropy cosmology module. Default uses Planck 2015 cosmology, with H0=100 h km/s/Mpc units [string] Specifies the units of output power spectum. Accepted values are 'Jy' and 'K' (default)) and the power spectrum will be in corresponding squared units. Output: Dictionary with the keys 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndays,) array), 'day_ind' ((ndays,) array), 'dday' ((ndays,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,). 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains 3 keys named 'whole', 'submodel', and 'residual' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum incoherently estiamted over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided bu avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum Examples: (1) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': 2, 'wts': None} xinfo = {'axes': None, 'avgcov': False, 'collapse_axes': [], 'wts':{'preX': None, 'preXnorm': False, 'postX': None, 'postXnorm': False}} Output delay power spectrum has shape (Nspw, Nlst, 1, Ntriads, Nlags) (2) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': 2, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': False, 'collapse_axes': [], 'wts':{'preX': None, 'preXnorm': False, 'postX': None, 'postXnorm': False}, 'dlst_range': None} Output delay power spectrum has shape (Nspw, 2, Nlst, 1, Ntriads, Ntriads, Nlags) diagoffsets = {1: NP.arange(n_dlst_range)}, axesmap = {1: [1,2], 3: [4,5]} (3) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': 2, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': False, 'collapse_axes': [3], 'dlst_range': [0.0, 1.0, 2.0]} Output delay power spectrum has shape (Nspw, 3, Nlst, 1, 2*Ntriads-1, Nlags) diagoffsets = {1: NP.arange(n_dlst_range), 3: NP.arange(-Ntriads,Ntriads)}, axesmap = {1: [1,2], 3: [4]} (4) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': None, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': False, 'collapse_axes': [1,3], 'dlst_range': [1.0, 2.0, 3.0, 4.0]} Output delay power spectrum has shape (Nspw, 4, Ndays, 2*Ntriads-1, Nlags) diagoffsets = {1: NP.arange(n_dlst_range), 3: NP.arange(-Ntriads,Ntriads)}, axesmap = {1: [1], 3: [3]} (5) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': None, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': True, 'collapse_axes': [3], 'dlst_range': None} Output delay power spectrum has shape (Nspw, 2, Nlst, Ndays, 1, Nlags) diagoffsets = {1: NP.arange(n_dlst_range)}, axesmap = {1: [1,2], 3: [4]} (6) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': None, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': True, 'collapse_axes': []} Output delay power spectrum has shape (Nspw, 1, Ndays, 1, Nlags) diagoffsets = {}, axesmap = {1: [1], 3: [3]} ------------------------------------------------------------------------ """ if not isinstance(units,str): raise TypeError('Input parameter units must be a string') if units.lower() == 'k': if not isinstance(beamparms, dict): raise TypeError('Input beamparms must be a dictionary') if 'freqs' not in beamparms: beamparms['freqs'] = self.f beamparms_orig = copy.deepcopy(beamparms) if autoinfo is None: autoinfo = {'axes': None, 'wts': [NP.ones(1, dtpye=NP.float)]} elif not isinstance(autoinfo, dict): raise TypeError('Input autoinfo must be a dictionary') if 'axes' not in autoinfo: autoinfo['axes'] = None else: if autoinfo['axes'] is not None: if not isinstance(autoinfo['axes'], (list,tuple,NP.ndarray,int)): raise TypeError('Value under key axes in input autoinfo must be an integer, list, tuple or numpy array') else: autoinfo['axes'] = NP.asarray(autoinfo['axes']).reshape(-1) if 'wts' not in autoinfo: if autoinfo['axes'] is not None: autoinfo['wts'] = [NP.ones(1, dtype=NP.float)] * len(autoinfo['axes']) else: autoinfo['wts'] = [NP.ones(1, dtype=NP.float)] else: if autoinfo['axes'] is not None: if not isinstance(autoinfo['wts'], list): raise TypeError('wts in input autoinfo must be a list of numpy arrays') else: if len(autoinfo['wts']) != len(autoinfo['axes']): raise ValueError('Input list of wts must be same as length of autoinfo axes') else: autoinfo['wts'] = [NP.ones(1, dtype=NP.float)] if xinfo is None: xinfo = {'axes': None, 'wts': {'preX': [NP.ones(1, dtpye=NP.float)], 'postX': [NP.ones(1, dtpye=NP.float)], 'preXnorm': False, 'postXnorm': False}} elif not isinstance(xinfo, dict): raise TypeError('Input xinfo must be a dictionary') if 'axes' not in xinfo: xinfo['axes'] = None else: if not isinstance(xinfo['axes'], (list,tuple,NP.ndarray,int)): raise TypeError('Value under key axes in input xinfo must be an integer, list, tuple or numpy array') else: xinfo['axes'] = NP.asarray(xinfo['axes']).reshape(-1) if 'wts' not in xinfo: xinfo['wts'] = {} for xkey in ['preX', 'postX']: if xinfo['axes'] is not None: xinfo['wts'][xkey] = [NP.ones(1, dtype=NP.float)] * len(xinfo['axes']) else: xinfo['wts'][xkey] = [NP.ones(1, dtype=NP.float)] xinfo['wts']['preXnorm'] = False xinfo['wts']['postXnorm'] = False else: if xinfo['axes'] is not None: if not isinstance(xinfo['wts'], dict): raise TypeError('wts in input xinfo must be a dictionary') for xkey in ['preX', 'postX']: if not isinstance(xinfo['wts'][xkey], list): raise TypeError('{0} wts in input xinfo must be a list of numpy arrays'.format(xkey)) else: if len(xinfo['wts'][xkey]) != len(xinfo['axes']): raise ValueError('Input list of {0} wts must be same as length of xinfo axes'.format(xkey)) else: for xkey in ['preX', 'postX']: xinfo['wts'][xkey] = [NP.ones(1, dtype=NP.float)] if 'preXnorm' not in xinfo['wts']: xinfo['wts']['preXnorm'] = False if 'postXnorm' not in xinfo['wts']: xinfo['wts']['postXnorm'] = False if not isinstance(xinfo['wts']['preXnorm'], NP.bool): raise TypeError('preXnorm in input xinfo must be a boolean') if not isinstance(xinfo['wts']['postXnorm'], NP.bool): raise TypeError('postXnorm in input xinfo must be a boolean') if 'avgcov' not in xinfo: xinfo['avgcov'] = False if not isinstance(xinfo['avgcov'], NP.bool): raise TypeError('avgcov under input xinfo must be boolean') if 'collapse_axes' not in xinfo: xinfo['collapse_axes'] = [] if not isinstance(xinfo['collapse_axes'], (int,list,tuple,NP.ndarray)): raise TypeError('collapse_axes under input xinfo must be an integer, tuple, list or numpy array') else: xinfo['collapse_axes'] = NP.asarray(xinfo['collapse_axes']).reshape(-1) if (autoinfo['axes'] is not None) and (xinfo['axes'] is not None): if NP.intersect1d(autoinfo['axes'], xinfo['axes']).size > 0: raise ValueError("Inputs autoinfo['axes'] and xinfo['axes'] must have no intersection") cohax = autoinfo['axes'] if cohax is None: cohax = [] incohax = xinfo['axes'] if incohax is None: incohax = [] if selection is None: selection = {'triads': None, 'lst': None, 'days': None} else: if not isinstance(selection, dict): raise TypeError('Input selection must be a dictionary') if cpds is None: cpds = {} sampling = ['oversampled', 'resampled'] for smplng in sampling: if smplng == 'oversampled': cpds[smplng] = copy.deepcopy(self.cPhaseDS) else: cpds[smplng] = copy.deepcopy(self.cPhaseDS_resampled) triad_ind, lst_ind, day_ind, day_ind_eicpdiff = self.subset(selection=selection) result = {'triads': self.cPhase.cpinfo['raw']['triads'][triad_ind], 'triads_ind': triad_ind, 'lst': self.cPhase.cpinfo['processed']['prelim']['lstbins'][lst_ind], 'lst_ind': lst_ind, 'dlst': self.cPhase.cpinfo['processed']['prelim']['dlstbins'][lst_ind], 'days': self.cPhase.cpinfo['processed']['prelim']['daybins'][day_ind], 'day_ind': day_ind, 'dday': self.cPhase.cpinfo['processed']['prelim']['diff_dbins'][day_ind]} dlstbin = NP.mean(self.cPhase.cpinfo['processed']['prelim']['dlstbins']) if 'dlst_range' in xinfo: if xinfo['dlst_range'] is None: dlst_range = None lstshifts = NP.arange(2) # LST index offsets of 0 and 1 are only estimated else: dlst_range = NP.asarray(xinfo['dlst_range']).ravel() / 60.0 # Difference in LST between a pair of LST (in hours) if dlst_range.size == 1: dlst_range = NP.insert(dlst_range, 0, 0.0) lstshifts = NP.arange(max([0, NP.ceil(1.0*dlst_range.min()/dlstbin).astype(NP.int)]), min([NP.ceil(1.0*dlst_range.max()/dlstbin).astype(NP.int), result['lst'].size])) else: dlst_range = None lstshifts = NP.arange(2) # LST index offsets of 0 and 1 are only estimated result['lstXoffsets'] = lstshifts * dlstbin # LST interval corresponding to diagonal offsets created by the LST covariance for smplng in sampling: result[smplng] = {} wl = FCNST.c / (cpds[smplng]['freq_center'] * U.Hz) z = CNST.rest_freq_HI / cpds[smplng]['freq_center'] - 1 dz = CNST.rest_freq_HI / cpds[smplng]['freq_center']**2 * cpds[smplng]['bw_eff'] dkprll_deta = DS.dkprll_deta(z, cosmo=cosmo) kprll = dkprll_deta.reshape(-1,1) * cpds[smplng]['lags'] rz_los = cosmo.comoving_distance(z) # in Mpc/h drz_los = FCNST.c * cpds[smplng]['bw_eff']*U.Hz * (1+z)**2 / (CNST.rest_freq_HI * U.Hz) / (cosmo.H0 * cosmo.efunc(z)) # in Mpc/h if units == 'Jy': jacobian1 = 1 / (cpds[smplng]['bw_eff'] * U.Hz) jacobian2 = drz_los / (cpds[smplng]['bw_eff'] * U.Hz) temperature_from_fluxdensity = 1.0 elif units == 'K': beamparms = copy.deepcopy(beamparms_orig) omega_bw = self.beam3Dvol(beamparms, freq_wts=cpds[smplng]['freq_wts']) jacobian1 = 1 / (omega_bw * U.Hz) # The steradian is present but not explicitly assigned jacobian2 = rz_los**2 * drz_los / (cpds[smplng]['bw_eff'] * U.Hz) temperature_from_fluxdensity = wl**2 / (2*FCNST.k_B) else: raise ValueError('Input value for units invalid') factor = jacobian1 * jacobian2 * temperature_from_fluxdensity**2 result[smplng]['z'] = z result[smplng]['kprll'] = kprll result[smplng]['lags'] = NP.copy(cpds[smplng]['lags']) result[smplng]['freq_center'] = cpds[smplng]['freq_center'] result[smplng]['bw_eff'] = cpds[smplng]['bw_eff'] result[smplng]['shape'] = cpds[smplng]['shape'] result[smplng]['freq_wts'] = cpds[smplng]['freq_wts'] result[smplng]['lag_corr_length'] = cpds[smplng]['lag_corr_length'] for dpool in ['whole', 'submodel', 'residual']: if dpool in cpds[smplng]: result[smplng][dpool] = {} inpshape = list(cpds[smplng]['whole']['dspec']['mean'].shape) inpshape[1] = lst_ind.size inpshape[2] = day_ind.size inpshape[3] = triad_ind.size if len(cohax) > 0: nsamples_coh = NP.prod(NP.asarray(inpshape)[NP.asarray(cohax)]) else: nsamples_coh = 1 if len(incohax) > 0: nsamples = NP.prod(NP.asarray(inpshape)[NP.asarray(incohax)]) nsamples_incoh = nsamples * (nsamples - 1) else: nsamples_incoh = 1 twts_multidim_idx = NP.ix_(lst_ind,day_ind,triad_ind,NP.arange(1)) # shape=(nlst,ndays,ntriads,1) dspec_multidim_idx = NP.ix_(NP.arange(wl.size),lst_ind,day_ind,triad_ind,NP.arange(inpshape[4])) # shape=(nspw,nlst,ndays,ntriads,nchan) max_wt_in_chan = NP.max(NP.sum(cpds[smplng]['whole']['dspec']['twts'].data, axis=(0,1,2))) select_chan = NP.argmax(NP.sum(cpds[smplng]['whole']['dspec']['twts'].data, axis=(0,1,2))) twts = NP.copy(cpds[smplng]['whole']['dspec']['twts'].data[:,:,:,[select_chan]]) # shape=(nlst,ndays,ntriads,nlags=1) if nsamples_coh > 1: awts_shape = tuple(NP.ones(cpds[smplng]['whole']['dspec']['mean'].ndim, dtype=NP.int)) awts = NP.ones(awts_shape, dtype=NP.complex) awts_shape = NP.asarray(awts_shape) for caxind,caxis in enumerate(cohax): curr_awts_shape = NP.copy(awts_shape) curr_awts_shape[caxis] = -1 awts = awts * autoinfo['wts'][caxind].reshape(tuple(curr_awts_shape)) for stat in ['mean', 'median']: if dpool == 'submodel': dspec = NP.copy(cpds[smplng][dpool]['dspec'][dspec_multidim_idx]) else: dspec = NP.copy(cpds[smplng][dpool]['dspec'][stat][dspec_multidim_idx]) if nsamples_coh > 1: if stat == 'mean': dspec = NP.sum(twts[twts_multidim_idx][NP.newaxis,...] * awts * dspec[dspec_multidim_idx], axis=cohax, keepdims=True) / NP.sum(twts[twts_multidim_idx][NP.newaxis,...] * awts, axis=cohax, keepdims=True) else: dspec = NP.median(dspec[dspec_multidim_idx], axis=cohax, keepdims=True) if nsamples_incoh > 1: expandax_map = {} wts_shape = tuple(NP.ones(dspec.ndim, dtype=NP.int)) preXwts = NP.ones(wts_shape, dtype=NP.complex) wts_shape = NP.asarray(wts_shape) for incaxind,incaxis in enumerate(xinfo['axes']): curr_wts_shape = NP.copy(wts_shape) curr_wts_shape[incaxis] = -1 preXwts = preXwts * xinfo['wts']['preX'][incaxind].reshape(tuple(curr_wts_shape)) dspec1 = NP.copy(dspec) dspec2 = NP.copy(dspec) preXwts1 = NP.copy(preXwts) preXwts2 = NP.copy(preXwts) for incax in NP.sort(incohax)[::-1]: dspec1 = NP.expand_dims(dspec1, axis=incax) preXwts1 = NP.expand_dims(preXwts1, axis=incax) if incax == 1: preXwts1_outshape = list(preXwts1.shape) preXwts1_outshape[incax+1] = dspec1.shape[incax+1] preXwts1_outshape = tuple(preXwts1_outshape) preXwts1 = NP.broadcast_to(preXwts1, preXwts1_outshape).copy() # For some strange reason the NP.broadcast_to() creates a "read-only" immutable array which is changed to writeable by copy() preXwts2_tmp = NP.expand_dims(preXwts2, axis=incax) preXwts2_shape = NP.asarray(preXwts2_tmp.shape) preXwts2_shape[incax] = lstshifts.size preXwts2_shape[incax+1] = preXwts1_outshape[incax+1] preXwts2_shape = tuple(preXwts2_shape) preXwts2 = NP.broadcast_to(preXwts2_tmp, preXwts2_shape).copy() # For some strange reason the NP.broadcast_to() creates a "read-only" immutable array which is changed to writeable by copy() dspec2_tmp = NP.expand_dims(dspec2, axis=incax) dspec2_shape = NP.asarray(dspec2_tmp.shape) dspec2_shape[incax] = lstshifts.size # dspec2_shape = NP.insert(dspec2_shape, incax, lstshifts.size) dspec2_shape = tuple(dspec2_shape) dspec2 = NP.broadcast_to(dspec2_tmp, dspec2_shape).copy() # For some strange reason the NP.broadcast_to() creates a "read-only" immutable array which is changed to writeable by copy() for lstshiftind, lstshift in enumerate(lstshifts): dspec2[:,lstshiftind,...] = NP.roll(dspec2_tmp[:,0,...], lstshift, axis=incax) dspec2[:,lstshiftind,:lstshift,...] = NP.nan preXwts2[:,lstshiftind,...] = NP.roll(preXwts2_tmp[:,0,...], lstshift, axis=incax) preXwts2[:,lstshiftind,:lstshift,...] = NP.nan else: dspec2 = NP.expand_dims(dspec2, axis=incax+1) preXwts2 = NP.expand_dims(preXwts2, axis=incax+1) expandax_map[incax] = incax + NP.arange(2) for ekey in expandax_map: if ekey > incax: expandax_map[ekey] += 1 result[smplng][dpool][stat] = factor.reshape((-1,)+tuple(NP.ones(dspec1.ndim-1, dtype=NP.int))) * (dspec1*U.Unit('Jy Hz') * preXwts1) * (dspec2*U.Unit('Jy Hz') * preXwts2).conj() if xinfo['wts']['preXnorm']: result[smplng][dpool][stat] = result[smplng][dpool][stat] / NP.nansum(preXwts1 * preXwts2.conj(), axis=NP.union1d(NP.where(logical_or(NP.asarray(preXwts1.shape)>1, NP.asarray(preXwts2.shape)>1))), keepdims=True) # Normalize by summing the weights over the expanded axes if (len(xinfo['collapse_axes']) > 0) or (xinfo['avgcov']): # if any one of collapsing of incoherent axes or # averaging of full covariance is requested diagoffsets = {} # Stores the correlation index difference along each axis. diagweights = {} # Stores the number of points summed in the trace along the offset diagonal for colaxind, colax in enumerate(xinfo['collapse_axes']): if colax == 1: shp = NP.ones(dspec.ndim, dtype=NP.int) shp[colax] = lst_ind.size multdim_idx = tuple([NP.arange(axdim) for axdim in shp]) diagweights[colax] = NP.sum(NP.logical_not(NP.isnan(dspec[multdim_idx]))) - lstshifts # diagweights[colax] = result[smplng][dpool][stat].shape[expandax_map[colax][-1]] - lstshifts if stat == 'mean': result[smplng][dpool][stat] = NP.nanmean(result[smplng][dpool][stat], axis=expandax_map[colax][-1]) else: result[smplng][dpool][stat] = NP.nanmedian(result[smplng][dpool][stat], axis=expandax_map[colax][-1]) diagoffsets[colax] = lstshifts else: pspec_unit = result[smplng][dpool][stat].si.unit result[smplng][dpool][stat], offsets, diagwts = OPS.array_trace(result[smplng][dpool][stat].si.value, offsets=None, axis1=expandax_map[colax][0], axis2=expandax_map[colax][1], outaxis='axis1') diagwts_shape = NP.ones(result[smplng][dpool][stat].ndim, dtype=NP.int) diagwts_shape[expandax_map[colax][0]] = diagwts.size diagoffsets[colax] = offsets diagweights[colax] = NP.copy(diagwts) result[smplng][dpool][stat] = result[smplng][dpool][stat] * pspec_unit / diagwts.reshape(diagwts_shape) for ekey in expandax_map: if ekey > colax: expandax_map[ekey] -= 1 expandax_map[colax] = NP.asarray(expandax_map[colax][0]).ravel() wts_shape = tuple(NP.ones(result[smplng][dpool][stat].ndim, dtype=NP.int)) postXwts = NP.ones(wts_shape, dtype=NP.complex) wts_shape = NP.asarray(wts_shape) for colaxind, colax in enumerate(xinfo['collapse_axes']): curr_wts_shape = NP.copy(wts_shape) curr_wts_shape[expandax_map[colax]] = -1 postXwts = postXwts * xinfo['wts']['postX'][colaxind].reshape(tuple(curr_wts_shape)) result[smplng][dpool][stat] = result[smplng][dpool][stat] * postXwts axes_to_sum = tuple(NP.asarray([expandax_map[colax] for colax in xinfo['collapse_axes']]).ravel()) # for post-X normalization and collapse of covariance matrix if xinfo['wts']['postXnorm']: result[smplng][dpool][stat] = result[smplng][dpool][stat] / NP.nansum(postXwts, axis=axes_to_sum, keepdims=True) # Normalize by summing the weights over the collapsed axes if xinfo['avgcov']: # collapse the axes further (postXwts have already # been applied) diagoffset_weights = 1.0 for colaxind in zip(*sorted(zip(NP.arange(xinfo['collapse_axes'].size), xinfo['collapse_axes']), reverse=True))[0]: # It is important to sort the collapsable axes in # reverse order before deleting elements below, # otherwise the axes ordering may be get messed up diagoffset_weights_shape = NP.ones(result[smplng][dpool][stat].ndim, dtype=NP.int) diagoffset_weights_shape[expandax_map[xinfo['collapse_axes'][colaxind]][0]] = diagweights[xinfo['collapse_axes'][colaxind]].size diagoffset_weights = diagoffset_weights * diagweights[xinfo['collapse_axes'][colaxind]].reshape(diagoffset_weights_shape) del diagoffsets[xinfo['collapse_axes'][colaxind]] result[smplng][dpool][stat] = NP.nansum(result[smplng][dpool][stat]*diagoffset_weights, axis=axes_to_sum, keepdims=True) / NP.nansum(diagoffset_weights, axis=axes_to_sum, keepdims=True) else: result[smplng][dpool][stat] = factor.reshape((-1,)+tuple(NP.ones(dspec.ndim-1, dtype=NP.int))) * NP.abs(dspec * U.Jy)**2 diagoffsets = {} expandax_map = {} if units == 'Jy': result[smplng][dpool][stat] = result[smplng][dpool][stat].to('Jy2 Mpc') elif units == 'K': result[smplng][dpool][stat] = result[smplng][dpool][stat].to('K2 Mpc3') else: raise ValueError('Input value for units invalid') result[smplng][dpool]['diagoffsets'] = diagoffsets result[smplng][dpool]['diagweights'] = diagweights result[smplng][dpool]['axesmap'] = expandax_map result[smplng][dpool]['nsamples_incoh'] = nsamples_incoh result[smplng][dpool]['nsamples_coh'] = nsamples_coh return result ############################################################################ def compute_power_spectrum_uncertainty(self, cpds=None, selection=None, autoinfo=None,xinfo=None, cosmo=cosmo100, units='K', beamparms=None): """ ------------------------------------------------------------------------ Compute uncertainty in the power spectrum of closure phase data. It is in units of Mpc/h Inputs: cpds [dictionary] A dictionary that contains the 'oversampled' (if resample=False) and/or 'resampled' (if resample=True) delay spectrum information on the key 'errinfo'. If it is not specified the attributes cPhaseDS['errinfo'] and cPhaseDS_resampled['errinfo'] are used. Under each of these sampling keys, it holds a dictionary that has the following keys and values: 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the window function applied. Accepted values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'npad' [scalar] Numbber of zero-padded channels before performing the subband delay transform. 'lags' [numpy array] lags of the subband delay spectra after padding in frequency during the transform. It is of size nlags. The lags roughly correspond to k_parallel. 'lag_kernel' [numpy array] delay transform of the frequency weights under the key 'freq_wts'. It is of size n_bl x n_win x nlags x n_t. 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff 'errinfo' [dictionary] It has two keys 'dspec0' and 'dspec1' each of which are dictionaries with the following keys and values: 'twts' [numpy array] Weights for the subsample difference. It is of shape (nlst, ndays, ntriads, nchan) 'mean' [numpy array] Delay spectrum of the subsample difference obtained by using the mean statistic. It is of shape (nspw, nlst, ndays, ntriads, nlags) 'median' [numpy array] Delay spectrum of the subsample difference obtained by using the median statistic. It is of shape (nspw, nlst, ndays, ntriads, nlags) selection [NoneType or dictionary] Selection parameters based on which triad, LST, and day indices will be returned. If set to None (default), all triad, LST, and day indices will be returned. Otherwise it must be a dictionary with the following keys and values: 'triads' [NoneType or list of 3-element tuples] If set to None (default), indices of all triads are returned. Otherwise, the specific triads must be specified such as [(1,2,3), (1,2,4), ...] and their indices will be returned 'lst' [NoneType, list or numpy array] If set to None (default), indices of all LST are returned. Otherwise must be a list or numpy array containing indices to LST. 'days' [NoneType, list or numpy array] If set to None (default), indices of all days are returned. Otherwise must be a list or numpy array containing indices to days. autoinfo [NoneType or dictionary] Specifies parameters for processing before power spectrum in auto or cross modes. If set to None, a dictionary will be created with the default values as described below. The dictionary must have the following keys and values: 'axes' [NoneType/int/list/tuple/numpy array] Axes that will be averaged coherently before squaring (for auto) or cross-multiplying (for cross) power spectrum. If set to None (default), no axes are averaged coherently. If set to int, list, tuple or numpy array, those axes will be averaged coherently after applying the weights specified under key 'wts' along those axes. 1=lst, 3=triads. Value of 2 for axes is not allowed since that denotes repeated days and it is along this axis that cross-power is computed regardless. 'wts' [NoneType/list/numpy array] If not provided (equivalent to setting it to None) or set to None (default), it is set to a one element list which is a one element numpy array of unity. Otherwise, it must be a list of same number of elements as in key 'axes' and each of these must be a numpy broadcast compatible array corresponding to each of the axis specified in 'axes' xinfo [NoneType or dictionary] Specifies parameters for processing cross power spectrum. If set to None, a dictionary will be created with the default values as described below. The dictionary must have the following keys and values: 'axes' [NoneType/int/list/tuple/numpy array] Axes over which power spectrum will be computed incoherently by cross- multiplication. If set to None (default), no cross- power spectrum is computed. If set to int, list, tuple or numpy array, cross-power over those axes will be computed incoherently by cross-multiplication. The cross-spectrum over these axes will be computed after applying the pre- and post- cross-multiplication weights specified in key 'wts'. 1=lst, 3=triads. Value of 2 for axes is not allowed since that denotes repeated days and it is along this axis that cross-power is computed regardless. 'collapse_axes' [list] The axes that will be collpased after the cross-power matrix is produced by cross-multiplication. If this key is not set, it will be initialized to an empty list (default), in which case none of the axes is collapsed and the full cross-power matrix will be output. it must be a subset of values under key 'axes'. This will reduce it from a square matrix along that axis to collapsed values along each of the leading diagonals. 1=lst, 3=triads. 'dlst' [scalar] LST interval (in mins) or difference between LST pairs which will be determined and used for cross-power spectrum. Will only apply if values under 'axes' contains the LST axis(=1). 'dlst_range' [scalar, numpy array, or NoneType] Specifies the LST difference(s) in minutes that are to be used in the computation of cross-power spectra. If a scalar, only the diagonal consisting of pairs with that LST difference will be computed. If a numpy array, those diagonals consisting of pairs with that LST difference will be computed. If set to None (default), the main diagonal (LST difference of 0) and the first off-main diagonal (LST difference of 1 unit) corresponding to pairs with 0 and 1 unit LST difference are computed. Applies only if key 'axes' contains LST axis (=1). 'avgcov' [boolean] It specifies if the collapse of square covariance matrix is to be collapsed further to a single number after applying 'postX' weights. If not set or set to False (default), this late stage collapse will not be performed. Otherwise, it will be averaged in a weighted average sense where the 'postX' weights would have already been applied during the collapsing operation 'wts' [NoneType or Dictionary] If not set, a default dictionary (see default values below) will be created. It must have the follwoing keys and values: 'preX' [list of numpy arrays] It contains pre-cross- multiplication weights. It is a list where each element in the list is a numpy array, and the number of elements in the list must match the number of entries in key 'axes'. If 'axes' is set None, 'preX' may be set to a list with one element which is a numpy array of ones. The number of elements in each of the numpy arrays must be numpy broadcastable into the number of elements along that axis in the delay spectrum. 'preXnorm' [boolean] If False (default), no normalization is done after the application of weights. If set to True, the delay spectrum will be normalized by the sum of the weights. 'postX' [list of numpy arrays] It contains post-cross- multiplication weights. It is a list where each element in the list is a numpy array, and the number of elements in the list must match the number of entries in key 'axes'. If 'axes' is set None, 'preX' may be set to a list with one element which is a numpy array of ones. The number of elements in each of the numpy arrays must be numpy broadcastable into the number of elements along that axis in the delay spectrum. 'preXnorm' [boolean] If False (default), no normalization is done after the application of 'preX' weights. If set to True, the delay spectrum will be normalized by the sum of the weights. 'postXnorm' [boolean] If False (default), no normalization is done after the application of postX weights. If set to True, the delay cross power spectrum will be normalized by the sum of the weights. cosmo [instance of cosmology class from astropy] An instance of class FLRW or default_cosmology of astropy cosmology module. Default uses Planck 2015 cosmology, with H0=100 h km/s/Mpc units [string] Specifies the units of output power spectum. Accepted values are 'Jy' and 'K' (default)) and the power spectrum will be in corresponding squared units. Output: Dictionary with the keys 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndaycomb,) array), 'day_ind' ((ndaycomb,) array), 'dday' ((ndaycomb,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,). 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains a key named 'errinfo' which is a dictionary. It contains information about power spectrum uncertainties obtained from subsample differences. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum uncertainties incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['errinfo']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum uncertainties incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['errinfo']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum Examples: (1) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': 2, 'wts': None} xinfo = {'axes': None, 'avgcov': False, 'collapse_axes': [], 'wts':{'preX': None, 'preXnorm': False, 'postX': None, 'postXnorm': False}} This will not do anything because axes cannot include value 2 which denote the 'days' axis and the uncertainties are obtained through subsample differencing along days axis regardless. Output delay power spectrum has shape (Nspw, Nlst, Ndaycomb, Ntriads, Nlags) (2) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': 2, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': False, 'collapse_axes': [], 'wts':{'preX': None, 'preXnorm': False, 'postX': None, 'postXnorm': False}, 'dlst_range': None} This will not do anything about coherent averaging along axis=2 because axes cannot include value 2 which denote the 'days' axis and the uncertainties are obtained through subsample differencing along days axis regardless. Output delay power spectrum has shape (Nspw, 2, Nlst, Ndaycomb, Ntriads, Ntriads, Nlags) diagoffsets = {1: NP.arange(n_dlst_range)}, axesmap = {1: [1,2], 3: [4,5]} (3) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': 2, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': False, 'collapse_axes': [3], 'dlst_range': [0.0, 1.0, 2.0]} This will not do anything about coherent averaging along axis=2 because axes cannot include value 2 which denote the 'days' axis and the uncertainties are obtained through subsample differencing along days axis regardless. Output delay power spectrum has shape (Nspw, 3, Nlst, 1, 2*Ntriads-1, Nlags) diagoffsets = {1: NP.arange(n_dlst_range), 3: NP.arange(-Ntriads,Ntriads)}, axesmap = {1: [1,2], 3: [4]} (4) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': None, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': False, 'collapse_axes': [1,3], 'dlst_range': [1.0, 2.0, 3.0, 4.0]} Output delay power spectrum has shape (Nspw, 4, Ndaycomb, 2*Ntriads-1, Nlags) diagoffsets = {1: NP.arange(n_dlst_range), 3: NP.arange(-Ntriads,Ntriads)}, axesmap = {1: [1], 3: [3]} (5) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': None, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': True, 'collapse_axes': [3], 'dlst_range': None} Output delay power spectrum has shape (Nspw, 2, Nlst, Ndays, 1, Nlags) diagoffsets = {1: NP.arange(n_dlst_range)}, axesmap = {1: [1,2], 3: [4]} (6) Input delay spectrum of shape (Nspw, Nlst, Ndays, Ntriads, Nlags) autoinfo = {'axes': None, 'wts': None} xinfo = {'axes': [1,3], 'avgcov': True, 'collapse_axes': []} Output delay power spectrum has shape (Nspw, 1, Ndays, 1, Nlags) diagoffsets = {}, axesmap = {1: [1], 3: [3]} ------------------------------------------------------------------------ """ if not isinstance(units,str): raise TypeError('Input parameter units must be a string') if units.lower() == 'k': if not isinstance(beamparms, dict): raise TypeError('Input beamparms must be a dictionary') if 'freqs' not in beamparms: beamparms['freqs'] = self.f beamparms_orig = copy.deepcopy(beamparms) if autoinfo is None: autoinfo = {'axes': None, 'wts': [NP.ones(1, dtpye=NP.float)]} elif not isinstance(autoinfo, dict): raise TypeError('Input autoinfo must be a dictionary') if 'axes' not in autoinfo: autoinfo['axes'] = None else: if autoinfo['axes'] is not None: if not isinstance(autoinfo['axes'], (list,tuple,NP.ndarray,int)): raise TypeError('Value under key axes in input autoinfo must be an integer, list, tuple or numpy array') else: autoinfo['axes'] = NP.asarray(autoinfo['axes']).reshape(-1) if 'wts' not in autoinfo: if autoinfo['axes'] is not None: autoinfo['wts'] = [NP.ones(1, dtype=NP.float)] * len(autoinfo['axes']) else: autoinfo['wts'] = [NP.ones(1, dtype=NP.float)] else: if autoinfo['axes'] is not None: if not isinstance(autoinfo['wts'], list): raise TypeError('wts in input autoinfo must be a list of numpy arrays') else: if len(autoinfo['wts']) != len(autoinfo['axes']): raise ValueError('Input list of wts must be same as length of autoinfo axes') else: autoinfo['wts'] = [NP.ones(1, dtype=NP.float)] if xinfo is None: xinfo = {'axes': None, 'wts': {'preX': [NP.ones(1, dtpye=NP.float)], 'postX': [NP.ones(1, dtpye=NP.float)], 'preXnorm': False, 'postXnorm': False}} elif not isinstance(xinfo, dict): raise TypeError('Input xinfo must be a dictionary') if 'axes' not in xinfo: xinfo['axes'] = None else: if not isinstance(xinfo['axes'], (list,tuple,NP.ndarray,int)): raise TypeError('Value under key axes in input xinfo must be an integer, list, tuple or numpy array') else: xinfo['axes'] = NP.asarray(xinfo['axes']).reshape(-1) if 'wts' not in xinfo: xinfo['wts'] = {} for xkey in ['preX', 'postX']: if xinfo['axes'] is not None: xinfo['wts'][xkey] = [NP.ones(1, dtype=NP.float)] * len(xinfo['axes']) else: xinfo['wts'][xkey] = [NP.ones(1, dtype=NP.float)] xinfo['wts']['preXnorm'] = False xinfo['wts']['postXnorm'] = False else: if xinfo['axes'] is not None: if not isinstance(xinfo['wts'], dict): raise TypeError('wts in input xinfo must be a dictionary') for xkey in ['preX', 'postX']: if not isinstance(xinfo['wts'][xkey], list): raise TypeError('{0} wts in input xinfo must be a list of numpy arrays'.format(xkey)) else: if len(xinfo['wts'][xkey]) != len(xinfo['axes']): raise ValueError('Input list of {0} wts must be same as length of xinfo axes'.format(xkey)) else: for xkey in ['preX', 'postX']: xinfo['wts'][xkey] = [NP.ones(1, dtype=NP.float)] if 'preXnorm' not in xinfo['wts']: xinfo['wts']['preXnorm'] = False if 'postXnorm' not in xinfo['wts']: xinfo['wts']['postXnorm'] = False if not isinstance(xinfo['wts']['preXnorm'], NP.bool): raise TypeError('preXnorm in input xinfo must be a boolean') if not isinstance(xinfo['wts']['postXnorm'], NP.bool): raise TypeError('postXnorm in input xinfo must be a boolean') if 'avgcov' not in xinfo: xinfo['avgcov'] = False if not isinstance(xinfo['avgcov'], NP.bool): raise TypeError('avgcov under input xinfo must be boolean') if 'collapse_axes' not in xinfo: xinfo['collapse_axes'] = [] if not isinstance(xinfo['collapse_axes'], (int,list,tuple,NP.ndarray)): raise TypeError('collapse_axes under input xinfo must be an integer, tuple, list or numpy array') else: xinfo['collapse_axes'] = NP.asarray(xinfo['collapse_axes']).reshape(-1) if (autoinfo['axes'] is not None) and (xinfo['axes'] is not None): if NP.intersect1d(autoinfo['axes'], xinfo['axes']).size > 0: raise ValueError("Inputs autoinfo['axes'] and xinfo['axes'] must have no intersection") cohax = autoinfo['axes'] if cohax is None: cohax = [] if 2 in cohax: # Remove axis=2 from cohax if isinstance(cohax, list): cohax.remove(2) if isinstance(cohax, NP.ndarray): cohax = cohax.tolist() cohax.remove(2) cohax = NP.asarray(cohax) incohax = xinfo['axes'] if incohax is None: incohax = [] if 2 in incohax: # Remove axis=2 from incohax if isinstance(incohax, list): incohax.remove(2) if isinstance(incohax, NP.ndarray): incohax = incohax.tolist() incohax.remove(2) incohax = NP.asarray(incohax) if selection is None: selection = {'triads': None, 'lst': None, 'days': None} else: if not isinstance(selection, dict): raise TypeError('Input selection must be a dictionary') if cpds is None: cpds = {} sampling = ['oversampled', 'resampled'] for smplng in sampling: if smplng == 'oversampled': cpds[smplng] = copy.deepcopy(self.cPhaseDS) else: cpds[smplng] = copy.deepcopy(self.cPhaseDS_resampled) triad_ind, lst_ind, day_ind, day_ind_eicpdiff = self.subset(selection=selection) result = {'triads': self.cPhase.cpinfo['raw']['triads'][triad_ind], 'triads_ind': triad_ind, 'lst': self.cPhase.cpinfo['errinfo']['lstbins'][lst_ind], 'lst_ind': lst_ind, 'dlst': self.cPhase.cpinfo['errinfo']['dlstbins'][lst_ind], 'days': self.cPhase.cpinfo['errinfo']['daybins'][day_ind], 'day_ind': day_ind_eicpdiff, 'dday': self.cPhase.cpinfo['errinfo']['diff_dbins'][day_ind]} dlstbin = NP.mean(self.cPhase.cpinfo['errinfo']['dlstbins']) if 'dlst_range' in xinfo: if xinfo['dlst_range'] is None: dlst_range = None lstshifts = NP.arange(2) # LST index offsets of 0 and 1 are only estimated else: dlst_range = NP.asarray(xinfo['dlst_range']).ravel() / 60.0 # Difference in LST between a pair of LST (in hours) if dlst_range.size == 1: dlst_range = NP.insert(dlst_range, 0, 0.0) lstshifts = NP.arange(max([0, NP.ceil(1.0*dlst_range.min()/dlstbin).astype(NP.int)]), min([NP.ceil(1.0*dlst_range.max()/dlstbin).astype(NP.int), result['lst'].size])) else: dlst_range = None lstshifts = NP.arange(2) # LST index offsets of 0 and 1 are only estimated result['lstXoffsets'] = lstshifts * dlstbin # LST interval corresponding to diagonal offsets created by the LST covariance for smplng in sampling: result[smplng] = {} wl = FCNST.c / (cpds[smplng]['freq_center'] * U.Hz) z = CNST.rest_freq_HI / cpds[smplng]['freq_center'] - 1 dz = CNST.rest_freq_HI / cpds[smplng]['freq_center']**2 * cpds[smplng]['bw_eff'] dkprll_deta = DS.dkprll_deta(z, cosmo=cosmo) kprll = dkprll_deta.reshape(-1,1) * cpds[smplng]['lags'] rz_los = cosmo.comoving_distance(z) # in Mpc/h drz_los = FCNST.c * cpds[smplng]['bw_eff']*U.Hz * (1+z)**2 / (CNST.rest_freq_HI * U.Hz) / (cosmo.H0 * cosmo.efunc(z)) # in Mpc/h if units == 'Jy': jacobian1 = 1 / (cpds[smplng]['bw_eff'] * U.Hz) jacobian2 = drz_los / (cpds[smplng]['bw_eff'] * U.Hz) temperature_from_fluxdensity = 1.0 elif units == 'K': beamparms = copy.deepcopy(beamparms_orig) omega_bw = self.beam3Dvol(beamparms, freq_wts=cpds[smplng]['freq_wts']) jacobian1 = 1 / (omega_bw * U.Hz) # The steradian is present but not explicitly assigned jacobian2 = rz_los**2 * drz_los / (cpds[smplng]['bw_eff'] * U.Hz) temperature_from_fluxdensity = wl**2 / (2*FCNST.k_B) else: raise ValueError('Input value for units invalid') factor = jacobian1 * jacobian2 * temperature_from_fluxdensity**2 result[smplng]['z'] = z result[smplng]['kprll'] = kprll result[smplng]['lags'] = NP.copy(cpds[smplng]['lags']) result[smplng]['freq_center'] = cpds[smplng]['freq_center'] result[smplng]['bw_eff'] = cpds[smplng]['bw_eff'] result[smplng]['shape'] = cpds[smplng]['shape'] result[smplng]['freq_wts'] = cpds[smplng]['freq_wts'] result[smplng]['lag_corr_length'] = cpds[smplng]['lag_corr_length'] dpool = 'errinfo' if dpool in cpds[smplng]: result[smplng][dpool] = {} inpshape = list(cpds[smplng][dpool]['dspec0']['mean'].shape) inpshape[1] = lst_ind.size inpshape[2] = day_ind_eicpdiff.size inpshape[3] = triad_ind.size if len(cohax) > 0: nsamples_coh = NP.prod(NP.asarray(inpshape)[NP.asarray(cohax)]) else: nsamples_coh = 1 if len(incohax) > 0: nsamples = NP.prod(NP.asarray(inpshape)[NP.asarray(incohax)]) nsamples_incoh = nsamples * (nsamples - 1) else: nsamples_incoh = 1 twts_multidim_idx = NP.ix_(lst_ind,day_ind_eicpdiff,triad_ind,NP.arange(1)) # shape=(nlst,ndays,ntriads,1) dspec_multidim_idx = NP.ix_(NP.arange(wl.size),lst_ind,day_ind_eicpdiff,triad_ind,NP.arange(inpshape[4])) # shape=(nspw,nlst,ndays,ntriads,nchan) max_wt_in_chan = NP.max(NP.sum(cpds[smplng]['errinfo']['dspec0']['twts'].data, axis=(0,1,2,3))) select_chan = NP.argmax(NP.sum(cpds[smplng]['errinfo']['dspec0']['twts'].data, axis=(0,1,2,3))) twts = {'0': NP.copy(cpds[smplng]['errinfo']['dspec0']['twts'].data[:,:,:,[select_chan]]), '1': NP.copy(cpds[smplng]['errinfo']['dspec1']['twts'].data[:,:,:,[select_chan]])} if nsamples_coh > 1: awts_shape = tuple(NP.ones(cpds[smplng]['errinfo']['dspec']['mean'].ndim, dtype=NP.int)) awts = NP.ones(awts_shape, dtype=NP.complex) awts_shape = NP.asarray(awts_shape) for caxind,caxis in enumerate(cohax): curr_awts_shape = NP.copy(awts_shape) curr_awts_shape[caxis] = -1 awts = awts * autoinfo['wts'][caxind].reshape(tuple(curr_awts_shape)) for stat in ['mean', 'median']: dspec0 = NP.copy(cpds[smplng][dpool]['dspec0'][stat][dspec_multidim_idx]) dspec1 = NP.copy(cpds[smplng][dpool]['dspec1'][stat][dspec_multidim_idx]) if nsamples_coh > 1: if stat == 'mean': dspec0 = NP.sum(twts['0'][NP.newaxis,...] * awts * dspec0, axis=cohax, keepdims=True) / NP.sum(twts['0'][twts_multidim_idx][NP.newaxis,...] * awts, axis=cohax, keepdims=True) dspec1 = NP.sum(twts['1'][NP.newaxis,...] * awts * dspec1, axis=cohax, keepdims=True) / NP.sum(twts['1'][twts_multidim_idx][NP.newaxis,...] * awts, axis=cohax, keepdims=True) else: dspec0 = NP.median(dspec0, axis=cohax, keepdims=True) dspec1 = NP.median(dspec1, axis=cohax, keepdims=True) if nsamples_incoh > 1: expandax_map = {} wts_shape = tuple(NP.ones(dspec0.ndim, dtype=NP.int)) preXwts = NP.ones(wts_shape, dtype=NP.complex) wts_shape = NP.asarray(wts_shape) for incaxind,incaxis in enumerate(xinfo['axes']): curr_wts_shape = NP.copy(wts_shape) curr_wts_shape[incaxis] = -1 preXwts = preXwts * xinfo['wts']['preX'][incaxind].reshape(tuple(curr_wts_shape)) preXwts0 = NP.copy(preXwts) preXwts1 = NP.copy(preXwts) for incax in NP.sort(incohax)[::-1]: dspec0 = NP.expand_dims(dspec0, axis=incax) preXwts0 = NP.expand_dims(preXwts0, axis=incax) if incax == 1: preXwts0_outshape = list(preXwts0.shape) preXwts0_outshape[incax+1] = dspec0.shape[incax+1] preXwts0_outshape = tuple(preXwts0_outshape) preXwts0 = NP.broadcast_to(preXwts0, preXwts0_outshape).copy() # For some strange reason the NP.broadcast_to() creates a "read-only" immutable array which is changed to writeable by copy() preXwts1_tmp = NP.expand_dims(preXwts1, axis=incax) preXwts1_shape = NP.asarray(preXwts1_tmp.shape) preXwts1_shape[incax] = lstshifts.size preXwts1_shape[incax+1] = preXwts0_outshape[incax+1] preXwts1_shape = tuple(preXwts1_shape) preXwts1 = NP.broadcast_to(preXwts1_tmp, preXwts1_shape).copy() # For some strange reason the NP.broadcast_to() creates a "read-only" immutable array which is changed to writeable by copy() dspec1_tmp = NP.expand_dims(dspec1, axis=incax) dspec1_shape = NP.asarray(dspec1_tmp.shape) dspec1_shape[incax] = lstshifts.size # dspec1_shape = NP.insert(dspec1_shape, incax, lstshifts.size) dspec1_shape = tuple(dspec1_shape) dspec1 = NP.broadcast_to(dspec1_tmp, dspec1_shape).copy() # For some strange reason the NP.broadcast_to() creates a "read-only" immutable array which is changed to writeable by copy() for lstshiftind, lstshift in enumerate(lstshifts): dspec1[:,lstshiftind,...] = NP.roll(dspec1_tmp[:,0,...], lstshift, axis=incax) dspec1[:,lstshiftind,:lstshift,...] = NP.nan preXwts1[:,lstshiftind,...] = NP.roll(preXwts1_tmp[:,0,...], lstshift, axis=incax) preXwts1[:,lstshiftind,:lstshift,...] = NP.nan else: dspec1 = NP.expand_dims(dspec1, axis=incax+1) preXwts1 = NP.expand_dims(preXwts1, axis=incax+1) expandax_map[incax] = incax + NP.arange(2) for ekey in expandax_map: if ekey > incax: expandax_map[ekey] += 1 result[smplng][dpool][stat] = factor.reshape((-1,)+tuple(NP.ones(dspec0.ndim-1, dtype=NP.int))) * (dspec0*U.Unit('Jy Hz') * preXwts0) * (dspec1*U.Unit('Jy Hz') * preXwts1).conj() if xinfo['wts']['preXnorm']: result[smplng][dpool][stat] = result[smplng][dpool][stat] / NP.nansum(preXwts0 * preXwts1.conj(), axis=NP.union1d(NP.where(logical_or(NP.asarray(preXwts0.shape)>1, NP.asarray(preXwts1.shape)>1))), keepdims=True) # Normalize by summing the weights over the expanded axes if (len(xinfo['collapse_axes']) > 0) or (xinfo['avgcov']): # Remove axis=2 if present if 2 in xinfo['collapse_axes']: # Remove axis=2 from cohax if isinstance(xinfo['collapse_axes'], list): xinfo['collapse_axes'].remove(2) if isinstance(xinfo['collapse_axes'], NP.ndarray): xinfo['collapse_axes'] = xinfo['collapse_axes'].tolist() xinfo['collapse_axes'].remove(2) xinfo['collapse_axes'] = NP.asarray(xinfo['collapse_axes']) if (len(xinfo['collapse_axes']) > 0) or (xinfo['avgcov']): # if any one of collapsing of incoherent axes or # averaging of full covariance is requested diagoffsets = {} # Stores the correlation index difference along each axis. diagweights = {} # Stores the number of points summed in the trace along the offset diagonal for colaxind, colax in enumerate(xinfo['collapse_axes']): if colax == 1: shp = NP.ones(cpds[smplng][dpool]['dspec0'][stat].ndim, dtype=NP.int) shp[colax] = lst_ind.size multdim_idx = tuple([NP.arange(axdim) for axdim in shp]) diagweights[colax] = NP.sum(NP.logical_not(NP.isnan(cpds[smplng][dpool]['dspec0'][stat][dspec_multidim_idx][multdim_idx]))) - lstshifts # diagweights[colax] = result[smplng][dpool][stat].shape[expandax_map[colax][-1]] - lstshifts if stat == 'mean': result[smplng][dpool][stat] = NP.nanmean(result[smplng][dpool][stat], axis=expandax_map[colax][-1]) else: result[smplng][dpool][stat] = NP.nanmedian(result[smplng][dpool][stat], axis=expandax_map[colax][-1]) diagoffsets[colax] = lstshifts else: pspec_unit = result[smplng][dpool][stat].si.unit result[smplng][dpool][stat], offsets, diagwts = OPS.array_trace(result[smplng][dpool][stat].si.value, offsets=None, axis1=expandax_map[colax][0], axis2=expandax_map[colax][1], outaxis='axis1') diagwts_shape = NP.ones(result[smplng][dpool][stat].ndim, dtype=NP.int) diagwts_shape[expandax_map[colax][0]] = diagwts.size diagoffsets[colax] = offsets diagweights[colax] = NP.copy(diagwts) result[smplng][dpool][stat] = result[smplng][dpool][stat] * pspec_unit / diagwts.reshape(diagwts_shape) for ekey in expandax_map: if ekey > colax: expandax_map[ekey] -= 1 expandax_map[colax] = NP.asarray(expandax_map[colax][0]).ravel() wts_shape = tuple(NP.ones(result[smplng][dpool][stat].ndim, dtype=NP.int)) postXwts = NP.ones(wts_shape, dtype=NP.complex) wts_shape = NP.asarray(wts_shape) for colaxind, colax in enumerate(xinfo['collapse_axes']): curr_wts_shape = NP.copy(wts_shape) curr_wts_shape[expandax_map[colax]] = -1 postXwts = postXwts * xinfo['wts']['postX'][colaxind].reshape(tuple(curr_wts_shape)) result[smplng][dpool][stat] = result[smplng][dpool][stat] * postXwts axes_to_sum = tuple(NP.asarray([expandax_map[colax] for colax in xinfo['collapse_axes']]).ravel()) # for post-X normalization and collapse of covariance matrix if xinfo['wts']['postXnorm']: result[smplng][dpool][stat] = result[smplng][dpool][stat] / NP.nansum(postXwts, axis=axes_to_sum, keepdims=True) # Normalize by summing the weights over the collapsed axes if xinfo['avgcov']: # collapse the axes further (postXwts have already # been applied) diagoffset_weights = 1.0 result[smplng][dpool][stat] = NP.nanmean(result[smplng][dpool][stat], axis=axes_to_sum, keepdims=True) for colaxind in zip(*sorted(zip(NP.arange(xinfo['collapse_axes'].size), xinfo['collapse_axes']), reverse=True))[0]: # It is import to sort the collapsable axes in # reverse order before deleting elements below, # otherwise the axes ordering may be get messed up diagoffset_weights_shape = NP.ones(result[smplng][dpool][stat].ndim, dtype=NP.int) diagoffset_weights_shape[expandax_map[xinfo['collapse_axes'][colaxind]][0]] = diagweights[xinfo['collapse_axes'][colaxind]].size diagoffset_weights = diagoffset_weights * diagweights[xinfo['collapse_axes'][colaxind]].reshape(diagoffset_weights_shape) del diagoffsets[xinfo['collapse_axes'][colaxind]] result[smplng][dpool][stat] = NP.nansum(result[smplng][dpool][stat]*diagoffset_weights, axis=axes_to_sum, keepdims=True) / NP.nansum(diagoffset_weights, axis=axes_to_sum, keepdims=True) else: result[smplng][dpool][stat] = factor.reshape((-1,)+tuple(NP.ones(dspec.ndim-1, dtype=NP.int))) * NP.abs(dspec * U.Jy)**2 diagoffsets = {} expandax_map = {} if units == 'Jy': result[smplng][dpool][stat] = result[smplng][dpool][stat].to('Jy2 Mpc') elif units == 'K': result[smplng][dpool][stat] = result[smplng][dpool][stat].to('K2 Mpc3') else: raise ValueError('Input value for units invalid') result[smplng][dpool]['diagoffsets'] = diagoffsets result[smplng][dpool]['diagweights'] = diagweights result[smplng][dpool]['axesmap'] = expandax_map result[smplng][dpool]['nsamples_incoh'] = nsamples_incoh result[smplng][dpool]['nsamples_coh'] = nsamples_coh return result ############################################################################ def rescale_power_spectrum(self, cpdps, visfile, blindex, visunits='Jy'): """ ------------------------------------------------------------------------ Rescale power spectrum to dimensional quantity by converting the ratio given visibility amplitude information Inputs: cpdps [dictionary] Dictionary with the keys 'triads', 'triads_ind', 'lstbins', 'lst', 'dlst', 'lst_ind', 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,). 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'mean' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape=(nspw,nlst,ndays,ntriads,nchan). It has units of Mpc/h. If incohax was set, those axes will be set to 1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape=(nspw,nlst,ndays,ntriads,nchan). It has units of Mpc/h. If incohax was set, those axes will be set to 1. visfile [string] Full path to the visibility file in NPZ format that consists of the following keys and values: 'vis' [numpy array] Complex visibilities averaged over all redundant baselines of different classes of baselines. It is of shape (nlst,nbl,nchan) 'last' [numpy array] Array of LST in units of days where the fractional part is LST in days. blindex [numpy array] 3-element array of baseline indices to use in selecting the triad corresponding to closure phase power spectrum in cpdps. It will index into the 'vis' array in NPZ file visfile visunits [string] Units of visibility in visfile. Accepted values are 'Jy' (default; for Jansky) and 'K' (for Kelvin) Outputs: Same dictionary as input cpdps except it has the following additional keys and values. Under 'resampled' and 'oversampled' keys, there are now new keys called 'mean-absscale' and 'median-absscale' keys which are each dictionaries with the following keys and values: 'converted' [numpy array] Values of power (in units of visunits^2) with same shape as the values under 'mean' and 'median' keys -- (nspw,nlst,ndays,ntriads,nchan) unless some of those axes have already been averaged coherently or incoherently 'units' [string] Units of power in key 'converted'. Its values are square of the input visunits -- 'Jy^2' or 'K^2' ------------------------------------------------------------------------ """ if not isinstance(cpdps, dict): raise TypeError('Input cpdps must be a dictionary') if not isinstance(visfile, str): raise TypeError('Input visfile must be a string containing full file path') if isinstance(blindex, NP.ndarray): raise TypeError('Input blindex must be a numpy array') if blindex.size != 3: raise ValueError('Input blindex must be a 3-element array') if not isinstance(visunits, str): raise TypeError('Input visunits must be a string') if visunits not in ['Jy', 'K']: raise ValueError('Input visunits currently not accepted') datapool = [] for dpool in ['resampled', 'oversampled']: if dpool in cpdps: datapool += [dpool] scaleinfo = NP.load(visfile) vis = scaleinfo['vis'][:,blindex,:] # shape=(nlst,nbl,nchan) vis_lstfrac, vis_lstint = NP.modf(scaleinfo['last']) # shape=(nlst,) vis_lstHA = vis_lstfrac * 24.0 # in hours vis_lstdeg = vis_lstHA * 15.0 # in degrees cpdps_lstdeg = 15.0*cpdps['lst'] # in degrees lstmatrix = cpdps_lstdeg.reshape(-1,1) - vis_lstdeg.reshape(1,-1) lstmatrix[NP.abs(lstmatrix) > 180.0] -= 360.0 ind_minlstsep = NP.argmin(NP.abs(lstmatrix), axis=1) vis_nearestLST = vis[blindex,ind_minlstsep,:] # nlst x nbl x nchan for dpool in datapool: freq_wts = cpdps[dpool]['freq_wts'] # nspw x nchan freqwtd_avgvis_nearestLST = NP.sum(freq_wts[:,NP.newaxis,NP.newaxis,:] * vis_nearestLST[NP.newaxis,:,:,:], axis=-1, keepdims=True) / NP.sum(freq_wts[:,NP.newaxis,NP.newaxis,:], axis=-1, keepdims=True) # nspw x nlst x nbl x (nchan=1) vis_square_multscalar = 1 / NP.sum(1/NP.abs(freqwtd_avgvis_nearestLST)**2, axis=2, keepdims=True) # nspw x nlst x (nbl=1) x (nchan=1) for stat in ['mean', 'median']: cpdps[dpool][stat+'-absscale'] = {} cpdps[dpool][stat+'-absscale']['converted'] = cpdps[dpool][stat] * vis_square_multscalar[:,:,NP.newaxis,:,:] # nspw x nlst x ndays x ntriads x nlags cpdps[dpool][stat+'-absscale']['units'] = '{0}^2'.format(visunits) return cpdps ############################################################################ def average_rescaled_power_spectrum(rcpdps, avgax, kprll_llim=None): """ ------------------------------------------------------------------------ Average the rescaled power spectrum with physical units along certain axes with inverse variance or regular averaging Inputs: rcpdps [dictionary] Dictionary with the keys 'triads', 'triads_ind', 'lstbins', 'lst', 'dlst', 'lst_ind', 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,). 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'mean' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape=(nspw,nlst,ndays,ntriads,nchan). It has units of Mpc/h. If incohax was set, those axes will be set to 1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape=(nspw,nlst,ndays,ntriads,nchan). It has units of Mpc/h. If incohax was set, those axes will be set to 1. 'mean-absscale' and 'median-absscale' [dictionary] Each dictionary consists of the following keys and values: 'converted' [numpy array] Values of power (in units of value in key 'units') with same shape as the values under 'mean' and 'median' keys -- (nspw,nlst,ndays,ntriads,nchan) unless some of those axes have already been averaged coherently or incoherently 'units' [string] Units of power in key 'converted'. Its values are square of either 'Jy^2' or 'K^2' avgax [int, list, tuple] Specifies the axes over which the power in absolute scale (with physical units) should be averaged. This counts as incoherent averaging. The averaging is done with inverse-variance weighting if the input kprll_llim is set to choose the range of kprll from which the variance and inverse variance will be determined. Otherwise, a regular averaging is performed. kprll_llim [float] Lower limit of absolute value of kprll (in Mpc/h) beyond which the variance will be determined in order to estimate the inverse variance weights. If set to None, the weights are uniform. If set to a value, values beyond this kprll_llim are used to estimate the variance and hence the inverse-variance weights. Outputs: Dictionary with the same structure as the input dictionary rcpdps except with the following additional keys and values. Under the dictionaries under keys 'mean-absscale' and 'median-absscale', there is an additional key-value pair: 'avg' [numpy array] Values of power (in units of value in key 'units') with same shape as the values under 'converted' -- (nspw,nlst,ndays,ntriads,nchan) except those axes which were averaged in this member function, and those axes will be retained but with axis size=1. ------------------------------------------------------------------------ """ if not isinstance(rcpdps, dict): raise TypeError('Input rcpdps must be a dictionary') if isinstance(avgax, int): if avgax >= 4: raise ValueError('Input avgax has a value greater than the maximum axis number over which averaging can be performed') avgax = NP.asarray(avgax) elif isinstance(avgax, (list,tuple)): avgax = NP.asarray(avgax) if NP.any(avgax >= 4): raise ValueError('Input avgax contains a value greater than the maximum axis number over which averaging can be performed') else: raise TypeError('Input avgax must be an integer, list, or tuple') if kprll_llim is not None: if not isinstance(kprll_llim, (int,float)): raise TypeError('Input kprll_llim must be a scalar') kprll_llim = NP.abs(kprll_llim) for dpool in datapool: for stat in ['mean', 'median']: wts = NP.ones((1,1,1,1,1)) if kprll_llim is not None: kprll_ind = NP.abs(rcpdps[dpool]['kprll']) >= kprll_llim # nspw x nlags if NP.any(kprll_ind): if rcpdps[dpool]['z'].size > 1: indsets = [NP.where(kprll_ind[i,:])[0] for i in range(rcpdps[dpool]['z'].size)] common_kprll_ind = reduce(NP.intersect1d(indsets)) multidim_idx = NP.ix_(NP.arange(rcpdps[dpool]['freq_center'].size), NP.arange(rcpdps['lst'].size), NP.arange(rcpdps['days'].size), NP.arange(rcpdps['triads'].size), common_kprll_ind) else: multidim_idx = NP.ix_(NP.arange(rcpdps[dpool]['freq_center'].size), NP.arange(rcpdps['lst'].size), NP.arange(rcpdps['days'].size), NP.arange(rcpdps['triads'].size), kprll_ind[0,:]) else: multidim_idx = NP.ix_(NP.arange(rcpdps[dpool]['freq_center'].size), NP.arange(rcpdps['lst'].size), NP.arange(rcpdps['days'].size), NP.arange(rcpdps['triads'].size), rcpdps[dpool]['lags'].size) wts = 1 / NP.var(rcpdps[dpool][stat]['absscale']['rescale'][multidim_idx], axis=avgax, keepdims=True) rcpdps[dpool][stat]['absscale']['avg'] = NP.sum(wts * rcpdps[dpool][stat]['absscale']['rescale'], axis=avgax, keepdims=True) / NP.sum(wts, axis=avgax, keepdims=True) return rcpdps ############################################################################ def beam3Dvol(self, beamparms, freq_wts=None): """ ------------------------------------------------------------------------ Compute three-dimensional (transverse-LOS) volume of the beam in units of "Sr Hz". Inputs: beamparms [dictionary] Contains beam information. It contains the following keys and values: 'beamfile' [string] If set to string, should contain the filename relative to default path or absolute path containing the power pattern. If both 'beamfile' and 'telescope' are set, the 'beamfile' will be used. The latter is used for determining analytic beam. 'filepathtype' [string] Specifies if the beamfile is to be found at the 'default' location or a 'custom' location. If set to 'default', the PRISim path is searched for the beam file. Only applies if 'beamfile' key is set. 'filefmt' [string] External file format of the beam. Accepted values are 'uvbeam', 'fits' and 'hdf5' 'telescope' [dictionary] Information used to analytically determine the power pattern. used only if 'beamfile' is not set or set to None. This specifies the type of element, its size and orientation. It consists of the following keys and values: 'id' [string] If set, will ignore the other keys and use telescope details for known telescopes. Accepted values are 'mwa', 'vla', 'gmrt', 'hera', 'paper', 'hirax', and 'chime' 'shape' [string] Shape of antenna element. Accepted values are 'dipole', 'delta', 'dish', 'gaussian', 'rect' and 'square'. Will be ignored if key 'id' is set. 'delta' denotes a delta function for the antenna element which has an isotropic radiation pattern. 'delta' is the default when keys 'id' and 'shape' are not set. 'size' [scalar or 2-element list/numpy array] Diameter of the telescope dish (in meters) if the key 'shape' is set to 'dish', side of the square aperture (in meters) if the key 'shape' is set to 'square', 2-element sides if key 'shape' is set to 'rect', or length of the dipole if key 'shape' is set to 'dipole'. Will be ignored if key 'shape' is set to 'delta'. Will be ignored if key 'id' is set and a preset value used for the diameter or dipole. 'orientation' [list or numpy array] If key 'shape' is set to dipole, it refers to the orientation of the dipole element unit vector whose magnitude is specified by length. If key 'shape' is set to 'dish', it refers to the position on the sky to which the dish is pointed. For a dipole, this unit vector must be provided in the local ENU coordinate system aligned with the direction cosines coordinate system or in the Alt-Az coordinate system. This will be used only when key 'shape' is set to 'dipole'. This could be a 2-element vector (transverse direction cosines) where the third (line-of-sight) component is determined, or a 3-element vector specifying all three direction cosines or a two-element coordinate in Alt-Az system. If not provided it defaults to an eastward pointing dipole. If key 'shape' is set to 'dish' or 'gaussian', the orientation refers to the pointing center of the dish on the sky. It can be provided in Alt-Az system as a two-element vector or in the direction cosine coordinate system as a two- or three-element vector. If not set in the case of a dish element, it defaults to zenith. This is not to be confused with the key 'pointing_center' in dictionary 'pointing_info' which refers to the beamformed pointing center of the array. The coordinate system is specified by the key 'ocoords' 'ocoords' [string] specifies the coordinate system for key 'orientation'. Accepted values are 'altaz' and 'dircos'. 'element_locs' [2- or 3-column array] Element locations that constitute the tile. Each row specifies location of one element in the tile. The locations must be specified in local ENU coordinate system. First column specifies along local east, second along local north and the third along local up. If only two columns are specified, the third column is assumed to be zeros. If 'elements_locs' is not provided, it assumed to be a one-element system and not a phased array as far as determination of primary beam is concerned. 'groundplane' [scalar] height of telescope element above the ground plane (in meteres). Default=None will denote no ground plane effects. 'ground_modify' [dictionary] contains specifications to modify the analytically computed ground plane pattern. If absent, the ground plane computed will not be modified. If set, it may contain the following keys: 'scale' [scalar] positive value to scale the modifying factor with. If not set, the scale factor to the modification is unity. 'max' [scalar] positive value to clip the modified and scaled values to. If not set, there is no upper limit 'freqs' [numpy array] Numpy array denoting frequencies (in Hz) at which beam integrals are to be evaluated. If set to None, it will automatically be set from the class attribute. 'nside' [integer] NSIDE parameter for determining and interpolating the beam. If not set, it will be set to 64 (default). 'chromatic' [boolean] If set to true, a chromatic power pattern is used. If false, an achromatic power pattern is used based on a reference frequency specified in 'select_freq'. 'select_freq' [scalar] Selected frequency for the achromatic beam. If not set, it will be determined to be mean of the array in 'freqs' 'spec_interp' [string] Method to perform spectral interpolation. Accepted values are those accepted in scipy.interpolate.interp1d() and 'fft'. Default='cubic'. freq_wts [numpy array] Frequency weights centered on different spectral windows or redshifts. Its shape is (nwin,nchan) and should match the number of spectral channels in input parameter 'freqs' under 'beamparms' dictionary Output: omega_bw [numpy array] Integral of the square of the power pattern over transverse and spectral axes. Its shape is (nwin,) ------------------------------------------------------------------------ """ if not isinstance(beamparms, dict): raise TypeError('Input beamparms must be a dictionary') if ('beamfile' not in beamparms) and ('telescope' not in beamparms): raise KeyError('Input beamparms does not contain either "beamfile" or "telescope" keys') if 'freqs' not in beamparms: raise KeyError('Key "freqs" not found in input beamparms') if not isinstance(beamparms['freqs'], NP.ndarray): raise TypeError('Key "freqs" in input beamparms must contain a numpy array') if 'nside' not in beamparms: beamparms['nside'] = 64 if not isinstance(beamparms['nside'], int): raise TypeError('"nside" parameter in input beamparms must be an integer') if 'chromatic' not in beamparms: beamparms['chromatic'] = True else: if not isinstance(beamparms['chromatic'], bool): raise TypeError('Beam chromaticity parameter in input beamparms must be a boolean') theta, phi = HP.pix2ang(beamparms['nside'], NP.arange(HP.nside2npix(beamparms['nside']))) theta_phi = NP.hstack((theta.reshape(-1,1), phi.reshape(-1,1))) if beamparms['beamfile'] is not None: if 'filepathtype' in beamparms: if beamparms['filepathtype'] == 'default': beamparms['beamfile'] = prisim_path+'data/beams/'+beamparms['beamfile'] if 'filefmt' not in beamparms: raise KeyError('Input beam file format must be specified for an external beam') if beamparms['filefmt'].lower() in ['hdf5', 'fits', 'uvbeam']: beamparms['filefmt'] = beamparms['filefmt'].lower() else: raise ValueError('Invalid beam file format specified') if 'pol' not in beamparms: raise KeyError('Beam polarization must be specified') if not beamparms['chromatic']: if 'select_freq' not in beamparms: raise KeyError('Input reference frequency for achromatic behavior must be specified') if beamparms['select_freq'] is None: beamparms['select_freq'] = NP.mean(beamparms['freqs']) if 'spec_interp' not in beamparms: beamparms['spec_interp'] = 'cubic' if beamparms['filefmt'] == 'fits': external_beam = fits.getdata(beamparms['beamfile'], extname='BEAM_{0}'.format(beamparms['pol'])) external_beam_freqs = fits.getdata(beamparms['beamfile'], extname='FREQS_{0}'.format(beamparms['pol'])) # in MHz external_beam = external_beam.reshape(-1,external_beam_freqs.size) # npix x nfreqs elif beamparms['filefmt'] == 'uvbeam': if uvbeam_module_found: uvbm = UVBeam() uvbm.read_beamfits(beamparms['beamfile']) axis_vec_ind = 0 # for power beam spw_ind = 0 # spectral window index if beamparms['pol'].lower() in ['x', 'e']: beam_pol_ind = 0 else: beam_pol_ind = 1 external_beam = uvbm.data_array[axis_vec_ind,spw_ind,beam_pol_ind,:,:].T # npix x nfreqs external_beam_freqs = uvbm.freq_array.ravel() # nfreqs (in Hz) else: raise ImportError('uvbeam module not installed/found') if NP.abs(NP.abs(external_beam).max() - 1.0) > 1e-10: external_beam /= NP.abs(external_beam).max() else: raise ValueError('Specified beam file format not currently supported') if beamparms['chromatic']: if beamparms['spec_interp'] == 'fft': external_beam = external_beam[:,:-1] external_beam_freqs = external_beam_freqs[:-1] interp_logbeam = OPS.healpix_interp_along_axis(NP.log10(external_beam), theta_phi=theta_phi, inloc_axis=external_beam_freqs, outloc_axis=beamparms['freqs'], axis=1, kind=beamparms['spec_interp'], assume_sorted=True) else: nearest_freq_ind = NP.argmin(NP.abs(external_beam_freqs - beamparms['select_freq'])) interp_logbeam = OPS.healpix_interp_along_axis(NP.log10(NP.repeat(external_beam[:,nearest_freq_ind].reshape(-1,1), beamparms['freqs'].size, axis=1)), theta_phi=theta_phi, inloc_axis=beamparms['freqs'], outloc_axis=beamparms['freqs'], axis=1, assume_sorted=True) interp_logbeam_max = NP.nanmax(interp_logbeam, axis=0) interp_logbeam_max[interp_logbeam_max <= 0.0] = 0.0 interp_logbeam_max = interp_logbeam_max.reshape(1,-1) interp_logbeam = interp_logbeam - interp_logbeam_max beam = 10**interp_logbeam else: altaz = NP.array([90.0, 0.0]).reshape(1,-1) + NP.array([-1,1]).reshape(1,-1) * NP.degrees(theta_phi) if beamparms['chromatic']: beam = PB.primary_beam_generator(altaz, beamparms['freqs'], beamparms['telescope'], skyunits='altaz', pointing_info=None, pointing_center=None, freq_scale='Hz', east2ax1=0.0) else: beam = PB.primary_beam_generator(altaz, beamparms['select_freq'], beamparms['telescope'], skyunits='altaz', pointing_info=None, pointing_center=None, freq_scale='Hz', east2ax1=0.0) beam = beam.reshape(-1,1) * NP.ones(beamparms['freqs'].size).reshape(1,-1) omega_bw = DS.beam3Dvol(beam, beamparms['freqs'], freq_wts=freq_wts, hemisphere=True) return omega_bw ############################################################################
[ "numpy.clip", "numpy.rollaxis", "numpy.isin", "numpy.array_split", "numpy.argsort", "copy.deepcopy", "numpy.sin", "numpy.arange", "numpy.exp", "numpy.nanmax", "numpy.concatenate", "warnings.warn", "numpy.ma.empty", "numpy.round", "numpy.ma.array", "astroutils.mathops.binned_statistic",...
[((15518, 15534), 'numpy.load', 'NP.load', (['npzfile'], {}), '(npzfile)\n', (15525, 15534), True, 'import numpy as NP\n'), ((20336, 20352), 'numpy.load', 'NP.load', (['npzfile'], {}), '(npzfile)\n', (20343, 20352), True, 'import numpy as NP\n'), ((12382, 12421), 'numpy.rollaxis', 'NP.rollaxis', (['cpdata[outkey]', '(3)'], {'start': '(0)'}), '(cpdata[outkey], 3, start=0)\n', (12393, 12421), True, 'import numpy as NP\n'), ((12442, 12487), 'numpy.zeros', 'NP.zeros', (['cpdata[outkey].shape'], {'dtype': 'NP.bool'}), '(cpdata[outkey].shape, dtype=NP.bool)\n', (12450, 12487), True, 'import numpy as NP\n'), ((21883, 21907), 'h5py.File', 'h5py.File', (['hdf5file', '"""w"""'], {}), "(hdf5file, 'w')\n", (21892, 21907), False, 'import h5py\n'), ((31147, 31170), 'h5py.File', 'h5py.File', (['outfile', '"""w"""'], {}), "(outfile, 'w')\n", (31156, 31170), False, 'import h5py\n'), ((41668, 41690), 'h5py.File', 'h5py.File', (['infile', '"""r"""'], {}), "(infile, 'r')\n", (41677, 41690), False, 'import h5py\n'), ((113557, 113578), 'numpy.any', 'NP.any', (['(rawlst > 24.0)'], {}), '(rawlst > 24.0)\n', (113563, 113578), True, 'import numpy as NP\n'), ((123542, 123563), 'numpy.exp', 'NP.exp', (['(1.0j * cphase)'], {}), '(1.0j * cphase)\n', (123548, 123563), True, 'import numpy as NP\n'), ((132317, 132349), 'numpy.ma.array', 'MA.array', (['wts_daybins'], {'mask': 'mask'}), '(wts_daybins, mask=mask)\n', (132325, 132349), True, 'import numpy.ma as MA\n'), ((132951, 132972), 'numpy.any', 'NP.any', (['(rawlst > 24.0)'], {}), '(rawlst > 24.0)\n', (132957, 132972), True, 'import numpy as NP\n'), ((143335, 143441), 'astroutils.nonmathops.save_dict_to_hdf5', 'NMO.save_dict_to_hdf5', (['self.cpinfo', 'outfile'], {'compressinfo': "{'compress_fmt': 'gzip', 'compress_opts': 9}"}), "(self.cpinfo, outfile, compressinfo={'compress_fmt':\n 'gzip', 'compress_opts': 9})\n", (143356, 143441), True, 'from astroutils import nonmathops as NMO\n'), ((179088, 179109), 'numpy.asarray', 'NP.asarray', (['triad_ind'], {}), '(triad_ind)\n', (179098, 179109), True, 'import numpy as NP\n'), ((211187, 211249), 'numpy.mean', 'NP.mean', (["self.cPhase.cpinfo['processed']['prelim']['dlstbins']"], {}), "(self.cPhase.cpinfo['processed']['prelim']['dlstbins'])\n", (211194, 211249), True, 'import numpy as NP\n'), ((258734, 258784), 'numpy.mean', 'NP.mean', (["self.cPhase.cpinfo['errinfo']['dlstbins']"], {}), "(self.cPhase.cpinfo['errinfo']['dlstbins'])\n", (258741, 258784), True, 'import numpy as NP\n'), ((282437, 282453), 'numpy.load', 'NP.load', (['visfile'], {}), '(visfile)\n', (282444, 282453), True, 'import numpy as NP\n'), ((282566, 282592), 'numpy.modf', 'NP.modf', (["scaleinfo['last']"], {}), "(scaleinfo['last'])\n", (282573, 282592), True, 'import numpy as NP\n'), ((309078, 309152), 'prisim.delay_spectrum.beam3Dvol', 'DS.beam3Dvol', (['beam', "beamparms['freqs']"], {'freq_wts': 'freq_wts', 'hemisphere': '(True)'}), "(beam, beamparms['freqs'], freq_wts=freq_wts, hemisphere=True)\n", (309090, 309152), True, 'from prisim import delay_spectrum as DS\n'), ((6550, 6638), 'prisim.interferometry.InterferometerArray', 'RI.InterferometerArray', (['None', 'None', 'None'], {'init_file': 'fullfnames_without_extension[0]'}), '(None, None, None, init_file=\n fullfnames_without_extension[0])\n', (6572, 6638), True, 'from prisim import interferometry as RI\n'), ((6669, 6736), 'prisim.interferometry.InterferometerArray', 'RI.InterferometerArray', (['None', 'None', 'None'], {'init_file': 'hdf5file_prefix'}), '(None, None, None, init_file=hdf5file_prefix)\n', (6691, 6736), True, 'from prisim import interferometry as RI\n'), ((7085, 7116), 'numpy.asarray', 'NP.asarray', (['simvis.timestamp[0]'], {}), '(simvis.timestamp[0])\n', (7095, 7116), True, 'import numpy as NP\n'), ((7695, 7789), 'prisim.interferometry.InterferometerArray', 'RI.InterferometerArray', (['None', 'None', 'None'], {'init_file': 'fullfnames_without_extension[fileind]'}), '(None, None, None, init_file=\n fullfnames_without_extension[fileind])\n', (7717, 7789), True, 'from prisim import interferometry as RI\n'), ((16259, 16283), 'numpy.modf', 'NP.modf', (["npzdata['last']"], {}), "(npzdata['last'])\n", (16266, 16283), True, 'import numpy as NP\n'), ((21078, 21102), 'numpy.modf', 'NP.modf', (["npzdata['last']"], {}), "(npzdata['last'])\n", (21085, 21102), True, 'import numpy as NP\n'), ((100611, 100648), 'astroutils.nonmathops.load_dict_from_hdf5', 'NMO.load_dict_from_hdf5', (['self.extfile'], {}), '(self.extfile)\n', (100634, 100648), True, 'from astroutils import nonmathops as NMO\n'), ((102867, 102926), 'numpy.exp', 'NP.exp', (["(1.0j * self.cpinfo['processed']['native']['cphase'])"], {}), "(1.0j * self.cpinfo['processed']['native']['cphase'])\n", (102873, 102926), True, 'import numpy as NP\n'), ((112723, 112755), 'numpy.ma.array', 'MA.array', (['wts_daybins'], {'mask': 'mask'}), '(wts_daybins, mask=mask)\n', (112731, 112755), True, 'import numpy.ma as MA\n'), ((112821, 112852), 'numpy.ma.array', 'MA.array', (['eicp_dmean'], {'mask': 'mask'}), '(eicp_dmean, mask=mask)\n', (112829, 112852), True, 'import numpy.ma as MA\n'), ((112920, 112953), 'numpy.ma.array', 'MA.array', (['eicp_dmedian'], {'mask': 'mask'}), '(eicp_dmedian, mask=mask)\n', (112928, 112953), True, 'import numpy.ma as MA\n'), ((113242, 113270), 'numpy.ma.array', 'MA.array', (['cp_drms'], {'mask': 'mask'}), '(cp_drms, mask=mask)\n', (113250, 113270), True, 'import numpy.ma as MA\n'), ((113337, 113365), 'numpy.ma.array', 'MA.array', (['cp_dmad'], {'mask': 'mask'}), '(cp_dmad, mask=mask)\n', (113345, 113365), True, 'import numpy.ma as MA\n'), ((121606, 121629), 'numpy.mean', 'NP.mean', (['rawlst'], {'axis': '(1)'}), '(rawlst, axis=1)\n', (121613, 121629), True, 'import numpy as NP\n'), ((123065, 123166), 'astroutils.mathops.is_broadcastable', 'OPS.is_broadcastable', (['cphase.shape', "self.cpinfo['processed']['prelim']['cphase']['median'].shape"], {}), "(cphase.shape, self.cpinfo['processed']['prelim'][\n 'cphase']['median'].shape)\n", (123085, 123166), True, 'from astroutils import mathops as OPS\n'), ((132378, 132398), 'numpy.angle', 'NP.angle', (['eicp_dmean'], {}), '(eicp_dmean)\n', (132386, 132398), True, 'import numpy as NP\n'), ((132441, 132463), 'numpy.angle', 'NP.angle', (['eicp_dmedian'], {}), '(eicp_dmedian)\n', (132449, 132463), True, 'import numpy as NP\n'), ((137084, 137104), 'numpy.ma.copy', 'MA.copy', (['wts_daybins'], {}), '(wts_daybins)\n', (137091, 137104), True, 'import numpy.ma as MA\n'), ((137463, 137486), 'numpy.mean', 'NP.mean', (['rawlst'], {'axis': '(1)'}), '(rawlst, axis=1)\n', (137470, 137486), True, 'import numpy as NP\n'), ((138152, 138193), 'numpy.ma.empty', 'MA.empty', (['diff_outshape'], {'dtype': 'NP.complex'}), '(diff_outshape, dtype=NP.complex)\n', (138160, 138193), True, 'import numpy.ma as MA\n'), ((138277, 138318), 'numpy.ma.empty', 'MA.empty', (['diff_outshape'], {'dtype': 'NP.complex'}), '(diff_outshape, dtype=NP.complex)\n', (138285, 138318), True, 'import numpy.ma as MA\n'), ((138386, 138425), 'numpy.ma.empty', 'MA.empty', (['diff_outshape'], {'dtype': 'NP.float'}), '(diff_outshape, dtype=NP.float)\n', (138394, 138425), True, 'import numpy.ma as MA\n'), ((161094, 161115), 'numpy.any', 'NP.any', (['(bw_eff <= 0.0)'], {}), '(bw_eff <= 0.0)\n', (161100, 161115), True, 'import numpy as NP\n'), ((161838, 161873), 'numpy.repeat', 'NP.repeat', (['bw_eff', 'freq_center.size'], {}), '(bw_eff, freq_center.size)\n', (161847, 161873), True, 'import numpy as NP\n'), ((205346, 205370), 'copy.deepcopy', 'copy.deepcopy', (['beamparms'], {}), '(beamparms)\n', (205359, 205370), False, 'import copy\n'), ((211955, 211967), 'numpy.arange', 'NP.arange', (['(2)'], {}), '(2)\n', (211964, 211967), True, 'import numpy as NP\n'), ((212482, 212512), 'prisim.delay_spectrum.dkprll_deta', 'DS.dkprll_deta', (['z'], {'cosmo': 'cosmo'}), '(z, cosmo=cosmo)\n', (212496, 212512), True, 'from prisim import delay_spectrum as DS\n'), ((213713, 213742), 'numpy.copy', 'NP.copy', (["cpds[smplng]['lags']"], {}), "(cpds[smplng]['lags'])\n", (213720, 213742), True, 'import numpy as NP\n'), ((252350, 252374), 'copy.deepcopy', 'copy.deepcopy', (['beamparms'], {}), '(beamparms)\n', (252363, 252374), False, 'import copy\n'), ((259490, 259502), 'numpy.arange', 'NP.arange', (['(2)'], {}), '(2)\n', (259499, 259502), True, 'import numpy as NP\n'), ((260017, 260047), 'prisim.delay_spectrum.dkprll_deta', 'DS.dkprll_deta', (['z'], {'cosmo': 'cosmo'}), '(z, cosmo=cosmo)\n', (260031, 260047), True, 'from prisim import delay_spectrum as DS\n'), ((261248, 261277), 'numpy.copy', 'NP.copy', (["cpds[smplng]['lags']"], {}), "(cpds[smplng]['lags'])\n", (261255, 261277), True, 'import numpy as NP\n'), ((282926, 282943), 'numpy.abs', 'NP.abs', (['lstmatrix'], {}), '(lstmatrix)\n', (282932, 282943), True, 'import numpy as NP\n'), ((290675, 290692), 'numpy.asarray', 'NP.asarray', (['avgax'], {}), '(avgax)\n', (290685, 290692), True, 'import numpy as NP\n'), ((291230, 291248), 'numpy.abs', 'NP.abs', (['kprll_llim'], {}), '(kprll_llim)\n', (291236, 291248), True, 'import numpy as NP\n'), ((308129, 308162), 'numpy.nanmax', 'NP.nanmax', (['interp_logbeam'], {'axis': '(0)'}), '(interp_logbeam, axis=0)\n', (308138, 308162), True, 'import numpy as NP\n'), ((5254, 5272), 'numpy.asarray', 'NP.asarray', (['triads'], {}), '(triads)\n', (5264, 5272), True, 'import numpy as NP\n'), ((8181, 8203), 'numpy.asarray', 'NP.asarray', (['bltriplets'], {}), '(bltriplets)\n', (8191, 8203), True, 'import numpy as NP\n'), ((8401, 8430), 'numpy.arange', 'NP.arange', (['bltriplet.shape[0]'], {}), '(bltriplet.shape[0])\n', (8410, 8430), True, 'import numpy as NP\n'), ((9155, 9184), 'numpy.arange', 'NP.arange', (['bltriplet.shape[0]'], {}), '(bltriplet.shape[0])\n', (9164, 9184), True, 'import numpy as NP\n'), ((16947, 16958), 'numpy.copy', 'NP.copy', (['cp'], {}), '(cp)\n', (16954, 16958), True, 'import numpy as NP\n'), ((69051, 69083), 'numpy.asarray', 'NP.asarray', (['diagoffsets[ind][ax]'], {}), '(diagoffsets[ind][ax])\n', (69061, 69083), True, 'import numpy as NP\n'), ((87163, 87193), 'numpy.insert', 'NP.insert', (['bins_kprll', '(0)', '(-eps)'], {}), '(bins_kprll, 0, -eps)\n', (87172, 87193), True, 'import numpy as NP\n'), ((87241, 87258), 'numpy.asarray', 'NP.asarray', (['kbins'], {}), '(kbins)\n', (87251, 87258), True, 'import numpy as NP\n'), ((102573, 102632), 'numpy.exp', 'NP.exp', (["(1.0j * self.cpinfo['processed']['native']['cphase'])"], {}), "(1.0j * self.cpinfo['processed']['native']['cphase'])\n", (102579, 102632), True, 'import numpy as NP\n'), ((109833, 109885), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['raw']['days']", 'ndaybins'], {}), "(self.cpinfo['raw']['days'], ndaybins)\n", (109847, 109885), True, 'import numpy as NP\n'), ((110087, 110133), 'numpy.asarray', 'NP.asarray', (['[days.size for days in days_split]'], {}), '([days.size for days in days_split])\n', (110097, 110133), True, 'import numpy as NP\n'), ((110167, 110252), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['processed']['native']['wts'].data", 'ndaybins'], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['wts'].data, ndaybins, axis=1\n )\n", (110181, 110252), True, 'import numpy as NP\n'), ((110519, 110549), 'numpy.moveaxis', 'NP.moveaxis', (['wts_daybins', '(0)', '(1)'], {}), '(wts_daybins, 0, 1)\n', (110530, 110549), True, 'import numpy as NP\n'), ((110615, 110700), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['processed']['native']['eicp'].mask", 'ndaybins'], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'].mask, ndaybins,\n axis=1)\n", (110629, 110700), True, 'import numpy as NP\n'), ((110726, 110811), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['processed']['native']['eicp'].data", 'ndaybins'], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'].data, ndaybins,\n axis=1)\n", (110740, 110811), True, 'import numpy as NP\n'), ((111073, 111102), 'numpy.moveaxis', 'NP.moveaxis', (['eicp_dmean', '(0)', '(1)'], {}), '(eicp_dmean, 0, 1)\n', (111084, 111102), True, 'import numpy as NP\n'), ((111499, 111530), 'numpy.moveaxis', 'NP.moveaxis', (['eicp_dmedian', '(0)', '(1)'], {}), '(eicp_dmedian, 0, 1)\n', (111510, 111530), True, 'import numpy as NP\n'), ((111611, 111698), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['processed']['native']['cphase'].data", 'ndaybins'], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['cphase'].data, ndaybins,\n axis=1)\n", (111625, 111698), True, 'import numpy as NP\n'), ((111893, 111919), 'numpy.moveaxis', 'NP.moveaxis', (['cp_drms', '(0)', '(1)'], {}), '(cp_drms, 0, 1)\n', (111904, 111919), True, 'import numpy as NP\n'), ((112176, 112202), 'numpy.moveaxis', 'NP.moveaxis', (['cp_dmad', '(0)', '(1)'], {}), '(cp_dmad, 0, 1)\n', (112187, 112202), True, 'import numpy as NP\n'), ((113030, 113050), 'numpy.angle', 'NP.angle', (['eicp_dmean'], {}), '(eicp_dmean)\n', (113038, 113050), True, 'import numpy as NP\n'), ((113141, 113163), 'numpy.angle', 'NP.angle', (['eicp_dmedian'], {}), '(eicp_dmedian)\n', (113149, 113163), True, 'import numpy as NP\n'), ((116395, 116462), 'astroutils.mathops.binned_statistic', 'OPS.binned_statistic', (['rawlst[:, 0]'], {'statistic': '"""count"""', 'bins': 'lstbins'}), "(rawlst[:, 0], statistic='count', bins=lstbins)\n", (116415, 116462), True, 'from astroutils import mathops as OPS\n'), ((117041, 117059), 'numpy.zeros', 'NP.zeros', (['outshape'], {}), '(outshape)\n', (117049, 117059), True, 'import numpy as NP\n'), ((117089, 117128), 'numpy.zeros', 'NP.zeros', (['outshape'], {'dtype': 'NP.complex128'}), '(outshape, dtype=NP.complex128)\n', (117097, 117128), True, 'import numpy as NP\n'), ((117160, 117199), 'numpy.zeros', 'NP.zeros', (['outshape'], {'dtype': 'NP.complex128'}), '(outshape, dtype=NP.complex128)\n', (117168, 117199), True, 'import numpy as NP\n'), ((117226, 117244), 'numpy.zeros', 'NP.zeros', (['outshape'], {}), '(outshape)\n', (117234, 117244), True, 'import numpy as NP\n'), ((117271, 117289), 'numpy.zeros', 'NP.zeros', (['outshape'], {}), '(outshape)\n', (117279, 117289), True, 'import numpy as NP\n'), ((119387, 119419), 'numpy.ma.array', 'MA.array', (['wts_lstbins'], {'mask': 'mask'}), '(wts_lstbins, mask=mask)\n', (119395, 119419), True, 'import numpy.ma as MA\n'), ((119767, 119798), 'numpy.ma.array', 'MA.array', (['eicp_tmean'], {'mask': 'mask'}), '(eicp_tmean, mask=mask)\n', (119775, 119798), True, 'import numpy.ma as MA\n'), ((119870, 119903), 'numpy.ma.array', 'MA.array', (['eicp_tmedian'], {'mask': 'mask'}), '(eicp_tmedian, mask=mask)\n', (119878, 119903), True, 'import numpy.ma as MA\n'), ((120204, 120232), 'numpy.ma.array', 'MA.array', (['cp_trms'], {'mask': 'mask'}), '(cp_trms, mask=mask)\n', (120212, 120232), True, 'import numpy.ma as MA\n'), ((120303, 120331), 'numpy.ma.array', 'MA.array', (['cp_tmad'], {'mask': 'mask'}), '(cp_tmad, mask=mask)\n', (120311, 120331), True, 'import numpy.ma as MA\n'), ((122033, 122044), 'numpy.zeros', 'NP.zeros', (['(1)'], {}), '(1)\n', (122041, 122044), True, 'import numpy as NP\n'), ((124161, 124185), 'numpy.angle', 'NP.angle', (['eicpratio.data'], {}), '(eicpratio.data)\n', (124169, 124185), True, 'import numpy as NP\n'), ((129854, 129906), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['raw']['days']", 'ndaybins'], {}), "(self.cpinfo['raw']['days'], ndaybins)\n", (129868, 129906), True, 'import numpy as NP\n'), ((130108, 130154), 'numpy.asarray', 'NP.asarray', (['[days.size for days in days_split]'], {}), '([days.size for days in days_split])\n', (130118, 130154), True, 'import numpy as NP\n'), ((130188, 130273), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['processed']['native']['wts'].data", 'ndaybins'], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['wts'].data, ndaybins, axis=1\n )\n", (130202, 130273), True, 'import numpy as NP\n'), ((130540, 130570), 'numpy.moveaxis', 'NP.moveaxis', (['wts_daybins', '(0)', '(1)'], {}), '(wts_daybins, 0, 1)\n', (130551, 130570), True, 'import numpy as NP\n'), ((130636, 130721), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['processed']['native']['eicp'].mask", 'ndaybins'], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'].mask, ndaybins,\n axis=1)\n", (130650, 130721), True, 'import numpy as NP\n'), ((130747, 130832), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['processed']['native']['eicp'].data", 'ndaybins'], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'].data, ndaybins,\n axis=1)\n", (130761, 130832), True, 'import numpy as NP\n'), ((131094, 131123), 'numpy.moveaxis', 'NP.moveaxis', (['eicp_dmean', '(0)', '(1)'], {}), '(eicp_dmean, 0, 1)\n', (131105, 131123), True, 'import numpy as NP\n'), ((131520, 131551), 'numpy.moveaxis', 'NP.moveaxis', (['eicp_dmedian', '(0)', '(1)'], {}), '(eicp_dmedian, 0, 1)\n', (131531, 131551), True, 'import numpy as NP\n'), ((131632, 131719), 'numpy.array_split', 'NP.array_split', (["self.cpinfo['processed']['native']['cphase'].data", 'ndaybins'], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['cphase'].data, ndaybins,\n axis=1)\n", (131646, 131719), True, 'import numpy as NP\n'), ((131914, 131940), 'numpy.moveaxis', 'NP.moveaxis', (['cp_drms', '(0)', '(1)'], {}), '(cp_drms, 0, 1)\n', (131925, 131940), True, 'import numpy as NP\n'), ((132197, 132223), 'numpy.moveaxis', 'NP.moveaxis', (['cp_dmad', '(0)', '(1)'], {}), '(cp_dmad, 0, 1)\n', (132208, 132223), True, 'import numpy as NP\n'), ((135607, 135674), 'astroutils.mathops.binned_statistic', 'OPS.binned_statistic', (['rawlst[:, 0]'], {'statistic': '"""count"""', 'bins': 'lstbins'}), "(rawlst[:, 0], statistic='count', bins=lstbins)\n", (135627, 135674), True, 'from astroutils import mathops as OPS\n'), ((135920, 135938), 'numpy.zeros', 'NP.zeros', (['outshape'], {}), '(outshape)\n', (135928, 135938), True, 'import numpy as NP\n'), ((135968, 136007), 'numpy.zeros', 'NP.zeros', (['outshape'], {'dtype': 'NP.complex128'}), '(outshape, dtype=NP.complex128)\n', (135976, 136007), True, 'import numpy as NP\n'), ((136039, 136078), 'numpy.zeros', 'NP.zeros', (['outshape'], {'dtype': 'NP.complex128'}), '(outshape, dtype=NP.complex128)\n', (136047, 136078), True, 'import numpy as NP\n'), ((136105, 136123), 'numpy.zeros', 'NP.zeros', (['outshape'], {}), '(outshape)\n', (136113, 136123), True, 'import numpy as NP\n'), ((136150, 136168), 'numpy.zeros', 'NP.zeros', (['outshape'], {}), '(outshape)\n', (136158, 136168), True, 'import numpy as NP\n'), ((136885, 136917), 'numpy.ma.array', 'MA.array', (['wts_lstbins'], {'mask': 'mask'}), '(wts_lstbins, mask=mask)\n', (136893, 136917), True, 'import numpy.ma as MA\n'), ((136947, 136978), 'numpy.ma.array', 'MA.array', (['eicp_tmean'], {'mask': 'mask'}), '(eicp_tmean, mask=mask)\n', (136955, 136978), True, 'import numpy.ma as MA\n'), ((137010, 137043), 'numpy.ma.array', 'MA.array', (['eicp_tmedian'], {'mask': 'mask'}), '(eicp_tmedian, mask=mask)\n', (137018, 137043), True, 'import numpy.ma as MA\n'), ((137741, 137752), 'numpy.zeros', 'NP.zeros', (['(1)'], {}), '(1)\n', (137749, 137752), True, 'import numpy as NP\n'), ((161960, 161995), 'numpy.repeat', 'NP.repeat', (['freq_center', 'bw_eff.size'], {}), '(freq_center, bw_eff.size)\n', (161969, 161995), True, 'import numpy as NP\n'), ((164349, 164377), 'numpy.ma.copy', 'MA.copy', (["visscaleinfo['vis']"], {}), "(visscaleinfo['vis'])\n", (164356, 164377), True, 'import numpy.ma as MA\n'), ((164588, 164698), 'astroutils.lookup_operations.find_1NN', 'LKP.find_1NN', (["visscaleinfo['vis'].baselines", "visscaleinfo['bltriplet']"], {'distance_ULIM': '(0.2)', 'remove_oob': '(True)'}), "(visscaleinfo['vis'].baselines, visscaleinfo['bltriplet'],\n distance_ULIM=0.2, remove_oob=True)\n", (164600, 164698), True, 'from astroutils import lookup_operations as LKP\n'), ((165458, 165530), 'numpy.transpose', 'NP.transpose', (["visscaleinfo['vis'].skyvis_freq[blrefind, :, :]", '(0, 2, 1)'], {}), "(visscaleinfo['vis'].skyvis_freq[blrefind, :, :], (0, 2, 1))\n", (165470, 165530), True, 'import numpy as NP\n'), ((165837, 165864), 'numpy.ones_like', 'NP.ones_like', (['vistriad.data'], {}), '(vistriad.data)\n', (165849, 165864), True, 'import numpy as NP\n'), ((166284, 166401), 'astroutils.mathops.interpolate_masked_array_1D', 'OPS.interpolate_masked_array_1D', (['vistriad', 'viswts', '(1)', "visscaleinfo['smoothinfo']"], {'inploc': 'lst_vis', 'outloc': 'lst_out'}), "(vistriad, viswts, 1, visscaleinfo[\n 'smoothinfo'], inploc=lst_vis, outloc=lst_out)\n", (166315, 166401), True, 'from astroutils import mathops as OPS\n'), ((166885, 166938), 'numpy.empty', 'NP.empty', (['(bw_eff.size, self.f.size)'], {'dtype': 'NP.float_'}), '((bw_eff.size, self.f.size), dtype=NP.float_)\n', (166893, 166938), True, 'import numpy as NP\n'), ((166983, 167092), 'astroutils.DSP_modules.window_N2width', 'DSP.window_N2width', ([], {'n_window': 'None', 'shape': 'shape', 'fftpow': 'fftpow', 'area_normalize': '(False)', 'power_normalize': '(True)'}), '(n_window=None, shape=shape, fftpow=fftpow,\n area_normalize=False, power_normalize=True)\n', (167001, 167092), True, 'from astroutils import DSP_modules as DSP\n'), ((167424, 167448), 'numpy.argsort', 'NP.argsort', (['ind_channels'], {}), '(ind_channels)\n', (167434, 167448), True, 'import numpy as NP\n'), ((168716, 168795), 'astroutils.DSP_modules.spectral_axis', 'DSP.spectral_axis', (['(self.f.size + npad)'], {'delx': 'self.df', 'use_real': '(False)', 'shift': '(True)'}), '(self.f.size + npad, delx=self.df, use_real=False, shift=True)\n', (168733, 168795), True, 'from astroutils import DSP_modules as DSP\n'), ((174790, 174811), 'copy.deepcopy', 'copy.deepcopy', (['result'], {}), '(result)\n', (174803, 174811), False, 'import copy\n'), ((174848, 174895), 'numpy.min', 'NP.min', (['((self.f.size + npad) * self.df / bw_eff)'], {}), '((self.f.size + npad) * self.df / bw_eff)\n', (174854, 174895), True, 'import numpy as NP\n'), ((174939, 175044), 'astroutils.DSP_modules.downsampler', 'DSP.downsampler', (["result_resampled['lags']", 'downsample_factor'], {'axis': '(-1)', 'method': '"""interp"""', 'kind': '"""linear"""'}), "(result_resampled['lags'], downsample_factor, axis=-1,\n method='interp', kind='linear')\n", (174954, 175044), True, 'from astroutils import DSP_modules as DSP\n'), ((175090, 175201), 'astroutils.DSP_modules.downsampler', 'DSP.downsampler', (["result_resampled['lag_kernel']", 'downsample_factor'], {'axis': '(-1)', 'method': '"""interp"""', 'kind': '"""linear"""'}), "(result_resampled['lag_kernel'], downsample_factor, axis=-1,\n method='interp', kind='linear')\n", (175105, 175201), True, 'from astroutils import DSP_modules as DSP\n'), ((179255, 179323), 'numpy.arange', 'NP.arange', (["self.cPhase.cpinfo['processed']['prelim']['wts'].shape[0]"], {}), "(self.cPhase.cpinfo['processed']['prelim']['wts'].shape[0])\n", (179264, 179323), True, 'import numpy as NP\n'), ((180322, 180390), 'numpy.arange', 'NP.arange', (["self.cPhase.cpinfo['processed']['prelim']['wts'].shape[1]"], {}), "(self.cPhase.cpinfo['processed']['prelim']['wts'].shape[1])\n", (180331, 180390), True, 'import numpy as NP\n'), ((211390, 211402), 'numpy.arange', 'NP.arange', (['(2)'], {}), '(2)\n', (211399, 211402), True, 'import numpy as NP\n'), ((257258, 257275), 'numpy.asarray', 'NP.asarray', (['cohax'], {}), '(cohax)\n', (257268, 257275), True, 'import numpy as NP\n'), ((257642, 257661), 'numpy.asarray', 'NP.asarray', (['incohax'], {}), '(incohax)\n', (257652, 257661), True, 'import numpy as NP\n'), ((258925, 258937), 'numpy.arange', 'NP.arange', (['(2)'], {}), '(2)\n', (258934, 258937), True, 'import numpy as NP\n'), ((282856, 282873), 'numpy.abs', 'NP.abs', (['lstmatrix'], {}), '(lstmatrix)\n', (282862, 282873), True, 'import numpy as NP\n'), ((283163, 283275), 'numpy.sum', 'NP.sum', (['(freq_wts[:, NP.newaxis, NP.newaxis, :] * vis_nearestLST[NP.newaxis, :, :, :])'], {'axis': '(-1)', 'keepdims': '(True)'}), '(freq_wts[:, NP.newaxis, NP.newaxis, :] * vis_nearestLST[NP.newaxis,\n :, :, :], axis=-1, keepdims=True)\n', (283169, 283275), True, 'import numpy as NP\n'), ((283268, 283338), 'numpy.sum', 'NP.sum', (['freq_wts[:, NP.newaxis, NP.newaxis, :]'], {'axis': '(-1)', 'keepdims': '(True)'}), '(freq_wts[:, NP.newaxis, NP.newaxis, :], axis=-1, keepdims=True)\n', (283274, 283338), True, 'import numpy as NP\n'), ((290759, 290776), 'numpy.asarray', 'NP.asarray', (['avgax'], {}), '(avgax)\n', (290769, 290776), True, 'import numpy as NP\n'), ((290792, 290810), 'numpy.any', 'NP.any', (['(avgax >= 4)'], {}), '(avgax >= 4)\n', (290798, 290810), True, 'import numpy as NP\n'), ((291347, 291371), 'numpy.ones', 'NP.ones', (['(1, 1, 1, 1, 1)'], {}), '((1, 1, 1, 1, 1))\n', (291354, 291371), True, 'import numpy as NP\n'), ((304573, 304606), 'healpy.nside2npix', 'HP.nside2npix', (["beamparms['nside']"], {}), "(beamparms['nside'])\n", (304586, 304606), True, 'import healpy as HP\n'), ((308585, 308761), 'prisim.primary_beams.primary_beam_generator', 'PB.primary_beam_generator', (['altaz', "beamparms['freqs']", "beamparms['telescope']"], {'skyunits': '"""altaz"""', 'pointing_info': 'None', 'pointing_center': 'None', 'freq_scale': '"""Hz"""', 'east2ax1': '(0.0)'}), "(altaz, beamparms['freqs'], beamparms['telescope'],\n skyunits='altaz', pointing_info=None, pointing_center=None, freq_scale=\n 'Hz', east2ax1=0.0)\n", (308610, 308761), True, 'from prisim import primary_beams as PB\n'), ((308794, 308977), 'prisim.primary_beams.primary_beam_generator', 'PB.primary_beam_generator', (['altaz', "beamparms['select_freq']", "beamparms['telescope']"], {'skyunits': '"""altaz"""', 'pointing_info': 'None', 'pointing_center': 'None', 'freq_scale': '"""Hz"""', 'east2ax1': '(0.0)'}), "(altaz, beamparms['select_freq'], beamparms[\n 'telescope'], skyunits='altaz', pointing_info=None, pointing_center=\n None, freq_scale='Hz', east2ax1=0.0)\n", (308819, 308977), True, 'from prisim import primary_beams as PB\n'), ((8598, 8624), 'numpy.ones', 'NP.ones', (['(3)'], {'dtype': 'NP.float'}), '(3, dtype=NP.float)\n', (8605, 8624), True, 'import numpy as NP\n'), ((8894, 8923), 'numpy.arange', 'NP.arange', (['bltriplet.shape[0]'], {}), '(bltriplet.shape[0])\n', (8903, 8923), True, 'import numpy as NP\n'), ((9448, 9490), 'numpy.intersect1d', 'NP.intersect1d', (['triadinds[1]', 'triadinds[2]'], {}), '(triadinds[1], triadinds[2])\n', (9462, 9490), True, 'import numpy as NP\n'), ((10327, 10374), 'numpy.asarray', 'NP.asarray', (["prisim_BSP_info['antenna_triplets']"], {}), "(prisim_BSP_info['antenna_triplets'])\n", (10337, 10374), True, 'import numpy as NP\n'), ((11106, 11209), 'numpy.concatenate', 'NP.concatenate', (["(cpdata[outkey], prisim_BSP_info['closure_phase_skyvis'][NP.newaxis, ...])"], {'axis': '(0)'}), "((cpdata[outkey], prisim_BSP_info['closure_phase_skyvis'][NP.\n newaxis, ...]), axis=0)\n", (11120, 11209), True, 'import numpy as NP\n'), ((11676, 11776), 'numpy.concatenate', 'NP.concatenate', (["(cpdata[outkey], prisim_BSP_info['closure_phase_vis'][NP.newaxis, ...])"], {'axis': '(0)'}), "((cpdata[outkey], prisim_BSP_info['closure_phase_vis'][NP.\n newaxis, ...]), axis=0)\n", (11690, 11776), True, 'import numpy as NP\n'), ((12233, 12335), 'numpy.concatenate', 'NP.concatenate', (["(cpdata[outkey], prisim_BSP_info['closure_phase_noise'][NP.newaxis, ...])"], {'axis': '(0)'}), "((cpdata[outkey], prisim_BSP_info['closure_phase_noise'][NP.\n newaxis, ...]), axis=0)\n", (12247, 12335), True, 'import numpy as NP\n'), ((12656, 12680), 'numpy.zeros', 'NP.zeros', (['(1, n_realize)'], {}), '((1, n_realize))\n', (12664, 12680), True, 'import numpy as NP\n'), ((12722, 12742), 'numpy.arange', 'NP.arange', (['n_realize'], {}), '(n_realize)\n', (12731, 12742), True, 'import numpy as NP\n'), ((17030, 17049), 'numpy.copy', 'NP.copy', (['triadsdata'], {}), '(triadsdata)\n', (17037, 17049), True, 'import numpy as NP\n'), ((22240, 22251), 'numpy.copy', 'NP.copy', (['cp'], {}), '(cp)\n', (22247, 22251), True, 'import numpy as NP\n'), ((87519, 87540), 'numpy.abs', 'NP.abs', (['kprll[spw, :]'], {}), '(kprll[spw, :])\n', (87525, 87540), True, 'import numpy as NP\n'), ((87692, 87707), 'numpy.copy', 'NP.copy', (['counts'], {}), '(counts)\n', (87699, 87707), True, 'import numpy as NP\n'), ((87848, 87864), 'numpy.copy', 'NP.copy', (['kbinnum'], {}), '(kbinnum)\n', (87855, 87864), True, 'import numpy as NP\n'), ((87919, 87930), 'numpy.copy', 'NP.copy', (['ri'], {}), '(ri)\n', (87926, 87930), True, 'import numpy as NP\n'), ((105295, 105329), 'numpy.clip', 'NP.clip', (['daybinsize', 'dres', 'dextent'], {}), '(daybinsize, dres, dextent)\n', (105302, 105329), True, 'import numpy as NP\n'), ((105569, 105628), 'numpy.concatenate', 'NP.concatenate', (['(daybins, [daybins[-1] + daybinsize + eps])'], {}), '((daybins, [daybins[-1] + daybinsize + eps]))\n', (105583, 105628), True, 'import numpy as NP\n'), ((106044, 106130), 'astroutils.mathops.binned_statistic', 'OPS.binned_statistic', (["self.cpinfo['raw']['days']"], {'statistic': '"""count"""', 'bins': 'daybins'}), "(self.cpinfo['raw']['days'], statistic='count', bins=\n daybins)\n", (106064, 106130), True, 'from astroutils import mathops as OPS\n'), ((106669, 106860), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]))\n", (106677, 106860), True, 'import numpy as NP\n'), ((106885, 107097), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {'dtype': 'NP.complex128'}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]), dtype=NP.complex128)\n", (106893, 107097), True, 'import numpy as NP\n'), ((107124, 107336), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {'dtype': 'NP.complex128'}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]), dtype=NP.complex128)\n", (107132, 107336), True, 'import numpy as NP\n'), ((107358, 107549), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]))\n", (107366, 107549), True, 'import numpy as NP\n'), ((107571, 107762), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]))\n", (107579, 107762), True, 'import numpy as NP\n'), ((113417, 113461), 'numpy.radians', 'NP.radians', (["(self.cpinfo['raw']['lst'] * 15.0)"], {}), "(self.cpinfo['raw']['lst'] * 15.0)\n", (113427, 113461), True, 'import numpy as NP\n'), ((114320, 114354), 'numpy.clip', 'NP.clip', (['lstbinsize', 'tres', 'textent'], {}), '(lstbinsize, tres, textent)\n', (114327, 114354), True, 'import numpy as NP\n'), ((114532, 114591), 'numpy.concatenate', 'NP.concatenate', (['(lstbins, [lstbins[-1] + lstbinsize + eps])'], {}), '((lstbins, [lstbins[-1] + lstbinsize + eps]))\n', (114546, 114591), True, 'import numpy as NP\n'), ((115303, 115443), 'warnings.warn', 'warnings.warn', (['"""LST bin size found to be smaller than the LST resolution in the data. No LST binning/averaging will be performed."""'], {}), "(\n 'LST bin size found to be smaller than the LST resolution in the data. No LST binning/averaging will be performed.'\n )\n", (115316, 115443), False, 'import warnings\n'), ((117826, 117881), 'numpy.sum', 'NP.sum', (["indict['wts'][ind_lstbin, :, :, :].data"], {'axis': '(0)'}), "(indict['wts'][ind_lstbin, :, :, :].data, axis=0)\n", (117832, 117881), True, 'import numpy as NP\n'), ((119984, 120004), 'numpy.angle', 'NP.angle', (['eicp_tmean'], {}), '(eicp_tmean)\n', (119992, 120004), True, 'import numpy as NP\n'), ((120099, 120121), 'numpy.angle', 'NP.angle', (['eicp_tmedian'], {}), '(eicp_tmedian)\n', (120107, 120121), True, 'import numpy as NP\n'), ((123027, 123043), 'numpy.isnan', 'NP.isnan', (['cphase'], {}), '(cphase)\n', (123035, 123043), True, 'import numpy as NP\n'), ((123306, 123406), 'numpy.ones', 'NP.ones', (["(self.cpinfo['processed']['prelim']['cphase']['median'].ndim - cphase.ndim)"], {'dtype': 'NP.int'}), "(self.cpinfo['processed']['prelim']['cphase']['median'].ndim -\n cphase.ndim, dtype=NP.int)\n", (123313, 123406), True, 'import numpy as NP\n'), ((126598, 126632), 'numpy.clip', 'NP.clip', (['daybinsize', 'dres', 'dextent'], {}), '(daybinsize, dres, dextent)\n', (126605, 126632), True, 'import numpy as NP\n'), ((126872, 126931), 'numpy.concatenate', 'NP.concatenate', (['(daybins, [daybins[-1] + daybinsize + eps])'], {}), '((daybins, [daybins[-1] + daybinsize + eps]))\n', (126886, 126931), True, 'import numpy as NP\n'), ((127318, 127404), 'astroutils.mathops.binned_statistic', 'OPS.binned_statistic', (["self.cpinfo['raw']['days']"], {'statistic': '"""count"""', 'bins': 'daybins'}), "(self.cpinfo['raw']['days'], statistic='count', bins=\n daybins)\n", (127338, 127404), True, 'from astroutils import mathops as OPS\n'), ((127490, 127681), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]))\n", (127498, 127681), True, 'import numpy as NP\n'), ((127706, 127918), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {'dtype': 'NP.complex128'}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]), dtype=NP.complex128)\n", (127714, 127918), True, 'import numpy as NP\n'), ((127945, 128157), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {'dtype': 'NP.complex128'}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]), dtype=NP.complex128)\n", (127953, 128157), True, 'import numpy as NP\n'), ((128179, 128370), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]))\n", (128187, 128370), True, 'import numpy as NP\n'), ((128392, 128583), 'numpy.zeros', 'NP.zeros', (["(self.cpinfo['processed']['native']['eicp'].shape[0], counts.size, self.\n cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo['processed'\n ]['native']['eicp'].shape[3])"], {}), "((self.cpinfo['processed']['native']['eicp'].shape[0], counts.size,\n self.cpinfo['processed']['native']['eicp'].shape[2], self.cpinfo[\n 'processed']['native']['eicp'].shape[3]))\n", (128400, 128583), True, 'import numpy as NP\n'), ((132811, 132855), 'numpy.radians', 'NP.radians', (["(self.cpinfo['raw']['lst'] * 15.0)"], {}), "(self.cpinfo['raw']['lst'] * 15.0)\n", (132821, 132855), True, 'import numpy as NP\n'), ((133601, 133635), 'numpy.clip', 'NP.clip', (['lstbinsize', 'tres', 'textent'], {}), '(lstbinsize, tres, textent)\n', (133608, 133635), True, 'import numpy as NP\n'), ((133813, 133872), 'numpy.concatenate', 'NP.concatenate', (['(lstbins, [lstbins[-1] + lstbinsize + eps])'], {}), '((lstbins, [lstbins[-1] + lstbinsize + eps]))\n', (133827, 133872), True, 'import numpy as NP\n'), ((134542, 134682), 'warnings.warn', 'warnings.warn', (['"""LST bin size found to be smaller than the LST resolution in the data. No LST binning/averaging will be performed."""'], {}), "(\n 'LST bin size found to be smaller than the LST resolution in the data. No LST binning/averaging will be performed.'\n )\n", (134555, 134682), False, 'import warnings\n'), ((136450, 136503), 'numpy.sum', 'NP.sum', (['wts_daybins[ind_lstbin, :, :, :].data'], {'axis': '(0)'}), '(wts_daybins[ind_lstbin, :, :, :].data, axis=0)\n', (136456, 136503), True, 'import numpy as NP\n'), ((161048, 161066), 'numpy.asarray', 'NP.asarray', (['bw_eff'], {}), '(bw_eff)\n', (161058, 161066), True, 'import numpy as NP\n'), ((161271, 161306), 'numpy.asarray', 'NP.asarray', (['self.f[self.f.size / 2]'], {}), '(self.f[self.f.size / 2])\n', (161281, 161306), True, 'import numpy as NP\n'), ((164882, 165016), 'astroutils.lookup_operations.find_1NN', 'LKP.find_1NN', (["visscaleinfo['vis'].baselines", "(-1 * visscaleinfo['bltriplet'][blind_missing, :])"], {'distance_ULIM': '(0.2)', 'remove_oob': '(True)'}), "(visscaleinfo['vis'].baselines, -1 * visscaleinfo['bltriplet'][\n blind_missing, :], distance_ULIM=0.2, remove_oob=True)\n", (164894, 165016), True, 'from astroutils import lookup_operations as LKP\n'), ((168220, 168248), 'numpy.argsort', 'NP.argsort', (['ind_window_chans'], {}), '(ind_window_chans)\n', (168230, 168248), True, 'import numpy as NP\n'), ((179473, 179541), 'numpy.arange', 'NP.arange', (["self.cPhase.cpinfo['processed']['prelim']['wts'].shape[0]"], {}), "(self.cPhase.cpinfo['processed']['prelim']['wts'].shape[0])\n", (179482, 179541), True, 'import numpy as NP\n'), ((180695, 180763), 'numpy.arange', 'NP.arange', (["self.cPhase.cpinfo['processed']['prelim']['wts'].shape[1]"], {}), "(self.cPhase.cpinfo['processed']['prelim']['wts'].shape[1])\n", (180704, 180763), True, 'import numpy as NP\n'), ((205447, 205473), 'numpy.ones', 'NP.ones', (['(1)'], {'dtpye': 'NP.float'}), '(1, dtpye=NP.float)\n', (205454, 205473), True, 'import numpy as NP\n'), ((206248, 206274), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (206255, 206274), True, 'import numpy as NP\n'), ((206732, 206758), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (206739, 206758), True, 'import numpy as NP\n'), ((209608, 209642), 'numpy.asarray', 'NP.asarray', (["xinfo['collapse_axes']"], {}), "(xinfo['collapse_axes'])\n", (209618, 209642), True, 'import numpy as NP\n'), ((209746, 209793), 'numpy.intersect1d', 'NP.intersect1d', (["autoinfo['axes']", "xinfo['axes']"], {}), "(autoinfo['axes'], xinfo['axes'])\n", (209760, 209793), True, 'import numpy as NP\n'), ((210524, 210552), 'copy.deepcopy', 'copy.deepcopy', (['self.cPhaseDS'], {}), '(self.cPhaseDS)\n', (210537, 210552), False, 'import copy\n'), ((210610, 210648), 'copy.deepcopy', 'copy.deepcopy', (['self.cPhaseDS_resampled'], {}), '(self.cPhaseDS_resampled)\n', (210623, 210648), False, 'import copy\n'), ((211674, 211703), 'numpy.insert', 'NP.insert', (['dlst_range', '(0)', '(0.0)'], {}), '(dlst_range, 0, 0.0)\n', (211683, 211703), True, 'import numpy as NP\n'), ((213059, 213088), 'copy.deepcopy', 'copy.deepcopy', (['beamparms_orig'], {}), '(beamparms_orig)\n', (213072, 213088), False, 'import copy\n'), ((215439, 215515), 'numpy.copy', 'NP.copy', (["cpds[smplng]['whole']['dspec']['twts'].data[:, :, :, [select_chan]]"], {}), "(cpds[smplng]['whole']['dspec']['twts'].data[:, :, :, [select_chan]])\n", (215446, 215515), True, 'import numpy as NP\n'), ((252451, 252477), 'numpy.ones', 'NP.ones', (['(1)'], {'dtpye': 'NP.float'}), '(1, dtpye=NP.float)\n', (252458, 252477), True, 'import numpy as NP\n'), ((253252, 253278), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (253259, 253278), True, 'import numpy as NP\n'), ((253736, 253762), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (253743, 253762), True, 'import numpy as NP\n'), ((256612, 256646), 'numpy.asarray', 'NP.asarray', (["xinfo['collapse_axes']"], {}), "(xinfo['collapse_axes'])\n", (256622, 256646), True, 'import numpy as NP\n'), ((256750, 256797), 'numpy.intersect1d', 'NP.intersect1d', (["autoinfo['axes']", "xinfo['axes']"], {}), "(autoinfo['axes'], xinfo['axes'])\n", (256764, 256797), True, 'import numpy as NP\n'), ((258110, 258138), 'copy.deepcopy', 'copy.deepcopy', (['self.cPhaseDS'], {}), '(self.cPhaseDS)\n', (258123, 258138), False, 'import copy\n'), ((258196, 258234), 'copy.deepcopy', 'copy.deepcopy', (['self.cPhaseDS_resampled'], {}), '(self.cPhaseDS_resampled)\n', (258209, 258234), False, 'import copy\n'), ((259209, 259238), 'numpy.insert', 'NP.insert', (['dlst_range', '(0)', '(0.0)'], {}), '(dlst_range, 0, 0.0)\n', (259218, 259238), True, 'import numpy as NP\n'), ((260594, 260623), 'copy.deepcopy', 'copy.deepcopy', (['beamparms_orig'], {}), '(beamparms_orig)\n', (260607, 260623), False, 'import copy\n'), ((262446, 262458), 'numpy.arange', 'NP.arange', (['(1)'], {}), '(1)\n', (262455, 262458), True, 'import numpy as NP\n'), ((262535, 262553), 'numpy.arange', 'NP.arange', (['wl.size'], {}), '(wl.size)\n', (262544, 262553), True, 'import numpy as NP\n'), ((262589, 262611), 'numpy.arange', 'NP.arange', (['inpshape[4]'], {}), '(inpshape[4])\n', (262598, 262611), True, 'import numpy as NP\n'), ((262693, 262766), 'numpy.sum', 'NP.sum', (["cpds[smplng]['errinfo']['dspec0']['twts'].data"], {'axis': '(0, 1, 2, 3)'}), "(cpds[smplng]['errinfo']['dspec0']['twts'].data, axis=(0, 1, 2, 3))\n", (262699, 262766), True, 'import numpy as NP\n'), ((262805, 262878), 'numpy.sum', 'NP.sum', (["cpds[smplng]['errinfo']['dspec0']['twts'].data"], {'axis': '(0, 1, 2, 3)'}), "(cpds[smplng]['errinfo']['dspec0']['twts'].data, axis=(0, 1, 2, 3))\n", (262811, 262878), True, 'import numpy as NP\n'), ((262906, 262985), 'numpy.copy', 'NP.copy', (["cpds[smplng]['errinfo']['dspec0']['twts'].data[:, :, :, [select_chan]]"], {}), "(cpds[smplng]['errinfo']['dspec0']['twts'].data[:, :, :, [select_chan]])\n", (262913, 262985), True, 'import numpy as NP\n'), ((262989, 263068), 'numpy.copy', 'NP.copy', (["cpds[smplng]['errinfo']['dspec1']['twts'].data[:, :, :, [select_chan]]"], {}), "(cpds[smplng]['errinfo']['dspec1']['twts'].data[:, :, :, [select_chan]])\n", (262996, 263068), True, 'import numpy as NP\n'), ((263241, 263278), 'numpy.ones', 'NP.ones', (['awts_shape'], {'dtype': 'NP.complex'}), '(awts_shape, dtype=NP.complex)\n', (263248, 263278), True, 'import numpy as NP\n'), ((263312, 263334), 'numpy.asarray', 'NP.asarray', (['awts_shape'], {}), '(awts_shape)\n', (263322, 263334), True, 'import numpy as NP\n'), ((263679, 263743), 'numpy.copy', 'NP.copy', (["cpds[smplng][dpool]['dspec0'][stat][dspec_multidim_idx]"], {}), "(cpds[smplng][dpool]['dspec0'][stat][dspec_multidim_idx])\n", (263686, 263743), True, 'import numpy as NP\n'), ((263773, 263837), 'numpy.copy', 'NP.copy', (["cpds[smplng][dpool]['dspec1'][stat][dspec_multidim_idx]"], {}), "(cpds[smplng][dpool]['dspec1'][stat][dspec_multidim_idx])\n", (263780, 263837), True, 'import numpy as NP\n'), ((291547, 291564), 'numpy.any', 'NP.any', (['kprll_ind'], {}), '(kprll_ind)\n', (291553, 291564), True, 'import numpy as NP\n'), ((292681, 292768), 'numpy.sum', 'NP.sum', (["(wts * rcpdps[dpool][stat]['absscale']['rescale'])"], {'axis': 'avgax', 'keepdims': '(True)'}), "(wts * rcpdps[dpool][stat]['absscale']['rescale'], axis=avgax,\n keepdims=True)\n", (292687, 292768), True, 'import numpy as NP\n'), ((292767, 292805), 'numpy.sum', 'NP.sum', (['wts'], {'axis': 'avgax', 'keepdims': '(True)'}), '(wts, axis=avgax, keepdims=True)\n', (292773, 292805), True, 'import numpy as NP\n'), ((305715, 305742), 'numpy.mean', 'NP.mean', (["beamparms['freqs']"], {}), "(beamparms['freqs'])\n", (305722, 305742), True, 'import numpy as NP\n'), ((307530, 307553), 'numpy.log10', 'NP.log10', (['external_beam'], {}), '(external_beam)\n', (307538, 307553), True, 'import numpy as NP\n'), ((307762, 307816), 'numpy.abs', 'NP.abs', (["(external_beam_freqs - beamparms['select_freq'])"], {}), "(external_beam_freqs - beamparms['select_freq'])\n", (307768, 307816), True, 'import numpy as NP\n'), ((308501, 308522), 'numpy.degrees', 'NP.degrees', (['theta_phi'], {}), '(theta_phi)\n', (308511, 308522), True, 'import numpy as NP\n'), ((8119, 8137), 'numpy.asarray', 'NP.asarray', (['triads'], {}), '(triads)\n', (8129, 8137), True, 'import numpy as NP\n'), ((8657, 8673), 'numpy.array', 'NP.array', (['revind'], {}), '(revind)\n', (8665, 8673), True, 'import numpy as NP\n'), ((9241, 9272), 'numpy.asarray', 'NP.asarray', (['matchinfo[0][blnum]'], {}), '(matchinfo[0][blnum])\n', (9251, 9272), True, 'import numpy as NP\n'), ((17120, 17134), 'numpy.copy', 'NP.copy', (['flags'], {}), '(flags)\n', (17127, 17134), True, 'import numpy as NP\n'), ((22317, 22336), 'numpy.copy', 'NP.copy', (['triadsdata'], {}), '(triadsdata)\n', (22324, 22336), True, 'import numpy as NP\n'), ((70322, 70371), 'numpy.copy', 'NP.copy', (["out_xcpdps[smplng][dpool]['diagweights']"], {}), "(out_xcpdps[smplng][dpool]['diagweights'])\n", (70329, 70371), True, 'import numpy as NP\n'), ((86806, 86829), 'numpy.diff', 'NP.diff', (['kprll'], {'axis': '(-1)'}), '(kprll, axis=-1)\n', (86813, 86829), True, 'import numpy as NP\n'), ((102990, 103033), 'numpy.logical_not', 'NP.logical_not', (["self.cpinfo['raw']['flags']"], {}), "(self.cpinfo['raw']['flags'])\n", (103004, 103033), True, 'import numpy as NP\n'), ((105061, 105096), 'numpy.diff', 'NP.diff', (["self.cpinfo['raw']['days']"], {}), "(self.cpinfo['raw']['days'])\n", (105068, 105096), True, 'import numpy as NP\n'), ((107926, 108013), 'numpy.sum', 'NP.sum', (["self.cpinfo['processed']['native']['wts'][:, ind_daybin, :, :].data"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['wts'][:, ind_daybin, :, :].data,\n axis=1)\n", (107932, 108013), True, 'import numpy as NP\n'), ((109930, 109943), 'numpy.mean', 'NP.mean', (['days'], {}), '(days)\n', (109937, 109943), True, 'import numpy as NP\n'), ((110402, 110425), 'numpy.sum', 'NP.sum', (['wtsitem'], {'axis': '(1)'}), '(wtsitem, axis=1)\n', (110408, 110425), True, 'import numpy as NP\n'), ((111022, 111042), 'numpy.angle', 'NP.angle', (['eicp_dmean'], {}), '(eicp_dmean)\n', (111030, 111042), True, 'import numpy as NP\n'), ((111444, 111466), 'numpy.angle', 'NP.angle', (['eicp_dmedian'], {}), '(eicp_dmedian)\n', (111452, 111466), True, 'import numpy as NP\n'), ((113935, 113956), 'numpy.diff', 'NP.diff', (['rawlst[:, 0]'], {}), '(rawlst[:, 0])\n', (113942, 113956), True, 'import numpy as NP\n'), ((121915, 121937), 'numpy.asarray', 'NP.asarray', (['lstbinsize'], {}), '(lstbinsize)\n', (121925, 121937), True, 'import numpy as NP\n'), ((126364, 126399), 'numpy.diff', 'NP.diff', (["self.cpinfo['raw']['days']"], {}), "(self.cpinfo['raw']['days'])\n", (126371, 126399), True, 'import numpy as NP\n'), ((128747, 128834), 'numpy.sum', 'NP.sum', (["self.cpinfo['processed']['native']['wts'][:, ind_daybin, :, :].data"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['wts'][:, ind_daybin, :, :].data,\n axis=1)\n", (128753, 128834), True, 'import numpy as NP\n'), ((129951, 129964), 'numpy.mean', 'NP.mean', (['days'], {}), '(days)\n', (129958, 129964), True, 'import numpy as NP\n'), ((130423, 130446), 'numpy.sum', 'NP.sum', (['wtsitem'], {'axis': '(1)'}), '(wtsitem, axis=1)\n', (130429, 130446), True, 'import numpy as NP\n'), ((131043, 131063), 'numpy.angle', 'NP.angle', (['eicp_dmean'], {}), '(eicp_dmean)\n', (131051, 131063), True, 'import numpy as NP\n'), ((131465, 131487), 'numpy.angle', 'NP.angle', (['eicp_dmedian'], {}), '(eicp_dmedian)\n', (131473, 131487), True, 'import numpy as NP\n'), ((133337, 133358), 'numpy.diff', 'NP.diff', (['rawlst[:, 0]'], {}), '(rawlst[:, 0])\n', (133344, 133358), True, 'import numpy as NP\n'), ((137635, 137657), 'numpy.asarray', 'NP.asarray', (['lstbinsize'], {}), '(lstbinsize)\n', (137645, 137657), True, 'import numpy as NP\n'), ((161413, 161436), 'numpy.asarray', 'NP.asarray', (['freq_center'], {}), '(freq_center)\n', (161423, 161436), True, 'import numpy as NP\n'), ((164783, 164795), 'numpy.arange', 'NP.arange', (['(3)'], {}), '(3)\n', (164792, 164795), True, 'import numpy as NP\n'), ((165235, 165278), 'numpy.append', 'NP.append', (['blind', 'blind_missing[blind_next]'], {}), '(blind, blind_missing[blind_next])\n', (165244, 165278), True, 'import numpy as NP\n'), ((165314, 165348), 'numpy.append', 'NP.append', (['blrefind', 'blrefind_next'], {}), '(blrefind, blrefind_next)\n', (165323, 165348), True, 'import numpy as NP\n'), ((165720, 165738), 'numpy.isnan', 'NP.isnan', (['vistriad'], {}), '(vistriad)\n', (165728, 165738), True, 'import numpy as NP\n'), ((167168, 167215), 'numpy.round', 'NP.round', (['(window_loss_factor * bw_eff / self.df)'], {}), '(window_loss_factor * bw_eff / self.df)\n', (167176, 167215), True, 'import numpy as NP\n'), ((167752, 167785), 'numpy.sqrt', 'NP.sqrt', (['(frac_width * n_window[i])'], {}), '(frac_width * n_window[i])\n', (167759, 167785), True, 'import numpy as NP\n'), ((167788, 167921), 'astroutils.DSP_modules.window_fftpow', 'DSP.window_fftpow', (['n_window[i]'], {'shape': 'shape', 'fftpow': 'fftpow', 'centering': '(True)', 'peak': 'None', 'area_normalize': '(False)', 'power_normalize': '(True)'}), '(n_window[i], shape=shape, fftpow=fftpow, centering=True,\n peak=None, area_normalize=False, power_normalize=True)\n', (167805, 167921), True, 'from astroutils import DSP_modules as DSP\n'), ((168985, 169010), 'numpy.sum', 'NP.sum', (['freq_wts'], {'axis': '(-1)'}), '(freq_wts, axis=-1)\n', (168991, 169010), True, 'import numpy as NP\n'), ((169566, 169655), 'numpy.nansum', 'NP.nansum', (['freq_wts[:, NP.newaxis, NP.newaxis, NP.newaxis, :]'], {'axis': '(-1)', 'keepdims': '(True)'}), '(freq_wts[:, NP.newaxis, NP.newaxis, NP.newaxis, :], axis=-1,\n keepdims=True)\n', (169575, 169655), True, 'import numpy as NP\n'), ((206143, 206169), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (206150, 206169), True, 'import numpy as NP\n'), ((206839, 206865), 'numpy.ones', 'NP.ones', (['(1)'], {'dtpye': 'NP.float'}), '(1, dtpye=NP.float)\n', (206846, 206865), True, 'import numpy as NP\n'), ((206878, 206904), 'numpy.ones', 'NP.ones', (['(1)'], {'dtpye': 'NP.float'}), '(1, dtpye=NP.float)\n', (206885, 206904), True, 'import numpy as NP\n'), ((207376, 207401), 'numpy.asarray', 'NP.asarray', (["xinfo['axes']"], {}), "(xinfo['axes'])\n", (207386, 207401), True, 'import numpy as NP\n'), ((207720, 207746), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (207727, 207746), True, 'import numpy as NP\n'), ((208578, 208604), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (208585, 208604), True, 'import numpy as NP\n'), ((214988, 215000), 'numpy.arange', 'NP.arange', (['(1)'], {}), '(1)\n', (214997, 215000), True, 'import numpy as NP\n'), ((215081, 215099), 'numpy.arange', 'NP.arange', (['wl.size'], {}), '(wl.size)\n', (215090, 215099), True, 'import numpy as NP\n'), ((215126, 215148), 'numpy.arange', 'NP.arange', (['inpshape[4]'], {}), '(inpshape[4])\n', (215135, 215148), True, 'import numpy as NP\n'), ((215234, 215301), 'numpy.sum', 'NP.sum', (["cpds[smplng]['whole']['dspec']['twts'].data"], {'axis': '(0, 1, 2)'}), "(cpds[smplng]['whole']['dspec']['twts'].data, axis=(0, 1, 2))\n", (215240, 215301), True, 'import numpy as NP\n'), ((215345, 215412), 'numpy.sum', 'NP.sum', (["cpds[smplng]['whole']['dspec']['twts'].data"], {'axis': '(0, 1, 2)'}), "(cpds[smplng]['whole']['dspec']['twts'].data, axis=(0, 1, 2))\n", (215351, 215412), True, 'import numpy as NP\n'), ((215734, 215771), 'numpy.ones', 'NP.ones', (['awts_shape'], {'dtype': 'NP.complex'}), '(awts_shape, dtype=NP.complex)\n', (215741, 215771), True, 'import numpy as NP\n'), ((215809, 215831), 'numpy.asarray', 'NP.asarray', (['awts_shape'], {}), '(awts_shape)\n', (215819, 215831), True, 'import numpy as NP\n'), ((253147, 253173), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (253154, 253173), True, 'import numpy as NP\n'), ((253843, 253869), 'numpy.ones', 'NP.ones', (['(1)'], {'dtpye': 'NP.float'}), '(1, dtpye=NP.float)\n', (253850, 253869), True, 'import numpy as NP\n'), ((253882, 253908), 'numpy.ones', 'NP.ones', (['(1)'], {'dtpye': 'NP.float'}), '(1, dtpye=NP.float)\n', (253889, 253908), True, 'import numpy as NP\n'), ((254380, 254405), 'numpy.asarray', 'NP.asarray', (["xinfo['axes']"], {}), "(xinfo['axes'])\n", (254390, 254405), True, 'import numpy as NP\n'), ((254724, 254750), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (254731, 254750), True, 'import numpy as NP\n'), ((255582, 255608), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (255589, 255608), True, 'import numpy as NP\n'), ((263144, 263212), 'numpy.ones', 'NP.ones', (["cpds[smplng]['errinfo']['dspec']['mean'].ndim"], {'dtype': 'NP.int'}), "(cpds[smplng]['errinfo']['dspec']['mean'].ndim, dtype=NP.int)\n", (263151, 263212), True, 'import numpy as NP\n'), ((263435, 263454), 'numpy.copy', 'NP.copy', (['awts_shape'], {}), '(awts_shape)\n', (263442, 263454), True, 'import numpy as NP\n'), ((264719, 264755), 'numpy.ones', 'NP.ones', (['wts_shape'], {'dtype': 'NP.complex'}), '(wts_shape, dtype=NP.complex)\n', (264726, 264755), True, 'import numpy as NP\n'), ((264792, 264813), 'numpy.asarray', 'NP.asarray', (['wts_shape'], {}), '(wts_shape)\n', (264802, 264813), True, 'import numpy as NP\n'), ((265154, 265170), 'numpy.copy', 'NP.copy', (['preXwts'], {}), '(preXwts)\n', (265161, 265170), True, 'import numpy as NP\n'), ((265206, 265222), 'numpy.copy', 'NP.copy', (['preXwts'], {}), '(preXwts)\n', (265213, 265222), True, 'import numpy as NP\n'), ((291443, 291473), 'numpy.abs', 'NP.abs', (["rcpdps[dpool]['kprll']"], {}), "(rcpdps[dpool]['kprll'])\n", (291449, 291473), True, 'import numpy as NP\n'), ((292532, 292627), 'numpy.var', 'NP.var', (["rcpdps[dpool][stat]['absscale']['rescale'][multidim_idx]"], {'axis': 'avgax', 'keepdims': '(True)'}), "(rcpdps[dpool][stat]['absscale']['rescale'][multidim_idx], axis=avgax,\n keepdims=True)\n", (292538, 292627), True, 'import numpy as NP\n'), ((306356, 306364), 'pyuvdata.UVBeam', 'UVBeam', ([], {}), '()\n', (306362, 306364), False, 'from pyuvdata import UVBeam\n'), ((308430, 308451), 'numpy.array', 'NP.array', (['[90.0, 0.0]'], {}), '([90.0, 0.0])\n', (308438, 308451), True, 'import numpy as NP\n'), ((16147, 16171), 'numpy.zeros', 'NP.zeros', (['lstHA.shape[0]'], {}), '(lstHA.shape[0])\n', (16155, 16171), True, 'import numpy as NP\n'), ((17203, 17217), 'numpy.copy', 'NP.copy', (['lstHA'], {}), '(lstHA)\n', (17210, 17217), True, 'import numpy as NP\n'), ((20966, 20990), 'numpy.zeros', 'NP.zeros', (['lstHA.shape[0]'], {}), '(lstHA.shape[0])\n', (20974, 20990), True, 'import numpy as NP\n'), ((22401, 22415), 'numpy.copy', 'NP.copy', (['flags'], {}), '(flags)\n', (22408, 22415), True, 'import numpy as NP\n'), ((65820, 65843), 'numpy.asarray', 'NP.asarray', (['diagweights'], {}), '(diagweights)\n', (65830, 65843), True, 'import numpy as NP\n'), ((65878, 65893), 'numpy.asarray', 'NP.asarray', (['arr'], {}), '(arr)\n', (65888, 65893), True, 'import numpy as NP\n'), ((66052, 66082), 'numpy.nansum', 'NP.nansum', (['diagweights'], {'axis': '(0)'}), '(diagweights, axis=0)\n', (66061, 66082), True, 'import numpy as NP\n'), ((68100, 68123), 'numpy.asarray', 'NP.asarray', (['diagweights'], {}), '(diagweights)\n', (68110, 68123), True, 'import numpy as NP\n'), ((68158, 68173), 'numpy.asarray', 'NP.asarray', (['arr'], {}), '(arr)\n', (68168, 68173), True, 'import numpy as NP\n'), ((68332, 68362), 'numpy.nansum', 'NP.nansum', (['diagweights'], {'axis': '(0)'}), '(diagweights, axis=0)\n', (68341, 68362), True, 'import numpy as NP\n'), ((69425, 69495), 'numpy.ones', 'NP.ones', (["out_xcpdps[smplng][dpool]['diagweights'].shape"], {'dtype': 'NP.bool'}), "(out_xcpdps[smplng][dpool]['diagweights'].shape, dtype=NP.bool)\n", (69432, 69495), True, 'import numpy as NP\n'), ((72952, 73002), 'numpy.copy', 'NP.copy', (["out_excpdps[smplng][dpool]['diagweights']"], {}), "(out_excpdps[smplng][dpool]['diagweights'])\n", (72959, 73002), True, 'import numpy as NP\n'), ((102700, 102743), 'numpy.logical_not', 'NP.logical_not', (["self.cpinfo['raw']['flags']"], {}), "(self.cpinfo['raw']['flags'])\n", (102714, 102743), True, 'import numpy as NP\n'), ((108456, 108541), 'numpy.ma.std', 'MA.std', (["self.cpinfo['processed']['native']['cphase'][:, ind_daybin, :, :]"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['cphase'][:, ind_daybin, :, :],\n axis=1)\n", (108462, 108541), True, 'import numpy.ma as MA\n'), ((110855, 110898), 'numpy.ma.array', 'MA.array', (['eicp_split[i]'], {'mask': 'mask_split[i]'}), '(eicp_split[i], mask=mask_split[i])\n', (110863, 110898), True, 'import numpy.ma as MA\n'), ((118344, 118397), 'numpy.ma.std', 'MA.std', (["indict['cphase'][ind_lstbin, :, :, :]"], {'axis': '(0)'}), "(indict['cphase'][ind_lstbin, :, :, :], axis=0)\n", (118350, 118397), True, 'import numpy.ma as MA\n'), ((119014, 119075), 'numpy.ma.std', 'MA.std', (["indict['cphase']['mean'][ind_lstbin, :, :, :]"], {'axis': '(0)'}), "(indict['cphase']['mean'][ind_lstbin, :, :, :], axis=0)\n", (119020, 119075), True, 'import numpy.ma as MA\n'), ((129277, 129362), 'numpy.ma.std', 'MA.std', (["self.cpinfo['processed']['native']['cphase'][:, ind_daybin, :, :]"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['cphase'][:, ind_daybin, :, :],\n axis=1)\n", (129283, 129362), True, 'import numpy.ma as MA\n'), ((130876, 130919), 'numpy.ma.array', 'MA.array', (['eicp_split[i]'], {'mask': 'mask_split[i]'}), '(eicp_split[i], mask=mask_split[i])\n', (130884, 130919), True, 'import numpy.ma as MA\n'), ((137194, 137217), 'numpy.exp', 'NP.exp', (['(1.0j * cp_dmean)'], {}), '(1.0j * cp_dmean)\n', (137200, 137217), True, 'import numpy as NP\n'), ((164291, 164320), 'numpy.isnan', 'NP.isnan', (["visscaleinfo['vis']"], {}), "(visscaleinfo['vis'])\n", (164299, 164320), True, 'import numpy as NP\n'), ((166120, 166141), 'numpy.ones', 'NP.ones', (['lst_out.size'], {}), '(lst_out.size)\n', (166127, 166141), True, 'import numpy as NP\n'), ((166193, 166214), 'numpy.ones', 'NP.ones', (['lst_out.size'], {}), '(lst_out.size)\n', (166200, 166214), True, 'import numpy as NP\n'), ((174516, 174620), 'numpy.pad', 'NP.pad', (['(flagwts * freq_wts[:, NP.newaxis, NP.newaxis, NP.newaxis, :])', 'ndim_padtuple'], {'mode': '"""constant"""'}), "(flagwts * freq_wts[:, NP.newaxis, NP.newaxis, NP.newaxis, :],\n ndim_padtuple, mode='constant')\n", (174522, 174620), True, 'import numpy as NP\n'), ((175854, 175950), 'astroutils.DSP_modules.downsampler', 'DSP.downsampler', (["result_resampled[dpool]['dspec']", 'downsample_factor'], {'axis': '(-1)', 'method': '"""FFT"""'}), "(result_resampled[dpool]['dspec'], downsample_factor, axis=-\n 1, method='FFT')\n", (175869, 175950), True, 'from astroutils import DSP_modules as DSP\n'), ((179749, 179850), 'numpy.logical_or', 'NP.logical_or', (['(lst_ind < 0)', "(lst_ind >= self.cPhase.cpinfo['processed']['prelim']['wts'].shape[0])"], {}), "(lst_ind < 0, lst_ind >= self.cPhase.cpinfo['processed'][\n 'prelim']['wts'].shape[0])\n", (179762, 179850), True, 'import numpy as NP\n'), ((181135, 181236), 'numpy.logical_or', 'NP.logical_or', (['(day_ind < 0)', "(day_ind >= self.cPhase.cpinfo['processed']['prelim']['wts'].shape[1])"], {}), "(day_ind < 0, day_ind >= self.cPhase.cpinfo['processed'][\n 'prelim']['wts'].shape[1])\n", (181148, 181236), True, 'import numpy as NP\n'), ((205987, 206015), 'numpy.asarray', 'NP.asarray', (["autoinfo['axes']"], {}), "(autoinfo['axes'])\n", (205997, 206015), True, 'import numpy as NP\n'), ((207607, 207633), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (207614, 207633), True, 'import numpy as NP\n'), ((211500, 211531), 'numpy.asarray', 'NP.asarray', (["xinfo['dlst_range']"], {}), "(xinfo['dlst_range'])\n", (211510, 211531), True, 'import numpy as NP\n'), ((215635, 215701), 'numpy.ones', 'NP.ones', (["cpds[smplng]['whole']['dspec']['mean'].ndim"], {'dtype': 'NP.int'}), "(cpds[smplng]['whole']['dspec']['mean'].ndim, dtype=NP.int)\n", (215642, 215701), True, 'import numpy as NP\n'), ((215940, 215959), 'numpy.copy', 'NP.copy', (['awts_shape'], {}), '(awts_shape)\n', (215947, 215959), True, 'import numpy as NP\n'), ((216251, 216308), 'numpy.copy', 'NP.copy', (["cpds[smplng][dpool]['dspec'][dspec_multidim_idx]"], {}), "(cpds[smplng][dpool]['dspec'][dspec_multidim_idx])\n", (216258, 216308), True, 'import numpy as NP\n'), ((216375, 216438), 'numpy.copy', 'NP.copy', (["cpds[smplng][dpool]['dspec'][stat][dspec_multidim_idx]"], {}), "(cpds[smplng][dpool]['dspec'][stat][dspec_multidim_idx])\n", (216382, 216438), True, 'import numpy as NP\n'), ((217115, 217151), 'numpy.ones', 'NP.ones', (['wts_shape'], {'dtype': 'NP.complex'}), '(wts_shape, dtype=NP.complex)\n', (217122, 217151), True, 'import numpy as NP\n'), ((217192, 217213), 'numpy.asarray', 'NP.asarray', (['wts_shape'], {}), '(wts_shape)\n', (217202, 217213), True, 'import numpy as NP\n'), ((217572, 217586), 'numpy.copy', 'NP.copy', (['dspec'], {}), '(dspec)\n', (217579, 217586), True, 'import numpy as NP\n'), ((217624, 217638), 'numpy.copy', 'NP.copy', (['dspec'], {}), '(dspec)\n', (217631, 217638), True, 'import numpy as NP\n'), ((217678, 217694), 'numpy.copy', 'NP.copy', (['preXwts'], {}), '(preXwts)\n', (217685, 217694), True, 'import numpy as NP\n'), ((217734, 217750), 'numpy.copy', 'NP.copy', (['preXwts'], {}), '(preXwts)\n', (217741, 217750), True, 'import numpy as NP\n'), ((252991, 253019), 'numpy.asarray', 'NP.asarray', (["autoinfo['axes']"], {}), "(autoinfo['axes'])\n", (253001, 253019), True, 'import numpy as NP\n'), ((254611, 254637), 'numpy.ones', 'NP.ones', (['(1)'], {'dtype': 'NP.float'}), '(1, dtype=NP.float)\n', (254618, 254637), True, 'import numpy as NP\n'), ((259035, 259066), 'numpy.asarray', 'NP.asarray', (["xinfo['dlst_range']"], {}), "(xinfo['dlst_range'])\n", (259045, 259066), True, 'import numpy as NP\n'), ((262025, 262045), 'numpy.asarray', 'NP.asarray', (['inpshape'], {}), '(inpshape)\n', (262035, 262045), True, 'import numpy as NP\n'), ((262046, 262063), 'numpy.asarray', 'NP.asarray', (['cohax'], {}), '(cohax)\n', (262056, 262063), True, 'import numpy as NP\n'), ((262201, 262221), 'numpy.asarray', 'NP.asarray', (['inpshape'], {}), '(inpshape)\n', (262211, 262221), True, 'import numpy as NP\n'), ((262222, 262241), 'numpy.asarray', 'NP.asarray', (['incohax'], {}), '(incohax)\n', (262232, 262241), True, 'import numpy as NP\n'), ((264395, 264439), 'numpy.median', 'NP.median', (['dspec0'], {'axis': 'cohax', 'keepdims': '(True)'}), '(dspec0, axis=cohax, keepdims=True)\n', (264404, 264439), True, 'import numpy as NP\n'), ((264477, 264521), 'numpy.median', 'NP.median', (['dspec1'], {'axis': 'cohax', 'keepdims': '(True)'}), '(dspec1, axis=cohax, keepdims=True)\n', (264486, 264521), True, 'import numpy as NP\n'), ((264649, 264683), 'numpy.ones', 'NP.ones', (['dspec0.ndim'], {'dtype': 'NP.int'}), '(dspec0.ndim, dtype=NP.int)\n', (264656, 264683), True, 'import numpy as NP\n'), ((264933, 264951), 'numpy.copy', 'NP.copy', (['wts_shape'], {}), '(wts_shape)\n', (264940, 264951), True, 'import numpy as NP\n'), ((265260, 265276), 'numpy.sort', 'NP.sort', (['incohax'], {}), '(incohax)\n', (265267, 265276), True, 'import numpy as NP\n'), ((265321, 265355), 'numpy.expand_dims', 'NP.expand_dims', (['dspec0'], {'axis': 'incax'}), '(dspec0, axis=incax)\n', (265335, 265355), True, 'import numpy as NP\n'), ((265395, 265431), 'numpy.expand_dims', 'NP.expand_dims', (['preXwts0'], {'axis': 'incax'}), '(preXwts0, axis=incax)\n', (265409, 265431), True, 'import numpy as NP\n'), ((272295, 272331), 'numpy.ones', 'NP.ones', (['wts_shape'], {'dtype': 'NP.complex'}), '(wts_shape, dtype=NP.complex)\n', (272302, 272331), True, 'import numpy as NP\n'), ((272372, 272393), 'numpy.asarray', 'NP.asarray', (['wts_shape'], {}), '(wts_shape)\n', (272382, 272393), True, 'import numpy as NP\n'), ((283417, 283450), 'numpy.abs', 'NP.abs', (['freqwtd_avgvis_nearestLST'], {}), '(freqwtd_avgvis_nearestLST)\n', (283423, 283450), True, 'import numpy as NP\n'), ((292331, 292375), 'numpy.arange', 'NP.arange', (["rcpdps[dpool]['freq_center'].size"], {}), "(rcpdps[dpool]['freq_center'].size)\n", (292340, 292375), True, 'import numpy as NP\n'), ((292377, 292406), 'numpy.arange', 'NP.arange', (["rcpdps['lst'].size"], {}), "(rcpdps['lst'].size)\n", (292386, 292406), True, 'import numpy as NP\n'), ((292408, 292438), 'numpy.arange', 'NP.arange', (["rcpdps['days'].size"], {}), "(rcpdps['days'].size)\n", (292417, 292438), True, 'import numpy as NP\n'), ((292440, 292472), 'numpy.arange', 'NP.arange', (["rcpdps['triads'].size"], {}), "(rcpdps['triads'].size)\n", (292449, 292472), True, 'import numpy as NP\n'), ((308468, 308485), 'numpy.array', 'NP.array', (['[-1, 1]'], {}), '([-1, 1])\n', (308476, 308485), True, 'import numpy as NP\n'), ((309012, 309044), 'numpy.ones', 'NP.ones', (["beamparms['freqs'].size"], {}), "(beamparms['freqs'].size)\n", (309019, 309044), True, 'import numpy as NP\n'), ((17290, 17308), 'numpy.copy', 'NP.copy', (['lstday.jd'], {}), '(lstday.jd)\n', (17297, 17308), True, 'import numpy as NP\n'), ((22478, 22492), 'numpy.copy', 'NP.copy', (['lstHA'], {}), '(lstHA)\n', (22485, 22492), True, 'import numpy as NP\n'), ((69905, 69923), 'numpy.copy', 'NP.copy', (['mask_ones'], {}), '(mask_ones)\n', (69912, 69923), True, 'import numpy as NP\n'), ((70269, 70286), 'numpy.copy', 'NP.copy', (['mask_agg'], {}), '(mask_agg)\n', (70276, 70286), True, 'import numpy as NP\n'), ((70602, 70651), 'numpy.copy', 'NP.copy', (['out_xcpdps[smplng][dpool][stat].si.value'], {}), '(out_xcpdps[smplng][dpool][stat].si.value)\n', (70609, 70651), True, 'import numpy as NP\n'), ((71924, 71995), 'numpy.ones', 'NP.ones', (["out_excpdps[smplng][dpool]['diagweights'].shape"], {'dtype': 'NP.bool'}), "(out_excpdps[smplng][dpool]['diagweights'].shape, dtype=NP.bool)\n", (71931, 71995), True, 'import numpy as NP\n'), ((88694, 88746), 'numpy.asarray', 'NP.asarray', (['xcpdps[smplng][dpool][stat][combi].shape'], {}), '(xcpdps[smplng][dpool][stat][combi].shape)\n', (88704, 88746), True, 'import numpy as NP\n'), ((105876, 105898), 'numpy.asarray', 'NP.asarray', (['daybinsize'], {}), '(daybinsize)\n', (105886, 105898), True, 'import numpy as NP\n'), ((111195, 111243), 'numpy.ma.array', 'MA.array', (['eicp_split[i].real'], {'mask': 'mask_split[i]'}), '(eicp_split[i].real, mask=mask_split[i])\n', (111203, 111243), True, 'import numpy.ma as MA\n'), ((111738, 111779), 'numpy.ma.array', 'MA.array', (['cp_split[i]'], {'mask': 'mask_split[i]'}), '(cp_split[i], mask=mask_split[i])\n', (111746, 111779), True, 'import numpy.ma as MA\n'), ((114839, 114861), 'numpy.asarray', 'NP.asarray', (['lstbinsize'], {}), '(lstbinsize)\n', (114849, 114861), True, 'import numpy as NP\n'), ((115803, 115825), 'numpy.asarray', 'NP.asarray', (['lstbinsize'], {}), '(lstbinsize)\n', (115813, 115825), True, 'import numpy as NP\n'), ((131216, 131264), 'numpy.ma.array', 'MA.array', (['eicp_split[i].real'], {'mask': 'mask_split[i]'}), '(eicp_split[i].real, mask=mask_split[i])\n', (131224, 131264), True, 'import numpy.ma as MA\n'), ((131759, 131800), 'numpy.ma.array', 'MA.array', (['cp_split[i]'], {'mask': 'mask_split[i]'}), '(cp_split[i], mask=mask_split[i])\n', (131767, 131800), True, 'import numpy.ma as MA\n'), ((134120, 134142), 'numpy.asarray', 'NP.asarray', (['lstbinsize'], {}), '(lstbinsize)\n', (134130, 134142), True, 'import numpy as NP\n'), ((135043, 135065), 'numpy.asarray', 'NP.asarray', (['lstbinsize'], {}), '(lstbinsize)\n', (135053, 135065), True, 'import numpy as NP\n'), ((137283, 137301), 'numpy.cos', 'NP.cos', (['cp_dmedian'], {}), '(cp_dmedian)\n', (137289, 137301), True, 'import numpy as NP\n'), ((167983, 168005), 'numpy.arange', 'NP.arange', (['n_window[i]'], {}), '(n_window[i])\n', (167992, 168005), True, 'import numpy as NP\n'), ((169421, 169497), 'numpy.transpose', 'NP.transpose', (['vis_ref[NP.newaxis, NP.newaxis, :, :, :]'], {'axes': '(0, 3, 1, 2, 4)'}), '(vis_ref[NP.newaxis, NP.newaxis, :, :, :], axes=(0, 3, 1, 2, 4))\n', (169433, 169497), True, 'import numpy as NP\n'), ((171793, 171855), 'numpy.copy', 'NP.copy', (["self.cPhase.cpinfo['processed'][datapool]['wts'].data"], {}), "(self.cPhase.cpinfo['processed'][datapool]['wts'].data)\n", (171800, 171855), True, 'import numpy as NP\n'), ((172260, 172320), 'numpy.copy', 'NP.copy', (["self.cPhase.cpinfo['processed'][dpool]['eicp'].data"], {}), "(self.cPhase.cpinfo['processed'][dpool]['eicp'].data)\n", (172267, 172320), True, 'import numpy as NP\n'), ((172521, 172612), 'numpy.broadcast_to', 'NP.broadcast_to', (['eicp', "self.cPhase.cpinfo['processed'][datapool]['eicp']['mean'].shape"], {}), "(eicp, self.cPhase.cpinfo['processed'][datapool]['eicp'][\n 'mean'].shape)\n", (172536, 172612), True, 'import numpy as NP\n'), ((175573, 175683), 'astroutils.DSP_modules.downsampler', 'DSP.downsampler', (["result_resampled[dpool]['dspec' + diffind][key]", 'downsample_factor'], {'axis': '(-1)', 'method': '"""FFT"""'}), "(result_resampled[dpool]['dspec' + diffind][key],\n downsample_factor, axis=-1, method='FFT')\n", (175588, 175683), True, 'from astroutils import DSP_modules as DSP\n'), ((214544, 214564), 'numpy.asarray', 'NP.asarray', (['inpshape'], {}), '(inpshape)\n', (214554, 214564), True, 'import numpy as NP\n'), ((214565, 214582), 'numpy.asarray', 'NP.asarray', (['cohax'], {}), '(cohax)\n', (214575, 214582), True, 'import numpy as NP\n'), ((214736, 214756), 'numpy.asarray', 'NP.asarray', (['inpshape'], {}), '(inpshape)\n', (214746, 214756), True, 'import numpy as NP\n'), ((214757, 214776), 'numpy.asarray', 'NP.asarray', (['incohax'], {}), '(incohax)\n', (214767, 214776), True, 'import numpy as NP\n'), ((216839, 216902), 'numpy.median', 'NP.median', (['dspec[dspec_multidim_idx]'], {'axis': 'cohax', 'keepdims': '(True)'}), '(dspec[dspec_multidim_idx], axis=cohax, keepdims=True)\n', (216848, 216902), True, 'import numpy as NP\n'), ((217042, 217075), 'numpy.ones', 'NP.ones', (['dspec.ndim'], {'dtype': 'NP.int'}), '(dspec.ndim, dtype=NP.int)\n', (217049, 217075), True, 'import numpy as NP\n'), ((217341, 217359), 'numpy.copy', 'NP.copy', (['wts_shape'], {}), '(wts_shape)\n', (217348, 217359), True, 'import numpy as NP\n'), ((217792, 217808), 'numpy.sort', 'NP.sort', (['incohax'], {}), '(incohax)\n', (217799, 217808), True, 'import numpy as NP\n'), ((217857, 217891), 'numpy.expand_dims', 'NP.expand_dims', (['dspec1'], {'axis': 'incax'}), '(dspec1, axis=incax)\n', (217871, 217891), True, 'import numpy as NP\n'), ((217935, 217971), 'numpy.expand_dims', 'NP.expand_dims', (['preXwts1'], {'axis': 'incax'}), '(preXwts1, axis=incax)\n', (217949, 217971), True, 'import numpy as NP\n'), ((224279, 224315), 'numpy.ones', 'NP.ones', (['wts_shape'], {'dtype': 'NP.complex'}), '(wts_shape, dtype=NP.complex)\n', (224286, 224315), True, 'import numpy as NP\n'), ((224360, 224381), 'numpy.asarray', 'NP.asarray', (['wts_shape'], {}), '(wts_shape)\n', (224370, 224381), True, 'import numpy as NP\n'), ((263959, 264036), 'numpy.sum', 'NP.sum', (["(twts['0'][NP.newaxis, ...] * awts * dspec0)"], {'axis': 'cohax', 'keepdims': '(True)'}), "(twts['0'][NP.newaxis, ...] * awts * dspec0, axis=cohax, keepdims=True)\n", (263965, 264036), True, 'import numpy as NP\n'), ((264038, 264129), 'numpy.sum', 'NP.sum', (["(twts['0'][twts_multidim_idx][NP.newaxis, ...] * awts)"], {'axis': 'cohax', 'keepdims': '(True)'}), "(twts['0'][twts_multidim_idx][NP.newaxis, ...] * awts, axis=cohax,\n keepdims=True)\n", (264044, 264129), True, 'import numpy as NP\n'), ((264162, 264239), 'numpy.sum', 'NP.sum', (["(twts['1'][NP.newaxis, ...] * awts * dspec1)"], {'axis': 'cohax', 'keepdims': '(True)'}), "(twts['1'][NP.newaxis, ...] * awts * dspec1, axis=cohax, keepdims=True)\n", (264168, 264239), True, 'import numpy as NP\n'), ((264241, 264332), 'numpy.sum', 'NP.sum', (["(twts['1'][twts_multidim_idx][NP.newaxis, ...] * awts)"], {'axis': 'cohax', 'keepdims': '(True)'}), "(twts['1'][twts_multidim_idx][NP.newaxis, ...] * awts, axis=cohax,\n keepdims=True)\n", (264247, 264332), True, 'import numpy as NP\n'), ((266009, 266045), 'numpy.expand_dims', 'NP.expand_dims', (['preXwts1'], {'axis': 'incax'}), '(preXwts1, axis=incax)\n', (266023, 266045), True, 'import numpy as NP\n'), ((266095, 266125), 'numpy.asarray', 'NP.asarray', (['preXwts1_tmp.shape'], {}), '(preXwts1_tmp.shape)\n', (266105, 266125), True, 'import numpy as NP\n'), ((266621, 266655), 'numpy.expand_dims', 'NP.expand_dims', (['dspec1'], {'axis': 'incax'}), '(dspec1, axis=incax)\n', (266635, 266655), True, 'import numpy as NP\n'), ((266703, 266731), 'numpy.asarray', 'NP.asarray', (['dspec1_tmp.shape'], {}), '(dspec1_tmp.shape)\n', (266713, 266731), True, 'import numpy as NP\n'), ((267736, 267774), 'numpy.expand_dims', 'NP.expand_dims', (['dspec1'], {'axis': '(incax + 1)'}), '(dspec1, axis=incax + 1)\n', (267750, 267774), True, 'import numpy as NP\n'), ((267816, 267856), 'numpy.expand_dims', 'NP.expand_dims', (['preXwts1'], {'axis': '(incax + 1)'}), '(preXwts1, axis=incax + 1)\n', (267830, 267856), True, 'import numpy as NP\n'), ((267913, 267925), 'numpy.arange', 'NP.arange', (['(2)'], {}), '(2)\n', (267922, 267925), True, 'import numpy as NP\n'), ((272199, 272254), 'numpy.ones', 'NP.ones', (['result[smplng][dpool][stat].ndim'], {'dtype': 'NP.int'}), '(result[smplng][dpool][stat].ndim, dtype=NP.int)\n', (272206, 272254), True, 'import numpy as NP\n'), ((272529, 272547), 'numpy.copy', 'NP.copy', (['wts_shape'], {}), '(wts_shape)\n', (272536, 272547), True, 'import numpy as NP\n'), ((273652, 273724), 'numpy.nanmean', 'NP.nanmean', (['result[smplng][dpool][stat]'], {'axis': 'axes_to_sum', 'keepdims': '(True)'}), '(result[smplng][dpool][stat], axis=axes_to_sum, keepdims=True)\n', (273662, 273724), True, 'import numpy as NP\n'), ((275038, 275058), 'numpy.abs', 'NP.abs', (['(dspec * U.Jy)'], {}), '(dspec * U.Jy)\n', (275044, 275058), True, 'import numpy as NP\n'), ((291784, 291807), 'numpy.intersect1d', 'NP.intersect1d', (['indsets'], {}), '(indsets)\n', (291798, 291807), True, 'import numpy as NP\n'), ((291859, 291903), 'numpy.arange', 'NP.arange', (["rcpdps[dpool]['freq_center'].size"], {}), "(rcpdps[dpool]['freq_center'].size)\n", (291868, 291903), True, 'import numpy as NP\n'), ((291905, 291934), 'numpy.arange', 'NP.arange', (["rcpdps['lst'].size"], {}), "(rcpdps['lst'].size)\n", (291914, 291934), True, 'import numpy as NP\n'), ((291936, 291966), 'numpy.arange', 'NP.arange', (["rcpdps['days'].size"], {}), "(rcpdps['days'].size)\n", (291945, 291966), True, 'import numpy as NP\n'), ((291968, 292000), 'numpy.arange', 'NP.arange', (["rcpdps['triads'].size"], {}), "(rcpdps['triads'].size)\n", (291977, 292000), True, 'import numpy as NP\n'), ((292100, 292144), 'numpy.arange', 'NP.arange', (["rcpdps[dpool]['freq_center'].size"], {}), "(rcpdps[dpool]['freq_center'].size)\n", (292109, 292144), True, 'import numpy as NP\n'), ((292146, 292175), 'numpy.arange', 'NP.arange', (["rcpdps['lst'].size"], {}), "(rcpdps['lst'].size)\n", (292155, 292175), True, 'import numpy as NP\n'), ((292177, 292207), 'numpy.arange', 'NP.arange', (["rcpdps['days'].size"], {}), "(rcpdps['days'].size)\n", (292186, 292207), True, 'import numpy as NP\n'), ((292209, 292241), 'numpy.arange', 'NP.arange', (["rcpdps['triads'].size"], {}), "(rcpdps['triads'].size)\n", (292218, 292241), True, 'import numpy as NP\n'), ((307117, 307138), 'numpy.abs', 'NP.abs', (['external_beam'], {}), '(external_beam)\n', (307123, 307138), True, 'import numpy as NP\n'), ((17378, 17397), 'numpy.copy', 'NP.copy', (['daydata.jd'], {}), '(daydata.jd)\n', (17385, 17397), True, 'import numpy as NP\n'), ((22559, 22577), 'numpy.copy', 'NP.copy', (['lstday.jd'], {}), '(lstday.jd)\n', (22566, 22577), True, 'import numpy as NP\n'), ((64874, 64932), 'numpy.ones', 'NP.ones', (['xcpdps[i][smplng][dpool][stat].ndim'], {'dtype': 'NP.int'}), '(xcpdps[i][smplng][dpool][stat].ndim, dtype=NP.int)\n', (64881, 64932), True, 'import numpy as NP\n'), ((65928, 65964), 'numpy.nansum', 'NP.nansum', (['(arr * diagweights)'], {'axis': '(0)'}), '(arr * diagweights, axis=0)\n', (65937, 65964), True, 'import numpy as NP\n'), ((65967, 65997), 'numpy.nansum', 'NP.nansum', (['diagweights'], {'axis': '(0)'}), '(diagweights, axis=0)\n', (65976, 65997), True, 'import numpy as NP\n'), ((67146, 67205), 'numpy.ones', 'NP.ones', (['excpdps[i][smplng][dpool][stat].ndim'], {'dtype': 'NP.int'}), '(excpdps[i][smplng][dpool][stat].ndim, dtype=NP.int)\n', (67153, 67205), True, 'import numpy as NP\n'), ((68208, 68244), 'numpy.nansum', 'NP.nansum', (['(arr * diagweights)'], {'axis': '(0)'}), '(arr * diagweights, axis=0)\n', (68217, 68244), True, 'import numpy as NP\n'), ((68247, 68277), 'numpy.nansum', 'NP.nansum', (['diagweights'], {'axis': '(0)'}), '(diagweights, axis=0)\n', (68256, 68277), True, 'import numpy as NP\n'), ((70094, 70111), 'numpy.copy', 'NP.copy', (['mask_tmp'], {}), '(mask_tmp)\n', (70101, 70111), True, 'import numpy as NP\n'), ((70197, 70230), 'numpy.logical_or', 'NP.logical_or', (['mask_agg', 'mask_tmp'], {}), '(mask_agg, mask_tmp)\n', (70210, 70230), True, 'import numpy as NP\n'), ((70926, 70960), 'numpy.ma.array', 'MA.array', (['diagwts'], {'mask': 'masks[ind]'}), '(diagwts, mask=masks[ind])\n', (70934, 70960), True, 'import numpy.ma as MA\n'), ((72895, 72912), 'numpy.copy', 'NP.copy', (['mask_agg'], {}), '(mask_agg)\n', (72902, 72912), True, 'import numpy as NP\n'), ((73251, 73301), 'numpy.copy', 'NP.copy', (['out_excpdps[smplng][dpool][stat].si.value'], {}), '(out_excpdps[smplng][dpool][stat].si.value)\n', (73258, 73301), True, 'import numpy as NP\n'), ((86940, 86953), 'numpy.abs', 'NP.abs', (['kprll'], {}), '(kprll)\n', (86946, 86953), True, 'import numpy as NP\n'), ((87077, 87090), 'numpy.abs', 'NP.abs', (['kprll'], {}), '(kprll)\n', (87083, 87090), True, 'import numpy as NP\n'), ((88899, 88946), 'astropy.units.Unit', 'U.Unit', (['xcpdps[smplng][dpool][stat][combi].unit'], {}), '(xcpdps[smplng][dpool][stat][combi].unit)\n', (88905, 88946), True, 'from astropy import units as U\n'), ((89043, 89103), 'astropy.units.Unit', 'U.Unit', (['(xcpdps[smplng][dpool][stat][combi].unit / U.Mpc ** 3)'], {}), '(xcpdps[smplng][dpool][stat][combi].unit / U.Mpc ** 3)\n', (89049, 89103), True, 'from astropy import units as U\n'), ((89314, 89364), 'numpy.copy', 'NP.copy', (["psinfo[smplng]['kbininfo']['counts'][spw]"], {}), "(psinfo[smplng]['kbininfo']['counts'][spw])\n", (89321, 89364), True, 'import numpy as NP\n'), ((89406, 89452), 'numpy.copy', 'NP.copy', (["psinfo[smplng]['kbininfo']['ri'][spw]"], {}), "(psinfo[smplng]['kbininfo']['ri'][spw])\n", (89413, 89452), True, 'import numpy as NP\n'), ((91175, 91197), 'copy.deepcopy', 'copy.deepcopy', (['tmp_dps'], {}), '(tmp_dps)\n', (91188, 91197), False, 'import copy\n'), ((91271, 91294), 'copy.deepcopy', 'copy.deepcopy', (['tmp_Del2'], {}), '(tmp_Del2)\n', (91284, 91294), False, 'import copy\n'), ((91372, 91396), 'copy.deepcopy', 'copy.deepcopy', (['tmp_kprll'], {}), '(tmp_kprll)\n', (91385, 91396), False, 'import copy\n'), ((108077, 108162), 'numpy.ma.mean', 'MA.mean', (["self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :]"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :], axis=1\n )\n", (108084, 108162), True, 'import numpy.ma as MA\n'), ((111270, 111318), 'numpy.ma.array', 'MA.array', (['eicp_split[i].imag'], {'mask': 'mask_split[i]'}), '(eicp_split[i].imag, mask=mask_split[i])\n', (111278, 111318), True, 'import numpy.ma as MA\n'), ((118021, 118073), 'numpy.ma.mean', 'MA.mean', (["indict['eicp'][ind_lstbin, :, :, :]"], {'axis': '(0)'}), "(indict['eicp'][ind_lstbin, :, :, :], axis=0)\n", (118028, 118073), True, 'import numpy.ma as MA\n'), ((128898, 128983), 'numpy.ma.mean', 'MA.mean', (["self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :]"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :], axis=1\n )\n", (128905, 128983), True, 'import numpy.ma as MA\n'), ((131291, 131339), 'numpy.ma.array', 'MA.array', (['eicp_split[i].imag'], {'mask': 'mask_split[i]'}), '(eicp_split[i].imag, mask=mask_split[i])\n', (131299, 131339), True, 'import numpy.ma as MA\n'), ((136575, 136619), 'numpy.exp', 'NP.exp', (['(1.0j * cp_dmean[ind_lstbin, :, :, :])'], {}), '(1.0j * cp_dmean[ind_lstbin, :, :, :])\n', (136581, 136619), True, 'import numpy as NP\n'), ((137309, 137327), 'numpy.sin', 'NP.sin', (['cp_dmedian'], {}), '(cp_dmedian)\n', (137315, 137327), True, 'import numpy as NP\n'), ((170389, 170429), 'numpy.mean', 'NP.mean', (['flagwts'], {'axis': '(-1)', 'keepdims': '(True)'}), '(flagwts, axis=-1, keepdims=True)\n', (170396, 170429), True, 'import numpy as NP\n'), ((172059, 172099), 'numpy.mean', 'NP.mean', (['flagwts'], {'axis': '(-1)', 'keepdims': '(True)'}), '(flagwts, axis=-1, keepdims=True)\n', (172066, 172099), True, 'import numpy as NP\n'), ((173339, 173404), 'numpy.copy', 'NP.copy', (["self.cPhase.cpinfo['processed'][dpool]['eicp'][key].data"], {}), "(self.cPhase.cpinfo['processed'][dpool]['eicp'][key].data)\n", (173346, 173404), True, 'import numpy as NP\n'), ((176198, 176300), 'astroutils.DSP_modules.downsampler', 'DSP.downsampler', (["result_resampled['whole']['dspec'][key]", 'downsample_factor'], {'axis': '(-1)', 'method': '"""FFT"""'}), "(result_resampled['whole']['dspec'][key], downsample_factor,\n axis=-1, method='FFT')\n", (176213, 176300), True, 'from astroutils import DSP_modules as DSP\n'), ((176411, 176511), 'astroutils.DSP_modules.downsampler', 'DSP.downsampler', (["result_resampled[dpool]['dspec'][key]", 'downsample_factor'], {'axis': '(-1)', 'method': '"""FFT"""'}), "(result_resampled[dpool]['dspec'][key], downsample_factor,\n axis=-1, method='FFT')\n", (176426, 176511), True, 'from astroutils import DSP_modules as DSP\n'), ((216571, 216686), 'numpy.sum', 'NP.sum', (['(twts[twts_multidim_idx][NP.newaxis, ...] * awts * dspec[dspec_multidim_idx])'], {'axis': 'cohax', 'keepdims': '(True)'}), '(twts[twts_multidim_idx][NP.newaxis, ...] * awts * dspec[\n dspec_multidim_idx], axis=cohax, keepdims=True)\n', (216577, 216686), True, 'import numpy as NP\n'), ((216683, 216769), 'numpy.sum', 'NP.sum', (['(twts[twts_multidim_idx][NP.newaxis, ...] * awts)'], {'axis': 'cohax', 'keepdims': '(True)'}), '(twts[twts_multidim_idx][NP.newaxis, ...] * awts, axis=cohax,\n keepdims=True)\n', (216689, 216769), True, 'import numpy as NP\n'), ((218577, 218613), 'numpy.expand_dims', 'NP.expand_dims', (['preXwts2'], {'axis': 'incax'}), '(preXwts2, axis=incax)\n', (218591, 218613), True, 'import numpy as NP\n'), ((218667, 218697), 'numpy.asarray', 'NP.asarray', (['preXwts2_tmp.shape'], {}), '(preXwts2_tmp.shape)\n', (218677, 218697), True, 'import numpy as NP\n'), ((219213, 219247), 'numpy.expand_dims', 'NP.expand_dims', (['dspec2'], {'axis': 'incax'}), '(dspec2, axis=incax)\n', (219227, 219247), True, 'import numpy as NP\n'), ((219299, 219327), 'numpy.asarray', 'NP.asarray', (['dspec2_tmp.shape'], {}), '(dspec2_tmp.shape)\n', (219309, 219327), True, 'import numpy as NP\n'), ((220376, 220414), 'numpy.expand_dims', 'NP.expand_dims', (['dspec2'], {'axis': '(incax + 1)'}), '(dspec2, axis=incax + 1)\n', (220390, 220414), True, 'import numpy as NP\n'), ((220460, 220500), 'numpy.expand_dims', 'NP.expand_dims', (['preXwts2'], {'axis': '(incax + 1)'}), '(preXwts2, axis=incax + 1)\n', (220474, 220500), True, 'import numpy as NP\n'), ((220561, 220573), 'numpy.arange', 'NP.arange', (['(2)'], {}), '(2)\n', (220570, 220573), True, 'import numpy as NP\n'), ((224179, 224234), 'numpy.ones', 'NP.ones', (['result[smplng][dpool][stat].ndim'], {'dtype': 'NP.int'}), '(result[smplng][dpool][stat].ndim, dtype=NP.int)\n', (224186, 224234), True, 'import numpy as NP\n'), ((224525, 224543), 'numpy.copy', 'NP.copy', (['wts_shape'], {}), '(wts_shape)\n', (224532, 224543), True, 'import numpy as NP\n'), ((226981, 227001), 'numpy.abs', 'NP.abs', (['(dspec * U.Jy)'], {}), '(dspec * U.Jy)\n', (226987, 227001), True, 'import numpy as NP\n'), ((267327, 267379), 'numpy.roll', 'NP.roll', (['dspec1_tmp[:, 0, ...]', 'lstshift'], {'axis': 'incax'}), '(dspec1_tmp[:, 0, ...], lstshift, axis=incax)\n', (267334, 267379), True, 'import numpy as NP\n'), ((267525, 267579), 'numpy.roll', 'NP.roll', (['preXwts1_tmp[:, 0, ...]', 'lstshift'], {'axis': 'incax'}), '(preXwts1_tmp[:, 0, ...], lstshift, axis=incax)\n', (267532, 267579), True, 'import numpy as NP\n'), ((269398, 269432), 'numpy.asarray', 'NP.asarray', (["xinfo['collapse_axes']"], {}), "(xinfo['collapse_axes'])\n", (269408, 269432), True, 'import numpy as NP\n'), ((270076, 270139), 'numpy.ones', 'NP.ones', (["cpds[smplng][dpool]['dspec0'][stat].ndim"], {'dtype': 'NP.int'}), "(cpds[smplng][dpool]['dspec0'][stat].ndim, dtype=NP.int)\n", (270083, 270139), True, 'import numpy as NP\n'), ((271251, 271400), 'astroutils.mathops.array_trace', 'OPS.array_trace', (['result[smplng][dpool][stat].si.value'], {'offsets': 'None', 'axis1': 'expandax_map[colax][0]', 'axis2': 'expandax_map[colax][1]', 'outaxis': '"""axis1"""'}), "(result[smplng][dpool][stat].si.value, offsets=None, axis1=\n expandax_map[colax][0], axis2=expandax_map[colax][1], outaxis='axis1')\n", (271266, 271400), True, 'from astroutils import mathops as OPS\n'), ((271448, 271503), 'numpy.ones', 'NP.ones', (['result[smplng][dpool][stat].ndim'], {'dtype': 'NP.int'}), '(result[smplng][dpool][stat].ndim, dtype=NP.int)\n', (271455, 271503), True, 'import numpy as NP\n'), ((271715, 271731), 'numpy.copy', 'NP.copy', (['diagwts'], {}), '(diagwts)\n', (271722, 271731), True, 'import numpy as NP\n'), ((273224, 273276), 'numpy.nansum', 'NP.nansum', (['postXwts'], {'axis': 'axes_to_sum', 'keepdims': '(True)'}), '(postXwts, axis=axes_to_sum, keepdims=True)\n', (273233, 273276), True, 'import numpy as NP\n'), ((274208, 274263), 'numpy.ones', 'NP.ones', (['result[smplng][dpool][stat].ndim'], {'dtype': 'NP.int'}), '(result[smplng][dpool][stat].ndim, dtype=NP.int)\n', (274215, 274263), True, 'import numpy as NP\n'), ((274735, 274832), 'numpy.nansum', 'NP.nansum', (['(result[smplng][dpool][stat] * diagoffset_weights)'], {'axis': 'axes_to_sum', 'keepdims': '(True)'}), '(result[smplng][dpool][stat] * diagoffset_weights, axis=\n axes_to_sum, keepdims=True)\n', (274744, 274832), True, 'import numpy as NP\n'), ((274828, 274890), 'numpy.nansum', 'NP.nansum', (['diagoffset_weights'], {'axis': 'axes_to_sum', 'keepdims': '(True)'}), '(diagoffset_weights, axis=axes_to_sum, keepdims=True)\n', (274837, 274890), True, 'import numpy as NP\n'), ((291661, 291686), 'numpy.where', 'NP.where', (['kprll_ind[i, :]'], {}), '(kprll_ind[i, :])\n', (291669, 291686), True, 'import numpy as NP\n'), ((22641, 22660), 'numpy.copy', 'NP.copy', (['daydata.jd'], {}), '(daydata.jd)\n', (22648, 22660), True, 'import numpy as NP\n'), ((43768, 43784), 'astropy.units.Unit', 'U.Unit', (['valunits'], {}), '(valunits)\n', (43774, 43784), True, 'from astropy import units as U\n'), ((65072, 65094), 'numpy.copy', 'NP.copy', (['diagwts_shape'], {}), '(diagwts_shape)\n', (65079, 65094), True, 'import numpy as NP\n'), ((65515, 65563), 'numpy.copy', 'NP.copy', (["xcpdps[i][smplng][dpool]['diagweights']"], {}), "(xcpdps[i][smplng][dpool]['diagweights'])\n", (65522, 65563), True, 'import numpy as NP\n'), ((67346, 67368), 'numpy.copy', 'NP.copy', (['diagwts_shape'], {}), '(diagwts_shape)\n', (67353, 67368), True, 'import numpy as NP\n'), ((67793, 67842), 'numpy.copy', 'NP.copy', (["excpdps[i][smplng][dpool]['diagweights']"], {}), "(excpdps[i][smplng][dpool]['diagweights'])\n", (67800, 67842), True, 'import numpy as NP\n'), ((69782, 69857), 'numpy.isin', 'NP.isin', (["out_xcpdps[smplng][dpool]['diagoffsets'][ax]", 'diagoffsets[ind][ax]'], {}), "(out_xcpdps[smplng][dpool]['diagoffsets'][ax], diagoffsets[ind][ax])\n", (69789, 69857), True, 'import numpy as NP\n'), ((72487, 72505), 'numpy.copy', 'NP.copy', (['mask_ones'], {}), '(mask_ones)\n', (72494, 72505), True, 'import numpy as NP\n'), ((73594, 73628), 'numpy.ma.array', 'MA.array', (['diagwts'], {'mask': 'masks[ind]'}), '(diagwts, mask=masks[ind])\n', (73602, 73628), True, 'import numpy.ma as MA\n'), ((108229, 108321), 'numpy.ma.median', 'MA.median', (["self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :].real"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :].\n real, axis=1)\n", (108238, 108321), True, 'import numpy.ma as MA\n'), ((108670, 108730), 'numpy.angle', 'NP.angle', (['eicp_dmedian[:, binnum, :, :][:, NP.newaxis, :, :]'], {}), '(eicp_dmedian[:, binnum, :, :][:, NP.newaxis, :, :])\n', (108678, 108730), True, 'import numpy as NP\n'), ((112028, 112064), 'numpy.angle', 'NP.angle', (['eicp_dmedian[:, [i], :, :]'], {}), '(eicp_dmedian[:, [i], :, :])\n', (112036, 112064), True, 'import numpy as NP\n'), ((118145, 118204), 'numpy.ma.median', 'MA.median', (["indict['eicp'][ind_lstbin, :, :, :].real"], {'axis': '(0)'}), "(indict['eicp'][ind_lstbin, :, :, :].real, axis=0)\n", (118154, 118204), True, 'import numpy.ma as MA\n'), ((118502, 118562), 'numpy.angle', 'NP.angle', (['eicp_tmedian[binnum, :, :, :][NP.newaxis, :, :, :]'], {}), '(eicp_tmedian[binnum, :, :, :][NP.newaxis, :, :, :])\n', (118510, 118562), True, 'import numpy as NP\n'), ((118676, 118736), 'numpy.exp', 'NP.exp', (["(1.0j * indict['cphase']['mean'][ind_lstbin, :, :, :])"], {}), "(1.0j * indict['cphase']['mean'][ind_lstbin, :, :, :])\n", (118682, 118736), True, 'import numpy as NP\n'), ((119190, 119250), 'numpy.angle', 'NP.angle', (['eicp_tmedian[binnum, :, :, :][NP.newaxis, :, :, :]'], {}), '(eicp_tmedian[binnum, :, :, :][NP.newaxis, :, :, :])\n', (119198, 119250), True, 'import numpy as NP\n'), ((129050, 129142), 'numpy.ma.median', 'MA.median', (["self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :].real"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :].\n real, axis=1)\n", (129059, 129142), True, 'import numpy.ma as MA\n'), ((129491, 129551), 'numpy.angle', 'NP.angle', (['eicp_dmedian[:, binnum, :, :][:, NP.newaxis, :, :]'], {}), '(eicp_dmedian[:, binnum, :, :][:, NP.newaxis, :, :])\n', (129499, 129551), True, 'import numpy as NP\n'), ((132049, 132085), 'numpy.angle', 'NP.angle', (['eicp_dmedian[:, [i], :, :]'], {}), '(eicp_dmedian[:, [i], :, :])\n', (132057, 132085), True, 'import numpy as NP\n'), ((136702, 136741), 'numpy.cos', 'NP.cos', (['cp_dmedian[ind_lstbin, :, :, :]'], {}), '(cp_dmedian[ind_lstbin, :, :, :])\n', (136708, 136741), True, 'import numpy as NP\n'), ((139131, 139159), 'copy.deepcopy', 'copy.deepcopy', (['pair_of_pairs'], {}), '(pair_of_pairs)\n', (139144, 139159), False, 'import copy\n'), ((142130, 142198), 'numpy.ma.array', 'MA.array', (["self.cpinfo['errinfo']['eicp_diff']['0'][stat]"], {'mask': 'mask0'}), "(self.cpinfo['errinfo']['eicp_diff']['0'][stat], mask=mask0)\n", (142138, 142198), True, 'import numpy.ma as MA\n'), ((142288, 142356), 'numpy.ma.array', 'MA.array', (["self.cpinfo['errinfo']['eicp_diff']['1'][stat]"], {'mask': 'mask1'}), "(self.cpinfo['errinfo']['eicp_diff']['1'][stat], mask=mask1)\n", (142296, 142356), True, 'import numpy.ma as MA\n'), ((142434, 142490), 'numpy.ma.array', 'MA.array', (["self.cpinfo['errinfo']['wts']['0']"], {'mask': 'mask0'}), "(self.cpinfo['errinfo']['wts']['0'], mask=mask0)\n", (142442, 142490), True, 'import numpy.ma as MA\n'), ((142568, 142624), 'numpy.ma.array', 'MA.array', (["self.cpinfo['errinfo']['wts']['1']"], {'mask': 'mask1'}), "(self.cpinfo['errinfo']['wts']['1'], mask=mask1)\n", (142576, 142624), True, 'import numpy.ma as MA\n'), ((169751, 169767), 'numpy.abs', 'NP.abs', (['visscale'], {}), '(visscale)\n', (169757, 169767), True, 'import numpy as NP\n'), ((219947, 219999), 'numpy.roll', 'NP.roll', (['dspec2_tmp[:, 0, ...]', 'lstshift'], {'axis': 'incax'}), '(dspec2_tmp[:, 0, ...], lstshift, axis=incax)\n', (219954, 219999), True, 'import numpy as NP\n'), ((220153, 220207), 'numpy.roll', 'NP.roll', (['preXwts2_tmp[:, 0, ...]', 'lstshift'], {'axis': 'incax'}), '(preXwts2_tmp[:, 0, ...], lstshift, axis=incax)\n', (220160, 220207), True, 'import numpy as NP\n'), ((222048, 222081), 'numpy.ones', 'NP.ones', (['dspec.ndim'], {'dtype': 'NP.int'}), '(dspec.ndim, dtype=NP.int)\n', (222055, 222081), True, 'import numpy as NP\n'), ((223191, 223340), 'astroutils.mathops.array_trace', 'OPS.array_trace', (['result[smplng][dpool][stat].si.value'], {'offsets': 'None', 'axis1': 'expandax_map[colax][0]', 'axis2': 'expandax_map[colax][1]', 'outaxis': '"""axis1"""'}), "(result[smplng][dpool][stat].si.value, offsets=None, axis1=\n expandax_map[colax][0], axis2=expandax_map[colax][1], outaxis='axis1')\n", (223206, 223340), True, 'from astroutils import mathops as OPS\n'), ((223392, 223447), 'numpy.ones', 'NP.ones', (['result[smplng][dpool][stat].ndim'], {'dtype': 'NP.int'}), '(result[smplng][dpool][stat].ndim, dtype=NP.int)\n', (223399, 223447), True, 'import numpy as NP\n'), ((223671, 223687), 'numpy.copy', 'NP.copy', (['diagwts'], {}), '(diagwts)\n', (223678, 223687), True, 'import numpy as NP\n'), ((225248, 225300), 'numpy.nansum', 'NP.nansum', (['postXwts'], {'axis': 'axes_to_sum', 'keepdims': '(True)'}), '(postXwts, axis=axes_to_sum, keepdims=True)\n', (225257, 225300), True, 'import numpy as NP\n'), ((226127, 226182), 'numpy.ones', 'NP.ones', (['result[smplng][dpool][stat].ndim'], {'dtype': 'NP.int'}), '(result[smplng][dpool][stat].ndim, dtype=NP.int)\n', (226134, 226182), True, 'import numpy as NP\n'), ((226670, 226767), 'numpy.nansum', 'NP.nansum', (['(result[smplng][dpool][stat] * diagoffset_weights)'], {'axis': 'axes_to_sum', 'keepdims': '(True)'}), '(result[smplng][dpool][stat] * diagoffset_weights, axis=\n axes_to_sum, keepdims=True)\n', (226679, 226767), True, 'import numpy as NP\n'), ((226763, 226825), 'numpy.nansum', 'NP.nansum', (['diagoffset_weights'], {'axis': 'axes_to_sum', 'keepdims': '(True)'}), '(diagoffset_weights, axis=axes_to_sum, keepdims=True)\n', (226772, 226825), True, 'import numpy as NP\n'), ((265751, 265795), 'numpy.broadcast_to', 'NP.broadcast_to', (['preXwts0', 'preXwts0_outshape'], {}), '(preXwts0, preXwts0_outshape)\n', (265766, 265795), True, 'import numpy as NP\n'), ((266396, 266441), 'numpy.broadcast_to', 'NP.broadcast_to', (['preXwts1_tmp', 'preXwts1_shape'], {}), '(preXwts1_tmp, preXwts1_shape)\n', (266411, 266441), True, 'import numpy as NP\n'), ((267005, 267046), 'numpy.broadcast_to', 'NP.broadcast_to', (['dspec1_tmp', 'dspec1_shape'], {}), '(dspec1_tmp, dspec1_shape)\n', (267020, 267046), True, 'import numpy as NP\n'), ((268256, 268271), 'astropy.units.Unit', 'U.Unit', (['"""Jy Hz"""'], {}), "('Jy Hz')\n", (268262, 268271), True, 'from astropy import units as U\n'), ((270723, 270792), 'numpy.nanmean', 'NP.nanmean', (['result[smplng][dpool][stat]'], {'axis': 'expandax_map[colax][-1]'}), '(result[smplng][dpool][stat], axis=expandax_map[colax][-1])\n', (270733, 270792), True, 'import numpy as NP\n'), ((270905, 270976), 'numpy.nanmedian', 'NP.nanmedian', (['result[smplng][dpool][stat]'], {'axis': 'expandax_map[colax][-1]'}), '(result[smplng][dpool][stat], axis=expandax_map[colax][-1])\n', (270917, 270976), True, 'import numpy as NP\n'), ((272101, 272135), 'numpy.asarray', 'NP.asarray', (['expandax_map[colax][0]'], {}), '(expandax_map[colax][0])\n', (272111, 272135), True, 'import numpy as NP\n'), ((272925, 272994), 'numpy.asarray', 'NP.asarray', (["[expandax_map[colax] for colax in xinfo['collapse_axes']]"], {}), "([expandax_map[colax] for colax in xinfo['collapse_axes']])\n", (272935, 272994), True, 'import numpy as NP\n'), ((274998, 275035), 'numpy.ones', 'NP.ones', (['(dspec.ndim - 1)'], {'dtype': 'NP.int'}), '(dspec.ndim - 1, dtype=NP.int)\n', (275005, 275035), True, 'import numpy as NP\n'), ((307036, 307057), 'numpy.abs', 'NP.abs', (['external_beam'], {}), '(external_beam)\n', (307042, 307057), True, 'import numpy as NP\n'), ((17524, 17542), 'numpy.copy', 'NP.copy', (['cp_dayavg'], {}), '(cp_dayavg)\n', (17531, 17542), True, 'import numpy as NP\n'), ((71486, 71541), 'numpy.ma.sum', 'MA.sum', (['masked_diagwts'], {'axis': 'axes_to_avg', 'keepdims': '(True)'}), '(masked_diagwts, axis=axes_to_avg, keepdims=True)\n', (71492, 71541), True, 'import numpy.ma as MA\n'), ((72700, 72717), 'numpy.copy', 'NP.copy', (['mask_tmp'], {}), '(mask_tmp)\n', (72707, 72717), True, 'import numpy as NP\n'), ((72819, 72852), 'numpy.logical_or', 'NP.logical_or', (['mask_agg', 'mask_tmp'], {}), '(mask_agg, mask_tmp)\n', (72832, 72852), True, 'import numpy as NP\n'), ((108321, 108413), 'numpy.ma.median', 'MA.median', (["self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :].imag"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :].\n imag, axis=1)\n", (108330, 108413), True, 'import numpy.ma as MA\n'), ((118209, 118301), 'numpy.ma.median', 'MA.median', (["self.cpinfo['processed']['native']['eicp'][ind_lstbin, :, :, :].imag"], {'axis': '(0)'}), "(self.cpinfo['processed']['native']['eicp'][ind_lstbin, :, :, :].\n imag, axis=0)\n", (118218, 118301), True, 'import numpy.ma as MA\n'), ((118823, 118878), 'numpy.cos', 'NP.cos', (["indict['cphase']['median'][ind_lstbin, :, :, :]"], {}), "(indict['cphase']['median'][ind_lstbin, :, :, :])\n", (118829, 118878), True, 'import numpy as NP\n'), ((129142, 129234), 'numpy.ma.median', 'MA.median', (["self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :].imag"], {'axis': '(1)'}), "(self.cpinfo['processed']['native']['eicp'][:, ind_daybin, :, :].\n imag, axis=1)\n", (129151, 129234), True, 'import numpy.ma as MA\n'), ((136765, 136804), 'numpy.sin', 'NP.sin', (['cp_dmedian[ind_lstbin, :, :, :]'], {}), '(cp_dmedian[ind_lstbin, :, :, :])\n', (136771, 136804), True, 'import numpy as NP\n'), ((218311, 218355), 'numpy.broadcast_to', 'NP.broadcast_to', (['preXwts1', 'preXwts1_outshape'], {}), '(preXwts1, preXwts1_outshape)\n', (218326, 218355), True, 'import numpy as NP\n'), ((218984, 219029), 'numpy.broadcast_to', 'NP.broadcast_to', (['preXwts2_tmp', 'preXwts2_shape'], {}), '(preXwts2_tmp, preXwts2_shape)\n', (218999, 219029), True, 'import numpy as NP\n'), ((219617, 219658), 'numpy.broadcast_to', 'NP.broadcast_to', (['dspec2_tmp', 'dspec2_shape'], {}), '(dspec2_tmp, dspec2_shape)\n', (219632, 219658), True, 'import numpy as NP\n'), ((220924, 220939), 'astropy.units.Unit', 'U.Unit', (['"""Jy Hz"""'], {}), "('Jy Hz')\n", (220930, 220939), True, 'from astropy import units as U\n'), ((222639, 222708), 'numpy.nanmean', 'NP.nanmean', (['result[smplng][dpool][stat]'], {'axis': 'expandax_map[colax][-1]'}), '(result[smplng][dpool][stat], axis=expandax_map[colax][-1])\n', (222649, 222708), True, 'import numpy as NP\n'), ((222829, 222900), 'numpy.nanmedian', 'NP.nanmedian', (['result[smplng][dpool][stat]'], {'axis': 'expandax_map[colax][-1]'}), '(result[smplng][dpool][stat], axis=expandax_map[colax][-1])\n', (222841, 222900), True, 'import numpy as NP\n'), ((224077, 224111), 'numpy.asarray', 'NP.asarray', (['expandax_map[colax][0]'], {}), '(expandax_map[colax][0])\n', (224087, 224111), True, 'import numpy as NP\n'), ((224941, 225010), 'numpy.asarray', 'NP.asarray', (["[expandax_map[colax] for colax in xinfo['collapse_axes']]"], {}), "([expandax_map[colax] for colax in xinfo['collapse_axes']])\n", (224951, 225010), True, 'import numpy as NP\n'), ((226941, 226978), 'numpy.ones', 'NP.ones', (['(dspec.ndim - 1)'], {'dtype': 'NP.int'}), '(dspec.ndim - 1, dtype=NP.int)\n', (226948, 226978), True, 'import numpy as NP\n'), ((268207, 268245), 'numpy.ones', 'NP.ones', (['(dspec0.ndim - 1)'], {'dtype': 'NP.int'}), '(dspec0.ndim - 1, dtype=NP.int)\n', (268214, 268245), True, 'import numpy as NP\n'), ((268294, 268309), 'astropy.units.Unit', 'U.Unit', (['"""Jy Hz"""'], {}), "('Jy Hz')\n", (268300, 268309), True, 'from astropy import units as U\n'), ((270259, 270275), 'numpy.arange', 'NP.arange', (['axdim'], {}), '(axdim)\n', (270268, 270275), True, 'import numpy as NP\n'), ((17669, 17691), 'numpy.copy', 'NP.copy', (['cp_std_triads'], {}), '(cp_std_triads)\n', (17676, 17691), True, 'import numpy as NP\n'), ((22785, 22803), 'numpy.copy', 'NP.copy', (['cp_dayavg'], {}), '(cp_dayavg)\n', (22792, 22803), True, 'import numpy as NP\n'), ((71163, 71224), 'numpy.ma.sum', 'MA.sum', (['(arr * masked_diagwts)'], {'axis': 'axes_to_avg', 'keepdims': '(True)'}), '(arr * masked_diagwts, axis=axes_to_avg, keepdims=True)\n', (71169, 71224), True, 'import numpy.ma as MA\n'), ((71227, 71282), 'numpy.ma.sum', 'MA.sum', (['masked_diagwts'], {'axis': 'axes_to_avg', 'keepdims': '(True)'}), '(masked_diagwts, axis=axes_to_avg, keepdims=True)\n', (71233, 71282), True, 'import numpy.ma as MA\n'), ((72355, 72431), 'numpy.isin', 'NP.isin', (["out_excpdps[smplng][dpool]['diagoffsets'][ax]", 'diagoffsets[ind][ax]'], {}), "(out_excpdps[smplng][dpool]['diagoffsets'][ax], diagoffsets[ind][ax])\n", (72362, 72431), True, 'import numpy as NP\n'), ((74183, 74238), 'numpy.ma.sum', 'MA.sum', (['masked_diagwts'], {'axis': 'axes_to_avg', 'keepdims': '(True)'}), '(masked_diagwts, axis=axes_to_avg, keepdims=True)\n', (74189, 74238), True, 'import numpy.ma as MA\n'), ((90132, 90199), 'numpy.take', 'NP.take', (['xcpdps[smplng][dpool][stat][combi][spw]', 'ind_kbin'], {'axis': '(-1)'}), '(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1)\n', (90139, 90199), True, 'import numpy as NP\n'), ((118902, 118957), 'numpy.sin', 'NP.sin', (["indict['cphase']['median'][ind_lstbin, :, :, :]"], {}), "(indict['cphase']['median'][ind_lstbin, :, :, :])\n", (118908, 118957), True, 'import numpy as NP\n'), ((139980, 140058), 'numpy.sqrt', 'NP.sqrt', (['(wts_lstbins[:, j, :, :].data ** 2 + wts_lstbins[:, i, :, :].data ** 2)'], {}), '(wts_lstbins[:, j, :, :].data ** 2 + wts_lstbins[:, i, :, :].data ** 2)\n', (139987, 140058), True, 'import numpy as NP\n'), ((140225, 140303), 'numpy.sqrt', 'NP.sqrt', (['(wts_lstbins[:, m, :, :].data ** 2 + wts_lstbins[:, k, :, :].data ** 2)'], {}), '(wts_lstbins[:, m, :, :].data ** 2 + wts_lstbins[:, k, :, :].data ** 2)\n', (140232, 140303), True, 'import numpy as NP\n'), ((220875, 220913), 'numpy.ones', 'NP.ones', (['(dspec1.ndim - 1)'], {'dtype': 'NP.int'}), '(dspec1.ndim - 1, dtype=NP.int)\n', (220882, 220913), True, 'import numpy as NP\n'), ((220962, 220977), 'astropy.units.Unit', 'U.Unit', (['"""Jy Hz"""'], {}), "('Jy Hz')\n", (220968, 220977), True, 'from astropy import units as U\n'), ((222209, 222225), 'numpy.arange', 'NP.arange', (['axdim'], {}), '(axdim)\n', (222218, 222225), True, 'import numpy as NP\n'), ((270374, 270452), 'numpy.isnan', 'NP.isnan', (["cpds[smplng][dpool]['dspec0'][stat][dspec_multidim_idx][multdim_idx]"], {}), "(cpds[smplng][dpool]['dspec0'][stat][dspec_multidim_idx][multdim_idx])\n", (270382, 270452), True, 'import numpy as NP\n'), ((17813, 17832), 'numpy.copy', 'NP.copy', (['cp_std_lst'], {}), '(cp_std_lst)\n', (17820, 17832), True, 'import numpy as NP\n'), ((22928, 22950), 'numpy.copy', 'NP.copy', (['cp_std_triads'], {}), '(cp_std_triads)\n', (22935, 22950), True, 'import numpy as NP\n'), ((73850, 73911), 'numpy.ma.sum', 'MA.sum', (['(arr * masked_diagwts)'], {'axis': 'axes_to_avg', 'keepdims': '(True)'}), '(arr * masked_diagwts, axis=axes_to_avg, keepdims=True)\n', (73856, 73911), True, 'import numpy.ma as MA\n'), ((73914, 73969), 'numpy.ma.sum', 'MA.sum', (['masked_diagwts'], {'axis': 'axes_to_avg', 'keepdims': '(True)'}), '(masked_diagwts, axis=axes_to_avg, keepdims=True)\n', (73920, 73969), True, 'import numpy.ma as MA\n'), ((90272, 90339), 'numpy.take', 'NP.take', (['xcpdps[smplng][dpool][stat][combi][spw]', 'ind_kbin'], {'axis': '(-1)'}), '(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1)\n', (90279, 90339), True, 'import numpy as NP\n'), ((139566, 139637), 'numpy.logical_or', 'NP.logical_or', (['eicp_tmean[:, j, :, :].mask', 'eicp_tmean[:, i, :, :].mask'], {}), '(eicp_tmean[:, j, :, :].mask, eicp_tmean[:, i, :, :].mask)\n', (139579, 139637), True, 'import numpy as NP\n'), ((139812, 139883), 'numpy.logical_or', 'NP.logical_or', (['eicp_tmean[:, m, :, :].mask', 'eicp_tmean[:, k, :, :].mask'], {}), '(eicp_tmean[:, m, :, :].mask, eicp_tmean[:, k, :, :].mask)\n', (139825, 139883), True, 'import numpy as NP\n'), ((140055, 140128), 'numpy.logical_or', 'NP.logical_or', (['wts_lstbins[:, j, :, :].mask', 'wts_lstbins[:, i, :, :].mask'], {}), '(wts_lstbins[:, j, :, :].mask, wts_lstbins[:, i, :, :].mask)\n', (140068, 140128), True, 'import numpy as NP\n'), ((140300, 140373), 'numpy.logical_or', 'NP.logical_or', (['wts_lstbins[:, m, :, :].mask', 'wts_lstbins[:, k, :, :].mask'], {}), '(wts_lstbins[:, m, :, :].mask, wts_lstbins[:, k, :, :].mask)\n', (140313, 140373), True, 'import numpy as NP\n'), ((141216, 141291), 'numpy.logical_or', 'NP.logical_or', (['eicp_tmedian[:, j, :, :].mask', 'eicp_tmedian[:, i, :, :].mask'], {}), '(eicp_tmedian[:, j, :, :].mask, eicp_tmedian[:, i, :, :].mask)\n', (141229, 141291), True, 'import numpy as NP\n'), ((141470, 141545), 'numpy.logical_or', 'NP.logical_or', (['eicp_tmedian[:, m, :, :].mask', 'eicp_tmedian[:, k, :, :].mask'], {}), '(eicp_tmedian[:, m, :, :].mask, eicp_tmedian[:, k, :, :].mask)\n', (141483, 141545), True, 'import numpy as NP\n'), ((222328, 222356), 'numpy.isnan', 'NP.isnan', (['dspec[multdim_idx]'], {}), '(dspec[multdim_idx])\n', (222336, 222356), True, 'import numpy as NP\n'), ((273789, 273827), 'numpy.arange', 'NP.arange', (["xinfo['collapse_axes'].size"], {}), "(xinfo['collapse_axes'].size)\n", (273798, 273827), True, 'import numpy as NP\n'), ((23070, 23089), 'numpy.copy', 'NP.copy', (['cp_std_lst'], {}), '(cp_std_lst)\n', (23077, 23089), True, 'import numpy as NP\n'), ((44378, 44394), 'astropy.units.Unit', 'U.Unit', (['valunits'], {}), '(valunits)\n', (44384, 44394), True, 'from astropy import units as U\n'), ((89685, 89701), 'progressbar.Percentage', 'PGB.Percentage', ([], {}), '()\n', (89699, 89701), True, 'import progressbar as PGB\n'), ((89703, 89745), 'progressbar.Bar', 'PGB.Bar', ([], {'marker': '"""-"""', 'left': '""" |"""', 'right': '"""| """'}), "(marker='-', left=' |', right='| ')\n", (89710, 89745), True, 'import progressbar as PGB\n'), ((89747, 89760), 'progressbar.Counter', 'PGB.Counter', ([], {}), '()\n', (89758, 89760), True, 'import progressbar as PGB\n'), ((89799, 89808), 'progressbar.ETA', 'PGB.ETA', ([], {}), '()\n', (89806, 89808), True, 'import progressbar as PGB\n'), ((90566, 90633), 'numpy.take', 'NP.take', (['xcpdps[smplng][dpool][stat][combi][spw]', 'ind_kbin'], {'axis': '(-1)'}), '(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1)\n', (90573, 90633), True, 'import numpy as NP\n'), ((90906, 90973), 'numpy.take', 'NP.take', (['xcpdps[smplng][dpool][stat][combi][spw]', 'ind_kbin'], {'axis': '(-1)'}), '(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1)\n', (90913, 90973), True, 'import numpy as NP\n'), ((225698, 225736), 'numpy.arange', 'NP.arange', (["xinfo['collapse_axes'].size"], {}), "(xinfo['collapse_axes'].size)\n", (225707, 225736), True, 'import numpy as NP\n'), ((268544, 268570), 'numpy.asarray', 'NP.asarray', (['preXwts0.shape'], {}), '(preXwts0.shape)\n', (268554, 268570), True, 'import numpy as NP\n'), ((268574, 268600), 'numpy.asarray', 'NP.asarray', (['preXwts1.shape'], {}), '(preXwts1.shape)\n', (268584, 268600), True, 'import numpy as NP\n'), ((90808, 90875), 'numpy.take', 'NP.take', (['xcpdps[smplng][dpool][stat][combi][spw]', 'ind_kbin'], {'axis': '(-1)'}), '(xcpdps[smplng][dpool][stat][combi][spw], ind_kbin, axis=-1)\n', (90815, 90875), True, 'import numpy as NP\n'), ((221220, 221246), 'numpy.asarray', 'NP.asarray', (['preXwts1.shape'], {}), '(preXwts1.shape)\n', (221230, 221246), True, 'import numpy as NP\n'), ((221250, 221276), 'numpy.asarray', 'NP.asarray', (['preXwts2.shape'], {}), '(preXwts2.shape)\n', (221260, 221276), True, 'import numpy as NP\n')]
# Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """ test_pynative_model """ import numpy as np import mindspore.nn as nn from mindspore import Parameter, ParameterTuple, Tensor from mindspore import context from mindspore.nn.optim import Momentum from mindspore.ops import composite as C from mindspore.ops import operations as P from ..ut_filter import non_graph_engine grad_by_list = C.GradOperation(get_by_list=True) def setup_module(module): context.set_context(mode=context.PYNATIVE_MODE) class GradWrap(nn.Cell): """ GradWrap definition """ def __init__(self, network): super(GradWrap, self).__init__() self.network = network self.weights = ParameterTuple(network.get_parameters()) def construct(self, x, label): weights = self.weights return grad_by_list(self.network, weights)(x, label) @non_graph_engine def test_softmaxloss_grad(): """ test_softmaxloss_grad """ class NetWithLossClass(nn.Cell): """ NetWithLossClass definition """ def __init__(self, network): super(NetWithLossClass, self).__init__() self.loss = nn.SoftmaxCrossEntropyWithLogits() self.network = network def construct(self, x, label): predict = self.network(x) return self.loss(predict, label) class Net(nn.Cell): """ Net definition """ def __init__(self): super(Net, self).__init__() self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name="weight") self.bias = Parameter(Tensor(np.ones([10]).astype(np.float32)), name="bias") self.fc = P.MatMul() self.biasAdd = P.BiasAdd() def construct(self, x): x = self.biasAdd(self.fc(x, self.weight), self.bias) return x net = GradWrap(NetWithLossClass(Net())) predict = Tensor(np.ones([1, 64]).astype(np.float32)) label = Tensor(np.zeros([1, 10]).astype(np.float32)) print("pynative run") out = net.construct(predict, label) print("out:", out) print(out[0], (out[0]).asnumpy(), ":result") @non_graph_engine def test_lenet_grad(): """ test_lenet_grad """ class NetWithLossClass(nn.Cell): """ NetWithLossClass definition """ def __init__(self, network): super(NetWithLossClass, self).__init__() self.loss = nn.SoftmaxCrossEntropyWithLogits() self.network = network def construct(self, x, label): predict = self.network(x) return self.loss(predict, label) class LeNet5(nn.Cell): """ LeNet5 definition """ def __init__(self): super(LeNet5, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5, pad_mode='valid') self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid') self.fc1 = nn.Dense(16 * 5 * 5, 120) self.fc2 = nn.Dense(120, 84) self.fc3 = nn.Dense(84, 10) self.relu = nn.ReLU() self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2) self.flatten = P.Flatten() def construct(self, x): x = self.max_pool2d(self.relu(self.conv1(x))) x = self.max_pool2d(self.relu(self.conv2(x))) x = self.flatten(x) x = self.relu(self.fc1(x)) x = self.relu(self.fc2(x)) x = self.fc3(x) return x input_data = Tensor(np.ones([1, 1, 32, 32]).astype(np.float32) * 0.01) label = Tensor(np.ones([1, 10]).astype(np.float32)) iteration_num = 1 verification_step = 0 net = LeNet5() loss = nn.SoftmaxCrossEntropyWithLogits() momen_opti = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9) train_net = GradWrap(NetWithLossClass(net)) train_net.set_train() for i in range(0, iteration_num): # get the gradients grads = train_net(input_data, label) # update parameters success = momen_opti(grads) if success is False: print("fail to run optimizer") # verification if i == verification_step: fw_output = net(input_data) loss_output = loss(fw_output, label) print("The loss of %s-th iteration is %s" % (i, loss_output.asnumpy()))
[ "numpy.ones", "mindspore.nn.MaxPool2d", "mindspore.ops.operations.BiasAdd", "mindspore.nn.SoftmaxCrossEntropyWithLogits", "mindspore.context.set_context", "mindspore.ops.operations.MatMul", "mindspore.nn.Conv2d", "mindspore.nn.ReLU", "numpy.zeros", "mindspore.ops.composite.GradOperation", "minds...
[((1008, 1041), 'mindspore.ops.composite.GradOperation', 'C.GradOperation', ([], {'get_by_list': '(True)'}), '(get_by_list=True)\n', (1023, 1041), True, 'from mindspore.ops import composite as C\n'), ((1074, 1121), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.PYNATIVE_MODE'}), '(mode=context.PYNATIVE_MODE)\n', (1093, 1121), False, 'from mindspore import context\n'), ((4263, 4297), 'mindspore.nn.SoftmaxCrossEntropyWithLogits', 'nn.SoftmaxCrossEntropyWithLogits', ([], {}), '()\n', (4295, 4297), True, 'import mindspore.nn as nn\n'), ((1759, 1793), 'mindspore.nn.SoftmaxCrossEntropyWithLogits', 'nn.SoftmaxCrossEntropyWithLogits', ([], {}), '()\n', (1791, 1793), True, 'import mindspore.nn as nn\n'), ((2285, 2295), 'mindspore.ops.operations.MatMul', 'P.MatMul', ([], {}), '()\n', (2293, 2295), True, 'from mindspore.ops import operations as P\n'), ((2323, 2334), 'mindspore.ops.operations.BiasAdd', 'P.BiasAdd', ([], {}), '()\n', (2332, 2334), True, 'from mindspore.ops import operations as P\n'), ((3021, 3055), 'mindspore.nn.SoftmaxCrossEntropyWithLogits', 'nn.SoftmaxCrossEntropyWithLogits', ([], {}), '()\n', (3053, 3055), True, 'import mindspore.nn as nn\n'), ((3373, 3409), 'mindspore.nn.Conv2d', 'nn.Conv2d', (['(1)', '(6)', '(5)'], {'pad_mode': '"""valid"""'}), "(1, 6, 5, pad_mode='valid')\n", (3382, 3409), True, 'import mindspore.nn as nn\n'), ((3435, 3472), 'mindspore.nn.Conv2d', 'nn.Conv2d', (['(6)', '(16)', '(5)'], {'pad_mode': '"""valid"""'}), "(6, 16, 5, pad_mode='valid')\n", (3444, 3472), True, 'import mindspore.nn as nn\n'), ((3496, 3521), 'mindspore.nn.Dense', 'nn.Dense', (['(16 * 5 * 5)', '(120)'], {}), '(16 * 5 * 5, 120)\n', (3504, 3521), True, 'import mindspore.nn as nn\n'), ((3545, 3562), 'mindspore.nn.Dense', 'nn.Dense', (['(120)', '(84)'], {}), '(120, 84)\n', (3553, 3562), True, 'import mindspore.nn as nn\n'), ((3586, 3602), 'mindspore.nn.Dense', 'nn.Dense', (['(84)', '(10)'], {}), '(84, 10)\n', (3594, 3602), True, 'import mindspore.nn as nn\n'), ((3627, 3636), 'mindspore.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (3634, 3636), True, 'import mindspore.nn as nn\n'), ((3667, 3704), 'mindspore.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)'}), '(kernel_size=2, stride=2)\n', (3679, 3704), True, 'import mindspore.nn as nn\n'), ((3732, 3743), 'mindspore.ops.operations.Flatten', 'P.Flatten', ([], {}), '()\n', (3741, 3743), True, 'from mindspore.ops import operations as P\n'), ((2521, 2537), 'numpy.ones', 'np.ones', (['[1, 64]'], {}), '([1, 64])\n', (2528, 2537), True, 'import numpy as np\n'), ((2577, 2594), 'numpy.zeros', 'np.zeros', (['[1, 10]'], {}), '([1, 10])\n', (2585, 2594), True, 'import numpy as np\n'), ((4147, 4163), 'numpy.ones', 'np.ones', (['[1, 10]'], {}), '([1, 10])\n', (4154, 4163), True, 'import numpy as np\n'), ((4077, 4100), 'numpy.ones', 'np.ones', (['[1, 1, 32, 32]'], {}), '([1, 1, 32, 32])\n', (4084, 4100), True, 'import numpy as np\n'), ((2120, 2137), 'numpy.ones', 'np.ones', (['[64, 10]'], {}), '([64, 10])\n', (2127, 2137), True, 'import numpy as np\n'), ((2215, 2228), 'numpy.ones', 'np.ones', (['[10]'], {}), '([10])\n', (2222, 2228), True, 'import numpy as np\n')]
# Runge-Kutta Driver for quaternions-described object orientation # Import other packages used import numpy as np # Import constants and parameters used from Parameters_and_Constants import pi, moi # Dual Matrix to a vector # Inputs: # - 3D array ( vec[ 3 ] ) # Outputs: # - 3x3 matrix ( dvec ) which is its dual for vector product ( vec x a = dvec . a ) def dual_matrix( vec ): dvec = [ [ 0.0 , - vec[ 2 ] , vec[ 1 ] ] , [ vec[ 2 ] , 0.0 , - vec[ 0 ] ] , [ - vec[ 1 ] , vec[ 0 ] , 0.0 ] ] return dvec # Dual Matrix to a quaternion # Inputs: # - 4D array for the quaternion ( qu[ 4 ] ) # Outputs: # - 4x3 matrix ( dquat ) which is its dual for quaternion left multiplication with a vector def q_mat( qu ): dquat = [ [ - qu[ 1 ] , - qu[ 2 ] , - qu[ 3 ] ] , [ qu[ 0 ] , - qu[ 3 ] , qu[ 2 ] ] , [ qu[ 3 ] , qu[ 0 ] , - qu[ 1 ] ] , [ - qu[ 2 ] , qu[ 1 ] , qu[ 0 ] ] ] return dquat # Directive Cosine Matrix (DCM) from a Quaternion # Inputs: # - 4D array for the unit quaternion ( qu[ 4 ] ) # Outputs: # - Directive Cosine Matrix (DCM) which is a 3x3 SO(3) rep dcm[ 3 ][ 3 ] # NOTE: The quaternion is renormed for each case (to make it unit even if it's not) def dcm_from_q( qu ): # If the length of the quaternion was wrong - return unit matrix and print the error if len( qu ) != 4: print( "Wrong quaternion length, len( qu ) == 4 is required!" ) print( "Returning unit DCM = diag( 1 , 1 , 1 )" ) dcm = [ [ 1.0 , 0.0 , 0.0 ] , [ 0.0 , 1.0 , 0.0 ] , [ 0.0 , 0.0 , 1.0 ] ] return dcm # Find the norm and renorm the Quaternion for each case q_norm = np.sqrt( np.dot( qu , qu ) ) for i in range( 0 , 4 ): qu[ i ] /= q_norm # Compute squares of quaternion and then compute the dcm q0s = qu[ 0 ]*qu[ 0 ] q1s = qu[ 1 ]*qu[ 1 ] q2s = qu[ 2 ]*qu[ 2 ] q3s = qu[ 3 ]*qu[ 3 ] dcm = [ [ q0s + q1s - q2s - q3s , 2.0*( qu[ 1 ]*qu[ 2 ] + qu[ 0 ]*qu[ 3 ] ) , 2.0*( qu[ 1 ]*qu[ 3 ] - qu[ 0 ]*qu[ 2 ] ) ] , [ 2.0*( qu[ 2 ]*qu[ 1 ] - qu[ 0 ]*qu[ 3 ] ) , q0s - q1s + q2s - q3s , 2.0*( qu[ 2 ]*qu[ 3 ] + qu[ 0 ]*qu[ 1 ] ) ] , [ 2.0*( qu[ 3 ]*qu[ 1 ] + qu[ 0 ]*qu[ 2 ] ) , 2.0*( qu[ 3 ]*qu[ 2 ] - qu[ 0 ]*qu[ 1 ] ) , q0s - q1s - q2s + q3s ] ] return dcm # Torque function # Inputs: # - time from some arbitrary epoch time [sec] # Outputs: # - torque vector as a 3D array [N*m] # NOTE: CURRENTLY RETURNING 0 VECTOR -> NO EXTERNAL TORQUE CONSIDERED def torque_func( time ): torque = [ 0.0 , 0.0 , 0.0 ] return torque # Right-Hand-Side (RHS) of the body attitude state # Inputs: # - Attitude State ( state[ 2 ] = [ qu[ 4 ] , om[ 3 ] ] ) consisting of: # -- quaternion attitude ( qu[ 4 ] ) [-] # -- angular velocity ( om[ 3 ] ) [rad/s] in Body Frame # - External Torques ( torque[ 3 ] ) [N*m] in Inertial Frame # Outputs: # - Right-Hand-Side of state's derivative ( rhs_state[ 2 ] = [ rhs_qu[ 4 ] , rhs_om[ 3 ] ] ) consisting of: # -- quaternion RHS ( rhs_qu[ 4 ] ) [1/s] # -- angular velocity RHS ( rhs_om[ 3 ] ) [rad/s^2] def rhs_quaternion( state , torque ): dual_om = dual_matrix( state[ 1 ] ) # get angular velocity dual matrix dual_quat = q_mat( state[ 0 ] ) # get quaternion dual matrix # Get RHS for the angular rate part from angular momentum conservation equation rhs_om = - np.matmul( dual_om , np.matmul( moi , state[ 1 ] ) ) + np.array( torque ) rhs_om = np.matmul( np.linalg.inv( moi ) , rhs_om ) # Get RHS for the quaternion part from quaternion derivative equation rhs_qu = 0.5*np.matmul( dual_quat , state[ 1 ] ) rhs_state = [ rhs_qu , rhs_om ] return rhs_state # Perform a Runge-Kutta Step of the attitude state # Inputs: # - Starting Attitude State ( state_in[ 2 ] = [ qu[ 4 ] , om[ 3 ] ] ) consisting of: # -- quaternion attitude ( qu[ 4 ] ) [-] # -- angular velocity ( om[ 3 ] ) [rad/s] in Body Frame # - Initial Time [sec] (measured from some initial epoch) # - Time Step (between input and output attitude states) [sec] # Outputs: # - Resulting Attitude State ( state_out[ 2 ] = [ qu[ 4 ] , om[ 3 ] ] ) consisting of: # -- quaternion attitude ( qu[ 4 ] ) [-] # -- angular velocity ( om[ 3 ] ) [rad/s] in Body Frame def rk_step( state_in , t_i , dt ): # Initialize Runge-Kutta coefficients arrays for the quaternion and angular velocity components rk_qu = np.zeros( ( 4 , 4 ) ) # Quaternion RK coefficients 4 x <dimension> rk_om = np.zeros( ( 4 , 3 ) ) # Angular rate RK coefficients 4 x <dimension> # Initialize intermediate state to be populated for intermediate computations inter_state = [ np.zeros( 4 ) , np.zeros( 3 ) ] # Find external torque at initial step torque = torque_func( t_i ) # Populate RK constants values at the first step ( k1 ) rhs_state = rhs_quaternion( state_in , torque ) rk_qu[ 0 ] = rhs_state[ 0 ]*dt rk_om[ 0 ] = rhs_state[ 1 ]*dt # Find intermediate state ( t + dt/2 , x + k1/2 ) and corresponding torque in preparation for next step inter_state[ 0 ] = state_in[ 0 ] + rk_qu[ 0 ]/2.0 inter_state[ 1 ] = state_in[ 1 ] + rk_om[ 0 ]/2.0 torque = torque_func( t_i + dt/2.0 ) # Populate RK constants values at the second step ( k2 ) rhs_state = rhs_quaternion( inter_state , torque ) rk_qu[ 1 ] = rhs_state[ 0 ]*dt rk_om[ 1 ] = rhs_state[ 1 ]*dt # Find intermediate state ( t + dt/2 , x + k2/2 ), corresponding torque is the same (same time) inter_state[ 0 ] = state_in[ 0 ] + rk_qu[ 1 ]/2.0 inter_state[ 1 ] = state_in[ 1 ] + rk_om[ 1 ]/2.0 # Populate RK constants values at the third step ( k3 ) rhs_state = rhs_quaternion( inter_state , torque ) rk_qu[ 2 ] = rhs_state[ 0 ]*dt rk_om[ 2 ] = rhs_state[ 1 ]*dt # Find intermediate state ( t + dt , x + k3 ) and corresponding torque in preparation for the last step inter_state[ 0 ] = state_in[ 0 ] + rk_qu[ 2 ] inter_state[ 1 ] = state_in[ 1 ] + rk_om[ 2 ] torque = torque_func( t_i + dt ) # Populate RK constants values at the last (forth) step ( k4 ) rhs_state = rhs_quaternion( inter_state , torque ) rk_qu[ 3 ] = rhs_state[ 0 ]*dt rk_om[ 3 ] = rhs_state[ 1 ]*dt # Compute the state at t_i + dt based on the RK values computed - populate this in inter_state inter_state[ 0 ] = state_in[ 0 ] + ( rk_qu[ 0 ] + 2.0*rk_qu[ 1 ] + 2.0*rk_qu[ 2 ] + rk_qu[ 3 ] )/6.0 inter_state[ 1 ] = state_in[ 1 ] + ( rk_om[ 0 ] + 2.0*rk_om[ 1 ] + 2.0*rk_om[ 2 ] + rk_om[ 3 ] )/6.0 # Out quaternions must be unit to describe valid rotation! # Compute the norm of the quaternion part and if different from 1, renorm it accordingly! q_norm = np.sqrt( np.dot( state_in[ 0 ] , state_in[ 0 ] ) ) # The only problematic point is if q_norm == 0 -> this is physically impossible (only if unphysical initial conditions were given) if q_norm == 0.0: print( "ERROR: Quaternion came up with 0 norm, invalid attitude specified!" ) inter_state = [ np.zeros( 4 ) , np.zeros( 3 ) ] else: inter_state[ 0 ] /= q_norm return inter_state
[ "numpy.array", "numpy.dot", "numpy.zeros", "numpy.linalg.inv", "numpy.matmul" ]
[((4470, 4486), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {}), '((4, 4))\n', (4478, 4486), True, 'import numpy as np\n'), ((4549, 4565), 'numpy.zeros', 'np.zeros', (['(4, 3)'], {}), '((4, 3))\n', (4557, 4565), True, 'import numpy as np\n'), ((1741, 1755), 'numpy.dot', 'np.dot', (['qu', 'qu'], {}), '(qu, qu)\n', (1747, 1755), True, 'import numpy as np\n'), ((3499, 3515), 'numpy.array', 'np.array', (['torque'], {}), '(torque)\n', (3507, 3515), True, 'import numpy as np\n'), ((3542, 3560), 'numpy.linalg.inv', 'np.linalg.inv', (['moi'], {}), '(moi)\n', (3555, 3560), True, 'import numpy as np\n'), ((3666, 3696), 'numpy.matmul', 'np.matmul', (['dual_quat', 'state[1]'], {}), '(dual_quat, state[1])\n', (3675, 3696), True, 'import numpy as np\n'), ((4720, 4731), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (4728, 4731), True, 'import numpy as np\n'), ((4736, 4747), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (4744, 4747), True, 'import numpy as np\n'), ((6777, 6809), 'numpy.dot', 'np.dot', (['state_in[0]', 'state_in[0]'], {}), '(state_in[0], state_in[0])\n', (6783, 6809), True, 'import numpy as np\n'), ((7087, 7098), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (7095, 7098), True, 'import numpy as np\n'), ((7103, 7114), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (7111, 7114), True, 'import numpy as np\n'), ((3465, 3489), 'numpy.matmul', 'np.matmul', (['moi', 'state[1]'], {}), '(moi, state[1])\n', (3474, 3489), True, 'import numpy as np\n')]
__author__ = 'otto.hannuksela' import numpy as np from lenstronomy.LensModel.Profiles.base_profile import LensProfileBase __all__ = ['PointMassShear'] class PointMassShear(LensProfileBase): """ class to compute the physical deflection angle of a point mass with macro-model magnifications """ # For simplicity, presume (X0, X1)=(0, 0) (centered at zero) and theta_E = 1. param_names = ['mu_0', 'mu_1'] lower_limit_default = {'mu_0': -100, 'mu_1': -100} upper_limit_default = {'mu_0': 100, 'mu_1': 100 } def __init__(self): self.r_min = 10**(-25) super(PointMassShear, self).__init__() def function(self, x, y, mu_0, mu_1, theta_E=1., center_x=0, center_y=0): """ :param x: x-coord (in angles) :param y: y-coord (in angles) :param theta_E: Einstein radius (in angles) :return: lensing potential """ x_ = x - center_x y_ = y - center_y psi_macro_00_ = (mu_0-1.)/mu_0 psi_macro_11_ = (mu_1-1.)/mu_1 phi_macro = 0.5*(psi_macro_00_*x**2 + psi_macro_11_*y**2) a = np.sqrt(x_**2 + y_**2) if isinstance(a, int) or isinstance(a, float): r = max(self.r_min, a) else: r = np.empty_like(a) r[a > self.r_min] = a[a > self.r_min] #in the SIS regime r[a <= self.r_min] = self.r_min phi_point = theta_E**2*np.log(r) phi = phi_macro + phi_point # Add point + macro model together return phi def derivatives(self, x, y, mu_0, mu_1, theta_E=1., center_x=0, center_y=0): """ :param x: x-coord (in angles) :param y: y-coord (in angles) :param theta_E: Einstein radius (in angles) :return: deflection angle (in angles) """ x_ = x - center_x y_ = y - center_y psi_macro_00_ = (mu_0-1.)/mu_0 psi_macro_11_ = (mu_1-1.)/mu_1 a = np.sqrt(x_**2 + y_**2) if isinstance(a, int) or isinstance(a, float): r = max(self.r_min, a) else: r = np.empty_like(a) r[a > self.r_min] = a[a > self.r_min] #in the SIS regime r[a <= self.r_min] = self.r_min alpha_macro_x = psi_macro_00_ * x_ alpha_macro_y = psi_macro_00_ * y_ alpha_point_x = theta_E**2 * x_ /r**2 alpha_point_y = theta_E**2 * y_ /r**2 alpha_x = alpha_macro_x + alpha_point_x alpha_y = alpha_macro_y + alpha_point_y return alpha_x, alpha_y def hessian(self, x, y, mu_0, mu_1, theta_E=1., center_x=0, center_y=0): """ :param x: x-coord (in angles) :param y: y-coord (in angles) :param theta_E: Einstein radius (in angles) :return: hessian matrix (in angles) """ x_ = x - center_x y_ = y - center_y psi_macro_00_ = (mu_0-1.)/mu_0 psi_macro_11_ = (mu_1-1.)/mu_1 C = theta_E**2 a = x_**2 + y_**2 if isinstance(a, int) or isinstance(a, float): r2 = max(self.r_min**2, a) else: r2 = np.empty_like(a) r2[a > self.r_min**2] = a[a > self.r_min**2] #in the SIS regime r2[a <= self.r_min**2] = self.r_min**2 f_point_xx = C * (y_**2-x_**2)/r2**2 f_point_yy = C * (x_**2-y_**2)/r2**2 f_point_xy = -C * 2*x_*y_/r2**2 f_macro_xx = psi_macro_00_ f_macro_yy = psi_macro_11_ f_macro_xy = 0 f_xx = f_point_xx + f_macro_xx f_yy = f_point_yy + f_macro_yy f_xy = f_point_xy + f_macro_xy return f_xx, f_xy, f_xy, f_yy
[ "numpy.empty_like", "numpy.log", "numpy.sqrt" ]
[((1121, 1147), 'numpy.sqrt', 'np.sqrt', (['(x_ ** 2 + y_ ** 2)'], {}), '(x_ ** 2 + y_ ** 2)\n', (1128, 1147), True, 'import numpy as np\n'), ((1952, 1978), 'numpy.sqrt', 'np.sqrt', (['(x_ ** 2 + y_ ** 2)'], {}), '(x_ ** 2 + y_ ** 2)\n', (1959, 1978), True, 'import numpy as np\n'), ((1264, 1280), 'numpy.empty_like', 'np.empty_like', (['a'], {}), '(a)\n', (1277, 1280), True, 'import numpy as np\n'), ((1427, 1436), 'numpy.log', 'np.log', (['r'], {}), '(r)\n', (1433, 1436), True, 'import numpy as np\n'), ((2095, 2111), 'numpy.empty_like', 'np.empty_like', (['a'], {}), '(a)\n', (2108, 2111), True, 'import numpy as np\n'), ((3116, 3132), 'numpy.empty_like', 'np.empty_like', (['a'], {}), '(a)\n', (3129, 3132), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import io,sys,os import numpy as np from pathlib import Path import mp2prod def get_alignconsts(filename, tablename): consts = [] iobuf = io.StringIO() read_lines = False with open(filename, 'r') as f: for line in f.readlines(): if 'TABLE' in line: if line.strip().split()[-1] == tablename: read_lines = True continue else: read_lines = False continue if read_lines: iobuf.write(line) iobuf.seek(0) return np.genfromtxt(iobuf,delimiter=',') def get_alignconsts_errors(filename, tablename): if '_in.txt' in filename: return None print ("reading corresponding millepede.res file for errors") # we need to look in the same folder for a millepede.res file path = Path(filename) mpres_path = os.path.join(path.parent, 'millepede.res') alignconsts = mp2prod.AlignmentConstants() alignconsts.read_mp_file(mpres_path) x_shift_errors = [] y_shift_errors = [] z_shift_errors = [] for plane in range(0,36): x_shift_errors.append(float(alignconsts.get_plane_const(plane, 0)[-1])) y_shift_errors.append(float(alignconsts.get_plane_const(plane, 1)[-1])) z_shift_errors.append(float(alignconsts.get_plane_const(plane, 2)[-1])) return x_shift_errors, y_shift_errors, z_shift_errors for param_col in [0,1,2]: # plt.figure(param_col) to_plot = [] col_str = ['x-shift', 'y-shift','z-shift'][param_col] for filename in sys.argv[1:]: shifts_errors = get_alignconsts_errors(filename, 'TrkAlignPlane') shifts = get_alignconsts(filename, 'TrkAlignPlane') shifts = shifts[:,1+param_col]*1000 # convert to micrometers if shifts_errors is None: shifts_errors = np.zeros((36,)) else: shifts_errors = np.array(shifts_errors[param_col])*1000 print (shifts_errors) to_plot += [(filename, shifts, shifts_errors)] plane_id = np.arange(0,35.5,1) with plt.style.context('bmh'): _, axs = plt.subplots(2, gridspec_kw={'height_ratios': [10, 5]}) for filename, shifts, shifts_errors in to_plot: #plt.scatter(plane_id, shifts, label=filename) axs[0].errorbar(plane_id, shifts, yerr=shifts_errors,label=filename, marker = '.', fmt='x-', linewidth=0.5, drawstyle = 'steps-mid') #plt.ylim(-1000,1000) axs[0].axhline(0,0,36, color='k',label='Nominal') axs[0].set_ylabel('%s (um)' % col_str) axs[0].set_title('%s after alignment fit' % col_str) axs[0].legend(fontsize='xx-small') for filename, shifts, shifts_errors in to_plot: #plt.scatter(plane_id, shifts, label=filename) pulls = shifts/shifts_errors axs[1].bar(np.arange(0,35.5,1), pulls,label=filename) # axs[1].errorbar(np.arange(0,35.5,1), pulls, yerr=np.arange(0,35.5,1)*0, # label=filename, # marker = '.', # fmt='x-', # linewidth=0.5, # drawstyle = 'steps-mid') axs[1].set_xlabel('Plane ID') axs[1].set_ylabel('%s / error' % col_str) axs[1].set_ylim(-5,5) plt.show()
[ "pathlib.Path", "numpy.arange", "os.path.join", "numpy.array", "numpy.zeros", "matplotlib.pyplot.style.context", "io.StringIO", "numpy.genfromtxt", "matplotlib.pyplot.subplots", "mp2prod.AlignmentConstants", "matplotlib.pyplot.show" ]
[((3460, 3470), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3468, 3470), True, 'import matplotlib.pyplot as plt\n'), ((182, 195), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (193, 195), False, 'import io, sys, os\n'), ((628, 663), 'numpy.genfromtxt', 'np.genfromtxt', (['iobuf'], {'delimiter': '""","""'}), "(iobuf, delimiter=',')\n", (641, 663), True, 'import numpy as np\n'), ((898, 912), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (902, 912), False, 'from pathlib import Path\n'), ((931, 973), 'os.path.join', 'os.path.join', (['path.parent', '"""millepede.res"""'], {}), "(path.parent, 'millepede.res')\n", (943, 973), False, 'import io, sys, os\n'), ((993, 1021), 'mp2prod.AlignmentConstants', 'mp2prod.AlignmentConstants', ([], {}), '()\n', (1019, 1021), False, 'import mp2prod\n'), ((2096, 2117), 'numpy.arange', 'np.arange', (['(0)', '(35.5)', '(1)'], {}), '(0, 35.5, 1)\n', (2105, 2117), True, 'import numpy as np\n'), ((2127, 2151), 'matplotlib.pyplot.style.context', 'plt.style.context', (['"""bmh"""'], {}), "('bmh')\n", (2144, 2151), True, 'import matplotlib.pyplot as plt\n'), ((2170, 2225), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {'gridspec_kw': "{'height_ratios': [10, 5]}"}), "(2, gridspec_kw={'height_ratios': [10, 5]})\n", (2182, 2225), True, 'import matplotlib.pyplot as plt\n'), ((1895, 1910), 'numpy.zeros', 'np.zeros', (['(36,)'], {}), '((36,))\n', (1903, 1910), True, 'import numpy as np\n'), ((1953, 1987), 'numpy.array', 'np.array', (['shifts_errors[param_col]'], {}), '(shifts_errors[param_col])\n', (1961, 1987), True, 'import numpy as np\n'), ((3002, 3023), 'numpy.arange', 'np.arange', (['(0)', '(35.5)', '(1)'], {}), '(0, 35.5, 1)\n', (3011, 3023), True, 'import numpy as np\n')]
#!/usr/bin/env python """02.GreenScreen.py Join a background to an image with a large green area.""" __author__ = "<NAME>" __copyright__ = "Copyright 2021, OpenCV-projects-with-Python" __licence__ = "MIT" __version__ = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" import numpy as np import cv2 # Original image and Background image path = "C:/Users/Mickael/PycharmProjects/OpenCV-projects-with-Python/Resources/Images/green_screen.jpg" imageOriginal = cv2.imread(path) print("Original Dimensions: ", imageOriginal.shape) path = "C:/Users/Mickael/PycharmProjects/OpenCV-projects-with-Python/Resources/Images/praiaNazare.jpg" imageBackground = cv2.imread(path) print("Background Dimensions: ", imageBackground.shape) # Preserve Aspect Ratio - Downscale process scale_percent = 40 # percent of original size height = int(imageOriginal.shape[0] * scale_percent / 100) width = int(imageOriginal.shape[1] * scale_percent / 100) dim = (width, height) # Resized images - Original and Background imageResized = cv2.resize(imageOriginal, dim, interpolation=cv2.INTER_AREA) print("Resized Dimensions: ", imageResized.shape) resize_x, resize_y = imageResized.shape[0], imageResized.shape[1] dimBackground = (resize_y, resize_x) imageBackgroundResized = cv2.resize(imageBackground, dimBackground) print("Resized Background Dimensions: ", imageBackgroundResized.shape) # Threshold - Green lowerGreen = np.array([0, 170, 0]) upperGreen = np.array([120, 180, 120]) mask = cv2.inRange(imageResized, lowerGreen, upperGreen) # Green masked area copyMask = np.copy(imageResized) copyMask[mask != 0] = [0, 0, 0] # Background masked area copyBackground = np.copy(imageBackgroundResized) copyBackground[mask == 0] = [0, 0, 0] # Image Final imageFinal = copyMask + copyBackground # Same size and horizontally def concat_vh(list_2d): # return final image return cv2.vconcat([cv2.hconcat(list_h) for list_h in list_2d]) # Function calling (concat_vh) img_tile = concat_vh([[imageResized, imageBackgroundResized], [copyMask, imageFinal]]) cv2.imshow('Green Screen', img_tile) cv2.waitKey(0) cv2.destroyAllWindows()
[ "numpy.copy", "cv2.inRange", "cv2.imshow", "numpy.array", "cv2.waitKey", "cv2.destroyAllWindows", "cv2.resize", "cv2.imread", "cv2.hconcat" ]
[((493, 509), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (503, 509), False, 'import cv2\n'), ((684, 700), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (694, 700), False, 'import cv2\n'), ((1047, 1107), 'cv2.resize', 'cv2.resize', (['imageOriginal', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(imageOriginal, dim, interpolation=cv2.INTER_AREA)\n', (1057, 1107), False, 'import cv2\n'), ((1287, 1329), 'cv2.resize', 'cv2.resize', (['imageBackground', 'dimBackground'], {}), '(imageBackground, dimBackground)\n', (1297, 1329), False, 'import cv2\n'), ((1435, 1456), 'numpy.array', 'np.array', (['[0, 170, 0]'], {}), '([0, 170, 0])\n', (1443, 1456), True, 'import numpy as np\n'), ((1470, 1495), 'numpy.array', 'np.array', (['[120, 180, 120]'], {}), '([120, 180, 120])\n', (1478, 1495), True, 'import numpy as np\n'), ((1503, 1552), 'cv2.inRange', 'cv2.inRange', (['imageResized', 'lowerGreen', 'upperGreen'], {}), '(imageResized, lowerGreen, upperGreen)\n', (1514, 1552), False, 'import cv2\n'), ((1585, 1606), 'numpy.copy', 'np.copy', (['imageResized'], {}), '(imageResized)\n', (1592, 1606), True, 'import numpy as np\n'), ((1682, 1713), 'numpy.copy', 'np.copy', (['imageBackgroundResized'], {}), '(imageBackgroundResized)\n', (1689, 1713), True, 'import numpy as np\n'), ((2122, 2158), 'cv2.imshow', 'cv2.imshow', (['"""Green Screen"""', 'img_tile'], {}), "('Green Screen', img_tile)\n", (2132, 2158), False, 'import cv2\n'), ((2161, 2175), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2172, 2175), False, 'import cv2\n'), ((2176, 2199), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2197, 2199), False, 'import cv2\n'), ((1911, 1930), 'cv2.hconcat', 'cv2.hconcat', (['list_h'], {}), '(list_h)\n', (1922, 1930), False, 'import cv2\n')]
''' Cross-Validation Data Classes ============================= Scikit-learn compatible classes for performing various types of cross-validation ''' __all__ = ['KFoldSubject','KFoldStratified','LeaveOneSubjectOut','set_cv'] __author__ = ["<NAME>"] __license__ = "MIT" from sklearn.cross_validation import _BaseKFold import numpy as np import random import pandas as pd class KFoldSubject(_BaseKFold): """K-Folds cross validation iterator which holds out same subjects. Provides train/test indices to split data in train test sets. Split dataset into k consecutive folds while ensuring that same subject is held out within each fold Each fold is then used a validation set once while the k - 1 remaining fold form the training set. Extension of KFold from scikit-learn cross_validation model Args: n: int Total number of elements. labels: vector of length Y indicating subject IDs n_folds: int, default=3 Number of folds. Must be at least 2. shuffle: boolean, optional Whether to shuffle the data before splitting into batches. random_state: None, int or RandomState Pseudo-random number generator state used for random sampling. If None, use default numpy RNG for shuffling """ def __init__(self, n, labels, n_folds=3, shuffle=False, random_state=None): super(KFoldSubject, self).__init__(n, n_folds, shuffle, random_state) self.idxs = np.arange(n) self.labels = np.array(labels, copy=True) self.n_subs = len(np.unique(self.labels)) if shuffle: rng = check_random_state(self.random_state) rng.shuffle(self.idxs) def _iter_test_indices(self): n = self.n n_folds = self.n_folds n_subs_fold = self.n/self.n_subs subs = np.unique(self.labels) random.shuffle(subs) # shuffle subjects divide_subs = lambda x,y: [ x[i:i+y] for i in range(0,len(x),y)] sub_divs = divide_subs(subs, self.n_folds+1) # seems to be adding one fold for some reason for d in sub_divs: idx = np.in1d(self.labels,d) yield self.idxs[np.where(idx)[0]] def __repr__(self): return '%s.%s(n=%i, n_subs=%i, n_folds=%i, shuffle=%s, random_state=%s)' % ( self.__class__.__module__, self.__class__.__name__, self.n, self.n_subs, self.n_folds, self.shuffle, self.random_state, ) def __len__(self): return self.n_folds class KFoldStratified(_BaseKFold): """K-Folds cross validation iterator which stratifies continuous data (unlike scikit-learn equivalent). Provides train/test indices to split data in train test sets. Split dataset into k consecutive folds while ensuring that same subject is held out within each fold Each fold is then used a validation set once while the k - 1 remaining folds form the training set. Extension of KFold from scikit-learn cross_validation model Args: y : array-like, [n_samples] Samples to split in K folds. n_folds: int, default=5 Number of folds. Must be at least 2. shuffle: boolean, optional Whether to shuffle the data before splitting into batches. random_state: None, int or RandomState Pseudo-random number generator state used for random sampling. If None, use default numpy RNG for shuffling """ def __init__(self, y, n_folds=5, shuffle=False, random_state=None): super(KFoldStratified, self).__init__(len(y), n_folds, shuffle, random_state) self.y = y self.idxs = np.arange(len(y)) self.sort_indx = self.y.argsort() if shuffle: rng = check_random_state(self.random_state) rng.shuffle(self.idxs) def _iter_test_indices(self): for k in range(0, self.n_folds): # yield self.idxs[self.sort_indx[range(k,len(self.y),self.n_folds)]] yield self.sort_indx[range(k,len(self.y),self.n_folds)] def __repr__(self): return '%s.%s(n_folds=%i, shuffle=%s, random_state=%s)' % ( self.__class__.__module__, self.__class__.__name__, self.y, self.n_folds, self.shuffle, self.random_state, ) def __len__(self): return self.n_folds class LeaveOneSubjectOut(_BaseKFold): """LOSO cross validation iterator which holds out same subjects. Provides train/test indices to split data in train test sets. Split dataset into n_subject consecutive folds Each fold is then used a validation set once while the n_subject - 1 remaining folds form the training set. Extension of KFold from scikit-learn cross_validation model Args: labels: vector of length Y indicating subject IDs shuffle: boolean, optional Whether to shuffle the data before splitting into batches. random_state: None, int or RandomState Pseudo-random number generator state used for random sampling. If None, use default numpy RNG for shuffling """ def __init__(self, n, labels, shuffle=False, random_state=None): super(LeaveOneSubjectOut, self).__init__(n, len(np.unique(labels)), shuffle, random_state) self.idxs = np.arange(len(labels)) self.labels = np.array(labels, copy=True) self.n_subs = len(np.unique(self.labels)) if shuffle: rng = check_random_state(self.random_state) rng.shuffle(self.idxs) def _iter_test_indices(self): for d in np.unique(self.labels): idx = np.in1d(self.labels,d) yield self.idxs[np.where(idx)[0]] def __repr__(self): return '%s.%s(n=%i, n_subs=%i, shuffle=%s, random_state=%s)' % ( self.__class__.__module__, self.__class__.__name__, self.n, self.n_subs, self.shuffle, self.random_state, ) def __len__(self): return self.n_subs def set_cv(cv_dict): """ Helper function to create a sci-kit learn compatible cv object using common parameters for prediction analyses. Args: cv_dict: Type of cross_validation to use. A dictionary of {'type': 'kfolds', 'n_folds': n}, {'type': 'kfolds', 'n_folds': n, 'stratified': Y}, {'type': 'kfolds', 'n_folds': n, 'subject_id': holdout}, or {'type': 'loso', 'subject_id': holdout} Returns: cv: a scikit-learn cross-validation instance """ if type(cv_dict) is dict: if cv_dict['type'] == 'kfolds': if 'subject_id' in cv_dict: # Hold out subjects within each fold from nltools.cross_validation import KFoldSubject cv = KFoldSubject(len(cv_dict['subject_id']), cv_dict['subject_id'], n_folds=cv_dict['n_folds']) elif 'stratified' in cv_dict: # Stratified K-Folds from nltools.cross_validation import KFoldStratified if isinstance(cv_dict['stratified'],pd.DataFrame): # need to pass numpy array not pandas cv_dict['stratified'] = np.array(cv_dict['stratified']).flatten() cv = KFoldStratified(cv_dict['stratified'], n_folds=cv_dict['n_folds']) else: # Normal K-Folds from sklearn.cross_validation import KFold cv = KFold(n=cv_dict['n'], n_folds=cv_dict['n_folds']) elif cv_dict['type'] == 'loso': # Leave One Subject Out from nltools.cross_validation import LeaveOneSubjectOut cv = LeaveOneSubjectOut(len(cv_dict['subject_id']), labels=cv_dict['subject_id']) else: raise ValueError("""Make sure you specify a dictionary of {'type': 'kfolds', 'n_folds': n}, {'type': 'kfolds', 'n_folds': n, 'stratified': Y}, {'type': 'kfolds', 'n_folds': n, 'subject_id': holdout}, or {'type': 'loso', 'subject_id': holdout}, where n = number of folds, and subject = vector of subject ids that corresponds to self.Y""") else: raise ValueError("Make sure 'cv_dict' is a dictionary.") return cv
[ "sklearn.cross_validation.KFold", "random.shuffle", "numpy.unique", "numpy.where", "numpy.in1d", "numpy.array", "numpy.arange", "nltools.cross_validation.KFoldStratified" ]
[((1526, 1538), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (1535, 1538), True, 'import numpy as np\n'), ((1561, 1588), 'numpy.array', 'np.array', (['labels'], {'copy': '(True)'}), '(labels, copy=True)\n', (1569, 1588), True, 'import numpy as np\n'), ((1891, 1913), 'numpy.unique', 'np.unique', (['self.labels'], {}), '(self.labels)\n', (1900, 1913), True, 'import numpy as np\n'), ((1922, 1942), 'random.shuffle', 'random.shuffle', (['subs'], {}), '(subs)\n', (1936, 1942), False, 'import random\n'), ((5523, 5550), 'numpy.array', 'np.array', (['labels'], {'copy': '(True)'}), '(labels, copy=True)\n', (5531, 5550), True, 'import numpy as np\n'), ((5764, 5786), 'numpy.unique', 'np.unique', (['self.labels'], {}), '(self.labels)\n', (5773, 5786), True, 'import numpy as np\n'), ((1615, 1637), 'numpy.unique', 'np.unique', (['self.labels'], {}), '(self.labels)\n', (1624, 1637), True, 'import numpy as np\n'), ((2183, 2206), 'numpy.in1d', 'np.in1d', (['self.labels', 'd'], {}), '(self.labels, d)\n', (2190, 2206), True, 'import numpy as np\n'), ((5577, 5599), 'numpy.unique', 'np.unique', (['self.labels'], {}), '(self.labels)\n', (5586, 5599), True, 'import numpy as np\n'), ((5806, 5829), 'numpy.in1d', 'np.in1d', (['self.labels', 'd'], {}), '(self.labels, d)\n', (5813, 5829), True, 'import numpy as np\n'), ((5415, 5432), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (5424, 5432), True, 'import numpy as np\n'), ((7465, 7531), 'nltools.cross_validation.KFoldStratified', 'KFoldStratified', (["cv_dict['stratified']"], {'n_folds': "cv_dict['n_folds']"}), "(cv_dict['stratified'], n_folds=cv_dict['n_folds'])\n", (7480, 7531), False, 'from nltools.cross_validation import KFoldStratified\n'), ((7663, 7712), 'sklearn.cross_validation.KFold', 'KFold', ([], {'n': "cv_dict['n']", 'n_folds': "cv_dict['n_folds']"}), "(n=cv_dict['n'], n_folds=cv_dict['n_folds'])\n", (7668, 7712), False, 'from sklearn.cross_validation import KFold\n'), ((2234, 2247), 'numpy.where', 'np.where', (['idx'], {}), '(idx)\n', (2242, 2247), True, 'import numpy as np\n'), ((5857, 5870), 'numpy.where', 'np.where', (['idx'], {}), '(idx)\n', (5865, 5870), True, 'import numpy as np\n'), ((7402, 7433), 'numpy.array', 'np.array', (["cv_dict['stratified']"], {}), "(cv_dict['stratified'])\n", (7410, 7433), True, 'import numpy as np\n')]
from io import TextIOWrapper import pandas as pd import numpy as np import json alphabet = "abcdefghijklmnopqrstuvwxyz" with open("src/data/generator/generative.json", "r") as f: data = json.load(f) def main(cases): goods = [] bads = [] for _ in range(cases): goods.extend(good()) bads.extend(bad()) sentences = goods + bads states = [2 for _ in goods] + [0 for _ in goods] pd.DataFrame(list(zip(sentences, states)), columns=("sentence", "state")).to_csv("src/data/generator/generated.csv", index=False) def mistake(text): text = list(text) for i, letter in enumerate(text): if not np.random.choice(45): text[i] if not np.random.choice(35): text.insert(i, alphabet[np.random.choice(26)]) return "".join(text) def rand_cap(text): text = list(text) for i, letter in enumerate(text): if not np.random.choice(45): text[i] = text[i].upper() return "".join(text) def good(): phrases = [] text = [] length = np.random.choice(3) + 1 for _ in range(length): if not np.random.choice(8): i = np.random.choice(len(data["words"]["good"])) text.append(data["words"]["good"][i]) else: i = np.random.choice(len(data["phrases"]["good"])) text.append(data["phrases"]["good"][i]) i = np.random.choice(len(data["banana"])) text.append(data["banana"][i]) for _ in range(length // 2): np.random.shuffle(text) phrase = " ".join(text) phrases.append(phrase.strip()) return phrases def bad(): phrases = [] text = [] length = np.random.choice(4) + 1 for _ in range(length): if not np.random.choice(8): i = np.random.choice(len(data["words"]["bad"])) text.append(data["words"]["bad"][i]) else: i = np.random.choice(len(data["phrases"]["bad"])) text.append(data["phrases"]["bad"][i]) i = np.random.choice(len(data["banana"])) text.append(data["banana"][i]) for _ in range(length // 2): np.random.shuffle(text) phrase = " ".join(text) phrases.append(phrase.strip()) return phrases if __name__ == '__main__': main(200)
[ "json.load", "numpy.random.shuffle", "numpy.random.choice" ]
[((191, 203), 'json.load', 'json.load', (['f'], {}), '(f)\n', (200, 203), False, 'import json\n'), ((1052, 1071), 'numpy.random.choice', 'np.random.choice', (['(3)'], {}), '(3)\n', (1068, 1071), True, 'import numpy as np\n'), ((1507, 1530), 'numpy.random.shuffle', 'np.random.shuffle', (['text'], {}), '(text)\n', (1524, 1530), True, 'import numpy as np\n'), ((1678, 1697), 'numpy.random.choice', 'np.random.choice', (['(4)'], {}), '(4)\n', (1694, 1697), True, 'import numpy as np\n'), ((2128, 2151), 'numpy.random.shuffle', 'np.random.shuffle', (['text'], {}), '(text)\n', (2145, 2151), True, 'import numpy as np\n'), ((648, 668), 'numpy.random.choice', 'np.random.choice', (['(45)'], {}), '(45)\n', (664, 668), True, 'import numpy as np\n'), ((706, 726), 'numpy.random.choice', 'np.random.choice', (['(35)'], {}), '(35)\n', (722, 726), True, 'import numpy as np\n'), ((909, 929), 'numpy.random.choice', 'np.random.choice', (['(45)'], {}), '(45)\n', (925, 929), True, 'import numpy as np\n'), ((1120, 1139), 'numpy.random.choice', 'np.random.choice', (['(8)'], {}), '(8)\n', (1136, 1139), True, 'import numpy as np\n'), ((1746, 1765), 'numpy.random.choice', 'np.random.choice', (['(8)'], {}), '(8)\n', (1762, 1765), True, 'import numpy as np\n'), ((764, 784), 'numpy.random.choice', 'np.random.choice', (['(26)'], {}), '(26)\n', (780, 784), True, 'import numpy as np\n')]
from Functions.General_Functions import isNaN, getNContext, pad_array, candidateClsf, filterNumbers, filterNumbers_MaintainDistances from Method_Handler import MethodHandler import nltk import math import sklearn as sk import numpy as np import pandas as pd import statistics as stats import os from tempfile import mkdtemp from joblib import load, dump pd.options.mode.chained_assignment = None # default='warn' def preprocessBy(method='CV-TFIDF', *args): return preprocessHandler.execMethod(method, None, *args) def classifyWith(method='CV-SVM', *args): return classifHandler.execMethod(method, None, *args) def CV_TFIDF(data, k): test_list, train_list = kSplit(data, k) pre_test = [] pre_train = [] IDF_list = [] for i,t in enumerate(train_list): IDF = getIDF(t) if not os.path.isdir('Models'): os.mkdir('Models') path = os.path.abspath('Models') filename = os.path.join(path, 'IDFv6') + '_' + str(i) + '.joblib' dump(IDF, filename, compress=1) IDF_list.append(IDF) pre_train.append(transformSet(t, IDF)) pre_test.append(transformSet(test_list[i], IDF)) return IDF_list, pre_train, pre_test def kSplit(data, k): data = sk.utils.shuffle(data) #randomly shuffled data = data.reset_index(drop=True) test = [] train = [] l = len(data) n = math.floor(l/k) r = l % k index = 0 n += 1 for i in range(k): if r == 0: r = -1 n -= 1 test_split = data.loc[index:(index+n-1),:] test_split = test_split.reset_index(drop=True) train_split = data.loc[:index-1,:] train_split = train_split.append(data.loc[(index+n):,:], ignore_index=True) train_split = train_split.reset_index(drop=True) index += n if r > 0: r -= 1 test.append(test_split) train.append(train_split) return test, train def filterDotEmpty(token): return False if token in ['.', '','(',')','<','>',',',':',';','!','?','[',']','{','}','-','/','\\'] else True def splitToken(tk, splitList): stk = tk isFraction = False for symbol in splitList: if symbol in stk: stk = stk.split(symbol)[1] if isNaN(stk): stk = tk elif '/' in tk: isFraction = True return stk, isFraction def text2int(textnum, numwords={}): if not numwords: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["hundred", "thousand", "million", "billion", "trillion"] numwords["and"] = (1, 0) for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) # ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12} # ordinal_endings = [('ieth', 'y'), ('th', '')] textnum = textnum.replace('-', ' ') current = result = 0 curstring = "" onnumber = False for i,word in enumerate(textnum.split()): # if word in ordinal_words: # scale, increment = (1, ordinal_words[word]) # current = current * scale + increment # if scale > 100: # result += current # current = 0 # onnumber = True # else: # for ending, replacement in ordinal_endings: # if word.endswith(ending): # word = "%s%s" % (word[:-len(ending)], replacement) if word not in numwords: if onnumber: if result == current == 0 and textnum.split()[i-1] == 'and': curstring += "and " else: curstring += repr(result + current) + " " curstring += word + " " result = current = 0 onnumber = False else: scale, increment = numwords[word] current = current * scale + increment if scale > 100: result += current current = 0 onnumber = True if onnumber: curstring += repr(result + current) return curstring def get_wordnet_pos(word): """Map POS tag to first character lemmatize() accepts""" tag = nltk.pos_tag([word])[0][1][0].upper() tag_dict = {"J": nltk.corpus.wordnet.ADJ, "N": nltk.corpus.wordnet.NOUN, "V": nltk.corpus.wordnet.VERB, "R": nltk.corpus.wordnet.ADV} return tag_dict.get(tag, nltk.corpus.wordnet.NOUN) def generateNumbersDataFrame(data): abstractList = data['Abstract'].to_list() for i, abstract in enumerate(abstractList): new_sentence = [] N_list = [] N_sentences_list = [] N_close_words_list = [] N_close_words_distances_list = [] N_isFraction_list = [] abstract = text2int(abstract) sentences = nltk.sent_tokenize(abstract) for sentence in sentences: #tokenize tokens = nltk.word_tokenize(sentence) #lemmatize lemmatizer = nltk.stem.WordNetLemmatizer() lemma_tokens = [lemmatizer.lemmatize(w, get_wordnet_pos(w)) for w in tokens] lemma_tokens, isFraction_list = filterTokens(lemma_tokens) #pos tagging pos_tokens = nltk.pos_tag(lemma_tokens) #chuncking grammar = r""" NP: # NP stage {(<DT>*)?(<CD>)*?(<RB>)?(<VBP>*)?(<JJ.*>*)?<NN.*>*(<VBP>*)?(<JJ.*>*)?(<NN.*>*)?} VP: {(<MD>)?(<TO>)?<VB.*>*(<RP>)?} """ chunk_parser = nltk.RegexpParser(grammar) sentence_tree = chunk_parser.parse(pos_tokens) #sentence_tree.draw() for j,token in enumerate(pos_tokens): if not isNaN(token[0]) and "." not in token[0] and float(token[0]) > 2: #token must be an integer number N_list.append(token[0]) N_sentences_list.append(filterNumbers(lemma_tokens)) #words, distances = getNContext(tokens, j, 3) method 1 words, distances = getNPfromNumber(sentence_tree, token[0], j) #method 2 N_close_words_list.append(words) N_close_words_distances_list.append(distances) N_isFraction_list.append(isFraction_list[j]) partial_data = pd.DataFrame(data={'PMID': [data['PMID'][i]]*len(N_list), 'N': N_list, 'N sentence words': N_sentences_list, 'N close words': N_close_words_list, 'N close words distances': N_close_words_distances_list, 'Is fraction': N_isFraction_list}) full_data = full_data.append(partial_data, ignore_index=True, sort=True) if 'full_data' in locals() else partial_data full_data = candidateClsf(full_data, data) return full_data def getNPfromNumber(sent_tree, number, index): a = q = -1 b = [] for tree in sent_tree: if isinstance(tree, tuple): tree = [tree] for word in tree: a += 1 if a == index: b = [w[0] for w in tree] c = [abs(index-q+i) for i,w in enumerate(tree)] return filterNumbers_MaintainDistances(b,c) q = a + 1 #indice inicio sub-arbol return [] def filterTokens(tokens): new_sentence = [] isFraction_list = [] tokens = list(filter(filterDotEmpty, tokens)) for token in tokens: token = token.replace(",", "") #Take out commas from numbers (english format) token, isFraction = splitToken(token, ['/', '-']) new_sentence.append(token) isFraction_list.append(isFraction) return new_sentence, isFraction_list def getIDF(train_set): #vocab = getVocab(train_set['N close words']) vect = sk.feature_extraction.text.TfidfVectorizer(max_features=None, use_idf=True, vocabulary=None, min_df=0.01) words = [] for i, doc in enumerate(train_set['N sentence words']): if train_set['Is Candidate'][i] == 1: words.append(' '.join(train_set['N close words'][i])) IDF = vect.fit(words) return IDF def getVocab(column): vocab = [] for word_bag in column: for word in word_bag: if word not in vocab and isNaN(word): vocab.append(word) return vocab def transformSet(dataset, IDF): close_words = [] for word_list in dataset['N close words']: close_words.append(' '.join(word_list)) X = IDF.transform(close_words) weights = [] means = [] for row in X: weights.append(row.toarray()) means.append(stats.mean(row.toarray()[0])) IDF_words = IDF.vocabulary_.keys() dataset['N close words weights'] = weights dataset['Weight means'] = means dataset = createWordColumns(dataset, IDF_words, True) return dataset def createWordColumns(df, words, use_distances=False): for i in df.index: l = len(df.index) weights = df['N close words weights'].iloc[i][0] distances = df['N close words distances'].iloc[i] for j, w in enumerate(words): if w not in df.columns: df[w] = pd.to_numeric([0.0]*l, downcast='float') df[str(w + ' dist')] = pd.to_numeric([50.0]*l, downcast='integer') #entendiendo 50 como una distancia muy grande if w in df.columns: df[w][i] = weights[j] if w in df['N close words'].iloc[i]: windex = df['N close words'].iloc[i].index(w) df[str(w + ' dist')][i] = distances[windex] return df def SVM(train, test, index, c, kernel, gamma, prob): classifier = sk.svm.SVC(C=c,kernel=kernel, gamma=gamma, class_weight='balanced', probability=prob) train_set = train.iloc[:,8:] train_set['Is fraction'] = train['Is fraction'] test_set = test.iloc[:,8:] test_set['Is fraction'] = test['Is fraction'] classifier.fit(np.matrix(train_set), train['Is Candidate']) class_results = classifier.predict(np.matrix(test_set)) class_prob = classifier.predict_proba(np.matrix(test_set)) if not os.path.isdir('Models'): os.mkdir('Models') path = os.path.abspath('Models') filename = os.path.join(path, 'SVMv8') if index != None and isinstance(index, int): dump(classifier, filename + '_' + str(index) + '.joblib', compress=1) else: dump(classifier, filename + '.joblib', compress=1) return class_results, class_prob def CV_SVM(train_list, test_list): true_class = [] predicted_class = [] true_class_probs = [] for i, t in enumerate(train_list): predictions, probs = classifyWith('SVM', t, test_list[i], i, 2, 'rbf', 'scale', True) true_class.extend(test_list[i]['Is Candidate']) predicted_class.extend(predictions) true_class_probs.extend(probs[:,1]) return true_class, predicted_class, true_class_probs def NN(train, test, index, *args): return 0 def CV_NN(train_list, test_list): true_class = [] predicted_class = [] true_class_probs = [] for i, t in enumerate(train_list): a = 0 return true_class, predicted_class, true_class_probs #PREPROCESS METHODS preProcessMethods = { "CV-TFIDF": CV_TFIDF } classifMethodDicc = { "SVM": SVM, "CV-SVM": CV_SVM, "NN": NN, "CV-NN": CV_NN } preprocessHandler = MethodHandler(preProcessMethods) classifHandler = MethodHandler(classifMethodDicc)
[ "math.floor", "nltk.RegexpParser", "nltk.sent_tokenize", "os.path.isdir", "os.mkdir", "joblib.dump", "Functions.General_Functions.filterNumbers", "nltk.pos_tag", "nltk.word_tokenize", "Functions.General_Functions.isNaN", "Functions.General_Functions.filterNumbers_MaintainDistances", "Functions...
[((11797, 11829), 'Method_Handler.MethodHandler', 'MethodHandler', (['preProcessMethods'], {}), '(preProcessMethods)\n', (11810, 11829), False, 'from Method_Handler import MethodHandler\n'), ((11847, 11879), 'Method_Handler.MethodHandler', 'MethodHandler', (['classifMethodDicc'], {}), '(classifMethodDicc)\n', (11860, 11879), False, 'from Method_Handler import MethodHandler\n'), ((1241, 1263), 'sklearn.utils.shuffle', 'sk.utils.shuffle', (['data'], {}), '(data)\n', (1257, 1263), True, 'import sklearn as sk\n'), ((1377, 1394), 'math.floor', 'math.floor', (['(l / k)'], {}), '(l / k)\n', (1387, 1394), False, 'import math\n'), ((2258, 2268), 'Functions.General_Functions.isNaN', 'isNaN', (['stk'], {}), '(stk)\n', (2263, 2268), False, 'from Functions.General_Functions import isNaN, getNContext, pad_array, candidateClsf, filterNumbers, filterNumbers_MaintainDistances\n'), ((7209, 7239), 'Functions.General_Functions.candidateClsf', 'candidateClsf', (['full_data', 'data'], {}), '(full_data, data)\n', (7222, 7239), False, 'from Functions.General_Functions import isNaN, getNContext, pad_array, candidateClsf, filterNumbers, filterNumbers_MaintainDistances\n'), ((8215, 8324), 'sklearn.feature_extraction.text.TfidfVectorizer', 'sk.feature_extraction.text.TfidfVectorizer', ([], {'max_features': 'None', 'use_idf': '(True)', 'vocabulary': 'None', 'min_df': '(0.01)'}), '(max_features=None, use_idf=True,\n vocabulary=None, min_df=0.01)\n', (8257, 8324), True, 'import sklearn as sk\n'), ((10088, 10178), 'sklearn.svm.SVC', 'sk.svm.SVC', ([], {'C': 'c', 'kernel': 'kernel', 'gamma': 'gamma', 'class_weight': '"""balanced"""', 'probability': 'prob'}), "(C=c, kernel=kernel, gamma=gamma, class_weight='balanced',\n probability=prob)\n", (10098, 10178), True, 'import sklearn as sk\n'), ((10601, 10626), 'os.path.abspath', 'os.path.abspath', (['"""Models"""'], {}), "('Models')\n", (10616, 10626), False, 'import os\n'), ((10642, 10669), 'os.path.join', 'os.path.join', (['path', '"""SVMv8"""'], {}), "(path, 'SVMv8')\n", (10654, 10669), False, 'import os\n'), ((894, 919), 'os.path.abspath', 'os.path.abspath', (['"""Models"""'], {}), "('Models')\n", (909, 919), False, 'import os\n'), ((1002, 1033), 'joblib.dump', 'dump', (['IDF', 'filename'], {'compress': '(1)'}), '(IDF, filename, compress=1)\n', (1006, 1033), False, 'from joblib import load, dump\n'), ((5286, 5314), 'nltk.sent_tokenize', 'nltk.sent_tokenize', (['abstract'], {}), '(abstract)\n', (5304, 5314), False, 'import nltk\n'), ((10359, 10379), 'numpy.matrix', 'np.matrix', (['train_set'], {}), '(train_set)\n', (10368, 10379), True, 'import numpy as np\n'), ((10443, 10462), 'numpy.matrix', 'np.matrix', (['test_set'], {}), '(test_set)\n', (10452, 10462), True, 'import numpy as np\n'), ((10506, 10525), 'numpy.matrix', 'np.matrix', (['test_set'], {}), '(test_set)\n', (10515, 10525), True, 'import numpy as np\n'), ((10538, 10561), 'os.path.isdir', 'os.path.isdir', (['"""Models"""'], {}), "('Models')\n", (10551, 10561), False, 'import os\n'), ((10571, 10589), 'os.mkdir', 'os.mkdir', (['"""Models"""'], {}), "('Models')\n", (10579, 10589), False, 'import os\n'), ((10815, 10865), 'joblib.dump', 'dump', (['classifier', "(filename + '.joblib')"], {'compress': '(1)'}), "(classifier, filename + '.joblib', compress=1)\n", (10819, 10865), False, 'from joblib import load, dump\n'), ((823, 846), 'os.path.isdir', 'os.path.isdir', (['"""Models"""'], {}), "('Models')\n", (836, 846), False, 'import os\n'), ((860, 878), 'os.mkdir', 'os.mkdir', (['"""Models"""'], {}), "('Models')\n", (868, 878), False, 'import os\n'), ((5393, 5421), 'nltk.word_tokenize', 'nltk.word_tokenize', (['sentence'], {}), '(sentence)\n', (5411, 5421), False, 'import nltk\n'), ((5470, 5499), 'nltk.stem.WordNetLemmatizer', 'nltk.stem.WordNetLemmatizer', ([], {}), '()\n', (5497, 5499), False, 'import nltk\n'), ((5710, 5736), 'nltk.pos_tag', 'nltk.pos_tag', (['lemma_tokens'], {}), '(lemma_tokens)\n', (5722, 5736), False, 'import nltk\n'), ((6045, 6071), 'nltk.RegexpParser', 'nltk.RegexpParser', (['grammar'], {}), '(grammar)\n', (6062, 6071), False, 'import nltk\n'), ((7624, 7661), 'Functions.General_Functions.filterNumbers_MaintainDistances', 'filterNumbers_MaintainDistances', (['b', 'c'], {}), '(b, c)\n', (7655, 7661), False, 'from Functions.General_Functions import isNaN, getNContext, pad_array, candidateClsf, filterNumbers, filterNumbers_MaintainDistances\n'), ((8686, 8697), 'Functions.General_Functions.isNaN', 'isNaN', (['word'], {}), '(word)\n', (8691, 8697), False, 'from Functions.General_Functions import isNaN, getNContext, pad_array, candidateClsf, filterNumbers, filterNumbers_MaintainDistances\n'), ((9591, 9633), 'pandas.to_numeric', 'pd.to_numeric', (['([0.0] * l)'], {'downcast': '"""float"""'}), "([0.0] * l, downcast='float')\n", (9604, 9633), True, 'import pandas as pd\n'), ((9671, 9716), 'pandas.to_numeric', 'pd.to_numeric', (['([50.0] * l)'], {'downcast': '"""integer"""'}), "([50.0] * l, downcast='integer')\n", (9684, 9716), True, 'import pandas as pd\n'), ((939, 966), 'os.path.join', 'os.path.join', (['path', '"""IDFv6"""'], {}), "(path, 'IDFv6')\n", (951, 966), False, 'import os\n'), ((4636, 4656), 'nltk.pos_tag', 'nltk.pos_tag', (['[word]'], {}), '([word])\n', (4648, 4656), False, 'import nltk\n'), ((6238, 6253), 'Functions.General_Functions.isNaN', 'isNaN', (['token[0]'], {}), '(token[0])\n', (6243, 6253), False, 'from Functions.General_Functions import isNaN, getNContext, pad_array, candidateClsf, filterNumbers, filterNumbers_MaintainDistances\n'), ((6424, 6451), 'Functions.General_Functions.filterNumbers', 'filterNumbers', (['lemma_tokens'], {}), '(lemma_tokens)\n', (6437, 6451), False, 'from Functions.General_Functions import isNaN, getNContext, pad_array, candidateClsf, filterNumbers, filterNumbers_MaintainDistances\n')]
import copy import operator import itertools import scipy.stats import numpy as np import pandas as pd import plum.util.data import scipy.optimize import sklearn.metrics from plum.models.modelABC import Model #from plum.util.cpruning import getNodeProbs, getNodeProbs_prior_weighted from plum.util.cpruning import cgetNodeProbs from plum.util.cfitting import _simulated_annealing, _simulated_annealing_multivariate class plumRecallPrecision(plum.util.data.plumData): '''Base class for optimizers that use recall-precision. Input file should be training data with each pairs having at least one taxon with a known state. The known labels will be ignored for inferring ancestral state probabilities, but will be used to compare predictions to when calculating recall-precision''' def __init__(self,markov_model,error_model,tree,data=None,as_sorted=False,prior_weighted=False): plum.util.data.plumData.__init__(self,markov_model,error_model,tree,data,as_sorted) assert type(prior_weighted) is bool, "`prior_weighted` must be boolean" if prior_weighted: raise Exception("**option `prior_weighted` needs to be deleted**") self._prior_weighted = True self._calc_ancStates = np.vectorize(getNodeProbs_prior_weighted) else: self._prior_weighted = False #self._calc_ancStates = np.vectorize(getNodeProbs) self._calc_ancStates = cgetNodeProbs self._outputDF = None self._blank_knownDs = np.array( [{}] * len(self._featureDs) ) print("Initializing model") self._update_all(self._param_vec) # calculate initial state print("Finished initializing model") self._precision_recall_dataframe = None self._results_dataframe = None #@property #def prior_weighted(self): # '''Whether to weight the likelihood under the error model by # the state prior from the stationary frequencies''' # return self._prior_weighted #@prior_weighted.setter #def prior_weighted(self,pw): # assert type(pw) is bool, "`prior_weighted` must be boolean" # if pw == True: # self._prior_weighted = True # self._calc_ancStates = np.vectorize(getNodeProbs_prior_weighted) # else: # self._prior_weighted = False # self._calc_ancStates = np.vectorize(getNodeProbs) @property def recall(self): '''Recall under current model''' return self._recall @property def precision(self): '''Precision under current model''' return self._precision @property def thresholds(self): '''Recall-precision thresholds under current model''' return self._thresholds @property def aps(self): '''Area under the recall-precision curve under current model''' return self._aps @property def probabilities(self): '''Vector of probabilities of known states under current model''' return self._classifier_probs @property def precision_recall_DF(self): '''Return a dataframe with the precision recall curve''' if self._precision_recall_dataframe is None: self._precision_recall_dataframe = pd.DataFrame( {"precision":self.precision, "recall":self.recall} ) self._precision_recall_dataframe.sort_values("recall", inplace=True) return self._precision_recall_dataframe @property def results_DF(self): if self._results_dataframe is None: self._results_dataframe = pd.DataFrame( {"ID1": self._outID1, "ID2": self._outID2, "species": self._outspecies, "state": self._labels, "P_1": self._classifier_probs}, columns=["ID1","ID2","species","state","P_1"] ).sort_values("P_1",ascending=False) self._results_dataframe["FDR"] = 1 - ( self._results_dataframe["state"].cumsum() / (np.arange(self._results_dataframe.shape[0])+1) ) self._results_dataframe.index = np.arange(self._results_dataframe.shape[0]) return self._results_dataframe def update_from_dict(self,param_dict,save_state=False): '''Update the parameters from a dictionary mapping parameter names to values. Doesn't need to include all parameters and will only update parameters included in the provided dictionary. If `save_state` is True, the previous state of the model will be saved in hidden attributes, this is only used internally by MCMC samplers at the moment''' if save_state: self._last_classifier_probs = copy.deepcopy(self._classifier_probs) self._last_params_vec = copy.deepcopy(self._param_vec) self._last_paramD = self._paramD.copy() self._last_pairAncStates = self._pairAncStates.copy() self._last_aps = copy.deepcopy(self._aps) for name,val in param_dict.items(): assert name in self._paramD, "Invalid parameter name for this model: {}".format(name) self._paramD[name] = np.float64( val ) # this is only a good idea so far as *every* parameter should have this type self._param_vec = [self._paramD[i] for i in self._free_params] # use properties to update models (they parse self._paramD) self._error_model.updateParams(self.errorModelParams) self._markov_model.updateParams(self.markovModelParams) self._state_priors = dict(list(zip(*self._markov_model.stationaryFrequencies))) # An empty dictionary is passed to knownD argument, so all labels in dataset will be # ignored. This is something that I could do differently self._pairAncStates = self._calc_ancStates(self.tree,self._featureDs,self._blank_knownDs, self._error_model, self._markov_model, self._state_priors) self._aps = self._calc_aps() def _reset_last(self): '''Reset to the last set of parameters, likelihoods etc. This is primarily for MCMC.''' assert self._last_params_vec != None, "No previous states saved" self._param_vec = self._last_params_vec self._paramD = self._last_paramD self._pairAncStates = self._last_pairAncStates self._aps = self._last_aps self._classifier_probs = self._last_classifier_probs self._error_model.updateParams(self.errorModelParams) self._markov_model.updateParams(self.markovModelParams) def _calc_aps(self): '''Calculate the area under the recall-precision curve for all labeled taxa''' self._classifier_probs = [] # probabilities of known tips from ancestral state reconstruction self._outspecies = [] self._outID1, self._outID2 = [], [] self._labels = [] for index,nodeD in enumerate(self._knownLabelDs): for taxon,label in nodeD.items(): if not pd.isnull(label): try: #prob = self._pairAncStates[index][taxon][1] prob = self._pairAncStates[index][taxon] except KeyError: raise Exception("{}".format(self._pairAncStates[index])) if pd.isnull(prob): # seems that these can be nan, perhaps with certain parameter combinations? prob = 0 # not sure this is the right way to do this. Got almost all nans for both means=0, both sds=.1, alpha/beta=.2 self._labels.append(label) self._classifier_probs.append(prob) self._outID1.append(self._pairs[index][0]) self._outID2.append(self._pairs[index][1]) self._outspecies.append(taxon) assert len(self._classifier_probs) == len(self._labels) self._precision,self._recall,self._thresholds = sklearn.metrics.precision_recall_curve(self._labels,self._classifier_probs,pos_label=1.) return sklearn.metrics.average_precision_score(self._labels,self._classifier_probs) def _update_all(self,param_array,save_state=False): '''Update all the params. 1. First turn parameter vector to dictionary keyed on parameters names. Works on the fact that self._free_params is list of keys phased to self._param_vec, the values 2. Then assign this dictionary to self._paramD 3. Then use markovModelParams and errorModelParams properties to update the models themselves. These will be passed to the tree likelihood function 4. Finally, call the tree likelihood function (Felsenstein pruning algorithm) and update the current site and tree likelihoods''' if save_state: self._last_classifier_probs = copy.deepcopy(self._classifier_probs) self._last_params_vec = copy.deepcopy(self._param_vec) self._last_paramD = self._paramD.copy() self._last_pairAncStates = self._pairAncStates.copy() self._last_aps = copy.deepcopy(self._aps) self._param_vec = param_array # could do this via a @property setter method instead assert len(self._param_vec) == len(self._free_params), "Why aren't parameter vector and free params same length" self._paramD = dict(list(zip(self._free_params,self._param_vec))) # update main holder of parameters # use properties to update models (they parse self._paramD) self._error_model.updateParams(self.errorModelParams) self._markov_model.updateParams(self.markovModelParams) self._state_priors = dict(list(zip(*self._markov_model.stationaryFrequencies))) # An empty dictionary is passed to knownD argument, so all labels in dataset will be # ignored. This is something that I could do differently self._pairAncStates = self._calc_ancStates(self.tree,self._featureDs,self._blank_knownDs, self._error_model, self._markov_model, self._state_priors) self._aps = self._calc_aps() def write_parameter_file(self,outfile): '''Write current parameters to a parameter file - `outfile`: <str> File to write to (will overwrite an existing file of the same name)''' plum.util.data.write_parameter_file(error_model=self._error_model,markov_model=self._markov_model,outfile=outfile) class sweep(plumRecallPrecision): '''Perform simple 1-dimensional sweep on a model parameter, logging effect on aps''' def __init__(self,markov_model,error_model,param,bound,tree,data=None,as_sorted=False,prior_weighted=False,step=.1): plumRecallPrecision.__init__(self,markov_model,error_model,tree,data,as_sorted,prior_weighted) self._param_sweep = [] self._aps_vec = [] self._best_aps = None self._best_param = None self._param_to_sweep = param self._bound = bound self._step = float(step) @property def bestAPS(self): '''Return the best APS value found on the sweep''' return self._best_aps @property def APS_sweep(self): '''Return the vector of APS values over the sweep''' return self._aps_vec @property def param_sweep(self): '''Return the vector of parameter values swept over''' return self._param_sweep def sweep(self): '''Sweep a single parameter value over given range, saving states and best aps and parameter values''' for i in np.arange(self._bound[0],self._bound[1],self._step): self._paramD[self._param_to_sweep] = i new_vec = [self._paramD[p] for p in self._free_params] self._update_all(new_vec) self._param_sweep.append(i) self._aps_vec.append(self._aps) if self._aps > self._best_aps: self._best_aps = self._aps self._best_param = i class mcmc(plumRecallPrecision): '''MCMC sampling using area under the recall-precision curve as a metric''' def __init__(self,markov_model,error_model,outfile,tree,data,as_sorted=False,prior_weighted=False,n_iters=10000,save_every=10,stringency=1,scale_dict=None): ''' -`markov_model`: A plum.models.MarkovModels object. Its parameters will be used as a starting point for optimization -`error_model`: A plum.models.ErrorModels object. Its parameters will be used as a starting point for optimization -`outfile`: File to write iterations to -`tree`: Path to the input newick tree -`data`: A file in tidy data format. -`as_sorted`: whether input data is presorted on ID1,ID2 -`n_iters`: number of MCMC iterations to perform -`save_every`: Save state after this many of generations -`stringency`: Scaling factor for acceptance ratio. Must be between 0 and 1, where 1 does not scale the Hastings ratio, and 0 means a lower APS will never be accepted -`scale_dict`: Standard deviations of normal distributions to sample parameter proposals from. Dictionary mapping parameter names to numbers. Defaults to .5 for every parameter ''' plumRecallPrecision.__init__(self,markov_model,error_model,tree,data,as_sorted,prior_weighted) # Run params self._map_aps = None self._map_params = None self.n_iters = n_iters self.save_every = save_every self.outfile = outfile self._accepts = [] assert np.logical_and(stringency >= 0, stringency <= 1), "`stringency` must be between 0 and 1" self._stringency = stringency self._scale_dict = {p:.5 for p in self.freeParams} # if scale_dict != None: for p,val in scale_dict: assert p in self.freeParams, "Parameter '{}' in scale_dict not found".format(p) self._scale_dict[p] = val @property def best_parameters(self): '''The free parameters with the highest APS found in the search and that APS value. Returns a tuple of the parameters dictionary and the APS value''' return self._map_params, self._map_aps def _draw_proposal(self): '''Draw a new parameter value from free parameters and update model''' # Right now, only move is a normally distributed step. Worth thinking # about the right way to make this more flexible, using scaling moves etc. # the way RevBayes does param = np.random.choice(self.freeParams) # could implement weights here proposal = scipy.stats.norm.rvs(loc=self._paramD[param],scale=self._scale_dict[param]) # I could tune the scale here ## hacky hard coding time!! ## if param in ["alpha",'beta','sd0','sd1']: proposal = abs(proposal) tmpD = self._paramD.copy() tmpD[param] = proposal new_vec = [tmpD[p] for p in self._free_params] self._update_all(new_vec,save_state=True) def metropolis_hastings(self): '''Accept or reject new proposal with the Hastings ratio''' old_state = self._paramD self._draw_proposal() alpha = self._aps / float(self._last_aps) if alpha > 1: self._accepts.append(True) if self._aps > self._map_aps: self._map_aps = copy.deepcopy(self._aps) self._map_params = copy.deepcopy(self._paramD) else: scaled = alpha * self._stringency pull = np.random.uniform() if pull >= scaled: # don't accept self._reset_last() self._accepts.append(False) else: self._accepts.append(True) if self._aps > self._map_aps: self._map_aps = copy.deepcopy(self._aps) self._map_params = copy.deepcopy(self._paramD) def run(self): '''Run the MCMC sampler, writing to outfile''' out = open(self.outfile,'w') out.write(",".join(["gen","APS"]+self._free_params)+ "\n") gen = 0 is_first = True while gen <= self.n_iters: if is_first: # initialize self._update_all(self._param_vec) is_first = False else: self.metropolis_hastings() print(gen) gen += 1 if gen % self.save_every == 0: out.write(",".join([str(gen),str(self._aps)] + list(map(str,self._param_vec))) + "\n") out.close() class basinhopping(plumRecallPrecision): '''Wrapper for scipy.optimize.basinhopping. Fits the model by basin-hopping using L-BFGS-B bounded minimization. Can modify bounds via the input error model and Markov model. -`markov_model`: A plum.models.MarkovModels object. Its parameters will be used as a starting point for optimization -`error_model`: A plum.models.ErrorModels object. Its parameters will be used as a starting point for optimization -`tree`: Path to the input newick tree or dendropy Tree object -`data`: A file in tidy data format or DataFrame -`as_sorted`: whether input data is presorted on ID1,ID2 -`n_iters`: Number of iterations for the basin-hopping algorithm to perform. Default = 100 -`temp`: Temperature scaling for the Metropolis acceptance criterion. See scipy docs. Default = 1.0 ''' def __init__(self,markov_model,error_model,tree,data,as_sorted=False,prior_weighted=False,n_iters=100,temp=1.0,stepsize=1.0): plumRecallPrecision.__init__(self,markov_model,error_model,tree,data,as_sorted,prior_weighted) self.n_iters = n_iters self.temp = temp self.stepsize = stepsize def fit(self): '''Fit the model by basin-hopping + L-BFGS-B''' print("Fitting model by basinhopping") self.results = scipy.optimize.basinhopping(self._run_calc,self._param_vec,disp=True,niter=self.n_iters, T=self.temp, stepsize=self.stepsize,minimizer_kwargs={"method":"L-BFGS-B",'bounds':self._param_boundVec}) self.estimate = dict(list(zip(self._free_params,self.results.x))) self.best_aps = 1 - self.results.fun def _run_calc(self,param_array): '''When called, reset self._param_vec and return negative log likelihood to feed into scipy.optimize.minimize''' self._update_all(param_array) return 1 - self.aps class simulated_annealing(plumRecallPrecision): '''Fit a PLVM by simulated annealing. -`markov_model`: A plum.models.MarkovModels object. Its parameters will be used as a starting point for optimization -`error_model`: A plum.models.ErrorModels object. Its parameters will be used as a starting point for optimization -`tree`: Path to the input newick tree or dendropy Tree object -`data`: A file in tidy data format or DataFrame -`as_sorted`: whether input data is presorted on ID1,ID2 -`start_temp`: Starting temperature for the simulated annealing. -`alpha`: Parameter that decrements the temperature. -`temp_steps`: Number of steps to take at each temperature. -`mutation_sd`: Standard deviation of the sampling distribution (a Gaussian) ''' def __init__(self,markov_model,error_model,tree,data,as_sorted=False,prior_weighted=False,start_temp=1, alpha=.9, temp_steps=10, mutation_sd=.5,random_seed=False): plumRecallPrecision.__init__(self,markov_model,error_model,tree,data,as_sorted,prior_weighted) self.start_temp = start_temp self.alpha = alpha self.temp_steps = temp_steps self.mutation_sd = mutation_sd if random_seed != False: self.random_seed = random_seed else: assert isinstance(random_seed, int), "random seed must be an int" self.random_seed = -1 def _run_calc(self,param_array): self._update_all(param_array) return self.aps @property def alpha(self): '''''' return self._alpha @alpha.setter def alpha(self, new_value): assert np.logical_and( 0 < new_value, new_value < 1), "Alpha must be between 1 and 0" self._alpha = new_value @property def start_temp(self): '''''' return self._start_temp @start_temp.setter def start_temp(self, new_value): assert new_value > .000001, "Starting temperature must be greater than .000001" self._start_temp = new_value @property def temp_steps(self): return self._temp_steps @temp_steps.setter def temp_steps(self, new_value): assert new_value > 0, "Temperature steps must be an integer greater than 0" assert type(new_value) is int, "Temperature steps must be an integer" self._temp_steps = new_value @property def mutation_sd(self): return self._mutation_sd @mutation_sd.setter def mutation_sd(self, new_value): self._mutation_sd = new_value def fit(self): '''Run the simulated annealing procedure. Populate class fields: - best_params: The best parameters found during the run - best_aps: The best fit, as determined by the average precision score (APS) - acceptance_rate: The proportion of steps that were accepted. ''' pvec = np.array(self._param_vec) if self.is_multivariate: best_params, best_score = _simulated_annealing_multivariate(self._run_calc, pvec, self._param_boundVec, self.start_temp, self.alpha, self.temp_steps, self.mutation_sd, self.random_seed) else: best_params, best_score = _simulated_annealing(self._run_calc, pvec, self._param_boundVec, self.start_temp, self.alpha, self.temp_steps, self.mutation_sd, self.random_seed) self.best_params = dict(list(zip(self.freeParams,best_params))) self.best_aps = best_score self._update_all(best_params) # final update turns model state to best parameters found during search self._param_vec = best_params # re-assign parameter vector as well
[ "pandas.isnull", "plum.util.cfitting._simulated_annealing", "numpy.logical_and", "numpy.random.choice", "numpy.float64", "numpy.array", "plum.util.cfitting._simulated_annealing_multivariate", "numpy.random.uniform", "copy.deepcopy", "pandas.DataFrame", "numpy.vectorize", "numpy.arange" ]
[((12372, 12425), 'numpy.arange', 'np.arange', (['self._bound[0]', 'self._bound[1]', 'self._step'], {}), '(self._bound[0], self._bound[1], self._step)\n', (12381, 12425), True, 'import numpy as np\n'), ((14493, 14541), 'numpy.logical_and', 'np.logical_and', (['(stringency >= 0)', '(stringency <= 1)'], {}), '(stringency >= 0, stringency <= 1)\n', (14507, 14541), True, 'import numpy as np\n'), ((15499, 15532), 'numpy.random.choice', 'np.random.choice', (['self.freeParams'], {}), '(self.freeParams)\n', (15515, 15532), True, 'import numpy as np\n'), ((21194, 21238), 'numpy.logical_and', 'np.logical_and', (['(0 < new_value)', '(new_value < 1)'], {}), '(0 < new_value, new_value < 1)\n', (21208, 21238), True, 'import numpy as np\n'), ((22496, 22521), 'numpy.array', 'np.array', (['self._param_vec'], {}), '(self._param_vec)\n', (22504, 22521), True, 'import numpy as np\n'), ((1271, 1312), 'numpy.vectorize', 'np.vectorize', (['getNodeProbs_prior_weighted'], {}), '(getNodeProbs_prior_weighted)\n', (1283, 1312), True, 'import numpy as np\n'), ((3375, 3441), 'pandas.DataFrame', 'pd.DataFrame', (["{'precision': self.precision, 'recall': self.recall}"], {}), "({'precision': self.precision, 'recall': self.recall})\n", (3387, 3441), True, 'import pandas as pd\n'), ((4432, 4475), 'numpy.arange', 'np.arange', (['self._results_dataframe.shape[0]'], {}), '(self._results_dataframe.shape[0])\n', (4441, 4475), True, 'import numpy as np\n'), ((5041, 5078), 'copy.deepcopy', 'copy.deepcopy', (['self._classifier_probs'], {}), '(self._classifier_probs)\n', (5054, 5078), False, 'import copy\n'), ((5115, 5145), 'copy.deepcopy', 'copy.deepcopy', (['self._param_vec'], {}), '(self._param_vec)\n', (5128, 5145), False, 'import copy\n'), ((5293, 5317), 'copy.deepcopy', 'copy.deepcopy', (['self._aps'], {}), '(self._aps)\n', (5306, 5317), False, 'import copy\n'), ((5502, 5517), 'numpy.float64', 'np.float64', (['val'], {}), '(val)\n', (5512, 5517), True, 'import numpy as np\n'), ((9457, 9494), 'copy.deepcopy', 'copy.deepcopy', (['self._classifier_probs'], {}), '(self._classifier_probs)\n', (9470, 9494), False, 'import copy\n'), ((9531, 9561), 'copy.deepcopy', 'copy.deepcopy', (['self._param_vec'], {}), '(self._param_vec)\n', (9544, 9561), False, 'import copy\n'), ((9709, 9733), 'copy.deepcopy', 'copy.deepcopy', (['self._aps'], {}), '(self._aps)\n', (9722, 9733), False, 'import copy\n'), ((16532, 16551), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (16549, 16551), True, 'import numpy as np\n'), ((22593, 22762), 'plum.util.cfitting._simulated_annealing_multivariate', '_simulated_annealing_multivariate', (['self._run_calc', 'pvec', 'self._param_boundVec', 'self.start_temp', 'self.alpha', 'self.temp_steps', 'self.mutation_sd', 'self.random_seed'], {}), '(self._run_calc, pvec, self.\n _param_boundVec, self.start_temp, self.alpha, self.temp_steps, self.\n mutation_sd, self.random_seed)\n', (22626, 22762), False, 'from plum.util.cfitting import _simulated_annealing, _simulated_annealing_multivariate\n'), ((22862, 23018), 'plum.util.cfitting._simulated_annealing', '_simulated_annealing', (['self._run_calc', 'pvec', 'self._param_boundVec', 'self.start_temp', 'self.alpha', 'self.temp_steps', 'self.mutation_sd', 'self.random_seed'], {}), '(self._run_calc, pvec, self._param_boundVec, self.\n start_temp, self.alpha, self.temp_steps, self.mutation_sd, self.random_seed\n )\n', (22882, 23018), False, 'from plum.util.cfitting import _simulated_annealing, _simulated_annealing_multivariate\n'), ((16365, 16389), 'copy.deepcopy', 'copy.deepcopy', (['self._aps'], {}), '(self._aps)\n', (16378, 16389), False, 'import copy\n'), ((16425, 16452), 'copy.deepcopy', 'copy.deepcopy', (['self._paramD'], {}), '(self._paramD)\n', (16438, 16452), False, 'import copy\n'), ((3701, 3900), 'pandas.DataFrame', 'pd.DataFrame', (["{'ID1': self._outID1, 'ID2': self._outID2, 'species': self._outspecies,\n 'state': self._labels, 'P_1': self._classifier_probs}"], {'columns': "['ID1', 'ID2', 'species', 'state', 'P_1']"}), "({'ID1': self._outID1, 'ID2': self._outID2, 'species': self.\n _outspecies, 'state': self._labels, 'P_1': self._classifier_probs},\n columns=['ID1', 'ID2', 'species', 'state', 'P_1'])\n", (3713, 3900), True, 'import pandas as pd\n'), ((7529, 7545), 'pandas.isnull', 'pd.isnull', (['label'], {}), '(label)\n', (7538, 7545), True, 'import pandas as pd\n'), ((7845, 7860), 'pandas.isnull', 'pd.isnull', (['prob'], {}), '(prob)\n', (7854, 7860), True, 'import pandas as pd\n'), ((16820, 16844), 'copy.deepcopy', 'copy.deepcopy', (['self._aps'], {}), '(self._aps)\n', (16833, 16844), False, 'import copy\n'), ((16884, 16911), 'copy.deepcopy', 'copy.deepcopy', (['self._paramD'], {}), '(self._paramD)\n', (16897, 16911), False, 'import copy\n'), ((4339, 4382), 'numpy.arange', 'np.arange', (['self._results_dataframe.shape[0]'], {}), '(self._results_dataframe.shape[0])\n', (4348, 4382), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Compare different norm and SE schemes for TiramisuNet, weighted, dr 0.2.""" import os import numpy as np import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from load_tfevents import func_load_event # %% Set input parameters # Set path to log directtory str_log_path = '/Users/Marian/Documents/Unet/MPRAGEsingle/results/' # List project names lst_prj = ['project53a_32strides_maxpool_tranposed_dense_IN_nose_weighted', 'project54a_32strides_maxpool_tranposed_dense_IN_cse_weighted', 'project55a_32strides_maxpool_tranposed_dense_IN_pe_weighted', 'project56a_32strides_maxpool_tranposed_dense_INLN_nose_weighted', 'project57a_32strides_maxpool_tranposed_dense_INLN_cse_weighted', 'project58a_32strides_maxpool_tranposed_dense_INLN_pe_weighted', 'project59a_32strides_maxpool_tranposed_dense_LN_nose_weighted', 'project60a_32strides_maxpool_tranposed_dense_LN_cse_weighted', 'project61a_32strides_maxpool_tranposed_dense_LN_pe_weighted', ] # list project names for plotting lst_names = ['_dense_IN_nose_w', '_dense_IN_cse_w', '_dense_IN_pe_w', '_dense_INLN_nose_w', '_dense_INLN_cse_w', '_dense_INLN_pe_w', '_dense_LN_nose_w', '_dense_LN_cse_w', '_dense_LN_pe_w' ] # Set subfolder to training logs lst_evnt_trn = ['events.out.tfevents.1579297598.bi-node1.bi.27178.7922.v2', 'events.out.tfevents.1579333136.bi-node1.bi.28396.7948.v2', 'events.out.tfevents.1579366512.bi-node1.bi.30148.7997.v2', 'events.out.tfevents.1579401688.bi-node1.bi.31020.9726.v2', 'events.out.tfevents.1579447158.bi-node1.bi.534.9752.v2', 'events.out.tfevents.1579491018.bi-node1.bi.1474.9801.v2', 'events.out.tfevents.1579576142.bi-node1.bi.4363.5810.v2', 'events.out.tfevents.1579654602.bi-node1.bi.7119.5836.v2', 'events.out.tfevents.1579733101.bi-node1.bi.9795.5885.v2'] # Set subfolder to validation logs lst_evnt_val = ['events.out.tfevents.1579298546.bi-node1.bi.27178.64050.v2', 'events.out.tfevents.1579334025.bi-node1.bi.28396.63858.v2', 'events.out.tfevents.1579367448.bi-node1.bi.30148.64285.v2', 'events.out.tfevents.1579402893.bi-node1.bi.31020.83058.v2', 'events.out.tfevents.1579448320.bi-node1.bi.534.82866.v2', 'events.out.tfevents.1579492220.bi-node1.bi.1474.83293.v2', 'events.out.tfevents.1579577174.bi-node1.bi.4363.57010.v2', 'events.out.tfevents.1579655596.bi-node1.bi.7119.56818.v2', 'events.out.tfevents.1579734129.bi-node1.bi.9795.57245.v2'] # Set color lst_colors = ['#6baed6', '#6baed6', '#3182bd', '#3182bd', '#08519c', '#08519c', '#74c476', '#74c476', '#31a354', '#31a354', '#006d2c', '#006d2c', '#fd8d3c', '#fd8d3c', '#e6550d', '#e6550d', '#a63603', '#a63603', ] # Set dashes lst_dashes = [(''), (2, 2), (''), (2, 2), (''), (2, 2), (''), (2, 2), (''), (2, 2), (''), (2, 2), (''), (2, 2), (''), (2, 2), (''), (2, 2)] # define size guidance for loading data tf_size_guidance = { 'compressedHistograms': 10, 'images': 0, 'scalars': 100, 'histograms': 1} # Initialize lists for collecting the results lst_trn_lss = [None] * len(lst_evnt_trn) lst_val_lss = [None] * len(lst_evnt_trn) lst_trn_acc = [None] * len(lst_evnt_trn) lst_val_acc = [None] * len(lst_evnt_trn) # %% Load data for ind in range(len(lst_evnt_trn)): # Derive paths to training and validation data str_evnt_trn = os.path.join(str_log_path, lst_prj[ind], 'logs', 'train', lst_evnt_trn[ind]) str_evnt_val = os.path.join(str_log_path, lst_prj[ind], 'logs', 'validation', lst_evnt_val[ind]) # Load training and validation loss lst_trn_lss[ind] = func_load_event(str_evnt_trn, tf_size_guidance=tf_size_guidance, name_scalar='epoch_loss') lst_val_lss[ind] = func_load_event(str_evnt_val, tf_size_guidance=tf_size_guidance, name_scalar='epoch_loss') # Load training and validation accuracy lst_trn_acc[ind] = func_load_event(str_evnt_trn, tf_size_guidance=tf_size_guidance, name_scalar='epoch_sparse_categorical_accuracy') lst_val_acc[ind] = func_load_event(str_evnt_val, tf_size_guidance=tf_size_guidance, name_scalar='epoch_sparse_categorical_accuracy') # %% Plot # increase font size sns.set(font_scale=2) # get number of epochs var_num_steps = len(lst_trn_lss[0]) ary_epochs = np.arange(var_num_steps) # initialize data frames df_loss = pd.DataFrame(index=ary_epochs) df_acc = pd.DataFrame(index=ary_epochs) for ind in range(len(lst_evnt_trn)): # add data to pandas loss data frame df_loss['trn_loss'+lst_names[ind]] = lst_trn_lss[ind] df_loss['val_loss'+lst_names[ind]] = lst_val_lss[ind] # add data to pandas loss data frame df_acc['trn_acc'+lst_names[ind]] = lst_trn_acc[ind] df_acc['val_acc'+lst_names[ind]] = lst_val_acc[ind] # plot losses fig, ax = plt.subplots() fig.set_size_inches(17.5, 12.5) sns.lineplot(data=df_loss, palette=lst_colors, dashes=lst_dashes, linewidth=2.5) plt.xlabel("Number of Epochs") plt.ylabel("Loss") ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) fig.savefig("/Users/Marian/Documents/Unet/presentation/results/plots/loss_norm_vs_se_weighted_dr0p20.svg", bbox_inches="tight") fig.savefig("/Users/Marian/Documents/Unet/presentation/results/plots/loss_norm_vs_se_weighted_dr0p20.png", bbox_inches="tight") # plot accuracies fig, ax = plt.subplots() fig.set_size_inches(17.5, 12.5) sns.lineplot(data=df_acc, palette=lst_colors, dashes=lst_dashes, linewidth=2.5) plt.xlabel("Number of Epochs") plt.ylabel("Accuracy") ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) fig.savefig("/Users/Marian/Documents/Unet/presentation/results/plots/accuracy_norm_vs_se_weighted_dr0p20.svg", bbox_inches="tight") fig.savefig("/Users/Marian/Documents/Unet/presentation/results/plots/accuracy_norm_vs_se_weighted_dr0p20.png", bbox_inches="tight")
[ "seaborn.set", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "os.path.join", "seaborn.lineplot", "pandas.DataFrame", "load_tfevents.func_load_event", "matplotlib.pyplot.subplots", "numpy.arange" ]
[((5087, 5108), 'seaborn.set', 'sns.set', ([], {'font_scale': '(2)'}), '(font_scale=2)\n', (5094, 5108), True, 'import seaborn as sns\n'), ((5181, 5205), 'numpy.arange', 'np.arange', (['var_num_steps'], {}), '(var_num_steps)\n', (5190, 5205), True, 'import numpy as np\n'), ((5241, 5271), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'ary_epochs'}), '(index=ary_epochs)\n', (5253, 5271), True, 'import pandas as pd\n'), ((5281, 5311), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'ary_epochs'}), '(index=ary_epochs)\n', (5293, 5311), True, 'import pandas as pd\n'), ((5686, 5700), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5698, 5700), True, 'import matplotlib.pyplot as plt\n'), ((5733, 5818), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'df_loss', 'palette': 'lst_colors', 'dashes': 'lst_dashes', 'linewidth': '(2.5)'}), '(data=df_loss, palette=lst_colors, dashes=lst_dashes, linewidth=2.5\n )\n', (5745, 5818), True, 'import seaborn as sns\n'), ((5827, 5857), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Epochs"""'], {}), "('Number of Epochs')\n", (5837, 5857), True, 'import matplotlib.pyplot as plt\n'), ((5858, 5876), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (5868, 5876), True, 'import matplotlib.pyplot as plt\n'), ((6216, 6230), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (6228, 6230), True, 'import matplotlib.pyplot as plt\n'), ((6263, 6342), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'df_acc', 'palette': 'lst_colors', 'dashes': 'lst_dashes', 'linewidth': '(2.5)'}), '(data=df_acc, palette=lst_colors, dashes=lst_dashes, linewidth=2.5)\n', (6275, 6342), True, 'import seaborn as sns\n'), ((6356, 6386), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Epochs"""'], {}), "('Number of Epochs')\n", (6366, 6386), True, 'import matplotlib.pyplot as plt\n'), ((6387, 6409), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (6397, 6409), True, 'import matplotlib.pyplot as plt\n'), ((3913, 3989), 'os.path.join', 'os.path.join', (['str_log_path', 'lst_prj[ind]', '"""logs"""', '"""train"""', 'lst_evnt_trn[ind]'], {}), "(str_log_path, lst_prj[ind], 'logs', 'train', lst_evnt_trn[ind])\n", (3925, 3989), False, 'import os\n'), ((4041, 4127), 'os.path.join', 'os.path.join', (['str_log_path', 'lst_prj[ind]', '"""logs"""', '"""validation"""', 'lst_evnt_val[ind]'], {}), "(str_log_path, lst_prj[ind], 'logs', 'validation', lst_evnt_val\n [ind])\n", (4053, 4127), False, 'import os\n'), ((4219, 4313), 'load_tfevents.func_load_event', 'func_load_event', (['str_evnt_trn'], {'tf_size_guidance': 'tf_size_guidance', 'name_scalar': '"""epoch_loss"""'}), "(str_evnt_trn, tf_size_guidance=tf_size_guidance,\n name_scalar='epoch_loss')\n", (4234, 4313), False, 'from load_tfevents import func_load_event\n'), ((4411, 4505), 'load_tfevents.func_load_event', 'func_load_event', (['str_evnt_val'], {'tf_size_guidance': 'tf_size_guidance', 'name_scalar': '"""epoch_loss"""'}), "(str_evnt_val, tf_size_guidance=tf_size_guidance,\n name_scalar='epoch_loss')\n", (4426, 4505), False, 'from load_tfevents import func_load_event\n'), ((4647, 4764), 'load_tfevents.func_load_event', 'func_load_event', (['str_evnt_trn'], {'tf_size_guidance': 'tf_size_guidance', 'name_scalar': '"""epoch_sparse_categorical_accuracy"""'}), "(str_evnt_trn, tf_size_guidance=tf_size_guidance,\n name_scalar='epoch_sparse_categorical_accuracy')\n", (4662, 4764), False, 'from load_tfevents import func_load_event\n'), ((4862, 4979), 'load_tfevents.func_load_event', 'func_load_event', (['str_evnt_val'], {'tf_size_guidance': 'tf_size_guidance', 'name_scalar': '"""epoch_sparse_categorical_accuracy"""'}), "(str_evnt_val, tf_size_guidance=tf_size_guidance,\n name_scalar='epoch_sparse_categorical_accuracy')\n", (4877, 4979), False, 'from load_tfevents import func_load_event\n')]
import numpy as np import pandas as pd import xarray as xr import matplotlib import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import os import itertools from scipy.interpolate import griddata if __name__ == "__main__": # # Initialization # matplotlib.rcParams.update({'font.size': 12, 'text.usetex': True}) # gParams (Lx, Ly, Lz) = (21, 21, 21) (dx, dy, dz) = (0.375, 0.375, 0.375) NGridPoints = (1 + 2 * Lx / dx) * (1 + 2 * Ly / dy) * (1 + 2 * Lz / dz) # datapath = '/home/kis/Dropbox/VariationalResearch/HarvardOdyssey/genPol_data/NGridPoints_{:.2E}'.format(NGridPoints) datapath = '/media/kis/Storage/Dropbox/VariationalResearch/HarvardOdyssey/genPol_data/NGridPoints_{:.2E}'.format(NGridPoints) innerdatapath = datapath + '/steadystate_cart' def xinterp2D(xdataset, coord1, coord2, mult): # xdataset is the desired xarray dataset with the desired plotting quantity already selected # coord1 and coord2 are the two coordinates making the 2d plot # mul is the multiplicative factor by which you wish to increase the resolution of the grid # e.g. xdataset = qds['nPI_xz_slice'].sel(P=P,aIBi=aIBi).dropna('PI_z'), coord1 = 'PI_x', coord2 = 'PI_z' # returns meshgrid values for C1_interp and C2_interp as well as the function value on this 2D grid -> these are ready to plot C1 = xdataset.coords[coord1].values C2 = xdataset.coords[coord2].values C1g, C2g = np.meshgrid(C1, C2, indexing='ij') C1_interp = np.linspace(np.min(C1), np.max(C1), mult * C1.size) C2_interp = np.linspace(np.min(C2), np.max(C2), mult * C2.size) C1g_interp, C2g_interp = np.meshgrid(C1_interp, C2_interp, indexing='ij') interp_vals = griddata((C1g.flatten(), C2g.flatten()), xdataset.values.flatten(), (C1g_interp, C2g_interp), method='cubic') return interp_vals, C1g_interp, C2g_interp # # # Concatenate Individual Datasets # ds_list = []; P_list = []; aIBi_list = []; mI_list = [] # for ind, filename in enumerate(os.listdir(innerdatapath)): # if filename == 'quench_Dataset_cart.nc': # continue # print(filename) # with xr.open_dataset(innerdatapath + '/' + filename) as dsf: # ds = dsf.compute() # ds_list.append(ds) # P_list.append(ds.attrs['P']) # aIBi_list.append(ds.attrs['aIBi']) # mI_list.append(ds.attrs['mI']) # s = sorted(zip(aIBi_list, P_list, ds_list)) # g = itertools.groupby(s, key=lambda x: x[0]) # aIBi_keys = []; aIBi_groups = []; aIBi_ds_list = [] # for key, group in g: # aIBi_keys.append(key) # aIBi_groups.append(list(group)) # for ind, group in enumerate(aIBi_groups): # aIBi = aIBi_keys[ind] # _, P_list_temp, ds_list_temp = zip(*group) # ds_temp = xr.concat(ds_list_temp, pd.Index(P_list_temp, name='P')) # aIBi_ds_list.append(ds_temp) # ds_tot = xr.concat(aIBi_ds_list, pd.Index(aIBi_keys, name='aIBi')) # del(ds_tot.attrs['P']); del(ds_tot.attrs['aIBi']); del(ds_tot.attrs['gIB']) # ds_tot.to_netcdf(innerdatapath + '/quench_Dataset_cart.nc') # # Analysis of Total Dataset fig, axes = plt.subplots() qds = xr.open_dataset(innerdatapath + '/quench_Dataset_cart.nc') nu = 0.792665459521 P = 0.8 aIBi = -5 PIm = qds.coords['PI_mag'].values # qds['nPI_mag'].sel(P=P, aIBi=aIBi).dropna('PI_mag').plot(ax=axes, label='') # axes.plot(P * np.ones(PIm.size), np.linspace(0, qds['mom_deltapeak'].sel(P=P, aIBi=-10).values, PIm.size), 'g--', label=r'$\delta$-peak') # axes.plot(nu * np.ones(len(PIm)), np.linspace(0, 1, len(PIm)), 'k:', label=r'$m_{I}\nu$') # axes.set_ylim([0, 1]) # axes.set_title('$P=${:.2f}'.format(P)) # axes.set_xlabel(r'$|P_{I}|$') # axes.set_ylabel(r'$n_{|P_{I}|}$') # axes.legend() # plt.show() qd_slice = qds['nPI_xz_slice'].sel(P=P, aIBi=aIBi).dropna('PI_z') slice_interp, PI_xg_interp, PI_zg_interp = xinterp2D(qd_slice, 'PI_x', 'PI_z', 8) axes.pcolormesh(PI_zg_interp, PI_xg_interp, slice_interp) # axes.pcolormesh(PI_zg, PI_xg, qd_slice.values) # qds['nPI_xz_slice'].sel(P=P, aIBi=aIBi).dropna('PI_z').plot(ax=axes) axes.set_title('Impurity Longitudinal Momentum Distribution ' + r'($a_{IB}^{-1}=$' + '{:.2f}'.format(aIBi) + '$P=${:.2f})'.format(P)) axes.set_ylabel(r'$P_{I,x}$') axes.set_xlabel(r'$P_{I,z}$') axes.set_xlim([-2, 2]) axes.set_ylim([-2, 2]) axes.grid(True, linewidth=0.5) plt.show()
[ "numpy.max", "numpy.min", "numpy.meshgrid", "xarray.open_dataset", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((3279, 3293), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3291, 3293), True, 'import matplotlib.pyplot as plt\n'), ((3304, 3362), 'xarray.open_dataset', 'xr.open_dataset', (["(innerdatapath + '/quench_Dataset_cart.nc')"], {}), "(innerdatapath + '/quench_Dataset_cart.nc')\n", (3319, 3362), True, 'import xarray as xr\n'), ((4609, 4619), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4617, 4619), True, 'import matplotlib.pyplot as plt\n'), ((1501, 1535), 'numpy.meshgrid', 'np.meshgrid', (['C1', 'C2'], {'indexing': '"""ij"""'}), "(C1, C2, indexing='ij')\n", (1512, 1535), True, 'import numpy as np\n'), ((1714, 1762), 'numpy.meshgrid', 'np.meshgrid', (['C1_interp', 'C2_interp'], {'indexing': '"""ij"""'}), "(C1_interp, C2_interp, indexing='ij')\n", (1725, 1762), True, 'import numpy as np\n'), ((1569, 1579), 'numpy.min', 'np.min', (['C1'], {}), '(C1)\n', (1575, 1579), True, 'import numpy as np\n'), ((1581, 1591), 'numpy.max', 'np.max', (['C1'], {}), '(C1)\n', (1587, 1591), True, 'import numpy as np\n'), ((1641, 1651), 'numpy.min', 'np.min', (['C2'], {}), '(C2)\n', (1647, 1651), True, 'import numpy as np\n'), ((1653, 1663), 'numpy.max', 'np.max', (['C2'], {}), '(C2)\n', (1659, 1663), True, 'import numpy as np\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable INITRANGE = 0.04 SOS_ID = 0 EOS_ID = 0 class Attention(nn.Module): def __init__(self, dim): super(Attention, self).__init__() self.linear_out = nn.Linear(dim * 2, dim) self.mask = None def set_mask(self, mask): self.mask = mask def forward(self, output, context): batch_size = output.size(0) hidden_size = output.size(2) input_size = context.size(1) # (batch, out_len, dim) * (batch, in_len, dim) -> (batch, out_len, in_len) attn = torch.bmm(output, context.transpose(1, 2)) if self.mask is not None: attn.data.masked_fill_(self.mask, -float('inf')) attn = F.softmax(attn.view(-1, input_size), dim=1).view(batch_size, -1, input_size) # (batch, out_len, in_len) * (batch, in_len, dim) -> (batch, out_len, dim) mix = torch.bmm(attn, context) # concat -> (batch, out_len, 2*dim) combined = torch.cat((mix, output), dim=2) # output -> (batch, out_len, dim) output = F.tanh(self.linear_out(combined.view(-1, 2 * hidden_size))).view(batch_size, -1, hidden_size) return output, attn class Decoder(nn.Module): KEY_ATTN_SCORE = 'attention_score' KEY_LENGTH = 'length' KEY_SEQUENCE = 'sequence' def __init__(self, params): super(Decoder, self).__init__() self.num_layers = params['decoder_num_layers'] self.hidden_size = params['decoder_hidden_size'] self.decoder_length = params['num_intermediate_nodes'] * 2 self.source_length = params['num_intermediate_nodes'] * 2 self.vocab_size = params['num_intermediate_nodes'] + params['num_operations'] + 1 self.dropout_p = params['decoder_dropout'] self.num_intermediate_nodes = params['num_intermediate_nodes'] self.dropout = nn.Dropout(p=self.dropout_p) self.rnn = nn.LSTM(self.hidden_size, self.hidden_size, self.num_layers, batch_first=True, dropout=self.dropout_p) self.sos_id = SOS_ID self.eos_id = EOS_ID self.init_input = None self.embedding = nn.Embedding(self.vocab_size, self.hidden_size) self.attention = Attention(self.hidden_size) self.out = nn.Linear(self.hidden_size, self.vocab_size) def forward_step(self, x, hidden, encoder_outputs, function): batch_size = x.size(0) output_size = x.size(1) embedded = self.embedding(x) embedded = self.dropout(embedded) output, hidden = self.rnn(embedded, hidden) output, attn = self.attention(output, encoder_outputs) predicted_softmax = function(self.out(output.contiguous().view(-1, self.hidden_size)), dim=1).view(batch_size, output_size, -1) return predicted_softmax, hidden, attn def forward(self, x, encoder_hidden=None, encoder_outputs=None, function=F.log_softmax): ret_dict = dict() ret_dict[Decoder.KEY_ATTN_SCORE] = list() if x is None: inference = True else: inference = False x, batch_size, length = self._validate_args(x, encoder_hidden, encoder_outputs) assert length == self.decoder_length decoder_hidden = self._init_state(encoder_hidden) decoder_outputs = [] sequence_symbols = [] lengths = np.array([length] * batch_size) def decode(step, step_output, step_attn, num_intermediate_nodes): decoder_outputs.append(step_output) ret_dict[Decoder.KEY_ATTN_SCORE].append(step_attn) if step % 2 == 0: # sample index, should be in [1, step+1] symbols = decoder_outputs[-1][:, 1:step // 2 + 2].topk(1)[1] + 1 else: # sample operation, should be in [12, 15] symbols = decoder_outputs[-1][:, num_intermediate_nodes + 1:].topk(1)[1] + num_intermediate_nodes+1 sequence_symbols.append(symbols) eos_batches = symbols.data.eq(self.eos_id) if eos_batches.dim() > 0: eos_batches = eos_batches.cpu().view(-1).numpy() update_idx = ((lengths > step) & eos_batches) != 0 lengths[update_idx] = len(sequence_symbols) return symbols decoder_input = x[:, 0].unsqueeze(1) for di in range(length): if not inference: decoder_input = x[:, di].unsqueeze(1) decoder_output, decoder_hidden, step_attn = self.forward_step(decoder_input, decoder_hidden, encoder_outputs, function=function) step_output = decoder_output.squeeze(1) symbols = decode(di, step_output, step_attn, self.num_intermediate_nodes) decoder_input = symbols ret_dict[Decoder.KEY_SEQUENCE] = sequence_symbols ret_dict[Decoder.KEY_LENGTH] = lengths.tolist() return decoder_outputs, decoder_hidden, ret_dict def _init_state(self, encoder_hidden): """ Initialize the encoder hidden state. """ if encoder_hidden is None: return None if isinstance(encoder_hidden, tuple): encoder_hidden = tuple([h for h in encoder_hidden]) else: encoder_hidden = encoder_hidden return encoder_hidden def _validate_args(self, x, encoder_hidden, encoder_outputs): if encoder_outputs is None: raise ValueError("Argument encoder_outputs cannot be None when attention is used.") # inference batch size if x is None and encoder_hidden is None: batch_size = 1 else: if x is not None: batch_size = x.size(0) else: batch_size = encoder_hidden[0].size(1) # set default input and max decoding length if x is None: x = Variable(torch.LongTensor([self.sos_id] * batch_size).view(batch_size, 1)) if torch.cuda.is_available(): x = x.cuda() max_length = self.decoder_length else: max_length = x.size(1) return x, batch_size, max_length def eval(self): return def infer(self, x, encoder_hidden=None, encoder_outputs=None): decoder_outputs, decoder_hidden, _ = self(x, encoder_hidden, encoder_outputs) return decoder_outputs, decoder_hidden
[ "torch.nn.Dropout", "torch.nn.Embedding", "torch.nn.LSTM", "torch.LongTensor", "numpy.array", "torch.cuda.is_available", "torch.nn.Linear", "torch.bmm", "torch.cat" ]
[((414, 437), 'torch.nn.Linear', 'nn.Linear', (['(dim * 2)', 'dim'], {}), '(dim * 2, dim)\n', (423, 437), True, 'import torch.nn as nn\n'), ((1096, 1120), 'torch.bmm', 'torch.bmm', (['attn', 'context'], {}), '(attn, context)\n', (1105, 1120), False, 'import torch\n'), ((1185, 1216), 'torch.cat', 'torch.cat', (['(mix, output)'], {'dim': '(2)'}), '((mix, output), dim=2)\n', (1194, 1216), False, 'import torch\n'), ((2075, 2103), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'self.dropout_p'}), '(p=self.dropout_p)\n', (2085, 2103), True, 'import torch.nn as nn\n'), ((2123, 2230), 'torch.nn.LSTM', 'nn.LSTM', (['self.hidden_size', 'self.hidden_size', 'self.num_layers'], {'batch_first': '(True)', 'dropout': 'self.dropout_p'}), '(self.hidden_size, self.hidden_size, self.num_layers, batch_first=\n True, dropout=self.dropout_p)\n', (2130, 2230), True, 'import torch.nn as nn\n'), ((2367, 2414), 'torch.nn.Embedding', 'nn.Embedding', (['self.vocab_size', 'self.hidden_size'], {}), '(self.vocab_size, self.hidden_size)\n', (2379, 2414), True, 'import torch.nn as nn\n'), ((2487, 2531), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_size', 'self.vocab_size'], {}), '(self.hidden_size, self.vocab_size)\n', (2496, 2531), True, 'import torch.nn as nn\n'), ((3787, 3818), 'numpy.array', 'np.array', (['([length] * batch_size)'], {}), '([length] * batch_size)\n', (3795, 3818), True, 'import numpy as np\n'), ((6491, 6516), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6514, 6516), False, 'import torch\n'), ((6410, 6454), 'torch.LongTensor', 'torch.LongTensor', (['([self.sos_id] * batch_size)'], {}), '([self.sos_id] * batch_size)\n', (6426, 6454), False, 'import torch\n')]
import numpy as np import argparse from csv import reader eps = 1e-8 # Probability density function of multivariate_normal for d dimensions where d > 1 def pdf(x, mean, cov): cl = (1 / ((np.linalg.det(cov) + eps) ** 0.5) * ((np.pi * 2) ** (cov.shape[0] / 2))) x_mu = (x - mean) e = np.sqrt(np.sum(np.square(np.matmul(np.matmul(x_mu, np.linalg.pinv(cov)), x_mu.T)), axis=-1)) ans = cl * np.exp((-1 / 2) * e) return ans class GMM: def __init__(self, k=1): self.k = k # Initialise weight vector self.w = np.ones(k) / k self.means = None self.cov = None def fit(self, x): x = np.array(x) self.means = np.random.choice(x.flatten(), (self.k, x.shape[1])) cov = [] for i in range(self.k): cov.append(np.cov(x, rowvar=False)) cov = np.array(cov) for step in range(55): # Expectation step: estimating the values of latent variables probabilities = [] for j in range(self.k): probabilities.append(pdf(x=x, mean=self.means[j], cov=cov[j]) + eps) probabilities = np.array(probabilities) # Maximization step: update mean, covariance and weights for j in range(self.k): # Bayes' Theorem b = ((probabilities[j] * self.w[j]) / ( np.sum([probabilities[i] * self.w[i] for i in range(self.k)], axis=0) + eps)) # update mean, covariance and weights to maximize b self.means[j] = np.sum(b.reshape(len(x), 1) * x, axis=0) / (np.sum(b + eps)) cov[j] = np.dot((b.reshape(len(x), 1) * (x - self.means[j])).T, (x - self.means[j])) / ( np.sum(b) + eps) self.w[j] = np.mean(b) self.cov = cov def prob(self, x): x = np.array(x) p = 0 for j in range(self.k): # calculate probability of each component and add all of them p += self.w[j] * pdf(x=x, mean=self.means[j], cov=self.cov[j]) return p def load_csv(inp_file): dataset = [] with open(inp_file, 'r') as file: csv_reader = reader(file) for data_row in csv_reader: dataset.append(data_row) return dataset parser = argparse.ArgumentParser() parser.add_argument('--components', help='components 1|3|4', required=True) parser.add_argument('--train', help='path to training data file', required=True) parser.add_argument('--test', help='path to test data file', required=True) args = vars(parser.parse_args()) k = int(args['components']) train_data = load_csv(args['train']) train_datas = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], } # Split data digit wise for row in train_data: y = int(row[64]) train_datas[y].append([float(x.strip()) for x in row[:-1]]) gmms = [] # Train GMM for each digit giving is 10 probability functions for i in range(10): gmm = GMM(k) gmm.fit(train_datas[i]) gmms.append(gmm) print('trained') test_data = load_csv(args['test']) preds = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], } # Test for row in test_data: y_act = int(row[64]) max_p = float('-inf') y_pred = -1 # Calculate the probability that the given x may correspond to a digit for all digits for idx in range(len(gmms)): p = gmms[idx].prob([float(x.strip()) for x in row[:-1]]) # select the digit with maximum probability if np.sum(p) > max_p: y_pred = idx max_p = np.sum(p) if y_pred == -1: print('never') accu = 0 if y_act == y_pred: accu = 1 # Save prediction according to digit preds[y_act].append(accu) total = 0 for idx in range(len(preds)): sum = np.sum(np.array(preds[idx])) print(f'{idx}: {(sum * 100) / len(preds[idx])}') total += sum print(f'total: {(total / len(test_data)) * 100}')
[ "numpy.mean", "numpy.ones", "argparse.ArgumentParser", "numpy.linalg.pinv", "numpy.linalg.det", "numpy.exp", "numpy.array", "numpy.sum", "numpy.cov", "csv.reader" ]
[((2320, 2345), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2343, 2345), False, 'import argparse\n'), ((405, 423), 'numpy.exp', 'np.exp', (['(-1 / 2 * e)'], {}), '(-1 / 2 * e)\n', (411, 423), True, 'import numpy as np\n'), ((654, 665), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (662, 665), True, 'import numpy as np\n'), ((851, 864), 'numpy.array', 'np.array', (['cov'], {}), '(cov)\n', (859, 864), True, 'import numpy as np\n'), ((1878, 1889), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1886, 1889), True, 'import numpy as np\n'), ((2204, 2216), 'csv.reader', 'reader', (['file'], {}), '(file)\n', (2210, 2216), False, 'from csv import reader\n'), ((3926, 3946), 'numpy.array', 'np.array', (['preds[idx]'], {}), '(preds[idx])\n', (3934, 3946), True, 'import numpy as np\n'), ((554, 564), 'numpy.ones', 'np.ones', (['k'], {}), '(k)\n', (561, 564), True, 'import numpy as np\n'), ((1151, 1174), 'numpy.array', 'np.array', (['probabilities'], {}), '(probabilities)\n', (1159, 1174), True, 'import numpy as np\n'), ((3625, 3634), 'numpy.sum', 'np.sum', (['p'], {}), '(p)\n', (3631, 3634), True, 'import numpy as np\n'), ((3689, 3698), 'numpy.sum', 'np.sum', (['p'], {}), '(p)\n', (3695, 3698), True, 'import numpy as np\n'), ((812, 835), 'numpy.cov', 'np.cov', (['x'], {'rowvar': '(False)'}), '(x, rowvar=False)\n', (818, 835), True, 'import numpy as np\n'), ((1807, 1817), 'numpy.mean', 'np.mean', (['b'], {}), '(b)\n', (1814, 1817), True, 'import numpy as np\n'), ((194, 212), 'numpy.linalg.det', 'np.linalg.det', (['cov'], {}), '(cov)\n', (207, 212), True, 'import numpy as np\n'), ((1616, 1631), 'numpy.sum', 'np.sum', (['(b + eps)'], {}), '(b + eps)\n', (1622, 1631), True, 'import numpy as np\n'), ((348, 367), 'numpy.linalg.pinv', 'np.linalg.pinv', (['cov'], {}), '(cov)\n', (362, 367), True, 'import numpy as np\n'), ((1762, 1771), 'numpy.sum', 'np.sum', (['b'], {}), '(b)\n', (1768, 1771), True, 'import numpy as np\n')]
from __future__ import print_function import os import argparse import torch import torch.backends.cudnn as cudnn import numpy as np from data import cfg from layers.functions.prior_box import PriorBox from utils.nms_wrapper import nms #from utils.nms.py_cpu_nms import py_cpu_nms import cv2 from models.faceboxes import FaceBoxes from utils.box_utils import decode from utils.timer import Timer def check_keys(model, pretrained_state_dict): ckpt_keys = set(pretrained_state_dict.keys()) model_keys = set(model.state_dict().keys()) used_pretrained_keys = model_keys & ckpt_keys unused_pretrained_keys = ckpt_keys - model_keys missing_keys = model_keys - ckpt_keys print('Missing keys:{}'.format(len(missing_keys))) print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys))) print('Used keys:{}'.format(len(used_pretrained_keys))) assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint' return True def remove_prefix(state_dict, prefix): ''' Old style model is stored with all names of parameters sharing common prefix 'module.' ''' print('remove prefix \'{}\''.format(prefix)) f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x return {f(key): value for key, value in state_dict.items()} def load_model(model, pretrained_path, load_to_cpu): print('Loading pretrained model from {}'.format(pretrained_path)) if load_to_cpu: pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage) else: device = torch.cuda.current_device() pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device)) if "state_dict" in pretrained_dict.keys(): pretrained_dict = remove_prefix(pretrained_dict['state_dict'], 'module.') else: pretrained_dict = remove_prefix(pretrained_dict, 'module.') check_keys(model, pretrained_dict) model.load_state_dict(pretrained_dict, strict=False) return model weightfile = 'FaceBoxes_epoch_90.pth' cpu=False confidenceTh = 0.05 nmsTh = 0.3 keepTopK=750 top_k = 5000 os.environ['CUDA_VISIBLE_DEVICES']='1' torch.set_grad_enabled(False) # net and model net = FaceBoxes(phase='test', size=None, num_classes=2) # initialize detector net = load_model(net, weightfile, cpu) net.eval() #print('Finished loading model!') #print(net) cudnn.benchmark = True device = torch.device("cpu" if cpu else "cuda") net = net.to(device) image_path = 'danbooru2018/original/0795/1081795.jpg' imgOrig = cv2.imread(image_path, cv2.IMREAD_COLOR) img=np.float32(imgOrig) im_height, im_width, _ = img.shape scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]]) img -= (104, 117, 123) img = img.transpose(2, 0, 1) img = torch.from_numpy(img).unsqueeze(0) img = img.to(device) scale = scale.to(device) loc, conf = net(img) # forward pass priorbox = PriorBox(cfg, image_size=(im_height, im_width)) priors = priorbox.forward() priors = priors.to(device) prior_data = priors.data boxes = decode(loc.data.squeeze(0), prior_data, cfg['variance']) boxes = boxes * scale boxes = boxes.cpu().numpy() scores = conf.data.cpu().numpy()[:, 1] # ignore low scores inds = np.where(scores > confidenceTh)[0] boxes = boxes[inds] scores = scores[inds] # keep top-K before NMS order = scores.argsort()[::-1][:top_k] boxes = boxes[order] scores = scores[order] # do NMS dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False) #keep = py_cpu_nms(dets, args.nms_threshold) keep = nms(dets, nmsTh,force_cpu=cpu) dets = dets[keep, :] # keep top-K faster NMS dets = dets[:keepTopK, :] for k in range(dets.shape[0]): xmin = dets[k, 0] ymin = dets[k, 1] xmax = dets[k, 2] ymax = dets[k, 3] ymin += 0.2 * (ymax - ymin + 1) score = dets[k, 4] print('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.format(image_path, score, xmin, ymin, xmax, ymax)) cv2.rectangle(imgOrig, (int(xmin), int(ymin)), (int(xmax), int(ymax)), (0, 0, 255), 15) cv2.imwrite('out.png', imgOrig)
[ "cv2.imwrite", "models.faceboxes.FaceBoxes", "numpy.hstack", "numpy.where", "torch.load", "torch.Tensor", "torch.from_numpy", "utils.nms_wrapper.nms", "torch.cuda.current_device", "torch.set_grad_enabled", "layers.functions.prior_box.PriorBox", "cv2.imread", "numpy.float32", "torch.device"...
[((2169, 2198), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (2191, 2198), False, 'import torch\n'), ((2221, 2270), 'models.faceboxes.FaceBoxes', 'FaceBoxes', ([], {'phase': '"""test"""', 'size': 'None', 'num_classes': '(2)'}), "(phase='test', size=None, num_classes=2)\n", (2230, 2270), False, 'from models.faceboxes import FaceBoxes\n'), ((2424, 2462), 'torch.device', 'torch.device', (["('cpu' if cpu else 'cuda')"], {}), "('cpu' if cpu else 'cuda')\n", (2436, 2462), False, 'import torch\n'), ((2549, 2589), 'cv2.imread', 'cv2.imread', (['image_path', 'cv2.IMREAD_COLOR'], {}), '(image_path, cv2.IMREAD_COLOR)\n', (2559, 2589), False, 'import cv2\n'), ((2594, 2613), 'numpy.float32', 'np.float32', (['imgOrig'], {}), '(imgOrig)\n', (2604, 2613), True, 'import numpy as np\n'), ((2657, 2727), 'torch.Tensor', 'torch.Tensor', (['[img.shape[1], img.shape[0], img.shape[1], img.shape[0]]'], {}), '([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])\n', (2669, 2727), False, 'import torch\n'), ((2916, 2963), 'layers.functions.prior_box.PriorBox', 'PriorBox', (['cfg'], {'image_size': '(im_height, im_width)'}), '(cfg, image_size=(im_height, im_width))\n', (2924, 2963), False, 'from layers.functions.prior_box import PriorBox\n'), ((3553, 3584), 'utils.nms_wrapper.nms', 'nms', (['dets', 'nmsTh'], {'force_cpu': 'cpu'}), '(dets, nmsTh, force_cpu=cpu)\n', (3556, 3584), False, 'from utils.nms_wrapper import nms\n'), ((4034, 4065), 'cv2.imwrite', 'cv2.imwrite', (['"""out.png"""', 'imgOrig'], {}), "('out.png', imgOrig)\n", (4045, 4065), False, 'import cv2\n'), ((3226, 3257), 'numpy.where', 'np.where', (['(scores > confidenceTh)'], {}), '(scores > confidenceTh)\n', (3234, 3257), True, 'import numpy as np\n'), ((1466, 1536), 'torch.load', 'torch.load', (['pretrained_path'], {'map_location': '(lambda storage, loc: storage)'}), '(pretrained_path, map_location=lambda storage, loc: storage)\n', (1476, 1536), False, 'import torch\n'), ((1564, 1591), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (1589, 1591), False, 'import torch\n'), ((2786, 2807), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (2802, 2807), False, 'import torch\n'), ((3428, 3469), 'numpy.hstack', 'np.hstack', (['(boxes, scores[:, np.newaxis])'], {}), '((boxes, scores[:, np.newaxis]))\n', (3437, 3469), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np import sys def show_log(log): tr = [] ev = [] mb = [] last_t = 0 with open(log) as log_file: for line in log_file.readlines(): tokens = line.split('\t') if tokens[0] == 'train': tr.append([last_t, *[float(t) for t in tokens[1:]]]) elif tokens[0] == 'eval': ev.append([last_t, *[float(t) for t in tokens[1:]]]) elif len(tokens) > 0: last_t = int(tokens[0]) mb.append([last_t, *[float(t) for t in tokens[1:-1]]]) tr = np.array(tr).T ev = np.array(ev).T mb = np.array(mb).T _, ax = plt.subplots(2, 2) ax[0, 0].set_title('Loss') ax[0, 0].plot(tr[0], tr[1], label='Train') ax[0, 0].plot(ev[0], ev[1], label='Eval') ax[0, 0].grid() ax[0, 0].legend() ax[0, 1].set_title('Partial losses') ax[0, 1].plot(tr[0], tr[2], label='Train detection') ax[0, 1].plot(tr[0], tr[3], label='Train localization') ax[0, 1].plot(tr[0], tr[4], label='Train classification') ax[0, 1].plot(ev[0], ev[2], label='Eval detection') ax[0, 1].plot(ev[0], ev[3], label='Eval localization') ax[0, 1].plot(ev[0], ev[4], label='Eval classification') ax[0, 1].grid() ax[0, 1].legend() ax[1, 1].set_title('Detection') ax[1, 1].plot(tr[0], tr[6], label='Train TP rate') ax[1, 1].plot(ev[0], ev[6], label='Eval TP rate') ax[1, 1].plot(tr[0], tr[7], label='Train FP rate') ax[1, 1].plot(ev[0], ev[7], label='Eval FP rate') ax[1, 1].grid() ax[1, 1].legend() ax[1, 0].set_title('Classification') ax[1, 0].plot(tr[0], tr[9], label='Train') ax[1, 0].plot(ev[0], ev[9], label='Eval') ax[1, 0].grid() ax[1, 0].legend() plt.show() plt.title('Train loss with minibatches loss') plt.plot(np.max(mb[0].reshape([-1, 8]), axis=-1), np.mean(mb[2].reshape([-1, 8]), axis=-1), label='Train loss') plt.plot(tr[0], tr[1], label='Minibatch loss (avg by 8)') plt.legend() plt.show() fig, ax = plt.subplots(1, 2) ax[0].plot(tr[7], tr[6], zorder=1, alpha=0.5) ax[0].scatter(tr[7], tr[6], c=tr[0], zorder=2) ax[0].set_xlabel('Train FP rate') ax[0].set_xlim([0, 1]) ax[0].set_ylabel('Train TP rate') ax[0].set_ylim([0, 1]) ax[0].set_aspect('equal') ax[1].plot(ev[7], ev[6], zorder=1, alpha=0.5) ax[1].scatter(ev[7], ev[6], c=tr[0], zorder=2) ax[1].set_xlabel('Eval FP rate') ax[1].set_xlim([0, 1]) ax[1].set_ylabel('Eval TP rate') ax[1].set_ylim([0, 1]) ax[1].set_aspect('equal') plt.show() if __name__ == '__main__': show_log(sys.argv[1])
[ "matplotlib.pyplot.plot", "numpy.array", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((692, 710), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {}), '(2, 2)\n', (704, 710), True, 'import matplotlib.pyplot as plt\n'), ((1799, 1809), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1807, 1809), True, 'import matplotlib.pyplot as plt\n'), ((1815, 1860), 'matplotlib.pyplot.title', 'plt.title', (['"""Train loss with minibatches loss"""'], {}), "('Train loss with minibatches loss')\n", (1824, 1860), True, 'import matplotlib.pyplot as plt\n'), ((1981, 2038), 'matplotlib.pyplot.plot', 'plt.plot', (['tr[0]', 'tr[1]'], {'label': '"""Minibatch loss (avg by 8)"""'}), "(tr[0], tr[1], label='Minibatch loss (avg by 8)')\n", (1989, 2038), True, 'import matplotlib.pyplot as plt\n'), ((2043, 2055), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2053, 2055), True, 'import matplotlib.pyplot as plt\n'), ((2060, 2070), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2068, 2070), True, 'import matplotlib.pyplot as plt\n'), ((2087, 2105), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {}), '(1, 2)\n', (2099, 2105), True, 'import matplotlib.pyplot as plt\n'), ((2636, 2646), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2644, 2646), True, 'import matplotlib.pyplot as plt\n'), ((616, 628), 'numpy.array', 'np.array', (['tr'], {}), '(tr)\n', (624, 628), True, 'import numpy as np\n'), ((640, 652), 'numpy.array', 'np.array', (['ev'], {}), '(ev)\n', (648, 652), True, 'import numpy as np\n'), ((664, 676), 'numpy.array', 'np.array', (['mb'], {}), '(mb)\n', (672, 676), True, 'import numpy as np\n')]
import torch.utils.data as data import torch from .human_parse_labels import get_label_map from PIL import Image import numpy as np import cv2 import torchvision.transforms as transforms import torch import copy, os, collections import json import random def listdir(root): all_fns = [] for fn in os.listdir(root): curr_root = os.path.join(root, fn) if os.path.isdir(curr_root): curr_all_fns = listdir(curr_root) all_fns += [os.path.join(fn, item) for item in curr_all_fns] else: all_fns += [fn] return all_fns def create_texsyn_dataset(opt, isTrain=True): normalize = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) train_transform = transforms.Compose([ transforms.Resize((296, 200)), transforms.RandomCrop((opt.crop_size)), # transforms.RandomResizedCrop(opt.crop_size), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize ]) test_transform = transforms.Compose([ transforms.Resize(opt.crop_size), transforms.ToTensor(), normalize, ]) dataset = TextureDataset(dataroot=opt.dataroot, isTrain=isTrain, transform=train_transform if isTrain else test_transform) return dataset class TextureDataset(data.Dataset): def __init__(self, dataroot, isTrain=True, transform=None): self.mask_dir = os.path.join(dataroot, "keypoints_heatmaps") self.isTrain = isTrain # if self.isTrain: self.tex_dir = os.path.join(dataroot, 'dtd/%s' % ("train" if isTrain else "test")) self.all_tex = [img for img in listdir(self.tex_dir) if img.endswith('.jpg') or img.endswith('.png')] # mask self.aiyu2atr, self.atr2aiyu = get_label_map(n_human_part=4) # transforms self.transform = transform def _load_img(self, fn): img = Image.open(fn).convert("RGB") img = self.transform(img) return img def __len__(self): if self.isTrain: return 101966 return len(self.all_tex) def __getitem__(self, index): tex_fn = self.all_tex[index % len(self.tex_dir)] tex = self._load_img(os.path.join(self.tex_dir, tex_fn)) return tex class TexSynDataset(data.Dataset): def __init__(self, dataroot, isTrain=True, crop_size=(256, 256)): self.mask_dir = os.path.join(dataroot, "keypoints_heatmaps") self.isTrain = isTrain if self.isTrain: self.all_masks = [ann + ".png" for ann in self._load_anns(dataroot)] self.tex_dir = os.path.join(dataroot, 'dtd/images') self.all_tex = [img for img in listdir(self.tex_dir) if img.endswith('.jpg') or img.endswith('.png')] else: self.all_masks = [ann + ".png" for ann in self._load_anns(dataroot, False)] self.tex_dir = os.path.join(dataroot, "keypoints_heatmaps") self.all_tex = [ann + ".jpg" for ann in self._load_anns(dataroot, False)] # mask self.aiyu2atr, self.atr2aiyu = get_label_map(n_human_part=4) # transforms self.crop_size=crop_size self.resize = transforms.Resize(self.crop_size) self.toTensor = transforms.ToTensor() self.normalize = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) def _load_anns(self, dataroot, isTrain=True): if isTrain: tmp_fn = "gan_same1_train_pairs.txt" tmp_fn = "Anno/train_pairs.txt"#"Anno/train_pairs.txt" with open(os.path.join(dataroot, tmp_fn), "r") as f: anns = f.readlines() print("[dataset] load %d data from train split" % len(anns)) else: tmp_fn = "Anno/test_pairs.txt" with open(os.path.join(dataroot, tmp_fn), "r") as f: anns = f.readlines() print("[dataset] load %d data from test split" % len(anns)) anns = [ann.split(',')[0] for ann in anns] return anns def _load_img(self, fn): img = Image.open(fn).convert("RGB") img = self.resize(img) img = self.toTensor(img) img = self.normalize(img) return img def _load_mask(self, fn): mask = Image.open(fn) mask = self.resize(mask) mask = torch.from_numpy(np.array(mask)) texture_mask = copy.deepcopy(mask) for atr in self.atr2aiyu: aiyu = self.atr2aiyu[atr] texture_mask[texture_mask == atr] = aiyu return texture_mask def __len__(self): return len(self.all_masks) def __getitem__(self, index): tex_fn = self.all_tex[index % len(self.all_tex)] mask_fn = self.all_masks[index] tex = self._load_img(os.path.join(self.tex_dir, tex_fn)) mask = self._load_mask(os.path.join(self.mask_dir, mask_fn)) i = random.randint(0,3) mask = (mask == i).long().unsqueeze(0) return tex * mask, tex, mask
[ "os.listdir", "PIL.Image.open", "os.path.join", "torchvision.transforms.RandomHorizontalFlip", "torchvision.transforms.RandomCrop", "numpy.array", "os.path.isdir", "torchvision.transforms.Normalize", "copy.deepcopy", "torchvision.transforms.Resize", "torchvision.transforms.ToTensor", "random.r...
[((306, 322), 'os.listdir', 'os.listdir', (['root'], {}), '(root)\n', (316, 322), False, 'import copy, os, collections\n'), ((648, 702), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5, 0.5, 0.5)', '(0.5, 0.5, 0.5)'], {}), '((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n', (668, 702), True, 'import torchvision.transforms as transforms\n'), ((344, 366), 'os.path.join', 'os.path.join', (['root', 'fn'], {}), '(root, fn)\n', (356, 366), False, 'import copy, os, collections\n'), ((378, 402), 'os.path.isdir', 'os.path.isdir', (['curr_root'], {}), '(curr_root)\n', (391, 402), False, 'import copy, os, collections\n'), ((1499, 1543), 'os.path.join', 'os.path.join', (['dataroot', '"""keypoints_heatmaps"""'], {}), "(dataroot, 'keypoints_heatmaps')\n", (1511, 1543), False, 'import copy, os, collections\n'), ((1625, 1692), 'os.path.join', 'os.path.join', (['dataroot', "('dtd/%s' % ('train' if isTrain else 'test'))"], {}), "(dataroot, 'dtd/%s' % ('train' if isTrain else 'test'))\n", (1637, 1692), False, 'import copy, os, collections\n'), ((2528, 2572), 'os.path.join', 'os.path.join', (['dataroot', '"""keypoints_heatmaps"""'], {}), "(dataroot, 'keypoints_heatmaps')\n", (2540, 2572), False, 'import copy, os, collections\n'), ((3327, 3360), 'torchvision.transforms.Resize', 'transforms.Resize', (['self.crop_size'], {}), '(self.crop_size)\n', (3344, 3360), True, 'import torchvision.transforms as transforms\n'), ((3385, 3406), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3404, 3406), True, 'import torchvision.transforms as transforms\n'), ((3432, 3486), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5, 0.5, 0.5)', '(0.5, 0.5, 0.5)'], {}), '((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n', (3452, 3486), True, 'import torchvision.transforms as transforms\n'), ((4413, 4427), 'PIL.Image.open', 'Image.open', (['fn'], {}), '(fn)\n', (4423, 4427), False, 'from PIL import Image\n'), ((4541, 4560), 'copy.deepcopy', 'copy.deepcopy', (['mask'], {}), '(mask)\n', (4554, 4560), False, 'import copy, os, collections\n'), ((5064, 5084), 'random.randint', 'random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (5078, 5084), False, 'import random\n'), ((763, 792), 'torchvision.transforms.Resize', 'transforms.Resize', (['(296, 200)'], {}), '((296, 200))\n', (780, 792), True, 'import torchvision.transforms as transforms\n'), ((810, 846), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['opt.crop_size'], {}), '(opt.crop_size)\n', (831, 846), True, 'import torchvision.transforms as transforms\n'), ((930, 963), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (961, 963), True, 'import torchvision.transforms as transforms\n'), ((981, 1002), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1000, 1002), True, 'import torchvision.transforms as transforms\n'), ((1104, 1136), 'torchvision.transforms.Resize', 'transforms.Resize', (['opt.crop_size'], {}), '(opt.crop_size)\n', (1121, 1136), True, 'import torchvision.transforms as transforms\n'), ((1154, 1175), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1173, 1175), True, 'import torchvision.transforms as transforms\n'), ((2330, 2364), 'os.path.join', 'os.path.join', (['self.tex_dir', 'tex_fn'], {}), '(self.tex_dir, tex_fn)\n', (2342, 2364), False, 'import copy, os, collections\n'), ((2737, 2773), 'os.path.join', 'os.path.join', (['dataroot', '"""dtd/images"""'], {}), "(dataroot, 'dtd/images')\n", (2749, 2773), False, 'import copy, os, collections\n'), ((3018, 3062), 'os.path.join', 'os.path.join', (['dataroot', '"""keypoints_heatmaps"""'], {}), "(dataroot, 'keypoints_heatmaps')\n", (3030, 3062), False, 'import copy, os, collections\n'), ((4493, 4507), 'numpy.array', 'np.array', (['mask'], {}), '(mask)\n', (4501, 4507), True, 'import numpy as np\n'), ((4947, 4981), 'os.path.join', 'os.path.join', (['self.tex_dir', 'tex_fn'], {}), '(self.tex_dir, tex_fn)\n', (4959, 4981), False, 'import copy, os, collections\n'), ((5014, 5050), 'os.path.join', 'os.path.join', (['self.mask_dir', 'mask_fn'], {}), '(self.mask_dir, mask_fn)\n', (5026, 5050), False, 'import copy, os, collections\n'), ((474, 496), 'os.path.join', 'os.path.join', (['fn', 'item'], {}), '(fn, item)\n', (486, 496), False, 'import copy, os, collections\n'), ((2004, 2018), 'PIL.Image.open', 'Image.open', (['fn'], {}), '(fn)\n', (2014, 2018), False, 'from PIL import Image\n'), ((4215, 4229), 'PIL.Image.open', 'Image.open', (['fn'], {}), '(fn)\n', (4225, 4229), False, 'from PIL import Image\n'), ((3704, 3734), 'os.path.join', 'os.path.join', (['dataroot', 'tmp_fn'], {}), '(dataroot, tmp_fn)\n', (3716, 3734), False, 'import copy, os, collections\n'), ((3936, 3966), 'os.path.join', 'os.path.join', (['dataroot', 'tmp_fn'], {}), '(dataroot, tmp_fn)\n', (3948, 3966), False, 'import copy, os, collections\n')]
import sys import logging from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import numpy as NP import pandas as PD from obspy.core.stream import Stream from obspy.core.utcdatetime import UTCDateTime from obspy.core.trace import Trace from fgm2iaga import parse from iaga2hdf import get_dec_tenths_arcminute, write_hdf logger = logging.getLogger('pyrsss.mat.fgm2hdf') def build_header(data_list, keys=[('geodetic_latitude', 'lat'), ('geodetic_longitude', 'lon'), ('station', 'siteid')], elevation=None, baseline_declination=None): """ Build and return meta information mapping based on information in *data_list* with *keys*, *elevation*, and *baseline_declination* (the baseline declination, determined from IGRF if not specified). """ header = {} for key, search_key in keys: values = set([getattr(x, search_key) for x in data_list]) if len(values) > 1: raise ValueError('multiple values for {} encountered'.format(search_key)) if len(values) == 0: logger.warning('{} not found'.format(key)) continue value = values.pop() header[key] = value if 'station' in header: header['station'] = header['station'][:3] d1 = PD.to_datetime(data_list[0].index.values[0]).to_pydatetime() d2 = PD.to_datetime(data_list[-1].index.values[-1]).to_pydatetime() d1_obj = UTCDateTime('{:%Y-%m-%d %H:%H:%S}'.format(d1)) d2_obj = UTCDateTime('{:%Y-%m-%d %H:%H:%S}'.format(d2)) header['starttime'] = d1_obj header['endtime'] = d2_obj if elevation is None: logger.warning('no elevation found --- using default of 0') header['elevation'] = 0 else: header['elevation'] = elevation delta = NP.diff(data_list[0].index.values[:2])[0] / NP.timedelta64(1, 's') fs = 1 / delta header['sampling_rate'] = fs if baseline_declination is None: d = {'starttime': header['starttime'], 'Geodetic Latitude': header['geodetic_latitude'], 'Geodetic Longitude': header['geodetic_longitude'], 'Elevation': header['elevation']} baseline_declination = get_dec_tenths_arcminute(d, d1) header['declination_base'] = baseline_declination header['npts'] = sum(map(len, data_list)) return header def fgm2hdf(hdf_fname, fgm_fnames, he=False, elevation=0, key='B_raw'): """ Convert data found in FGM files *fgm_fnames* to an HDF record at *hdf_fname*. Write to the HDF record associated with *key*. If *he*, store the h (mag north) and e (mag east) components. Use *elevation* in specifying the measurement location. Return the tuple containing *hdf_fname* and *key*. """ data_list = [] for fgm_fname in fgm_fnames: logger.info('reading {}'.format(fgm_fname)) data_list.append(parse(fgm_fname)) header = build_header(data_list, elevation=elevation) df = PD.concat(data_list) df.loc[df.flag, ['x', 'y', 'z', 'f']] = NP.nan df.drop(columns='flag', inplace=True) df.rename(columns={'x': 'B_X', 'y': 'B_Y', 'z': 'B_Z', 'f': 'B_F'}, inplace=True) write_hdf(hdf_fname, df, key, header) return hdf_fname, key def main(argv=None): if argv is None: argv = sys.argv parser = ArgumentParser('Convert FGM format data to HDF.', formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('hdf_fname', type=str, help='output HDF file name') parser.add_argument('fgm_fnames', type=str, metavar='fgm_fname', nargs='*', help='input FGM file (in time order)') args = parser.parse_args(argv[1:]) fgm2hdf(args.hdf_fname, args.fgm_fnames) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) sys.exit(main())
[ "logging.getLogger", "logging.basicConfig", "argparse.ArgumentParser", "fgm2iaga.parse", "numpy.diff", "iaga2hdf.get_dec_tenths_arcminute", "iaga2hdf.write_hdf", "numpy.timedelta64", "pandas.concat", "pandas.to_datetime" ]
[((347, 386), 'logging.getLogger', 'logging.getLogger', (['"""pyrsss.mat.fgm2hdf"""'], {}), "('pyrsss.mat.fgm2hdf')\n", (364, 386), False, 'import logging\n'), ((3109, 3129), 'pandas.concat', 'PD.concat', (['data_list'], {}), '(data_list)\n', (3118, 3129), True, 'import pandas as PD\n'), ((3396, 3433), 'iaga2hdf.write_hdf', 'write_hdf', (['hdf_fname', 'df', 'key', 'header'], {}), '(hdf_fname, df, key, header)\n', (3405, 3433), False, 'from iaga2hdf import get_dec_tenths_arcminute, write_hdf\n'), ((3542, 3643), 'argparse.ArgumentParser', 'ArgumentParser', (['"""Convert FGM format data to HDF."""'], {'formatter_class': 'ArgumentDefaultsHelpFormatter'}), "('Convert FGM format data to HDF.', formatter_class=\n ArgumentDefaultsHelpFormatter)\n", (3556, 3643), False, 'from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n'), ((4137, 4176), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (4156, 4176), False, 'import logging\n'), ((1902, 1924), 'numpy.timedelta64', 'NP.timedelta64', (['(1)', '"""s"""'], {}), "(1, 's')\n", (1916, 1924), True, 'import numpy as NP\n'), ((2267, 2298), 'iaga2hdf.get_dec_tenths_arcminute', 'get_dec_tenths_arcminute', (['d', 'd1'], {}), '(d, d1)\n', (2291, 2298), False, 'from iaga2hdf import get_dec_tenths_arcminute, write_hdf\n'), ((1353, 1397), 'pandas.to_datetime', 'PD.to_datetime', (['data_list[0].index.values[0]'], {}), '(data_list[0].index.values[0])\n', (1367, 1397), True, 'import pandas as PD\n'), ((1423, 1469), 'pandas.to_datetime', 'PD.to_datetime', (['data_list[-1].index.values[-1]'], {}), '(data_list[-1].index.values[-1])\n', (1437, 1469), True, 'import pandas as PD\n'), ((1858, 1896), 'numpy.diff', 'NP.diff', (['data_list[0].index.values[:2]'], {}), '(data_list[0].index.values[:2])\n', (1865, 1896), True, 'import numpy as NP\n'), ((2998, 3014), 'fgm2iaga.parse', 'parse', (['fgm_fname'], {}), '(fgm_fname)\n', (3003, 3014), False, 'from fgm2iaga import parse\n')]
import boto3 import json from base64 import b64decode from dynamodb_json import json_util import numpy as np from decimal import * from collections import OrderedDict iot_data = boto3.client('iot-data') dedup_table_name='dedup-table' counts_table_name='counts-table' dealer_hand_table='dealer-hand' region = 'us-east-1' dynamodb_resource = boto3.resource('dynamodb', region_name=region) dedup_table = dynamodb_resource.Table(dedup_table_name) counts_table = dynamodb_resource.Table(counts_table_name) dealer_table = dynamodb_resource.Table(dealer_hand_table) lambda_client = boto3.client('lambda') getcontext().rounding = ROUND_HALF_UP def decode_kinesis(records): '''convert b64 encoded kinesis data records to list of json objects''' kinesis_json=[] for record in records: line = json.loads(b64decode(record['kinesis']['data'])) kinesis_json.append(line) return kinesis_json def get_hands(deduped_records_dict): hands = {} for x in deduped_records_dict: player_dealer = x['playerDealer'] hands[player_dealer] = {} ''' { 'pl4': { '2': 2, 'K': 1 }, 'dlr': { } } ''' for pred in x['preds']: card = pred['cls'][:-1] if card not in hands[player_dealer]: hands[player_dealer][card] = 1 else: hands[player_dealer][card] = hands[player_dealer][card] + 1 for k, v in hands.items(): for k1, v1 in hands[k].items(): hands[k][k1] = int(Decimal.to_integral_value(Decimal(v1) /2)) return hands def deduped_records(new_preds): '''where the magic happens''' pl_existing_cards_list = [] new_preds_deduped_list = [] for new_pred in new_preds: # read ddb for existing preds in this player/dealer region pl_existing_cards = json_util.loads( dedup_table.get_item( Key={'tablename': 'dayone','playerDealer': new_pred['playerDealer']} )['Item'] ) # debugging, comment out later print("Dynamo response") print(pl_existing_cards) if 'preds' in pl_existing_cards: if pl_existing_cards['preds'] != []: # if we already saw predictions for a player/dealer region new_preds_deduped=[] old_preds = pl_existing_cards['preds'] for pred in new_pred['preds']: for old_pred in old_preds: # for a detection, calculate its bounding box euclidean distance from the previous detected bboxes within the player/dealer region new_top_left = np.array((pred['xmin-ymin'][0], pred['xmin-ymin'][1])) old_top_left = np.array((old_pred['xmin-ymin'][0], old_pred['xmin-ymin'][1])) top_left_distance = np.linalg.norm(new_top_left-old_top_left) new_bottom_right = np.array((pred['xmax-ymax'][0], pred['xmax-ymax'][1])) old_bottom_right = np.array((old_pred['xmax-ymax'][0], old_pred['xmax-ymax'][1])) bottom_right_distance = np.linalg.norm(new_bottom_right-old_bottom_right) # ASSUMPTION! May need to modify these distances and include a condition on matching suit/rank if top_left_distance < 20 and bottom_right_distance < 20: # if the distance is pretty short, discard the prediction. print statements below for debugging print("card too similar") print("New preds deduped before:") print(new_preds_deduped) # all we need to do is "match" a detection with an old detection once. if we do, we should discard it. while pred in new_preds_deduped: new_preds_deduped.remove(pred) print("New preds deduped after:") print(new_preds_deduped) # never run this loop again for the new detection since it "matched" a card in the given player/dealer region. start the loop for a new detection: break new_preds_deduped.append(pred) pl_existing_cards['preds'].extend(new_preds_deduped) else: pl_existing_cards['preds'] = new_pred['preds'] new_preds_deduped=new_pred['preds'] else: # if the dedup table is cleared via the browser button, that means there were no cards on the table and this is a brand new hand, so we skip the dedup logic: pl_existing_cards['preds'] = new_pred['preds'] new_preds_deduped=new_pred['preds'] pl_existing_cards_list.append(pl_existing_cards) new_preds_deduped_list.extend(new_preds_deduped) return pl_existing_cards_list, new_preds_deduped_list def remove_second_ranksuit(new_preds_deduped): '''We store the count of ranks and count of cards from the deduped detections and then divide in half. ASSUMPTION 1: dealer must place cards with both values on a card uncovered. otherwise, this will completely break. ASSUMPTION 2: this also assumes our ML Model accurately detects both values on a card.''' classes = { "01-A": 0, "02-K": 0, "03-Q": 0, "04-J": 0, "05-10": 0, "06-9": 0, "07-8": 0, "08-7": 0, "09-6": 0, "10-5": 0, "11-4": 0, "12-3": 0, "13-2": 0, "14-shoe": 0 } for preds in new_preds_deduped: classes['14-shoe'] = classes['14-shoe'] + 1 if preds['cls'][:-1] == 'A': classes['01-A'] = classes['01-A'] + 1 elif preds['cls'][:-1] == 'K': classes['02-K'] = classes['02-K'] + 1 elif preds['cls'][:-1] == 'Q': classes['03-Q'] = classes['03-Q'] + 1 elif preds['cls'][:-1] == 'J': classes['04-J'] = classes['04-J'] + 1 elif preds['cls'][:-1] == '10': classes['05-10'] = classes['05-10'] + 1 elif preds['cls'][:-1] == '9': classes['06-9'] = classes['06-9'] + 1 elif preds['cls'][:-1] == '8': classes['07-8'] = classes['07-8'] + 1 elif preds['cls'][:-1] == '7': classes['08-7'] = classes['08-7'] + 1 elif preds['cls'][:-1] == '6': classes['09-6'] = classes['09-6'] + 1 elif preds['cls'][:-1] == '5': classes['10-5'] = classes['10-5'] + 1 elif preds['cls'][:-1] == '4': classes['11-4'] = classes['11-4'] + 1 elif preds['cls'][:-1] == '3': classes['12-3'] = classes['12-3'] + 1 elif preds['cls'][:-1] == '2': classes['13-2'] = classes['13-2'] + 1 for k, v in classes.items(): classes[k] = int(Decimal.to_integral_value(Decimal(v) /2)) return classes def handler(event, context): '''this lambda function is designed to run with a concurrency of 1 to prevent race conditions on the dynamodb table!!! therefore the unit of scale is per table since dedup is stored at the tablename level''' # read the kinesis record from the kinesis lambda trigger kinesis_records=event['Records'] # list of objects new_preds = decode_kinesis(kinesis_records) # debugging print("New preds before dedup:") print(new_preds) deduped_records_dict, new_preds_deduped = deduped_records(new_preds=new_preds) print("Deduped preds:") print(deduped_records_dict) print(new_preds_deduped) hands = get_hands(deduped_records_dict) print("Player/Dealer Hands:") print(hands) ''' { 'pl4': { '2': 2, 'K': 1 }, 'dlr': { } } ''' for handkey, value in hands.items(): if 'dlr' not in handkey: # submit the hand to the hueristic function. the function will check if the dealer's hand has been processed, and backoff until it's there lambda_client.invoke( FunctionName='heuristic-function', InvocationType='Event', Payload=json.dumps({handkey: value}) ) else: # store the dealer hand so the heuristic function can read the dealer's up card dealer_table.put_item(Item={'dlr': handkey,'hand': value}) for item in deduped_records_dict: deduped_records_dump = json.dumps(item) deduped_records_dec = json.loads(deduped_records_dump, parse_float=Decimal) # store deduped results to DynamoDB for next trigger dedup_table.put_item(Item=deduped_records_dec) klasses = remove_second_ranksuit(new_preds_deduped) print("Dedup-ed classes from the stream:") print(klasses) ''' klasses = { 'A':16, 'K':16, ... '2':16 } ''' counts = counts_table.get_item(Key={'tablename': 'dayone'})['Item'] print("Counts read from DDB:") print(counts) ''' counts = { 'tablename': 'dayone', 'counts': { 'A':16, 'K':16, ... '2':16 } } ''' for k,v in klasses.items(): counts['counts'][k] = counts['counts'][k] - v print("Counts after subtracting:") print(counts) counts_dec = json_util.loads(counts) print("Counts after using the json utils:") print(counts_dec) counts_table.put_item(Item=counts_dec) # generate probabilities: ordered_dict = OrderedDict(sorted(counts_dec['counts'].items(), key=lambda t: t[0])) counts_list = [] probabilities = [] cards_left_in_shoe = counts_dec['counts']['14-shoe'] ordered_dict['00-HiCount'] = ordered_dict['02-K'] + ordered_dict['03-Q'] + ordered_dict['04-J'] + ordered_dict['05-10'] ordered_dict.move_to_end('00-HiCount', last=False) for k,v in ordered_dict.items(): if k == '14-shoe' or k == '02-K' or k == '03-Q' or k == '04-J' or k == '05-10': continue counts_list.append(v) probability = (v/cards_left_in_shoe) * 100 probabilities.append(probability) print("Just a count list") print(counts_list) print("Just a probabilities list") print(probabilities) probabilities_clean = list(np.around(np.array(probabilities), 2)) print("Just a probabilities list rounded") print(probabilities_clean) iot_data.publish( topic='probabilities', payload=json.dumps(probabilities_clean)) iot_data.publish( topic='counts', payload=json.dumps(counts_list)) return
[ "json.loads", "boto3.client", "json.dumps", "base64.b64decode", "dynamodb_json.json_util.loads", "numpy.array", "boto3.resource", "numpy.linalg.norm" ]
[((179, 203), 'boto3.client', 'boto3.client', (['"""iot-data"""'], {}), "('iot-data')\n", (191, 203), False, 'import boto3\n'), ((343, 389), 'boto3.resource', 'boto3.resource', (['"""dynamodb"""'], {'region_name': 'region'}), "('dynamodb', region_name=region)\n", (357, 389), False, 'import boto3\n'), ((578, 600), 'boto3.client', 'boto3.client', (['"""lambda"""'], {}), "('lambda')\n", (590, 600), False, 'import boto3\n'), ((9673, 9696), 'dynamodb_json.json_util.loads', 'json_util.loads', (['counts'], {}), '(counts)\n', (9688, 9696), False, 'from dynamodb_json import json_util\n'), ((8772, 8788), 'json.dumps', 'json.dumps', (['item'], {}), '(item)\n', (8782, 8788), False, 'import json\n'), ((8819, 8872), 'json.loads', 'json.loads', (['deduped_records_dump'], {'parse_float': 'Decimal'}), '(deduped_records_dump, parse_float=Decimal)\n', (8829, 8872), False, 'import json\n'), ((818, 854), 'base64.b64decode', 'b64decode', (["record['kinesis']['data']"], {}), "(record['kinesis']['data'])\n", (827, 854), False, 'from base64 import b64decode\n'), ((10646, 10669), 'numpy.array', 'np.array', (['probabilities'], {}), '(probabilities)\n', (10654, 10669), True, 'import numpy as np\n'), ((10822, 10853), 'json.dumps', 'json.dumps', (['probabilities_clean'], {}), '(probabilities_clean)\n', (10832, 10853), False, 'import json\n'), ((10917, 10940), 'json.dumps', 'json.dumps', (['counts_list'], {}), '(counts_list)\n', (10927, 10940), False, 'import json\n'), ((8482, 8510), 'json.dumps', 'json.dumps', (['{handkey: value}'], {}), '({handkey: value})\n', (8492, 8510), False, 'import json\n'), ((2738, 2792), 'numpy.array', 'np.array', (["(pred['xmin-ymin'][0], pred['xmin-ymin'][1])"], {}), "((pred['xmin-ymin'][0], pred['xmin-ymin'][1]))\n", (2746, 2792), True, 'import numpy as np\n'), ((2832, 2894), 'numpy.array', 'np.array', (["(old_pred['xmin-ymin'][0], old_pred['xmin-ymin'][1])"], {}), "((old_pred['xmin-ymin'][0], old_pred['xmin-ymin'][1]))\n", (2840, 2894), True, 'import numpy as np\n'), ((2939, 2982), 'numpy.linalg.norm', 'np.linalg.norm', (['(new_top_left - old_top_left)'], {}), '(new_top_left - old_top_left)\n', (2953, 2982), True, 'import numpy as np\n'), ((3025, 3079), 'numpy.array', 'np.array', (["(pred['xmax-ymax'][0], pred['xmax-ymax'][1])"], {}), "((pred['xmax-ymax'][0], pred['xmax-ymax'][1]))\n", (3033, 3079), True, 'import numpy as np\n'), ((3123, 3185), 'numpy.array', 'np.array', (["(old_pred['xmax-ymax'][0], old_pred['xmax-ymax'][1])"], {}), "((old_pred['xmax-ymax'][0], old_pred['xmax-ymax'][1]))\n", (3131, 3185), True, 'import numpy as np\n'), ((3234, 3285), 'numpy.linalg.norm', 'np.linalg.norm', (['(new_bottom_right - old_bottom_right)'], {}), '(new_bottom_right - old_bottom_right)\n', (3248, 3285), True, 'import numpy as np\n')]
from .i_tree_ensemble_parser import ITreeEnsembleParser from typing import List import pandas as pd import numpy as np from .single_tree import BinaryTree from ..common.math_utils import threshold from ..common.constants import TreeBasedDriftValueType class AbstractTreeEnsembleParser(ITreeEnsembleParser): def __init__(self, model, model_type, iteration_range): super().__init__() self.original_model = model self.model_type = model_type self.iteration_range = iteration_range self.trees = None self.parse(iteration_range) def fit(self, X1, X2, sample_weights1, sample_weights2): self.node_weights1 = self.get_node_weights(X1, sample_weights=sample_weights1) self.node_weights2 = self.get_node_weights(X2, sample_weights=sample_weights2) #self._check_drift_values_mean(X1, X2, sample_weights1, sample_weights2) def get_predictions(self, X: pd.DataFrame, prediction_type: str) -> np.array: # return array of shape (nb. obs, nb. class) for multiclass and shape array of shape (nb. obs, ) # for binary class and regression """ :param X: :param prediction_type: "raw" or "proba" :return: """ # array of shape (nb. obs, nb. class) for multiclass and shape array of shape (nb. obs, ) # for binary class and regression if prediction_type == 'raw': return self.predict_raw(X) elif prediction_type == 'proba': return self.predict_proba(X) else: raise ValueError(f'Bad value for prediction_type: {prediction_type}') def get_node_weights(self, X: pd.DataFrame, sample_weights: np.array) -> List[np.array]: """return sum of observation weights in each node of each tree of the model""" # pass X through the trees : compute node sample weights, and node values from each tree predicted_leaves = self.predict_leaf(X) node_weights = [] for index in range(self.n_trees): tree = self.trees[index] # add sample weighs of terminal leaves node_weights_in_tree = [] for j in range(tree.n_nodes): if tree.children_left[j] == -1: # if leaf node_weights_in_tree.append(np.sum(sample_weights[predicted_leaves[:, index] == j])) else: # if not a leaf node_weights_in_tree.append(-1) # populate in reverse order to add sample weights of nodes for j in range(tree.n_nodes-1, -1, -1): if node_weights_in_tree[j] == -1: # if not a leaf node_weights_in_tree[j] = (node_weights_in_tree[tree.children_left[j]] + node_weights_in_tree[tree.children_right[j]]) # update node_weights node_weights.append(np.array(node_weights_in_tree)) return node_weights @staticmethod def _get_iteration_range(iteration_range, initial_n_trees): if iteration_range is None: iteration_range = (0, initial_n_trees) elif iteration_range[1] > initial_n_trees: raise ValueError(f'"iteration_range" values exceeds {initial_n_trees} which is the number of trees in the model') else: pass return iteration_range @staticmethod def _model_parser_error(): raise ValueError('Error in parsing "model": the passed model is not supported in DriftExplainer') def _check_parsing_with_leaf_predictions(self, X): if not np.array_equal(self.predict_leaf_with_model_parser(X), self.predict_leaf(X)): self._model_parser_error() def _check_drift_values_mean(self, X1, X2, sample_weights1, sample_weights2): sample_weights1_norm = sample_weights1 / np.sum(sample_weights1) sample_weights2_norm = sample_weights2 / np.sum(sample_weights2) if self.prediction_dim == 1: mean_prediction_diff = np.sum(sample_weights2_norm * self.predict_raw(X2)) - \ np.sum(sample_weights1_norm * self.predict_raw(X1)) else: mean_prediction_diff = np.sum(sample_weights2_norm[:, np.newaxis] * self.predict_raw(X2), axis=0) - \ np.sum(sample_weights1_norm[:, np.newaxis] * self.predict_raw(X1), axis=0) stat = abs(self.compute_tree_based_drift_values(type=TreeBasedDriftValueType.MEAN.value).sum(axis=0) - mean_prediction_diff) if any(stat > 10**(-3)): # any works because difference is an array raise ValueError('Error in computation of feature contributions') def compute_tree_based_drift_values(self, type: str): """ :param node_weights1: :param node_weights2: :param type: type: 'mean_norm', 'node_size', or 'mean' :return: """ if type == TreeBasedDriftValueType.NODE_SIZE.value: drift_values = np.zeros((self.n_features, 1)) elif type in [TreeBasedDriftValueType.MEAN.value, TreeBasedDriftValueType.MEAN_NORM.value]: drift_values = np.zeros((self.n_features, self.prediction_dim)) else: raise ValueError(f'Bad value for "type": {type}') drift_values_details = [] for i, tree in enumerate(self.trees): drift_values_tree = tree.compute_drift_values(self.node_weights1[i], self.node_weights2[i], type=type) drift_values = self.add_drift_values(drift_values, drift_values_tree, i, self.prediction_dim, type) drift_values_details.append(drift_values_tree) return drift_values #, drift_values_details def plot_tree_drift(self, tree_idx: int, type: str, feature_names: List[str]): if self.node_weights1 is None: raise ValueError('You need to run drift_explainer.fit before calling plot_tree_drift') if type not in [e.value for e in TreeBasedDriftValueType]: raise ValueError(f'Bad value for "type"') else: self.trees[tree_idx].plot_drift(node_weights1=self.node_weights1[tree_idx], node_weights2=self.node_weights2[tree_idx], type=type, feature_names=feature_names) def compute_tree_based_correction_weights(self, X1: pd.DataFrame, max_depth: int, max_ratio: int, sample_weights1: np.array) -> np.array: weights_all = np.zeros((X1.shape[0], self.n_trees)) predicted_leaves1 = self.predict_leaf(X1) for i, tree in enumerate(self.trees): weights_all[:, i] = self._get_weights_tree(tree, predicted_leaves1[:, i], self.node_weights1[i], self.node_weights2[i], max_depth, max_ratio) geometric_mean_weights = np.power(weights_all.prod(axis=1), 1/self.n_trees) # corresponds to correction weights new_weights = sample_weights1 * geometric_mean_weights # update initial sample_weights with the correction return new_weights * len(new_weights) / np.sum(new_weights) @staticmethod def _get_weights_tree(tree: BinaryTree, predicted_leaves: np.array, node_weights1: np.array, node_weights2: np.array, max_depth: int, max_ratio: int): weights = np.zeros(len(predicted_leaves)) for leaf_idx in np.unique(predicted_leaves): if max_depth is not None: leaf_depth = tree.get_depth(leaf_idx) if leaf_depth > max_depth: # node_idx is the node above leaf that is at the good depth taking into account the max_depth # parameter node_idx = tree.up(leaf_idx, n=leaf_depth - max_depth) else: node_idx = leaf_idx else: node_idx = leaf_idx node_weight_fractions1 = node_weights1 / node_weights1[0] node_weight_fractions2 = node_weights2 / node_weights2[0] # denominator can't be 0 because the leaf observation is inside the node weights[predicted_leaves == leaf_idx] = \ threshold(node_weight_fractions2[node_idx] / node_weight_fractions1[node_idx], max_ratio) return weights @staticmethod def add_drift_values(drift_values, drift_values_tree, i, prediction_dim, type): drift_values += drift_values_tree return drift_values def predict_leaf(self, X: pd.DataFrame) -> np.array: # output dtype = np.int32 pass def predict_raw(self, X: pd.DataFrame) -> np.array: pass def predict_proba(self, X: pd.DataFrame) -> np.array: pass def predict_leaf_with_model_parser(self, X: pd.DataFrame) -> np.array: pass
[ "numpy.array", "numpy.sum", "numpy.zeros", "numpy.unique" ]
[((6744, 6781), 'numpy.zeros', 'np.zeros', (['(X1.shape[0], self.n_trees)'], {}), '((X1.shape[0], self.n_trees))\n', (6752, 6781), True, 'import numpy as np\n'), ((7666, 7693), 'numpy.unique', 'np.unique', (['predicted_leaves'], {}), '(predicted_leaves)\n', (7675, 7693), True, 'import numpy as np\n'), ((3837, 3860), 'numpy.sum', 'np.sum', (['sample_weights1'], {}), '(sample_weights1)\n', (3843, 3860), True, 'import numpy as np\n'), ((3910, 3933), 'numpy.sum', 'np.sum', (['sample_weights2'], {}), '(sample_weights2)\n', (3916, 3933), True, 'import numpy as np\n'), ((4985, 5015), 'numpy.zeros', 'np.zeros', (['(self.n_features, 1)'], {}), '((self.n_features, 1))\n', (4993, 5015), True, 'import numpy as np\n'), ((7372, 7391), 'numpy.sum', 'np.sum', (['new_weights'], {}), '(new_weights)\n', (7378, 7391), True, 'import numpy as np\n'), ((2892, 2922), 'numpy.array', 'np.array', (['node_weights_in_tree'], {}), '(node_weights_in_tree)\n', (2900, 2922), True, 'import numpy as np\n'), ((5165, 5213), 'numpy.zeros', 'np.zeros', (['(self.n_features, self.prediction_dim)'], {}), '((self.n_features, self.prediction_dim))\n', (5173, 5213), True, 'import numpy as np\n'), ((2300, 2355), 'numpy.sum', 'np.sum', (['sample_weights[predicted_leaves[:, index] == j]'], {}), '(sample_weights[predicted_leaves[:, index] == j])\n', (2306, 2355), True, 'import numpy as np\n')]
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # 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. # @Author : bamtercelboo # @Datetime : 2019/3/14 15:26 # @File : BERT.py # @Last Modify Time : 2019/3/14 15:26 # @Contact : <EMAIL>, 163.com} """Extract pre-computed feature vectors from a PyTorch BERT model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import argparse import collections import logging import json import re import numpy as np import torch import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from torch.utils.data.distributed import DistributedSampler from pytorch_pretrained_bert.tokenization import BertTokenizer from pytorch_pretrained_bert.modeling import BertModel # logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', # datefmt = '%m/%d/%Y %H:%M:%S', # level = logging.INFO) # logger = logging.getLogger(__name__) class InputExample(object): """ InputExample """ def __init__(self, unique_id, text_a, text_b): self.unique_id = unique_id self.text_a = text_a self.text_b = text_b class InputFeatures(object): """A single set of features of data.""" def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): self.unique_id = unique_id self.tokens = tokens self.input_ids = input_ids self.input_mask = input_mask self.input_type_ids = input_type_ids class BERT(object): """ BERT """ def __init__(self, **kwargs): self.bert_model = kwargs["bert_model"] self.vocab = kwargs["vocab"] self.max_seq_length = kwargs["max_seq_length"] self.batch_size = kwargs["batch_size"] self.extract_dim = kwargs["extract_dim"] self.layers = kwargs["layers"] self.local_rank = kwargs["local_rank"] self.no_cuda = kwargs["no_cuda"] self.do_lower_case = kwargs["do_lower_case"] # example index self.ex_index = -1 # Now default -1 # self.layer_indexes = [int(x) for x in self.layers.split(",")] self.layer_indexes = -1 # cpu cuda device self.device, self.n_gpu = self._set_device() # tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case) self.tokenizer = BertTokenizer.from_pretrained(os.path.join(self.bert_model, self.vocab)) # Bert Model self.model = self._load_bert_model() def extract_feature(self, batch_features): """ :param batch_features: :return: """ # print("extract bert feature") examples, uniqueid_to_line = self._read_examples(batch_features, self.max_seq_length) features = self._convert_examples_to_features( examples=examples, seq_length=self.max_seq_length, tokenizer=self.tokenizer) unique_id_to_feature = {} for feature in features: unique_id_to_feature[feature.unique_id] = feature all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long) eval_data = TensorDataset(all_input_ids, all_input_mask, all_example_index) if self.local_rank == -1: eval_sampler = SequentialSampler(eval_data) else: eval_sampler = DistributedSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=self.batch_size) bert_feature = self._get_bert_hidden(eval_dataloader, features, uniqueid_to_line) return bert_feature def _get_bert_hidden(self, eval_dataloader, features, uniqueid_to_line): """ :param eval_dataloader: :param features: :param uniqueid_to_line: :return: """ print(uniqueid_to_line) self.model.eval() batch_count = len(eval_dataloader) batch_num = 0 line_index_exist = [] result = [] for input_ids, input_mask, example_indices in eval_dataloader: batch_num += 1 # sys.stdout.write("\rBert Model For the {} Batch, All {} batch.".format(batch_num, batch_count)) input_ids = input_ids.to(self.device) input_mask = input_mask.to(self.device) all_encoder_layers, _ = self.model(input_ids, token_type_ids=None, attention_mask=input_mask) all_encoder_layers = all_encoder_layers layer_index = self.layer_indexes layer_output_all = all_encoder_layers[layer_index].detach().cpu().numpy()[:, :, :self.extract_dim] for b, example_index in enumerate(example_indices): feature = features[example_index.item()] tokens = feature.tokens token_length = len(tokens) layer_output = np.round(layer_output_all[b][:token_length].tolist(), 6).tolist() out_features = collections.OrderedDict() out_features["tokens"] = tokens out_features["values"] = layer_output unique_id = int(feature.unique_id) line_index = uniqueid_to_line[str(unique_id)] if line_index in line_index_exist: output_json["features"]["tokens"].extend(tokens) output_json["features"]["values"].extend(layer_output) continue else: if len(line_index_exist) != 0: result.append(output_json) line_index_exist.clear() line_index_exist.append(line_index) output_json = collections.OrderedDict() output_json["linex_index"] = line_index output_json["layer_index"] = layer_index output_json["features"] = out_features # continue result.append(output_json) bert_feature = self._batch(result) return bert_feature def _batch(self, result): """ :param result: :return: """ batch_size = len(result) max_char_size = -1 extract_dim = len(result[0]["features"]["values"][0]) for line in result: char_size = len(line["features"]["tokens"]) if char_size > max_char_size: max_char_size = char_size bert_feature = np.zeros((batch_size, max_char_size, extract_dim)) for b in range(batch_size): values = result[b]["features"]["values"] length = len(values) bert_feature[b][:length] = np.array(result[b]["features"]["values"]) bert_feature = torch.from_numpy(bert_feature).float() bert_feature.to(self.device) return bert_feature def _load_bert_model(self): model = BertModel.from_pretrained(self.bert_model) model.to(self.device) if self.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[self.local_rank], output_device=self.local_rank) elif self.n_gpu > 1: model = torch.nn.DataParallel(model) return model def _set_device(self): if self.local_rank == -1 or self.no_cuda: device = torch.device("cuda" if torch.cuda.is_available() and not self.no_cuda else "cpu") n_gpu = torch.cuda.device_count() else: device = torch.device("cuda", self.local_rank) n_gpu = 1 # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.distributed.init_process_group(backend='nccl') print("device: {} n_gpu: {} distributed training: {}".format(device, n_gpu, bool(self.local_rank != -1))) return device, n_gpu def _convert_examples_to_features(self, examples, seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" features = [] for (ex_index, example) in enumerate(examples): # print(example.text_a) tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) if tokens_b: # Modifies `tokens_a` and `tokens_b` in place so that the total # length is less than the specified length. # Account for [CLS], [SEP], [SEP] with "- 3" self._truncate_seq_pair(tokens_a, tokens_b, seq_length - 3) else: # Account for [CLS] and [SEP] with "- 2" if len(tokens_a) > seq_length - 2: tokens_a = tokens_a[0:(seq_length - 2)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambigiously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens = [] input_type_ids = [] tokens.append("[CLS]") input_type_ids.append(0) for token in tokens_a: tokens.append(token) input_type_ids.append(0) tokens.append("[SEP]") input_type_ids.append(0) if tokens_b: for token in tokens_b: tokens.append(token) input_type_ids.append(1) tokens.append("[SEP]") input_type_ids.append(1) input_ids = tokenizer.convert_tokens_to_ids(tokens) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. input_mask = [1] * len(input_ids) # Zero-pad up to the sequence length. while len(input_ids) < seq_length: input_ids.append(0) input_mask.append(0) input_type_ids.append(0) assert len(input_ids) == seq_length assert len(input_mask) == seq_length assert len(input_type_ids) == seq_length if ex_index < self.ex_index: print("*** Example ***") print("unique_id: %s" % (example.unique_id)) print("tokens: %s" % " ".join([str(x) for x in tokens])) print("input_ids: %s" % " ".join([str(x) for x in input_ids])) print("input_mask: %s" % " ".join([str(x) for x in input_mask])) print("input_type_ids: %s" % " ".join([str(x) for x in input_type_ids])) features.append( InputFeatures( unique_id=example.unique_id, tokens=tokens, input_ids=input_ids, input_mask=input_mask, input_type_ids=input_type_ids)) return features @staticmethod def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that's truncated likely contains more information than a longer sequence. while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_length: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() @staticmethod def _cut_text_by_len(text, length): """ :param text: :param length: :return: """ textArr = re.findall('.{' + str(length) + '}', text) textArr.append(text[(len(textArr) * length):]) return textArr def _read_examples(self, batch_features, max_seq_length): """Read a list of `InputExample`s from an input file.""" examples = [] unique_id = 0 line_index = 0 uniqueid_to_line = collections.OrderedDict() for inst in batch_features.inst: line = inst.bert_line line = line.strip() # print(line) # line = "".join(json.loads(line)["fact"].split()) line_cut = self._cut_text_by_len(line, max_seq_length) for l in line_cut: uniqueid_to_line[str(unique_id)] = line_index text_a = None text_b = None m = re.match(r"^(.*) \|\|\| (.*)$", l) if m is None: text_a = l else: text_a = m.group(1) text_b = m.group(2) examples.append( InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b)) unique_id += 1 line_index += 1 # print(uniqueid_to_line) return examples, uniqueid_to_line
[ "collections.OrderedDict", "torch.device", "re.match", "os.path.join", "pytorch_pretrained_bert.modeling.BertModel.from_pretrained", "torch.utils.data.TensorDataset", "torch.utils.data.SequentialSampler", "torch.cuda.device_count", "torch.tensor", "numpy.zeros", "torch.utils.data.distributed.Dis...
[((3742, 3805), 'torch.tensor', 'torch.tensor', (['[f.input_ids for f in features]'], {'dtype': 'torch.long'}), '([f.input_ids for f in features], dtype=torch.long)\n', (3754, 3805), False, 'import torch\n'), ((3831, 3895), 'torch.tensor', 'torch.tensor', (['[f.input_mask for f in features]'], {'dtype': 'torch.long'}), '([f.input_mask for f in features], dtype=torch.long)\n', (3843, 3895), False, 'import torch\n'), ((3999, 4062), 'torch.utils.data.TensorDataset', 'TensorDataset', (['all_input_ids', 'all_input_mask', 'all_example_index'], {}), '(all_input_ids, all_input_mask, all_example_index)\n', (4012, 4062), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n'), ((4250, 4321), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_data'], {'sampler': 'eval_sampler', 'batch_size': 'self.batch_size'}), '(eval_data, sampler=eval_sampler, batch_size=self.batch_size)\n', (4260, 4321), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n'), ((7257, 7307), 'numpy.zeros', 'np.zeros', (['(batch_size, max_char_size, extract_dim)'], {}), '((batch_size, max_char_size, extract_dim))\n', (7265, 7307), True, 'import numpy as np\n'), ((7689, 7731), 'pytorch_pretrained_bert.modeling.BertModel.from_pretrained', 'BertModel.from_pretrained', (['self.bert_model'], {}), '(self.bert_model)\n', (7714, 7731), False, 'from pytorch_pretrained_bert.modeling import BertModel\n'), ((14021, 14046), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (14044, 14046), False, 'import collections\n'), ((3079, 3120), 'os.path.join', 'os.path.join', (['self.bert_model', 'self.vocab'], {}), '(self.bert_model, self.vocab)\n', (3091, 3120), False, 'import os\n'), ((4124, 4152), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['eval_data'], {}), '(eval_data)\n', (4141, 4152), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n'), ((4194, 4223), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['eval_data'], {}), '(eval_data)\n', (4212, 4223), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((7470, 7511), 'numpy.array', 'np.array', (["result[b]['features']['values']"], {}), "(result[b]['features']['values'])\n", (7478, 7511), True, 'import numpy as np\n'), ((7816, 7930), 'torch.nn.parallel.DistributedDataParallel', 'torch.nn.parallel.DistributedDataParallel', (['model'], {'device_ids': '[self.local_rank]', 'output_device': 'self.local_rank'}), '(model, device_ids=[self.\n local_rank], output_device=self.local_rank)\n', (7857, 7930), False, 'import torch\n'), ((8350, 8375), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (8373, 8375), False, 'import torch\n'), ((8411, 8448), 'torch.device', 'torch.device', (['"""cuda"""', 'self.local_rank'], {}), "('cuda', self.local_rank)\n", (8423, 8448), False, 'import torch\n'), ((8581, 8633), 'torch.distributed.init_process_group', 'torch.distributed.init_process_group', ([], {'backend': '"""nccl"""'}), "(backend='nccl')\n", (8617, 8633), False, 'import torch\n'), ((5781, 5806), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (5804, 5806), False, 'import collections\n'), ((7536, 7566), 'torch.from_numpy', 'torch.from_numpy', (['bert_feature'], {}), '(bert_feature)\n', (7552, 7566), False, 'import torch\n'), ((8099, 8127), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (8120, 8127), False, 'import torch\n'), ((14483, 14519), 're.match', 're.match', (['"""^(.*) \\\\|\\\\|\\\\| (.*)$"""', 'l'], {}), "('^(.*) \\\\|\\\\|\\\\| (.*)$', l)\n", (14491, 14519), False, 'import re\n'), ((6506, 6531), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (6529, 6531), False, 'import collections\n'), ((8271, 8296), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (8294, 8296), False, 'import torch\n')]
import os from datetime import datetime, timedelta, timezone, date import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from src.loss import JointsMSELoss from src.model import * from src.dataset import * from src.util import * from src.evaluate import * import itertools import matplotlib.pyplot as plt MEAN = 0.5 STD = 0.5 NUM_WORKER = 0 def train(args): ## Set Hyperparameters for the Training mode = args.mode train_continue = args.train_continue lr = args.lr batch_size = args.batch_size num_epoch = args.num_epoch data_dir = args.data_dir ckpt_dir = args.ckpt_dir log_dir = args.log_dir result_dir = args.result_dir log_prefix = args.log_prefix task = args.task num_mark = args.num_mark ny = args.ny nx = args.nx nch = args.nch nker = args.nker norm = args.norm network = args.network resnet_depth = args.resnet_depth joint_weight = args.joint_weight cuda = args.cuda device = torch.device(cuda if torch.cuda.is_available() else 'cpu') ## Open log file and write date_time = datetime.now().strftime("%m/%d/%Y, %H:%M:%S") f = open(log_prefix + "-" + mode + ".txt", "a") f.write("initiate %s loop : " % mode + date_time + "\n") f.write("mode: %s\n" % mode) f.write("norm: %s\n" % norm) f.write("learning rate: %.4e\n" % lr) f.write("batch size: %d\n" % batch_size) f.write("number of epoch: %d\n" % num_epoch) f.write("task: %s\n" % task) f.write("number of markers: %s\n" % num_mark) f.write("network: %s\n" % network) f.write("data dir: %s\n" % data_dir) f.write("ckpt dir: %s\n" % ckpt_dir) f.write("log dir: %s\n" % log_dir) f.write("result dir: %s\n" % result_dir) f.write("device: %s\n" % device) ## Create Result Directories result_dir_train = os.path.join(result_dir, 'train') if not os.path.exists(result_dir_train): os.makedirs(os.path.join(result_dir_train)) if mode == 'train': transform_train = "3R1N" # Resize - RandomCrop - RandomFlip - Normalization dataset_full = Dataset(data_dir=os.path.join(data_dir, 'train'), transform=transform_train, shape=(ny, nx, nch), hm_shape=(ny, nx, num_mark)) # Set Other Variables num_data = len(dataset_full) num_data_train = num_data // 10 * 9 num_batch_train = np.ceil(num_data_train / batch_size) dataset_train, dataset_val = torch.utils.data.random_split(dataset_full, [num_data_train, num_data-num_data_train]) loader_train = DataLoader(dataset_train, batch_size=batch_size, shuffle=True, num_workers=NUM_WORKER) loader_val = DataLoader(dataset_val, batch_size=batch_size, shuffle=True, num_workers=NUM_WORKER) if network == "PoseResNet": netP = PoseResNet(in_channels=nch, out_channels=num_mark, nker=nker, norm=norm, num_layers=resnet_depth).to(device) message = init_weights(netP, init_type='normal', init_gain=0.02) f.write(message) elif network == "PoseResNetv2": netP = PoseResNetv2(out_channels=num_mark, num_layers=resnet_depth, pretrained=True).to(device) f.write("initialize network with pretrained parameters\n") ## Define the Loss Functions fn_pose = JointsMSELoss(use_target_weight=joint_weight).to(device) ## Set the Optimizers optimP = torch.optim.Adam(netP.parameters(), lr=lr, betas=(0.5, 0.999)) ## Define Other Functions fn_tonumpy = lambda x: x.to('cpu').detach().numpy().transpose(0, 2, 3, 1) fn_denorm = lambda x: (x * STD) + MEAN cmap = None ## Set SummaryWriter for the Tensorboard writer_train = SummaryWriter(log_dir=os.path.join(log_dir, 'train')) ## Train the Networks st_epoch = 0 if mode == 'train': if train_continue == "on": st_epoch, netP, optimP = load(ckpt_dir=ckpt_dir, netP=netP, optimP=optimP) early_stop = EarlyStopping(ckpt_dir=ckpt_dir, trace_func=f.write) for epoch in range(st_epoch + 1, num_epoch + 1): netP.train() loss_P_train = [] val_data = next(iter(loader_val)) val_input = val_data["image"].to(device) val_target = val_data["hmap"] for batch, data in enumerate(loader_train, 1): input_data = data["image"].to(device) target = data["hmap"].to(device) target_weight = None # forward netP output = netP(input_data) # Build target heatmap from pose labels # try interpolation - deprecated # target = nn.functional.interpolate(target, (output.size()[1], output.size()[2], output.size()[3]), mode="nearest") size = (output.size()[2], output.size()[3]) target = Resample()(size=size, target=target) # backward netP set_requires_grad(netP, True) optimP.zero_grad() loss_P = fn_pose(output, target) loss_P.backward() optimP.step() # compute the losses loss_P_train += [float(loss_P.item())] f.write("TRAIN: EPOCH %04d / %04d | BATCH %04d / %04d | " "POSE LOSS %.8f | \n"% (epoch, num_epoch, batch, num_batch_train, np.mean(loss_P_train))) if batch % 50 == 0: # Save to the Tensorboard input_data = fn_tonumpy(fn_denorm(input_data)).squeeze() output = fn_tonumpy(fn_denorm(output)).squeeze() input_data = np.clip(input_data, a_min=0, a_max=1) # Convert pose heatmap into image form output = pose2image(output) output = np.clip(output, a_min=0, a_max=1) id = num_batch_train * (epoch - 1) + batch if not batch_size==1: plt.imsave(os.path.join(result_dir_train, '%04d_input.png' % id), input_data[0], cmap=cmap) plt.imsave(os.path.join(result_dir_train, '%04d_output.png' % id), output[0], cmap=cmap) writer_train.add_image('input', input_data, id, dataformats='NHWC') writer_train.add_image('output', input_data, id, dataformats='NHWC') else: plt.imsave(os.path.join(result_dir_train, '%04d_input.png' % id), input_data, cmap=cmap) plt.imsave(os.path.join(result_dir_train, '%04d_output.png' % id), output, cmap=cmap) writer_train.add_image('input', input_data, id, dataformats='HWC') writer_train.add_image('output', input_data, id, dataformats='HWC') writer_train.add_scalar('loss_P', np.mean(loss_P_train), epoch) if epoch % 10 == 0 or epoch == num_epoch: save(ckpt_dir=ckpt_dir, epoch=epoch, netP=netP, optimP=optimP) # forward netP with torch.no_grad(): netP.eval() val_output = netP(val_input) val_target = nn.functional.interpolate(val_target, (val_output.size()[2], val_output.size()[3]), mode="nearest").to(device) # Early stop when validation loss does not reduce val_loss = fn_pose(val_output, val_target) early_stop(val_loss=val_loss, model=netP, optim=optimP, epoch=epoch) if early_stop.early_stop: break writer_train.close() f.close() def test(args): ## Set Hyperparameters for the Testing mode = args.mode train_continue = args.train_continue lr = args.lr batch_size = args.batch_size num_epoch = args.num_epoch data_dir = args.data_dir ckpt_dir = args.ckpt_dir log_dir = args.log_dir result_dir = args.result_dir log_prefix = args.log_prefix task = args.task num_mark = args.num_mark ny = args.ny nx = args.nx nch = args.nch nker = args.nker norm = args.norm network = args.network resnet_depth = args.resnet_depth joint_weight = args.joint_weight cuda = args.cuda device = torch.device(cuda if torch.cuda.is_available() else 'cpu') ## Open log file and write date_time = datetime.now().strftime("%m/%d/%Y, %H:%M:%S") f = open(log_prefix + "-" + mode + ".txt", "a") f.write("initiate %s loop : " % mode + date_time + "\n") f.write("mode: %s\n" % mode) f.write("norm: %s\n" % norm) f.write("learning rate: %.4e\n" % lr) f.write("batch size: %d\n" % batch_size) f.write("number of epoch: %d\n" % num_epoch) f.write("task: %s\n" % task) f.write("number of markers: %s\n" % num_mark) f.write("network: %s\n" % network) f.write("data dir: %s\n" % data_dir) f.write("ckpt dir: %s\n" % ckpt_dir) f.write("log dir: %s\n" % log_dir) f.write("result dir: %s\n" % result_dir) f.write("device: %s\n" % device) ## Create Result Directories result_dir_test = os.path.join(result_dir, 'test') if not os.path.exists(result_dir_test): os.makedirs(os.path.join(result_dir_test)) if mode == 'test': transform_test = "RN" # Resize - Normalization dataset_test = Dataset(data_dir=os.path.join(data_dir, 'test'), transform=transform_test, shape=(ny, nx, nch), hm_shape=(ny, nx, num_mark)) loader_test = DataLoader(dataset_test, batch_size=batch_size, shuffle=False, num_workers=NUM_WORKER) # Set Other Variables num_data_test = len(dataset_test) num_batch_test = np.ceil(num_data_test / batch_size) if network == "PoseResNet": netP = PoseResNet(in_channels=nch, out_channels=num_mark, nker=nker, norm=norm, num_layers=resnet_depth).to(device) message = init_weights(netP, init_type='normal', init_gain=0.02) f.write(message) elif network == "PoseResNetv2": netP = PoseResNetv2(out_channels=num_mark, num_layers=resnet_depth, pretrained=True).to(device) f.write("initialize network with pretrained parameters\n") ## Define the Loss Functions fn_pose = JointsMSELoss(use_target_weight=joint_weight).to(device) ## Set the Optimizers optimP = torch.optim.Adam(netP.parameters(), lr=lr, betas=(0.5, 0.999)) ## Define Other Functions fn_tonumpy = lambda x: x.to('cpu').detach().numpy().transpose(0, 2, 3, 1) fn_denorm = lambda x: (x * STD) + MEAN cmap = None ## Set SummaryWriter for the Tensorboard writer_test = SummaryWriter(log_dir=os.path.join(log_dir, 'test')) ## Inference st_epoch = 0 if mode == 'test': epoch, netP, optimP = load(ckpt_dir=ckpt_dir, netP=netP, optimP=optimP) with torch.no_grad(): netP.eval() loss_P = [] for batch, data in enumerate(loader_test, 1): input_data = data["image"].to(device) target = data["hmap"].to(device) target_weight = None # forward netP output = netP(input_data) # Build target heatmap from pose labels # try interpolation - deprecated # target = nn.functional.interpolate(target, (output.size()[1], output.size()[2], output.size()[3]), mode="nearest") size = (output.size()[2], output.size()[3]) target = Resample()(size=size, target=target) loss = fn_pose(output, target) # compute the losses loss_P_test = float(loss.item()) loss_P += [loss_P_test] # Save to the Tensorboard input_data = fn_tonumpy(fn_denorm(input_data)) output = fn_tonumpy(fn_denorm(output)) target = fn_tonumpy(fn_denorm(target)) if not batch_size==1: for j in range(input_data.shape[0]): id = batch_size * (batch - 1) + j input_data_ = input_data[j] output_ = output[j] target_ = target[j] input_data_ = np.clip(input_data_, a_min=0, a_max=1) # Convert pose heatmaps into image form output_ = reshape2image(output_) output_ = np.clip(output_, a_min=0, a_max=1) target_ = reshape2image(target_) target_ = np.clip(target_, a_min=0, a_max=1) plt.imsave(os.path.join(result_dir_test, '%04d_input.png' % id), input_data_) plt.imsave(os.path.join(result_dir_test, '%04d_output.png' % id), output_) plt.imsave(os.path.join(result_dir_test, '%04d_target.png' % id), target_) writer_test.add_image('input', input_data, id, dataformats='NHWC') writer_test.add_image('output', output, id, dataformats='NHWC') writer_test.add_image('target', target, id, dataformats='NHWC') f.write("TEST: BATCH %04d / %04d | POSE LOSS %.8f | \n" % (id + 1, num_data_test, np.mean(loss_P_test))) else: id = batch_size * (batch - 1) + 0 input_data_ = input_data output_ = output target_ = target input_data_ = reshape2image(input_data_) input_data_ = np.clip(input_data_, a_min=0, a_max=1) # Convert pose heatmaps into image form output_ = reshape2image(output_) output_ = np.clip(output_, a_min=0, a_max=1) target_ = reshape2image(target_) target_ = np.clip(target_, a_min=0, a_max=1) plt.imsave(os.path.join(result_dir_test, '%04d_input.png' % id), input_data_) plt.imsave(os.path.join(result_dir_test, '%04d_output.png' % id), output_) plt.imsave(os.path.join(result_dir_test, '%04d_target.png' % id), target_) writer_test.add_image('input', input_data_, id, dataformats='HWC') writer_test.add_image('output', output_, id, dataformats='HWC') writer_test.add_image('target', target_, id, dataformats='HWC') f.write("TEST: BATCH %04d / %04d | POSE LOSS %.8f | \n" % (id + 1, num_data_test, np.mean(loss_P_test))) writer_test.add_scalar('loss', np.mean(loss_P), batch) writer_test.close() f.close() def evaluate(args): ## Set Hyperparameters for the Evaluation mode = "test" lr = args.lr batch_size = args.batch_size data_dir = args.data_dir ckpt_dir = args.ckpt_dir num_mark = args.num_mark ny = args.ny nx = args.nx nch = args.nch nker = args.nker norm = args.norm network = args.network resnet_depth = args.resnet_depth joint_weight = args.joint_weight cuda = args.cuda device = torch.device(cuda if torch.cuda.is_available() else 'cpu') if mode == 'test': dataset_test = Dataset(data_dir=os.path.join(data_dir, args.mode), transform=None, shape=(ny, nx, nch), hm_shape=(ny, nx, num_mark)) loader_test = DataLoader(dataset_test, batch_size=batch_size, shuffle=False, num_workers=NUM_WORKER) if network == "PoseResNet": netP = PoseResNet(in_channels=nch, out_channels=num_mark, nker=nker, norm=norm, num_layers=resnet_depth).to(device) message = init_weights(netP, init_type='normal', init_gain=0.02) del message elif network == "PoseResNetv2": netP = PoseResNetv2(out_channels=num_mark, num_layers=resnet_depth, pretrained=True).to(device) ## Define the Loss Functions fn_pose = JointsMSELoss(use_target_weight=joint_weight).to(device) ## Set the Optimizers optimP = torch.optim.Adam(netP.parameters(), lr=lr, betas=(0.5, 0.999)) ## Define Other Functions fn_tonumpy = lambda x: x.to('cpu').detach().numpy() fn_denorm = lambda x: (x * STD) + MEAN ## Inference if mode == 'test': epoch, netP, optimP = load(ckpt_dir=ckpt_dir, netP=netP, optimP=optimP) with torch.no_grad(): netP.eval() evals = [] for batch, data in enumerate(loader_test, 1): input_data = data["image"].to(device) target = data["hmap"].to(device) target_weight = None # forward netP output = netP(input_data) # Build target heatmap from pose labels # try interpolation - deprecated # target = nn.functional.interpolate(target, (output.size()[1], output.size()[2], output.size()[3]), mode="nearest") size = (output.size()[2], output.size()[3]) target = Resample()(size=size, target=target) # Convert tensors to numpy arrays input_data = fn_tonumpy(fn_denorm(input_data)) output = fn_tonumpy(fn_denorm(output)) target = fn_tonumpy(fn_denorm(target)) if not batch_size==1: for j in range(input_data.shape[0]): output_ = output[j] target_ = target[j] # print(output_.shape) acc, avg_acc, cnt, pred = accuracy(output_, target_) evals.append({"acc" : acc.tolist(), "avg_acc" : avg_acc, "cnt" : cnt, "pred" : pred.tolist()}) else: output_ = output target_ = target # print(output_.shape) acc, avg_acc, cnt, pred = accuracy(output_, target_) evals.append({"acc" : acc.tolist(), "avg_acc" : avg_acc, "cnt" : cnt, "pred" : pred.tolist()}) return evals
[ "numpy.clip", "os.path.exists", "numpy.ceil", "numpy.mean", "torch.utils.data.random_split", "src.loss.JointsMSELoss", "os.path.join", "datetime.datetime.now", "torch.cuda.is_available", "torch.utils.data.DataLoader", "torch.no_grad" ]
[((1942, 1975), 'os.path.join', 'os.path.join', (['result_dir', '"""train"""'], {}), "(result_dir, 'train')\n", (1954, 1975), False, 'import os\n'), ((9718, 9750), 'os.path.join', 'os.path.join', (['result_dir', '"""test"""'], {}), "(result_dir, 'test')\n", (9730, 9750), False, 'import os\n'), ((1988, 2020), 'os.path.exists', 'os.path.exists', (['result_dir_train'], {}), '(result_dir_train)\n', (2002, 2020), False, 'import os\n'), ((2513, 2549), 'numpy.ceil', 'np.ceil', (['(num_data_train / batch_size)'], {}), '(num_data_train / batch_size)\n', (2520, 2549), True, 'import numpy as np\n'), ((2588, 2680), 'torch.utils.data.random_split', 'torch.utils.data.random_split', (['dataset_full', '[num_data_train, num_data - num_data_train]'], {}), '(dataset_full, [num_data_train, num_data -\n num_data_train])\n', (2617, 2680), False, 'import torch\n'), ((2699, 2790), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_train'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'NUM_WORKER'}), '(dataset_train, batch_size=batch_size, shuffle=True, num_workers=\n NUM_WORKER)\n', (2709, 2790), False, 'from torch.utils.data import DataLoader\n'), ((2876, 2965), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_val'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'NUM_WORKER'}), '(dataset_val, batch_size=batch_size, shuffle=True, num_workers=\n NUM_WORKER)\n', (2886, 2965), False, 'from torch.utils.data import DataLoader\n'), ((9763, 9794), 'os.path.exists', 'os.path.exists', (['result_dir_test'], {}), '(result_dir_test)\n', (9777, 9794), False, 'import os\n'), ((10135, 10226), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_test'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'NUM_WORKER'}), '(dataset_test, batch_size=batch_size, shuffle=False, num_workers=\n NUM_WORKER)\n', (10145, 10226), False, 'from torch.utils.data import DataLoader\n'), ((10401, 10436), 'numpy.ceil', 'np.ceil', (['(num_data_test / batch_size)'], {}), '(num_data_test / batch_size)\n', (10408, 10436), True, 'import numpy as np\n'), ((16321, 16412), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_test'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'NUM_WORKER'}), '(dataset_test, batch_size=batch_size, shuffle=False, num_workers=\n NUM_WORKER)\n', (16331, 16412), False, 'from torch.utils.data import DataLoader\n'), ((1102, 1127), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1125, 1127), False, 'import torch\n'), ((1189, 1203), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1201, 1203), False, 'from datetime import datetime, timedelta, timezone, date\n'), ((2042, 2072), 'os.path.join', 'os.path.join', (['result_dir_train'], {}), '(result_dir_train)\n', (2054, 2072), False, 'import os\n'), ((3543, 3588), 'src.loss.JointsMSELoss', 'JointsMSELoss', ([], {'use_target_weight': 'joint_weight'}), '(use_target_weight=joint_weight)\n', (3556, 3588), False, 'from src.loss import JointsMSELoss\n'), ((3959, 3989), 'os.path.join', 'os.path.join', (['log_dir', '"""train"""'], {}), "(log_dir, 'train')\n", (3971, 3989), False, 'import os\n'), ((8883, 8908), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (8906, 8908), False, 'import torch\n'), ((8969, 8983), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8981, 8983), False, 'from datetime import datetime, timedelta, timezone, date\n'), ((9816, 9845), 'os.path.join', 'os.path.join', (['result_dir_test'], {}), '(result_dir_test)\n', (9828, 9845), False, 'import os\n'), ((10951, 10996), 'src.loss.JointsMSELoss', 'JointsMSELoss', ([], {'use_target_weight': 'joint_weight'}), '(use_target_weight=joint_weight)\n', (10964, 10996), False, 'from src.loss import JointsMSELoss\n'), ((11366, 11395), 'os.path.join', 'os.path.join', (['log_dir', '"""test"""'], {}), "(log_dir, 'test')\n", (11378, 11395), False, 'import os\n'), ((11614, 11629), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11627, 11629), False, 'import torch\n'), ((16058, 16083), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (16081, 16083), False, 'import torch\n'), ((16922, 16967), 'src.loss.JointsMSELoss', 'JointsMSELoss', ([], {'use_target_weight': 'joint_weight'}), '(use_target_weight=joint_weight)\n', (16935, 16967), False, 'from src.loss import JointsMSELoss\n'), ((17412, 17427), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (17425, 17427), False, 'import torch\n'), ((2224, 2255), 'os.path.join', 'os.path.join', (['data_dir', '"""train"""'], {}), "(data_dir, 'train')\n", (2236, 2255), False, 'import os\n'), ((7646, 7661), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7659, 7661), False, 'import torch\n'), ((9967, 9997), 'os.path.join', 'os.path.join', (['data_dir', '"""test"""'], {}), "(data_dir, 'test')\n", (9979, 9997), False, 'import os\n'), ((16160, 16193), 'os.path.join', 'os.path.join', (['data_dir', 'args.mode'], {}), '(data_dir, args.mode)\n', (16172, 16193), False, 'import os\n'), ((6049, 6086), 'numpy.clip', 'np.clip', (['input_data'], {'a_min': '(0)', 'a_max': '(1)'}), '(input_data, a_min=0, a_max=1)\n', (6056, 6086), True, 'import numpy as np\n'), ((6224, 6257), 'numpy.clip', 'np.clip', (['output'], {'a_min': '(0)', 'a_max': '(1)'}), '(output, a_min=0, a_max=1)\n', (6231, 6257), True, 'import numpy as np\n'), ((14457, 14495), 'numpy.clip', 'np.clip', (['input_data_'], {'a_min': '(0)', 'a_max': '(1)'}), '(input_data_, a_min=0, a_max=1)\n', (14464, 14495), True, 'import numpy as np\n'), ((14640, 14674), 'numpy.clip', 'np.clip', (['output_'], {'a_min': '(0)', 'a_max': '(1)'}), '(output_, a_min=0, a_max=1)\n', (14647, 14674), True, 'import numpy as np\n'), ((14758, 14792), 'numpy.clip', 'np.clip', (['target_'], {'a_min': '(0)', 'a_max': '(1)'}), '(target_, a_min=0, a_max=1)\n', (14765, 14792), True, 'import numpy as np\n'), ((15511, 15526), 'numpy.mean', 'np.mean', (['loss_P'], {}), '(loss_P)\n', (15518, 15526), True, 'import numpy as np\n'), ((7393, 7414), 'numpy.mean', 'np.mean', (['loss_P_train'], {}), '(loss_P_train)\n', (7400, 7414), True, 'import numpy as np\n'), ((13063, 13101), 'numpy.clip', 'np.clip', (['input_data_'], {'a_min': '(0)', 'a_max': '(1)'}), '(input_data_, a_min=0, a_max=1)\n', (13070, 13101), True, 'import numpy as np\n'), ((13282, 13316), 'numpy.clip', 'np.clip', (['output_'], {'a_min': '(0)', 'a_max': '(1)'}), '(output_, a_min=0, a_max=1)\n', (13289, 13316), True, 'import numpy as np\n'), ((13408, 13442), 'numpy.clip', 'np.clip', (['target_'], {'a_min': '(0)', 'a_max': '(1)'}), '(target_, a_min=0, a_max=1)\n', (13415, 13442), True, 'import numpy as np\n'), ((14825, 14877), 'os.path.join', 'os.path.join', (['result_dir_test', "('%04d_input.png' % id)"], {}), "(result_dir_test, '%04d_input.png' % id)\n", (14837, 14877), False, 'import os\n'), ((14923, 14976), 'os.path.join', 'os.path.join', (['result_dir_test', "('%04d_output.png' % id)"], {}), "(result_dir_test, '%04d_output.png' % id)\n", (14935, 14976), False, 'import os\n'), ((15018, 15071), 'os.path.join', 'os.path.join', (['result_dir_test', "('%04d_target.png' % id)"], {}), "(result_dir_test, '%04d_target.png' % id)\n", (15030, 15071), False, 'import os\n'), ((5746, 5767), 'numpy.mean', 'np.mean', (['loss_P_train'], {}), '(loss_P_train)\n', (5753, 5767), True, 'import numpy as np\n'), ((6400, 6453), 'os.path.join', 'os.path.join', (['result_dir_train', "('%04d_input.png' % id)"], {}), "(result_dir_train, '%04d_input.png' % id)\n", (6412, 6453), False, 'import os\n'), ((6548, 6602), 'os.path.join', 'os.path.join', (['result_dir_train', "('%04d_output.png' % id)"], {}), "(result_dir_train, '%04d_output.png' % id)\n", (6560, 6602), False, 'import os\n'), ((6904, 6957), 'os.path.join', 'os.path.join', (['result_dir_train', "('%04d_input.png' % id)"], {}), "(result_dir_train, '%04d_input.png' % id)\n", (6916, 6957), False, 'import os\n'), ((7049, 7103), 'os.path.join', 'os.path.join', (['result_dir_train', "('%04d_output.png' % id)"], {}), "(result_dir_train, '%04d_output.png' % id)\n", (7061, 7103), False, 'import os\n'), ((13479, 13531), 'os.path.join', 'os.path.join', (['result_dir_test', "('%04d_input.png' % id)"], {}), "(result_dir_test, '%04d_input.png' % id)\n", (13491, 13531), False, 'import os\n'), ((13581, 13634), 'os.path.join', 'os.path.join', (['result_dir_test', "('%04d_output.png' % id)"], {}), "(result_dir_test, '%04d_output.png' % id)\n", (13593, 13634), False, 'import os\n'), ((13680, 13733), 'os.path.join', 'os.path.join', (['result_dir_test', "('%04d_target.png' % id)"], {}), "(result_dir_test, '%04d_target.png' % id)\n", (13692, 13733), False, 'import os\n'), ((15440, 15460), 'numpy.mean', 'np.mean', (['loss_P_test'], {}), '(loss_P_test)\n', (15447, 15460), True, 'import numpy as np\n'), ((14118, 14138), 'numpy.mean', 'np.mean', (['loss_P_test'], {}), '(loss_P_test)\n', (14125, 14138), True, 'import numpy as np\n')]
# Copyright 2019 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. # ============================================================================== """Local feature aggregation similarity computation. For more details, please refer to the paper: "Detect-to-Retrieve: Efficient Regional Aggregation for Image Search", Proc. CVPR'19 (https://arxiv.org/abs/1812.01584). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from delf import aggregation_config_pb2 # Aliases for aggregation types. _VLAD = aggregation_config_pb2.AggregationConfig.VLAD _ASMK = aggregation_config_pb2.AggregationConfig.ASMK _ASMK_STAR = aggregation_config_pb2.AggregationConfig.ASMK_STAR class SimilarityAggregatedRepresentation(object): """Class for computing similarity of aggregated local feature representations. Args: aggregation_config: AggregationConfig object defining type of aggregation to use. Raises: ValueError: If aggregation type is invalid. """ def __init__(self, aggregation_config): self._feature_dimensionality = aggregation_config.feature_dimensionality self._aggregation_type = aggregation_config.aggregation_type # Only relevant if using ASMK/ASMK*. Otherwise, ignored. self._use_l2_normalization = aggregation_config.use_l2_normalization self._alpha = aggregation_config.alpha self._tau = aggregation_config.tau # Only relevant if using ASMK*. Otherwise, ignored. self._number_bits = np.array([bin(n).count('1') for n in range(256)]) def ComputeSimilarity(self, aggregated_descriptors_1, aggregated_descriptors_2, feature_visual_words_1=None, feature_visual_words_2=None): """Computes similarity between aggregated descriptors. Args: aggregated_descriptors_1: 1-D NumPy array. aggregated_descriptors_2: 1-D NumPy array. feature_visual_words_1: Used only for ASMK/ASMK* aggregation type. 1-D sorted NumPy integer array denoting visual words corresponding to `aggregated_descriptors_1`. feature_visual_words_2: Used only for ASMK/ASMK* aggregation type. 1-D sorted NumPy integer array denoting visual words corresponding to `aggregated_descriptors_2`. Returns: similarity: Float. The larger, the more similar. Raises: ValueError: If aggregation type is invalid. """ if self._aggregation_type == _VLAD: similarity = np.dot(aggregated_descriptors_1, aggregated_descriptors_2) elif self._aggregation_type == _ASMK: similarity = self._AsmkSimilarity( aggregated_descriptors_1, aggregated_descriptors_2, feature_visual_words_1, feature_visual_words_2, binarized=False) elif self._aggregation_type == _ASMK_STAR: similarity = self._AsmkSimilarity( aggregated_descriptors_1, aggregated_descriptors_2, feature_visual_words_1, feature_visual_words_2, binarized=True) else: raise ValueError('Invalid aggregation type: %d' % self._aggregation_type) return similarity def _CheckAsmkDimensionality(self, aggregated_descriptors, num_visual_words, descriptor_name): """Checks that ASMK dimensionality is as expected. Args: aggregated_descriptors: 1-D NumPy array. num_visual_words: Integer. descriptor_name: String. Raises: ValueError: If descriptor dimensionality is incorrect. """ if len(aggregated_descriptors ) / num_visual_words != self._feature_dimensionality: raise ValueError( 'Feature dimensionality for aggregated descriptor %s is invalid: %d;' ' expected %d.' % (descriptor_name, len(aggregated_descriptors) / num_visual_words, self._feature_dimensionality)) def _SigmaFn(self, x): """Selectivity ASMK/ASMK* similarity function. Args: x: Scalar or 1-D NumPy array. Returns: result: Same type as input, with output of selectivity function. """ if np.isscalar(x): if x > self._tau: result = np.sign(x) * np.power(np.absolute(x), self._alpha) else: result = 0.0 else: result = np.zeros_like(x) above_tau = np.nonzero(x > self._tau) result[above_tau] = np.sign(x[above_tau]) * np.power( np.absolute(x[above_tau]), self._alpha) return result def _BinaryNormalizedInnerProduct(self, descriptors_1, descriptors_2): """Computes normalized binary inner product. Args: descriptors_1: 1-D NumPy integer array. descriptors_2: 1-D NumPy integer array. Returns: inner_product: Float. Raises: ValueError: If the dimensionality of descriptors is different. """ num_descriptors = len(descriptors_1) if num_descriptors != len(descriptors_2): raise ValueError( 'Descriptors have incompatible dimensionality: %d vs %d' % (len(descriptors_1), len(descriptors_2))) h = 0 for i in range(num_descriptors): h += self._number_bits[np.bitwise_xor(descriptors_1[i], descriptors_2[i])] # If local feature dimensionality is lower than 8, then use that to compute # proper binarized inner product. bits_per_descriptor = min(self._feature_dimensionality, 8) total_num_bits = bits_per_descriptor * num_descriptors return 1.0 - 2.0 * h / total_num_bits def _AsmkSimilarity(self, aggregated_descriptors_1, aggregated_descriptors_2, visual_words_1, visual_words_2, binarized=False): """Compute ASMK-based similarity. If `aggregated_descriptors_1` or `aggregated_descriptors_2` is empty, we return a similarity of -1.0. If binarized is True, `aggregated_descriptors_1` and `aggregated_descriptors_2` must be of type uint8. Args: aggregated_descriptors_1: 1-D NumPy array. aggregated_descriptors_2: 1-D NumPy array. visual_words_1: 1-D sorted NumPy integer array denoting visual words corresponding to `aggregated_descriptors_1`. visual_words_2: 1-D sorted NumPy integer array denoting visual words corresponding to `aggregated_descriptors_2`. binarized: If True, compute ASMK* similarity. Returns: similarity: Float. The larger, the more similar. Raises: ValueError: If input descriptor dimensionality is inconsistent, or if descriptor type is unsupported. """ num_visual_words_1 = len(visual_words_1) num_visual_words_2 = len(visual_words_2) if not num_visual_words_1 or not num_visual_words_2: return -1.0 # Parse dimensionality used per visual word. They must be the same for both # aggregated descriptors. If using ASMK, they also must be equal to # self._feature_dimensionality. if binarized: if aggregated_descriptors_1.dtype != 'uint8': raise ValueError('Incorrect input descriptor type: %s' % aggregated_descriptors_1.dtype) if aggregated_descriptors_2.dtype != 'uint8': raise ValueError('Incorrect input descriptor type: %s' % aggregated_descriptors_2.dtype) per_visual_word_dimensionality = int( len(aggregated_descriptors_1) / num_visual_words_1) if len(aggregated_descriptors_2 ) / num_visual_words_2 != per_visual_word_dimensionality: raise ValueError('ASMK* dimensionality is inconsistent.') else: per_visual_word_dimensionality = self._feature_dimensionality self._CheckAsmkDimensionality(aggregated_descriptors_1, num_visual_words_1, '1') self._CheckAsmkDimensionality(aggregated_descriptors_2, num_visual_words_2, '2') aggregated_descriptors_1_reshape = np.reshape( aggregated_descriptors_1, [num_visual_words_1, per_visual_word_dimensionality]) aggregated_descriptors_2_reshape = np.reshape( aggregated_descriptors_2, [num_visual_words_2, per_visual_word_dimensionality]) # Loop over visual words, compute similarity. unnormalized_similarity = 0.0 ind_1 = 0 ind_2 = 0 while ind_1 < num_visual_words_1 and ind_2 < num_visual_words_2: if visual_words_1[ind_1] == visual_words_2[ind_2]: if binarized: inner_product = self._BinaryNormalizedInnerProduct( aggregated_descriptors_1_reshape[ind_1], aggregated_descriptors_2_reshape[ind_2]) else: inner_product = np.dot(aggregated_descriptors_1_reshape[ind_1], aggregated_descriptors_2_reshape[ind_2]) unnormalized_similarity += self._SigmaFn(inner_product) ind_1 += 1 ind_2 += 1 elif visual_words_1[ind_1] > visual_words_2[ind_2]: ind_2 += 1 else: ind_1 += 1 final_similarity = unnormalized_similarity if self._use_l2_normalization: final_similarity /= np.sqrt(num_visual_words_1 * num_visual_words_2) return final_similarity
[ "numpy.reshape", "numpy.isscalar", "numpy.sqrt", "numpy.bitwise_xor", "numpy.absolute", "numpy.dot", "numpy.sign", "numpy.nonzero", "numpy.zeros_like" ]
[((4742, 4756), 'numpy.isscalar', 'np.isscalar', (['x'], {}), '(x)\n', (4753, 4756), True, 'import numpy as np\n'), ((8593, 8687), 'numpy.reshape', 'np.reshape', (['aggregated_descriptors_1', '[num_visual_words_1, per_visual_word_dimensionality]'], {}), '(aggregated_descriptors_1, [num_visual_words_1,\n per_visual_word_dimensionality])\n', (8603, 8687), True, 'import numpy as np\n'), ((8740, 8834), 'numpy.reshape', 'np.reshape', (['aggregated_descriptors_2', '[num_visual_words_2, per_visual_word_dimensionality]'], {}), '(aggregated_descriptors_2, [num_visual_words_2,\n per_visual_word_dimensionality])\n', (8750, 8834), True, 'import numpy as np\n'), ((3098, 3156), 'numpy.dot', 'np.dot', (['aggregated_descriptors_1', 'aggregated_descriptors_2'], {}), '(aggregated_descriptors_1, aggregated_descriptors_2)\n', (3104, 3156), True, 'import numpy as np\n'), ((4908, 4924), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (4921, 4924), True, 'import numpy as np\n'), ((4943, 4968), 'numpy.nonzero', 'np.nonzero', (['(x > self._tau)'], {}), '(x > self._tau)\n', (4953, 4968), True, 'import numpy as np\n'), ((9762, 9810), 'numpy.sqrt', 'np.sqrt', (['(num_visual_words_1 * num_visual_words_2)'], {}), '(num_visual_words_1 * num_visual_words_2)\n', (9769, 9810), True, 'import numpy as np\n'), ((4995, 5016), 'numpy.sign', 'np.sign', (['x[above_tau]'], {}), '(x[above_tau])\n', (5002, 5016), True, 'import numpy as np\n'), ((5765, 5815), 'numpy.bitwise_xor', 'np.bitwise_xor', (['descriptors_1[i]', 'descriptors_2[i]'], {}), '(descriptors_1[i], descriptors_2[i])\n', (5779, 5815), True, 'import numpy as np\n'), ((4799, 4809), 'numpy.sign', 'np.sign', (['x'], {}), '(x)\n', (4806, 4809), True, 'import numpy as np\n'), ((5039, 5064), 'numpy.absolute', 'np.absolute', (['x[above_tau]'], {}), '(x[above_tau])\n', (5050, 5064), True, 'import numpy as np\n'), ((9321, 9413), 'numpy.dot', 'np.dot', (['aggregated_descriptors_1_reshape[ind_1]', 'aggregated_descriptors_2_reshape[ind_2]'], {}), '(aggregated_descriptors_1_reshape[ind_1],\n aggregated_descriptors_2_reshape[ind_2])\n', (9327, 9413), True, 'import numpy as np\n'), ((4821, 4835), 'numpy.absolute', 'np.absolute', (['x'], {}), '(x)\n', (4832, 4835), True, 'import numpy as np\n')]
''' ############################################################################### "MajoranaNanowire" Python3 Module v 1.0 (2020) Created by <NAME> (2018) ############################################################################### "Hamiltonian" submodule This sub-package builds and solves Kitaev, Lutchyn-Oreg and 8-band k.p Hamiltonians for nanowires. ############################################################################### ''' #%%############################################################################ ######################## Required Packages ############################ ############################################################################### import os import multiprocessing os.environ["MKL_NUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" os.environ["OMP_NUM_THREADS"] = "1" import numpy as np import MajoranaNanowires.H_class.Lutchyn_Oreg.builders import MajoranaNanowires.H_class.Lutchyn_Oreg.solvers import MajoranaNanowires.H_class.Kitaev.builders import MajoranaNanowires.H_class.Kitaev.solvers import MajoranaNanowires.H_class.Kane.builders import MajoranaNanowires.H_class.Kane.solvers #%%############################################################################ ######################## Kitaev Nanowires ############################# ############################################################################### #%% def Kitaev_builder(N,mu,t,Δ,sparse='no'): """ Kitaev Hamiltonian builder. It obtaines the Hamiltoninan for a Kitaev chain. Parameters ---------- N: int or arr Number of sites. If it is an array, each element is the number of sites in each direction. mu: float or arr Chemical potential. If it is an array, each element is the chemical potential on each site of the lattice. t: float Hopping elements between sites. t[N] is not used. Δ: float or arr Superconductor hopping element between sites. If it is an array, each element is the hopping on each site of the lattice. Δ(N) is not used. sparse: {"yes","no"} Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix, while "no" builds a dense matrix. Returns ------- H: arr Hamiltonian matrix. Notes ----- 2-dimensional and 3-dimensional Kitaev Hamiltonians are not still avialable. """ #Obtain the dimension of the system: if np.isscalar(N): n_dim=1 else: n_dim=len(N) #Error handler assert (n_dim<3),"The number of dimensions must be 1<=N<=3." if not(sparse=='no' or sparse=='yes'): print('AssertionError: Please, for sparse argument, choose between {"yes","no"}. "yes" argument has been chosen as default.') sparse='yes' #Compute the Hamiltonian: if n_dim==1: H=MajoranaNanowires.H_class.Kitaev.builders.Kitaev_1D_builder(N,mu,t,Δ, sparse=sparse) else: assert (n_dim<=1),"2D and 3D Kitaev chains are not still avialable." return (H) #%% def Kitaev_solver(H,n=1,mu=0,n_eig='none'): """ Kitaev Hamiltonian solver. It solves the Hamiltonian of a Kitaev chain. Parameters ---------- H: arr Kitaev Hamiltonian built with Kitaev_builder(). n: int Number of times you want to diagonalize the Hamiltonian. In each step, it is expected that mu, B or aR is different. mu: float or arr -If mu is a float, the Hamiltonian is diagonalized once adding this value to the Hamiltonian -If mu is a 1-D array of length=N, the Hamiltonian is diagonalized once adding each element of mu to each site of the built Hamiltonian. -If mu is a 1-D array of length=n, the Hamiltonian is diagonalized n times, adding in each step i, the same chemical potential mu[i] in every site. -If mu is a 2-D array (n x N), the Hamiltonian is diagonalized n times, adding to the Hamiltonian in each step i the chemical potential mu[i,:]. n_eig: int Number of desire eigenvalues (if H is sparse). 'none' means all. Returns ------- E: arr (n_eig x n) Eigevalues (energies), ordered from smaller to larger. U: arr ((2 x N) x n_eig x n) Eigenvectors of the system with the same ordering. Notes ----- 2-dimensional and 3-dimensional Kitaev Hamiltonians are not still avialable. """ #Obtain the number of sites: N=int(len(H)/2) #Obtain the dimension of the system: if np.isscalar(N): n_dim=1 else: n_dim=len(N) #Obtain the number of desire eigenvalues: if n_eig=='none' or n_eig==0: if n_dim==1: n_eig=2*N else: for i_dim in range(n_dim): n_eig=2*len(N[i_dim]) #Compute the solution: if n_dim==1: H=MajoranaNanowires.H_class.Kitaev.solvers.Kitaev_1D_solver(H,n,mu=mu,n_eig=n_eig) else: assert (n_dim>=1),"2D and 3D Kitaev chains are not still avialable." #%%############################################################################ ######################## Lutchyn Nanowires ############################ ############################################################################### #%% def LO_builder(N,dis,m_eff, mu,B,aR, BdG='yes', d=0, space='position',k_vec=np.array([]), sparse='yes', method='BF',Nxp=None): """ Lutchy-Oreg Hamiltonian builder. It obtaines the Hamiltoninan for a Lutchy-Oreg chain. Parameters ---------- N: int or arr Number of sites. If it is an array, each element is the number of sites in each direction. dis: int or arr Distance (in nm) between sites. If it is an array, each element is the distance between sites in each direction. m_eff: int or arr Effective mass. If it is an array (1D, 2D or 3D), each element is the effective mass on each site of the lattice. mu: float or arr Chemical potential. If it is an array (1D, 2D or 3D), each element is the chemical potential on each site of the lattice. B: float or arr Zeeman splitting. If it is an array, each element is the Zeeman splitting in each direction. aR: float or arr Rashba coupling. -If aR is a float, aR is the Rashba coupling along the z-direction, with the same value in every site. -If aR is a 1D array with length=3, each element of the array is the rashba coupling in each direction. -If aR is an array of arrays (3 x N), each element of aR[i] is an array (1D, 2D or 3D) with the on-site Rashba couplings in the direction i. BdG: {"yes","no"} If BdG is "yes", it is built the Hamiltonian in the Bogoliubov-de Gennes formalism. d: float or arr Superconductor paring amplitud. -If d is a float, d is the Rashba coupling along the y-direction, with the same value in every site. -If d is an array (1D, 2D or 3D), each element of the array is the superconductor paring amplitud in each site. space: {"position","momentum"} Space in which the Hamiltonian is built. "position" means real-space (r-space). In this case the boundary conditions are open. On the other hand, "momentum" means reciprocal space (k-space). In this case the built Hamiltonian corresponds to the Hamiltonian of the unit cell, with periodic boundary conditions along the x-direction. For large matrices, build them in real space, and then you can diagonalize it in momentum space with the option "position2momentum" in the Lutchy_solver funtion. k_vec: arr If space=='momentum', k_vec is the (discretized) momentum vector, usually in the First Brillouin Zone. sparse: {"yes","no"} Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix, while "no" builds a dense matrix. method: {"BF","MO"} Aproach used to build (and solve in future steps) the Hamiltonian. The possible methods are: 1. BF: Brute Force- The entire Hamiltonian is built, so it is directly diagonalize in the solver. 2. MO: Molecular Orbitals (decomposition)- The 3D Hamiltonian is projected into the molecular orbital basis spanned by the sections along the wire. In this case, the returnted Hamiltonian is a tuple where: H[0] is a 1D array whose elements H[0][i] are 2D arrays describing the cross-section Hamiltonian at the position x[i] of the wire; H[1] is the 3D Hamiltonian which includes the orbital-coupling terms; and, if BdG==yes, H[2] is the 3D Hamiltonian which includes the SC-coupling terms. Nxp: int (If method=='MO') Number of points to compute the molecular orbitals of the H_2D. For the remaining (N[0]-Nxp) slices, it is considered that the molecular orbitals corresponding to the first (N[0]-Nxp)/2 slices are the same than for the slice N[Nxp]. Similarly, it is considered that for the last (N[0]-Nxp)/2 slices, the molecular orbitals are the same than that of N[N[0]-Nxp]. Returns ------- H: arr Hamiltonian matrix. """ ##Obtain default parameters if there are none given: #Obtain k_vec (if necesssary): if space=='momentum': assert not(k_vec==np.array([])), 'You have to choose the reciprocal-space vector k_vec in which you want to diagonalize the spectrum.' #Obtain the effective mass: if np.isscalar(m_eff) and m_eff=='InAs': m_eff=0.023 elif np.isscalar(m_eff) and m_eff=='InSb': m_eff=0.015 #Obtain the SC pairing amplitud: if np.isscalar(d) and d=='Al': d=0.2 elif np.isscalar(d) and d=='NbTiN': d=0.5 ##Compute the Hamiltonian: if method=='BF': if BdG=='no': if np.isscalar(N): H=MajoranaNanowires.H_class.Lutchyn_Oreg.builders.LO_1D_builder_NoSC(N,dis,m_eff,mu,B,aR, space=space, k_vec=k_vec, sparse=sparse) elif len(N)==2: H=MajoranaNanowires.H_class.Lutchyn_Oreg.builders.LO_2D_builder_NoSC(N,dis,m_eff,mu,B,aR, space=space, k_vec=k_vec, sparse=sparse) elif len(N)==3: H=MajoranaNanowires.H_class.Lutchyn_Oreg.builders.LO_3D_builder_NoSC(N,dis,m_eff,mu,B,aR, space=space, k_vec=k_vec, sparse=sparse) else: if np.isscalar(N): H=MajoranaNanowires.H_class.Lutchyn_Oreg.builders.LO_1D_builder(N,dis,m_eff,mu,B,aR,d, space=space, k_vec=k_vec, sparse=sparse) elif len(N)==2: H=MajoranaNanowires.H_class.Lutchyn_Oreg.builders.LO_2D_builder(N,dis,m_eff,mu,B,aR,d, space=space, k_vec=k_vec, sparse=sparse) elif len(N)==3: H=MajoranaNanowires.H_class.Lutchyn_Oreg.builders.LO_3D_builder(N,dis,m_eff,mu,B,aR,d, space=space, k_vec=k_vec, sparse=sparse) elif method=='MO': if len(N)==3: H=MajoranaNanowires.H_class.Lutchyn_Oreg.builders.LO_3D_builder_MO(N,dis,m_eff,mu,B,aR,d=d,Nxp=Nxp,BdG=BdG) return (H) #%% def LO_solver_multiprocessing(H,N,dis, args,pipe): """ Allows to solve the Hamiltonian using several CPUs. Parameters ---------- H: arr Discretized Lutchyn-Oreg Hamiltonian built with Lutchyn_builder. N: int or arr Number of sites. If it is an array, each element is the number of sites in each direction. dis: int or arr Distance (in nm) between sites. If it is an array, each element is the distance between sites in each direction. arg: dictionary Dictionary with the keywords arguments of Lutchyn_solver. pipe: pipe Pipe to the corresponding process. """ #Send work to a given process: E,U=LO_solver(H,N,dis,1,n_CPU=1, mu=args['mu'],B=args['B'],aR=args['aR'],d=args['d'], BdG=args['BdG'], space=args['space'],k_vec=args['k_vec'], m_eff=args['m_eff'], sparse=args['sparse'],n_eig=args['n_eig'], near=args['near'], section=args['section'], method=args['method'],Nxp=args['Nxp'],n_orb=args['n_orb']) #Recover output: pipe.send((E,U)) #Close process: pipe.close() return True #%% def LO_solver(H,N,dis, n,n_CPU=1, mu=0,B=0,aR=0,d=0, BdG='yes', space='position',k_vec=np.array([]), m_eff=0.023, sparse='yes',n_eig=None,near=None, section='rectangular', method='BF',Nxp=None,n_orb=None): """ Lutchy-Oreg Hamiltonian solver. It solves the Hamiltoninan (built with Lutchyn_builder) of a Lutchy-Oreg chain. Parameters ---------- H: arr Discretized Lutchyn-Oreg Hamiltonian built with Lutchyn_builder. N: int or arr Number of sites. If it is an array, each element is the number of sites in each direction. dis: int or arr Distance (in nm) between sites. If it is an array, each element is the distance between sites in each direction. n: int Number of times that the Hamiltonian is diagonalized. In each step, it is expected that mu, B or aR is different. n_CPU: int Number of CPUs to be used. Each CPU is used to solve one of the n steps. Therefore, n must be a multiple of n_CPU. mu: float or arr Chemical potential. -If mu is a float or a 1D array of length=N, the same chemical potential is added to the Hamiltonian in every diagonalization step. If it is a float, the constant is added in each site, while if it is an array, each element of the array corresponds to the on-site chemical potential. -If mu is a 1D array of length=n, it is added in each diagonalization step i, the constant value mu[i] in every site. -If mu is an array of arrays (n x (N)), in each diagonalization step i, it is added to the Hamiltonian the chemical potential mu[i], whose matrix elements are the chemical potential in each site of the lattice. B: float or arr Zeeman splitting. -If B is a float, the same constant B is added in the x direction in each site and in every diagonalization step. -If B is a 1D array of length=3, each element of the array is the (constant) Zeeman splitting in each direction, which is added in every diagonalization step. -If B is a 1D array of length=n, each element of the array B[i] is added in each diagonalization step i in the x-direction. -If B is an 2D array (n x 3), in each diagonalization step i, it is added to the Hamiltonian the Zeeman spliting B[i], whose matrix elements are the (constant) Zeeman splitting in the 3 directions. aR: float or arr Rashba coupling. -If aR is a float, the same constant aR is added in the z direction in each site and in every diagonalization step. -If aR is a 1D array of length=3, each element of the array is the (constant) Rashba coupling in each direction, which is added in every diagonalization step. -If aR is a 2D array (3 x (N)), each element of the array aR[i] is the Rashba coupling in each direction, whose matrix alements are the on-site Rashba couplings. -If aR is an array of arrays (n x 3 x (N)), in each diagonalization step i, it is added to the Hamiltonian the Rashba coupling aR[i], whose matrix elements are the on-site Rashba coupling in the 3 directions. d: float or arr Superconducting pairing amplitude. -If d is a float or a 1D array of length=N, the same SC pairing amplitude is added to the Hamiltonian in every diagonalization step. If it is a float, the constant is added in each site, while if it is an array, each element of the array corresponds to the on-site superconductivity. -If d is a 1D array of length=n, it is added in each diagonalization step i, the constant value d[i] in every site. -If d is an array of arrays (n x (N)), in each diagonalization step i, it is added to the Hamiltonian the SC pairing amplitude d[i], whose matrix elements are the on-site superconductivity in each site of the lattice. BdG: {"yes","no"} If BdG is "yes", it is solved the Hamiltonian in the Bogoliubov-de Gennes formalism. space: {"position","momentum","position2momentum"} Space in which the Hamiltonian is built. "position" means real-space (r-space). In this case the boundary conditions are open. On the other hand, "momentum" means reciprocal space (k-space). In this case the built Hamiltonian corresponds to the Hamiltonian of the unit cell, with periodic boundary conditions along the x-direction. "position2momentum" means that the Hamiltonian is built in real space, but you want to diagonalize it in momentum space (so in each step is converted to a momentum space).This option is recommended for large matrices. k_vec: arr If space=='momentum' or "position2momentum", k_vec is the (discretized) momentum vector, usually in the First Brillouin Zone. m_eff: int Effective mass. It is only necessary in the 2D Hamiltonian when solving in momentum space. sparse: {"yes","no"} Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix, while "no" builds a dense matrix. n_eig: int If sparse=="yes", n_eig is the number of eigenvalues you want to obtain. If BdG=='yes', these eigenvalues are obtained around zero energy, whil if BdG=='no' these eigenvalues correspond to the lowest-energy eigenstates. This can be changed with the near option. near: float If sparse=="yes" and BdG=='no', near provides the value around to which the eigenvalues must be found. section: {"rectangular","hexagonal"} Whether the system have a rectangular or hexagonal cross-section in the plane zy. method: {"BF","MO"} Aproach used to solve the Hamiltonian. The builder should have the same method argument. The possible methods are: 1. BF: Brute Force- The 3D Hamiltonain is directly diagonalize in the solver. 2. MO: Molecular Orbitals (decomposition)- The 3D Hamiltonian is projected into the molecular orbital basis spanned by the sections along the wire. Nxp: int (If method=='MO') Number of points to compute the molecular orbitals of the H_2D. For the remaining (N[0]-Nxp) slices, it is considered that the molecular orbitals corresponding to the first (N[0]-Nxp)/2 slices are the same than for the slice N[Nxp]. Similarly, it is considered that for the last (N[0]-Nxp)/2 slices, the molecular orbitals are the same than that of N[N[0]-Nxp]. n_orb: int (If method=='MO') Number of moelcular orbitals to include in the diagonalization. Returns ------- E: arr (n_eig x n) Eigevalues (energies), ordered from smaller to larger. U: arr ((2 x N) x n_eig x n) Eigenvectors of the system with the same ordering. """ ##Obtain default parameters if there are none given: #Obtain the dimension of the system: if np.isscalar(N): n_dim=1 else: n_dim=len(N) #Obtain the dimension of H: if BdG=='yes': m=4*np.prod(N) else: m=2*np.prod(N) #Obtain the number of eigenvalues: if sparse=='yes' or method=='MO': assert not(n_eig==None), 'You have to choose the number of bands n_eig you want to find.' else: n_eig=m #Obtain the k_vec (if necessary): if space=='momentum': assert not(k_vec==np.array([])), 'You have to choose the reciprocal-space vector k_vec in which you want to diagonalize the spectrum.' #Obtain the effective mass: if np.isscalar(m_eff) and m_eff=='InAs': m_eff=0.023 elif np.isscalar(m_eff) and m_eff=='InSb': m_eff=0.015 ##Solve the Hamiltonian: #For one value: if n==1 and n_CPU==1: if BdG=='yes': if n_dim==1: E,U=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver(H,N,dis,mu=mu,B=B,aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E,U=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver(H,N,dis,m_eff=m_eff,mu=mu,B=B,aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E,U=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver(H,N,dis,mu=mu,B=B,aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif method=='MO': E,U=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_MO(H,N,dis,n_eig,n_orb,Nxp=Nxp,mu=mu,aR=aR,d=d,sparse=sparse,section=section,BdG=BdG) else: if n_dim==1: E,U=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver_NoSC(H,N,dis,mu=mu,B=B,aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E,U=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver_NoSC(H,N,dis,m_eff=m_eff,mu=mu,B=B,aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E,U=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_NoSC(H,N,dis,mu=mu,B=B,aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif method=='MO': E,U=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_MO(H,N,dis,n_eig,n_orb,Nxp=Nxp,mu=mu,aR=aR,d=d,sparse=sparse,section=section,BdG=BdG) #For several (serial): elif not(n==1) and n_CPU==1: E=np.empty([n_eig,n]) U=np.empty([m,n_eig,n],dtype=complex) if not(np.isscalar(mu)) and len(mu)==n: for i in range(n): if BdG=='yes': if n_dim==1: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver(H,N,dis,mu=mu[i],B=B,aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver(H,N,dis,m_eff=m_eff,mu=mu[i],B=B,aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver(H,N,dis,mu=mu[i],B=B,aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif method=='MO': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_MO(H,N,dis,n_eig,n_orb,Nxp=Nxp,mu=mu[i],aR=aR,d=d,sparse=sparse,section=section,BdG=BdG) else: if n_dim==1: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver_NoSC(H,N,dis,mu=mu[i],B=B,aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver_NoSC(H,N,dis,m_eff=m_eff,mu=mu[i],B=B,aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_NoSC(H,N,dis,mu=mu[i],B=B,aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif method=='MO': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_MO(H,N,dis,n_eig,n_orb,Nxp=Nxp,mu=mu[i],aR=aR,d=d,sparse=sparse,section=section,BdG=BdG) elif not(np.isscalar(B)) and len(B)==n: for i in range(n): if BdG=='yes': if n_dim==1: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver(H,N,dis,mu=mu,B=B[i],aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver(H,N,dis,m_eff=m_eff,mu=mu,B=B[i],aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver(H,N,dis,mu=mu,B=B[i],aR=aR,d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) else: if n_dim==1: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver_NoSC(H,N,dis,mu=mu,B=B[i],aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver_NoSC(H,N,dis,m_eff=m_eff,mu=mu,B=B[i],aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_NoSC(H,N,dis,mu=mu,B=B[i],aR=aR,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif not(np.isscalar(aR)) and len(aR)==n: for i in range(n): if BdG=='yes': if n_dim==1: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver(H,N,dis,mu=mu,B=B,aR=aR[i],d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver(H,N,dis,m_eff=m_eff,mu=mu,B=B,aR=aR[i],d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver(H,N,dis,mu=mu,B=B,aR=aR[i],d=d,space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif method=='MO': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_MO(H,N,dis,n_eig,n_orb,Nxp=Nxp,mu=mu,aR=aR[i],d=d,sparse=sparse,section=section,BdG=BdG) else: if n_dim==1: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver_NoSC(H,N,dis,mu=mu,B=B,aR=aR[i],space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver_NoSC(H,N,dis,m_eff=m_eff,mu=mu,B=B,aR=aR[i],space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_NoSC(H,N,dis,mu=mu,B=B,aR=aR[i],space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif method=='MO': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_MO(H,N,dis,n_eig,n_orb,Nxp=Nxp,mu=mu,aR=aR[i],d=d,sparse=sparse,section=section,BdG=BdG) elif BdG=='yes' and not(np.isscalar(d)) and len(d)==n: for i in range(n): if BdG=='yes': if n_dim==1: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_1D_solver(H,N,dis,mu=mu,B=B,aR=aR,d=d[i],space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near) elif n_dim==2: E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_2D_solver(H,N,dis,m_eff=m_eff,mu=mu,B=B,aR=aR,d=d[i],space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif n_dim==3: if method=='BF': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver(H,N,dis,mu=mu,B=B,aR=aR,d=d[i],space=space,k_vec=k_vec,sparse=sparse,n_eig=n_eig,near=near,section=section) elif method=='MO': E[:,i],U[:,:,i]=MajoranaNanowires.H_class.Lutchyn_Oreg.solvers.LO_3D_solver_MO(H,N,dis,n_eig,n_orb,Nxp=Nxp,mu=mu,aR=aR,d=d[i],sparse=sparse,section=section,BdG=BdG) #For several (Multiprocessing): elif not(n_CPU==1) and not(n==1): E=np.empty([n_eig,n]) U=np.empty([m,n_eig,n],dtype=complex) args={'mu':mu,'B':B,'aR':aR,'d':d,'BdG':BdG,'space':space,'k_vec':k_vec,'m_eff':m_eff,'sparse':sparse,'n_eig':n_eig,'near':near,'section':section,'method':method,'Nxp':Nxp,'n_orb':n_orb} for i_tot in range(int(n/n_CPU)): jobs=[] pipes=[] for i_CPU in range(n_CPU): pipe_start, pipe_end = multiprocessing.Pipe() pipes.append(pipe_start) if not(np.isscalar(mu)) and len(mu)==n: args['mu']=mu[n_CPU*i_tot+i_CPU] thread=multiprocessing.Process(target=LO_solver_multiprocessing,args=(H,N,dis,args,pipe_end,)) if not(np.isscalar(B)) and len(B)==n: args['B']=B[n_CPU*i_tot+i_CPU] thread=multiprocessing.Process(target=LO_solver_multiprocessing,args=(H,N,dis,args,pipe_end,)) if not(np.isscalar(aR)) and len(aR)==n: args['aR']=aR[n_CPU*i_tot+i_CPU] thread=multiprocessing.Process(target=LO_solver_multiprocessing,args=(H,N,dis,args,pipe_end,)) if BdG=='yes' and not(np.isscalar(d)) and len(d)==n: args['d']=d[n_CPU*i_tot+i_CPU] thread=multiprocessing.Process(target=LO_solver_multiprocessing,args=(H,N,dis,args,pipe_end,)) jobs.append(thread) thread.start() for i_CPU in range(n_CPU): (E[:,n_CPU*i_tot+i_CPU],U[:,:,n_CPU*i_tot+i_CPU])=pipes[i_CPU].recv() for i_CPU in jobs: i_CPU.join() return (E),(U) #%%############################################################################ ########################### Kane Nanowires ############################ ############################################################################### #%% def Kane_builder(N,dis, mu,B=0, mesh=0,sparse='yes', params={},crystal='zincblende'): """ 8-band Kane Hamiltonian builder. It obtaines the Hamiltoninan for a 8-band Kane model. Parameters ---------- N: int or arr Number of sites. If it is an array, each element is the number of sites in each direction. dis: int or arr Distance (in nm) between sites. If it is an array, each element is the distance between sites in each direction. mu: float or arr Chemical potential. If it is an array (1D, 2D or 3D), each element is the chemical potential on each site of the lattice. B: float Magnetic field along the wire's direction. mesh: arr Discretization mesh. sparse: {"yes","no"} Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix, while "no" builds a dense matrix. params: Dictionary or str Parameters to use for the Kane model. There are some default ones, for InAs, InSb, GaAs, and GaSb. crystal: {'minimal','zincblende','wurtzite'} Crystalography of the crystal. Returns ------- H: arr Hamiltonian matrix. """ ##Compute the Hamiltonian: if np.isscalar(N): H=MajoranaNanowires.H_class.Kane.builders.Kane_1D_builder(N,dis,mu,mesh=mesh,sparse=sparse,params=params,crystal=crystal) elif len(N)==2: H=MajoranaNanowires.H_class.Kane.builders.Kane_2D_builder(N,dis,mu,B=B,mesh=mesh,sparse=sparse,params=params,crystal=crystal) elif len(N)==3: H=MajoranaNanowires.H_class.Kane.builders.Kane_3D_builder(N,dis,mu,mesh=mesh,sparse=sparse,params=params,crystal=crystal) return (H) #%% def Kane_solver(H,N,dis, mu,k_vec, mesh=0,sparse='yes',n_eig=0, near=0, params={},crystal='zincblende',section='rectangular'): """ 8-band Kane Hamiltonian solver. It obtaines the eigenspectrum of a 8-band model (built with Kane_builder). Parameters ---------- H: arr Discretized Lutchyn-Oreg Hamiltonian built with Lutchyn_builder. N: int or arr Number of sites. If it is an array, each element is the number of sites in each direction. dis: int or arr Distance (in nm) between sites. If it is an array, each element is the distance between sites in each direction. mu: float or arr Chemical potential. If it is a float, the constant is added in each site, while if it is an array, each element of the array corresponds to the on-site chemical potential. k_vec: arr If space=='momentum' or "position2momentum", k_vec is the (discretized) momentum vector, usually in the First Brillouin Zone. sparse: {"yes","no"} Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix, while "no" builds a dense matrix. n_eig: int If sparse=="yes", n_eig is the number of eigenvalues you want to obtain. If BdG=='yes', these eigenvalues are obtained around zero energy, whil if BdG=='no' these eigenvalues correspond to the lowest-energy eigenstates. This can be changed with the near option. near: float If sparse=="yes" and BdG=='no', near provides the value around to which the eigenvalues must be found. params: Dictionary or str Parameters to use for the Kane model. There are some default ones, for InAs, InSb, GaAs, and GaSb. crystal: {'minimal','zincblende','wurtzite'} Crystalography of the crystal. section: {"rectangular","hexagonal"} Whether the system have a rectangular or hexagonal cross-section in the plane zy. Returns ------- E: arr (n_eig x n) Eigevalues (energies), ordered from smaller to larger. U: arr ((2 x N) x n_eig x n) Eigenvectors of the system with the same ordering. """ ##Obtain default parameters if there are none given: #Obtain the dimension of the system: if np.isscalar(N): n_dim=1 else: n_dim=len(N) #Obtain the number of eigenvalues: if sparse=='yes': assert not(n_eig==None), 'You have to choose the number of bands n_eig you want to find.' else: n_eig=8*np.prod(N) #Obtain the k_vec (if necessary): assert not(k_vec==np.array([])), 'You have to choose the reciprocal-space vector k_vec in which you want to diagonalize the spectrum.' ##Solve the Hamiltonian: if n_dim==1: E,U=MajoranaNanowires.H_class.Kane.solvers.Kane_1D_solver(H,N,dis,mu,k_vec,mesh=mesh,sparse=sparse,n_eig=n_eig,near=near,params=params,crystal=crystal,section=section) elif n_dim==2: E,U=MajoranaNanowires.H_class.Kane.solvers.Kane_2D_solver(H,N,dis,mu,k_vec,mesh=mesh,sparse=sparse,n_eig=n_eig,near=near,params=params,crystal=crystal,section=section) elif n_dim==3: E,U=MajoranaNanowires.H_class.Kane.solvers.Kane_3D_solver(H,N,dis,mu,k_vec,mesh=mesh,sparse=sparse,n_eig=n_eig,near=near,params=params,crystal=crystal,section=section) return (E),(U)
[ "numpy.prod", "numpy.isscalar", "multiprocessing.Process", "numpy.array", "numpy.empty", "multiprocessing.Pipe" ]
[((2785, 2799), 'numpy.isscalar', 'np.isscalar', (['N'], {}), '(N)\n', (2796, 2799), True, 'import numpy as np\n'), ((5169, 5183), 'numpy.isscalar', 'np.isscalar', (['N'], {}), '(N)\n', (5180, 5183), True, 'import numpy as np\n'), ((6120, 6132), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6128, 6132), True, 'import numpy as np\n'), ((14156, 14168), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (14164, 14168), True, 'import numpy as np\n'), ((22197, 22211), 'numpy.isscalar', 'np.isscalar', (['N'], {}), '(N)\n', (22208, 22211), True, 'import numpy as np\n'), ((35703, 35717), 'numpy.isscalar', 'np.isscalar', (['N'], {}), '(N)\n', (35714, 35717), True, 'import numpy as np\n'), ((38894, 38908), 'numpy.isscalar', 'np.isscalar', (['N'], {}), '(N)\n', (38905, 38908), True, 'import numpy as np\n'), ((11006, 11024), 'numpy.isscalar', 'np.isscalar', (['m_eff'], {}), '(m_eff)\n', (11017, 11024), True, 'import numpy as np\n'), ((11184, 11198), 'numpy.isscalar', 'np.isscalar', (['d'], {}), '(d)\n', (11195, 11198), True, 'import numpy as np\n'), ((22826, 22844), 'numpy.isscalar', 'np.isscalar', (['m_eff'], {}), '(m_eff)\n', (22837, 22844), True, 'import numpy as np\n'), ((11073, 11091), 'numpy.isscalar', 'np.isscalar', (['m_eff'], {}), '(m_eff)\n', (11084, 11091), True, 'import numpy as np\n'), ((11235, 11249), 'numpy.isscalar', 'np.isscalar', (['d'], {}), '(d)\n', (11246, 11249), True, 'import numpy as np\n'), ((11370, 11384), 'numpy.isscalar', 'np.isscalar', (['N'], {}), '(N)\n', (11381, 11384), True, 'import numpy as np\n'), ((11925, 11939), 'numpy.isscalar', 'np.isscalar', (['N'], {}), '(N)\n', (11936, 11939), True, 'import numpy as np\n'), ((22324, 22334), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (22331, 22334), True, 'import numpy as np\n'), ((22357, 22367), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (22364, 22367), True, 'import numpy as np\n'), ((22893, 22911), 'numpy.isscalar', 'np.isscalar', (['m_eff'], {}), '(m_eff)\n', (22904, 22911), True, 'import numpy as np\n'), ((24908, 24928), 'numpy.empty', 'np.empty', (['[n_eig, n]'], {}), '([n_eig, n])\n', (24916, 24928), True, 'import numpy as np\n'), ((24938, 24976), 'numpy.empty', 'np.empty', (['[m, n_eig, n]'], {'dtype': 'complex'}), '([m, n_eig, n], dtype=complex)\n', (24946, 24976), True, 'import numpy as np\n'), ((39151, 39161), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (39158, 39161), True, 'import numpy as np\n'), ((39227, 39239), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (39235, 39239), True, 'import numpy as np\n'), ((10841, 10853), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (10849, 10853), True, 'import numpy as np\n'), ((22669, 22681), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (22677, 22681), True, 'import numpy as np\n'), ((32251, 32271), 'numpy.empty', 'np.empty', (['[n_eig, n]'], {}), '([n_eig, n])\n', (32259, 32271), True, 'import numpy as np\n'), ((32281, 32319), 'numpy.empty', 'np.empty', (['[m, n_eig, n]'], {'dtype': 'complex'}), '([m, n_eig, n], dtype=complex)\n', (32289, 32319), True, 'import numpy as np\n'), ((24998, 25013), 'numpy.isscalar', 'np.isscalar', (['mu'], {}), '(mu)\n', (25009, 25013), True, 'import numpy as np\n'), ((27161, 27175), 'numpy.isscalar', 'np.isscalar', (['B'], {}), '(B)\n', (27172, 27175), True, 'import numpy as np\n'), ((32682, 32704), 'multiprocessing.Pipe', 'multiprocessing.Pipe', ([], {}), '()\n', (32702, 32704), False, 'import multiprocessing\n'), ((28850, 28865), 'numpy.isscalar', 'np.isscalar', (['aR'], {}), '(aR)\n', (28861, 28865), True, 'import numpy as np\n'), ((32882, 32977), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'LO_solver_multiprocessing', 'args': '(H, N, dis, args, pipe_end)'}), '(target=LO_solver_multiprocessing, args=(H, N, dis,\n args, pipe_end))\n', (32905, 32977), False, 'import multiprocessing\n'), ((33102, 33197), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'LO_solver_multiprocessing', 'args': '(H, N, dis, args, pipe_end)'}), '(target=LO_solver_multiprocessing, args=(H, N, dis,\n args, pipe_end))\n', (33125, 33197), False, 'import multiprocessing\n'), ((33326, 33421), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'LO_solver_multiprocessing', 'args': '(H, N, dis, args, pipe_end)'}), '(target=LO_solver_multiprocessing, args=(H, N, dis,\n args, pipe_end))\n', (33349, 33421), False, 'import multiprocessing\n'), ((33561, 33656), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'LO_solver_multiprocessing', 'args': '(H, N, dis, args, pipe_end)'}), '(target=LO_solver_multiprocessing, args=(H, N, dis,\n args, pipe_end))\n', (33584, 33656), False, 'import multiprocessing\n'), ((31044, 31058), 'numpy.isscalar', 'np.isscalar', (['d'], {}), '(d)\n', (31055, 31058), True, 'import numpy as np\n'), ((32769, 32784), 'numpy.isscalar', 'np.isscalar', (['mu'], {}), '(mu)\n', (32780, 32784), True, 'import numpy as np\n'), ((32993, 33007), 'numpy.isscalar', 'np.isscalar', (['B'], {}), '(B)\n', (33004, 33007), True, 'import numpy as np\n'), ((33213, 33228), 'numpy.isscalar', 'np.isscalar', (['aR'], {}), '(aR)\n', (33224, 33228), True, 'import numpy as np\n'), ((33452, 33466), 'numpy.isscalar', 'np.isscalar', (['d'], {}), '(d)\n', (33463, 33466), True, 'import numpy as np\n')]
from itertools import combinations import pickle import numpy as np import os from PCGMM_Evaluation_Method.constant import tileTypes, TRAINING_DATA_DIR, CLUSTER_MODEL_DIR from PCGMM_Evaluation_Method.utils import readMaps, compute_room_list_histogram from PCGMM_Evaluation_Method.clustering_data import cluster_data from PCGMM_Evaluation_Method.similarity_tile_base import tile_base_similarity_score from PCGMM_Evaluation_Method.similarity_histogram_base import histogram_base_similarity_score from PCGMM_Evaluation_Method.similarity_markov_base import markov_base_similarity_score ####### CONFIG ############ # location for room folder # ROOMS_DIR = "map_data/map_reduced_OI" # T: 28.57, F: 76.17 # ROOMS_DIR = "generate_map/generate_map_RM_2" # 67.82 68.25 # ROOMS_DIR = "generate_map/generate_map_BMC_2" # 27.48 57.12 # ROOMS_DIR = "./simple_maps" # function for compute similarity score # similarity_score_fn = tile_base_similarity_score # similarity_score_fn = histogram_base_similarity_score # similarity_score_fn = markov_base_similarity_score # flag if use cluster # ENABLE_CLUSTER = False ########################### # def total_avg_score(room_list): # comb = list(combinations(room_list, 2)) # total_score = 0 # for room1, room2 in comb: # score = similarity_score_fn(room1, room2) # total_score = total_score + score # return total_score / len(comb) def evaluate_similarity(evaluate_data, similarity_function, enable_cluster): def total_avg_score(rooms): comb = list(combinations(rooms, 2)) total_score = 0 for room1, room2 in comb: score = similarity_score_fn(room1, room2) total_score = total_score + score return total_score / len(comb) sim_fn_dict = { "tile_base": tile_base_similarity_score, "histogram_base": histogram_base_similarity_score, "markov_base": markov_base_similarity_score } similarity_score_fn = sim_fn_dict[similarity_function] room_list = evaluate_data if enable_cluster: # restore the model with open(CLUSTER_MODEL_DIR, 'rb') as fid: cluster_model = pickle.load(fid) # predict label for room list pred_labels_ = cluster_model.predict(compute_room_list_histogram(room_list)) # find index list for each unique value cluster_dict = {i: (pred_labels_ == i).nonzero()[0] for i in np.unique(pred_labels_)} # print(cluster_dict) total_avg = 0.0 for v, idx in cluster_dict.items(): # print(idx) cluster_room = room_list[idx] if cluster_room.shape[0] < 2: continue same_type_rooms = [cluster_room[i, :, :] for i in range(cluster_room.shape[0])] # print(cluster_room.shape) avg = total_avg_score(same_type_rooms) # print(avg) total_avg = total_avg + (cluster_room.shape[0] / room_list.shape[0]) * avg # print("average simliarity score = ", total_avg) else: total_avg = total_avg_score(room_list) # print("average simliarity score = ", total_avg) return total_avg # if __name__ == "__main__": # room_list = readMaps(tileTypes, ROOMS_DIR) # print("length of room list = ", len(room_list)) # print(room_list[0].shape) # if ENABLE_CLUSTER: # # restore the model # with open(CLUSTER_MODEL_DIR, 'rb') as fid: # cluster_model = pickle.load(fid) # room_list = np.asarray(room_list) # # predict label for room list # pred_labels_ = cluster_model.predict(compute_room_list_histogram(room_list)) # # find index list for each unique value # cluster_dict = {i: (pred_labels_ == i).nonzero()[0] for i in np.unique(pred_labels_)} # # print(cluster_dict) # total_avg = 0.0 # for v, idx in cluster_dict.items(): # # print(idx) # cluster_room = room_list[idx] # if cluster_room.shape[0] < 2: # continue # same_type_rooms = [cluster_room[i, :, :] for i in range(cluster_room.shape[0])] # # print(cluster_room.shape) # avg = total_avg_score(same_type_rooms) # # print(avg) # total_avg = total_avg + (cluster_room.shape[0] / room_list.shape[0]) * avg # print("average simliarity score = ", total_avg) # else: # total_avg = total_avg_score(room_list) # print("average simliarity score = ", total_avg)
[ "itertools.combinations", "PCGMM_Evaluation_Method.utils.compute_room_list_histogram", "pickle.load", "numpy.unique" ]
[((1532, 1554), 'itertools.combinations', 'combinations', (['rooms', '(2)'], {}), '(rooms, 2)\n', (1544, 1554), False, 'from itertools import combinations\n'), ((2171, 2187), 'pickle.load', 'pickle.load', (['fid'], {}), '(fid)\n', (2182, 2187), False, 'import pickle\n'), ((2272, 2310), 'PCGMM_Evaluation_Method.utils.compute_room_list_histogram', 'compute_room_list_histogram', (['room_list'], {}), '(room_list)\n', (2299, 2310), False, 'from PCGMM_Evaluation_Method.utils import readMaps, compute_room_list_histogram\n'), ((2438, 2461), 'numpy.unique', 'np.unique', (['pred_labels_'], {}), '(pred_labels_)\n', (2447, 2461), True, 'import numpy as np\n')]
""" Implementation of various calibration methods from https://github.com/JonathanWenger/pycalib. """ import warnings import matplotlib.pyplot as plt import numpy as np import scipy.cluster.vq import scipy.optimize import scipy.special import scipy.stats import sklearn import sklearn.isotonic import sklearn.linear_model import sklearn.multiclass import sklearn.utils from sklearn.base import clone from sklearn.preprocessing import LabelBinarizer from sklearn.utils._joblib import Parallel from sklearn.utils._joblib import delayed from sklearn.utils.validation import check_is_fitted # Ignore binned_statistic FutureWarning # warnings.simplefilter(action='ignore', category=FutureWarning) class CalibrationMethod(sklearn.base.BaseEstimator): """ A generic class for probability calibration A calibration method takes a set of posterior class probabilities and transform them into calibrated posterior probabilities. Calibrated in this sense means that the empirical frequency of a correct class prediction matches its predicted posterior probability. """ def __init__(self): super().__init__() def fit(self, X, y): """ Fit the calibration method based on the given uncalibrated class probabilities X and ground truth labels y. Parameters ---------- X : array-like, shape (n_samples, n_classes) Training data, i.e. predicted probabilities of the base classifier on the calibration set. y : array-like, shape (n_samples,) Target classes. Returns ------- self : object Returns an instance of self. """ raise NotImplementedError("Subclass must implement this method.") def predict_proba(self, X): """ Compute calibrated posterior probabilities for a given array of posterior probabilities from an arbitrary classifier. Parameters ---------- X : array-like, shape (n_samples, n_classes) The uncalibrated posterior probabilities. Returns ------- P : array, shape (n_samples, n_classes) The predicted probabilities. """ raise NotImplementedError("Subclass must implement this method.") def predict(self, X): """ Predict the class of new samples after scaling. Predictions are identical to the ones from the uncalibrated classifier. Parameters ---------- X : array-like, shape (n_samples, n_classes) The uncalibrated posterior probabilities. Returns ------- C : array, shape (n_samples,) The predicted classes. """ return np.argmax(self.predict_proba(X), axis=1) def plot(self, filename, xlim=[0, 1], **kwargs): """ Plot the calibration map. Parameters ---------- xlim : array-like Range of inputs of the calibration map to be plotted. **kwargs : Additional arguments passed on to :func:`matplotlib.plot`. """ # TODO: Fix this plotting function # Generate data and transform x = np.linspace(0, 1, 10000) y = self.predict_proba(np.column_stack([1 - x, x]))[:, 1] # Plot and label plt.plot(x, y, **kwargs) plt.xlim(xlim) plt.xlabel("p(y=1|x)") plt.ylabel("f(p(y=1|x))") class NoCalibration(CalibrationMethod): """ A class that performs no calibration. This class can be used as a baseline for benchmarking. logits : bool, default=False Are the inputs for calibration logits (e.g. from a neural network)? """ def __init__(self, logits=False): self.logits = logits def fit(self, X, y): return self def predict_proba(self, X): if self.logits: return scipy.special.softmax(X, axis=1) else: return X class TemperatureScaling(CalibrationMethod): """ Probability calibration using temperature scaling Temperature scaling [1]_ is a one parameter multi-class scaling method. Output confidence scores are calibrated, meaning they match empirical frequencies of the associated class prediction. Temperature scaling does not change the class predictions of the underlying model. Parameters ---------- T_init : float Initial temperature parameter used for scaling. This parameter is optimized in order to calibrate output probabilities. verbose : bool Print information on optimization procedure. References ---------- .. [1] On calibration of modern neural networks, <NAME>, <NAME>, <NAME>, <NAME>, ICML 2017 """ def __init__(self, T_init=1.0, verbose=False): super().__init__() if T_init <= 0: raise ValueError("Temperature not greater than 0.") self.T_init = T_init self.verbose = verbose def fit(self, X, y): """ Fit the calibration method based on the given uncalibrated class probabilities or logits X and ground truth labels y. Parameters ---------- X : array-like, shape (n_samples, n_classes) Training data, i.e. predicted probabilities or logits of the base classifier on the calibration set. y : array-like, shape (n_samples,) Target classes. Returns ------- self : object Returns an instance of self. """ # Define objective function (NLL / cross entropy) def objective(T): # Calibrate with given T P = scipy.special.softmax(X / T, axis=1) # Compute negative log-likelihood P_y = P[np.array(np.arange(0, X.shape[0])), y] tiny = np.finfo(np.float).tiny # to avoid division by 0 warning NLL = - np.sum(np.log(P_y + tiny)) return NLL # Derivative of the objective with respect to the temperature T def gradient(T): # Exponential terms E = np.exp(X / T) # Gradient dT_i = (np.sum(E * (X - X[np.array(np.arange(0, X.shape[0])), y].reshape(-1, 1)), axis=1)) \ / np.sum(E, axis=1) grad = - dT_i.sum() / T ** 2 return grad # Optimize self.T = scipy.optimize.fmin_bfgs(f=objective, x0=self.T_init, fprime=gradient, gtol=1e-06, disp=self.verbose)[0] # Check for T > 0 if self.T <= 0: raise ValueError("Temperature not greater than 0.") return self def predict_proba(self, X): """ Compute calibrated posterior probabilities for a given array of posterior probabilities from an arbitrary classifier. Parameters ---------- X : array-like, shape (n_samples, n_classes) The uncalibrated posterior probabilities. Returns ------- P : array, shape (n_samples, n_classes) The predicted probabilities. """ # Check is fitted check_is_fitted(self, "T") # Transform with scaled softmax return scipy.special.softmax(X / self.T, axis=1) def latent(self, z): """ Evaluate the latent function Tz of temperature scaling. Parameters ---------- z : array-like, shape=(n_evaluations,) Input confidence for which to evaluate the latent function. Returns ------- f : array-like, shape=(n_evaluations,) Values of the latent function at z. """ check_is_fitted(self, "T") return self.T * z def plot_latent(self, z, filename, **kwargs): """ Plot the latent function of the calibration method. Parameters ---------- z : array-like, shape=(n_evaluations,) Input confidence to plot latent function for. filename : Filename / -path where to save output. kwargs Additional arguments passed on to matplotlib.pyplot.subplots. Returns ------- """ pass class PlattScaling(CalibrationMethod): """ Probability calibration using Platt scaling Platt scaling [1]_ [2]_ is a parametric method designed to output calibrated posterior probabilities for (non-probabilistic) binary classifiers. It was originally introduced in the context of SVMs. It works by fitting a logistic regression model to the model output using the negative log-likelihood as a loss function. Parameters ---------- regularization : float, default=10^(-12) Regularization constant, determining degree of regularization in logistic regression. random_state : int, RandomState instance or None, optional (default=None) The seed of the pseudo random number generator to use when shuffling the data. If `int`, `random_state` is the seed used by the random number generator; If `RandomState` instance, `random_state` is the random number generator; If `None`, the random number generator is the RandomState instance used by `np.random`. References ---------- .. [1] <NAME>. Probabilistic Outputs for Support Vector Machines and Comparisons to Regularized Likelihood Methods in Advances in Large-Margin Classifiers (MIT Press, 1999) .. [2] <NAME>., <NAME>. & <NAME>. A note on Platt’s probabilistic outputs for support vector machines. Machine learning 68, 267–276 (2007) """ def __init__(self, regularization=10 ** -12, random_state=None): super().__init__() self.regularization = regularization self.random_state = sklearn.utils.check_random_state(random_state) def fit(self, X, y, n_jobs=None): """ Fit the calibration method based on the given uncalibrated class probabilities X and ground truth labels y. Parameters ---------- X : array-like, shape (n_samples, n_classes) Training data, i.e. predicted probabilities of the base classifier on the calibration set. y : array-like, shape (n_samples,) Target classes. n_jobs : int or None, optional (default=None) The number of jobs to use for the computation. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- self : object Returns an instance of self. """ if X.ndim == 1: raise ValueError("Calibration training data must have shape (n_samples, n_classes).") elif np.shape(X)[1] == 2: self.logistic_regressor_ = sklearn.linear_model.LogisticRegression(C=1 / self.regularization, solver='lbfgs', random_state=self.random_state) self.logistic_regressor_.fit(X[:, 1].reshape(-1, 1), y) elif np.shape(X)[1] > 2: self.onevsrest_calibrator_ = OneVsRestCalibrator(calibrator=clone(self), n_jobs=n_jobs) self.onevsrest_calibrator_.fit(X, y) return self def predict_proba(self, X): """ Compute calibrated posterior probabilities for a given array of posterior probabilities from an arbitrary classifier. Parameters ---------- X : array-like, shape (n_samples, n_classes) The uncalibrated posterior probabilities. Returns ------- P : array, shape (n_samples, n_classes) The predicted probabilities. """ if X.ndim == 1: raise ValueError("Calibration data must have shape (n_samples, n_classes).") elif np.shape(X)[1] == 2: check_is_fitted(self, "logistic_regressor_") return self.logistic_regressor_.predict_proba(X[:, 1].reshape(-1, 1)) elif np.shape(X)[1] > 2: check_is_fitted(self, "onevsrest_calibrator_") return self.onevsrest_calibrator_.predict_proba(X) class IsotonicRegression(CalibrationMethod): """ Probability calibration using Isotonic Regression Isotonic regression [1]_ [2]_ is a non-parametric approach to mapping (non-probabilistic) classifier scores to probabilities. It assumes an isotonic (non-decreasing) relationship between classifier scores and probabilities. Parameters ---------- out_of_bounds : string, optional, default: "clip" The ``out_of_bounds`` parameter handles how x-values outside of the training domain are handled. When set to "nan", predicted y-values will be NaN. When set to "clip", predicted y-values will be set to the value corresponding to the nearest train interval endpoint. When set to "raise", allow ``interp1d`` to throw ValueError. References ---------- .. [1] Transforming Classifier Scores into Accurate Multiclass Probability Estimates, <NAME> & <NAME>, (KDD 2002) .. [2] Predicting Good Probabilities with Supervised Learning, <NAME> & <NAME>, ICML 2005 """ def __init__(self, out_of_bounds="clip"): super().__init__() self.out_of_bounds = out_of_bounds def fit(self, X, y, n_jobs=None): """ Fit the calibration method based on the given uncalibrated class probabilities X and ground truth labels y. Parameters ---------- X : array-like, shape (n_samples, n_classes) Training data, i.e. predicted probabilities of the base classifier on the calibration set. y : array-like, shape (n_samples,) Target classes. n_jobs : int or None, optional (default=None) The number of jobs to use for the computation. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- self : object Returns an instance of self. """ if X.ndim == 1: raise ValueError("Calibration training data must have shape (n_samples, n_classes).") elif np.shape(X)[1] == 2: self.isotonic_regressor_ = sklearn.isotonic.IsotonicRegression(increasing=True, out_of_bounds=self.out_of_bounds) self.isotonic_regressor_.fit(X[:, 1], y) elif np.shape(X)[1] > 2: self.onevsrest_calibrator_ = OneVsRestCalibrator(calibrator=clone(self), n_jobs=n_jobs) self.onevsrest_calibrator_.fit(X, y) return self def predict_proba(self, X): """ Compute calibrated posterior probabilities for a given array of posterior probabilities from an arbitrary classifier. Parameters ---------- X : array-like, shape (n_samples, n_classes) The uncalibrated posterior probabilities. Returns ------- P : array, shape (n_samples, n_classes) The predicted probabilities. """ if X.ndim == 1: raise ValueError("Calibration data must have shape (n_samples, n_classes).") elif np.shape(X)[1] == 2: check_is_fitted(self, "isotonic_regressor_") p1 = self.isotonic_regressor_.predict(X[:, 1]) return np.column_stack([1 - p1, p1]) elif np.shape(X)[1] > 2: check_is_fitted(self, "onevsrest_calibrator_") return self.onevsrest_calibrator_.predict_proba(X) class HistogramBinning(CalibrationMethod): """ Probability calibration using histogram binning Histogram binning [1]_ is a nonparametric approach to probability calibration. Classifier scores are binned into a given number of bins either based on fixed width or frequency. Classifier scores are then computed based on the empirical frequency of class 1 in each bin. Parameters ---------- mode : str, default='equal_width' Binning mode used. One of ['equal_width', 'equal_freq']. n_bins : int, default=20 Number of bins to bin classifier scores into. input_range : list, shape (2,), default=[0, 1] Range of the classifier scores. .. [1] <NAME>. & <NAME>. Obtaining calibrated probability estimates from decision trees and naive Bayesian classifiers in Proceedings of the 18th International Conference on Machine Learning (ICML, 2001), 609–616. """ def __init__(self, mode='equal_width', n_bins=20, input_range=[0, 1]): super().__init__() if mode in ['equal_width', 'equal_freq']: self.mode = mode else: raise ValueError("Mode not recognized. Choose on of 'equal_width', or 'equal_freq'.") self.n_bins = n_bins self.input_range = input_range def fit(self, X, y, n_jobs=None): """ Fit the calibration method based on the given uncalibrated class probabilities X and ground truth labels y. Parameters ---------- X : array-like, shape (n_samples, n_classes) Training data, i.e. predicted probabilities of the base classifier on the calibration set. y : array-like, shape (n_samples,) Target classes. n_jobs : int or None, optional (default=None) The number of jobs to use for the computation. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- self : object Returns an instance of self. """ if X.ndim == 1: raise ValueError("Calibration training data must have shape (n_samples, n_classes).") elif np.shape(X)[1] == 2: return self._fit_binary(X, y) elif np.shape(X)[1] > 2: self.onevsrest_calibrator_ = OneVsRestCalibrator(calibrator=clone(self), n_jobs=n_jobs) self.onevsrest_calibrator_.fit(X, y) return self def _fit_binary(self, X, y): if self.mode == 'equal_width': # Compute probability of class 1 in each equal width bin binned_stat = scipy.stats.binned_statistic(x=X[:, 1], values=np.equal(1, y), statistic='mean', bins=self.n_bins, range=self.input_range) self.prob_class_1 = binned_stat.statistic # TODO: test this and correct attributes self.binning = binned_stat.bin_edges elif self.mode == 'equal_freq': # Find binning based on equal frequency self.binning = np.quantile(X[:, 1], q=np.linspace(self.input_range[0], self.input_range[1], self.n_bins + 1)) # Compute probability of class 1 in equal frequency bins digitized = np.digitize(X[:, 1], bins=self.binning) digitized[digitized == len(self.binning)] = len(self.binning) - 1 # include rightmost edge in partition self.prob_class_1 = [y[digitized == i].mean() for i in range(1, len(self.binning))] return self def predict_proba(self, X): """ Compute calibrated posterior probabilities for a given array of posterior probabilities from an arbitrary classifier. Parameters ---------- X : array-like, shape (n_samples, n_classes) The uncalibrated posterior probabilities. Returns ------- P : array, shape (n_samples, n_classes) The predicted probabilities. """ if X.ndim == 1: raise ValueError("Calibration data must have shape (n_samples, n_classes).") elif np.shape(X)[1] == 2: check_is_fitted(self, ["binning", "prob_class_1"]) # Find bin of predictions digitized = np.digitize(X[:, 1], bins=self.binning) digitized[digitized == len(self.binning)] = len(self.binning) - 1 # include rightmost edge in partition # Transform to empirical frequency of class 1 in each bin p1 = np.array([self.prob_class_1[j] for j in (digitized - 1)]) # If empirical frequency is NaN, do not change prediction p1 = np.where(np.isfinite(p1), p1, X[:, 1]) assert np.all(np.isfinite(p1)), "Predictions are not all finite." return np.column_stack([1 - p1, p1]) elif np.shape(X)[1] > 2: check_is_fitted(self, "onevsrest_calibrator_") return self.onevsrest_calibrator_.predict_proba(X) class BayesianBinningQuantiles(CalibrationMethod): """ Probability calibration using Bayesian binning into quantiles Bayesian binning into quantiles [1]_ considers multiple equal frequency binning models and combines them through Bayesian model averaging. Each binning model :math:`M` is scored according to :math:`\\text{Score}(M) = P(M) \\cdot P(D | M),` where a uniform prior :math:`P(M)` is assumed. The marginal likelihood :math:`P(D | M)` has a closed form solution under the assumption of independent binomial class distributions in each bin with beta priors. Parameters ---------- C : int, default = 10 Constant controlling the number of binning models. input_range : list, shape (2,), default=[0, 1] Range of the scores to calibrate. .. [1] <NAME>., <NAME>. & <NAME>. Obtaining Well Calibrated Probabilities Using Bayesian Binning in Proceedings of the Twenty-Ninth AAAI Conference on Artificial Intelligence, Austin, Texas, USA. """ def __init__(self, C=10, input_range=[0, 1]): super().__init__() self.C = C self.input_range = input_range def _binning_model_logscore(self, probs, y, partition, N_prime=2): """ Compute the log score of a binning model Each binning model :math:`M` is scored according to :math:`Score(M) = P(M) \\cdot P(D | M),` where a uniform prior :math:`P(M)` is assumed and the marginal likelihood :math:`P(D | M)` has a closed form solution under the assumption of a binomial class distribution in each bin with beta priors. Parameters ---------- probs : array-like, shape (n_samples, ) Predicted posterior probabilities. y : array-like, shape (n_samples, ) Target classes. partition : array-like, shape (n_bins + 1, ) Interval partition defining a binning. N_prime : int, default=2 Equivalent sample size expressing the strength of the belief in the prior distribution. Returns ------- log_score : float Log of Bayesian score for a given binning model """ # Setup B = len(partition) - 1 p = (partition[1:] - partition[:-1]) / 2 + partition[:-1] # Compute positive and negative samples in given bins N = np.histogram(probs, bins=partition)[0] digitized = np.digitize(probs, bins=partition) digitized[digitized == len(partition)] = len(partition) - 1 # include rightmost edge in partition m = [y[digitized == i].sum() for i in range(1, len(partition))] n = N - m # Compute the parameters of the Beta priors tiny = np.finfo(np.float).tiny # Avoid scipy.special.gammaln(0), which can arise if bin has zero width alpha = N_prime / B * p alpha[alpha == 0] = tiny beta = N_prime / B * (1 - p) beta[beta == 0] = tiny # Prior for a given binning model (uniform) log_prior = - np.log(self.T) # Compute the marginal log-likelihood for the given binning model log_likelihood = np.sum( scipy.special.gammaln(N_prime / B) + scipy.special.gammaln(m + alpha) + scipy.special.gammaln(n + beta) - ( scipy.special.gammaln(N + N_prime / B) + scipy.special.gammaln(alpha) + scipy.special.gammaln( beta))) # Compute score for the given binning model log_score = log_prior + log_likelihood return log_score def fit(self, X, y, n_jobs=None): """ Fit the calibration method based on the given uncalibrated class probabilities X and ground truth labels y. Parameters ---------- X : array-like, shape (n_samples, n_classes) Training data, i.e. predicted probabilities of the base classifier on the calibration set. y : array-like, shape (n_samples,) Target classes. n_jobs : int or None, optional (default=None) The number of jobs to use for the computation. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- self : object Returns an instance of self. """ if X.ndim == 1: raise ValueError("Calibration training data must have shape (n_samples, n_classes).") elif np.shape(X)[1] == 2: self.binnings = [] self.log_scores = [] self.prob_class_1 = [] self.T = 0 return self._fit_binary(X, y) elif np.shape(X)[1] > 2: self.onevsrest_calibrator_ = OneVsRestCalibrator(calibrator=clone(self), n_jobs=n_jobs) self.onevsrest_calibrator_.fit(X, y) return self def _fit_binary(self, X, y): # Determine number of bins N = len(y) min_bins = int(max(1, np.floor(N ** (1 / 3) / self.C))) max_bins = int(min(np.ceil(N / 5), np.ceil(self.C * N ** (1 / 3)))) self.T = max_bins - min_bins + 1 # Define (equal frequency) binning models and compute scores self.binnings = [] self.log_scores = [] self.prob_class_1 = [] for i, n_bins in enumerate(range(min_bins, max_bins + 1)): # Compute binning from data and set outer edges to range binning_tmp = np.quantile(X[:, 1], q=np.linspace(self.input_range[0], self.input_range[1], n_bins + 1)) binning_tmp[0] = self.input_range[0] binning_tmp[-1] = self.input_range[1] # Enforce monotonicity of binning (np.quantile does not guarantee monotonicity) self.binnings.append(np.maximum.accumulate(binning_tmp)) # Compute score self.log_scores.append(self._binning_model_logscore(probs=X[:, 1], y=y, partition=self.binnings[i])) # Compute empirical accuracy for all bins digitized = np.digitize(X[:, 1], bins=self.binnings[i]) # include rightmost edge in partition digitized[digitized == len(self.binnings[i])] = len(self.binnings[i]) - 1 def empty_safe_bin_mean(a, empty_value): """ Assign the bin mean to an empty bin. Corresponds to prior assumption of the underlying classifier being calibrated. """ if a.size == 0: return empty_value else: return a.mean() self.prob_class_1.append( [empty_safe_bin_mean(y[digitized == k], empty_value=(self.binnings[i][k] + self.binnings[i][k - 1]) / 2) for k in range(1, len(self.binnings[i]))]) return self def predict_proba(self, X): """ Compute calibrated posterior probabilities for a given array of posterior probabilities from an arbitrary classifier. Parameters ---------- X : array-like, shape (n_samples, n_classes) The uncalibrated posterior probabilities. Returns ------- P : array, shape (n_samples, n_classes) The predicted probabilities. """ if X.ndim == 1: raise ValueError("Calibration data must have shape (n_samples, n_classes).") elif np.shape(X)[1] == 2: check_is_fitted(self, ["binnings", "log_scores", "prob_class_1", "T"]) # Find bin for all binnings and the associated empirical accuracy posterior_prob_binnings = np.zeros(shape=[np.shape(X)[0], len(self.binnings)]) for i, binning in enumerate(self.binnings): bin_ids = np.searchsorted(binning, X[:, 1]) bin_ids = np.clip(bin_ids, a_min=0, a_max=len(binning) - 1) # necessary if X is out of range posterior_prob_binnings[:, i] = [self.prob_class_1[i][j] for j in (bin_ids - 1)] # Computed score-weighted average norm_weights = np.exp(np.array(self.log_scores) - scipy.special.logsumexp(self.log_scores)) posterior_prob = np.sum(posterior_prob_binnings * norm_weights, axis=1) # Compute probability for other class return np.column_stack([1 - posterior_prob, posterior_prob]) elif np.shape(X)[1] > 2: check_is_fitted(self, "onevsrest_calibrator_") return self.onevsrest_calibrator_.predict_proba(X) class OneVsRestCalibrator(sklearn.base.BaseEstimator): """One-vs-the-rest (OvR) multiclass strategy Also known as one-vs-all, this strategy consists in fitting one calibrator per class. The probabilities to be calibrated of the other classes are summed. For each calibrator, the class is fitted against all the other classes. Parameters ---------- calibrator : CalibrationMethod object A CalibrationMethod object implementing `fit` and `predict_proba`. n_jobs : int or None, optional (default=None) The number of jobs to use for the computation. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Attributes ---------- calibrators_ : list of `n_classes` estimators Estimators used for predictions. classes_ : array, shape = [`n_classes`] Class labels. label_binarizer_ : LabelBinarizer object Object used to transform multiclass labels to binary labels and vice-versa. """ def __init__(self, calibrator, n_jobs=None): self.calibrator = calibrator self.n_jobs = n_jobs def fit(self, X, y): """Fit underlying estimators. Parameters ---------- X : (sparse) array-like, shape = [n_samples, n_features] Calibration data. y : (sparse) array-like, shape = [n_samples, ] Multi-class labels. Returns ------- self """ # A sparse LabelBinarizer, with sparse_output=True, has been shown to # outperform or match a dense label binarizer in all cases and has also # resulted in less or equal memory consumption in the fit_ovr function # overall. self.label_binarizer_ = LabelBinarizer(sparse_output=True) Y = self.label_binarizer_.fit_transform(y) Y = Y.tocsc() self.classes_ = self.label_binarizer_.classes_ columns = (col.toarray().ravel() for col in Y.T) # In cases where individual estimators are very fast to train setting # n_jobs > 1 in can results in slower performance due to the overhead # of spawning threads. See joblib issue #112. self.calibrators_ = Parallel(n_jobs=self.n_jobs)( delayed(OneVsRestCalibrator._fit_binary)(self.calibrator, X, column, classes=[ "not %s" % self.label_binarizer_.classes_[i], self.label_binarizer_.classes_[i]]) for i, column in enumerate(columns)) return self def predict_proba(self, X): """ Probability estimates. The returned estimates for all classes are ordered by label of classes. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- T : (sparse) array-like, shape = [n_samples, n_classes] Returns the probability of the sample for each class in the model, where classes are ordered as they are in `self.classes_`. """ check_is_fitted(self, ["classes_", "calibrators_"]) # Y[i, j] gives the probability that sample i has the label j. Y = np.array([c.predict_proba( np.column_stack([np.sum(np.delete(X, obj=i, axis=1), axis=1), X[:, self.classes_[i]]]))[:, 1] for i, c in enumerate(self.calibrators_)]).T if len(self.calibrators_) == 1: # Only one estimator, but we still want to return probabilities for two classes. Y = np.concatenate(((1 - Y), Y), axis=1) # Pad with zeros for classes not in training data if np.shape(Y)[1] != np.shape(X)[1]: p_pred = np.zeros(np.shape(X)) p_pred[:, self.classes_] = Y Y = p_pred # Normalize probabilities to 1. Y = sklearn.preprocessing.normalize(Y, norm='l1', axis=1, copy=True, return_norm=False) return np.clip(Y, a_min=0, a_max=1) @property def n_classes_(self): return len(self.classes_) @property def _first_calibrator(self): return self.calibrators_[0] @staticmethod def _fit_binary(calibrator, X, y, classes=None): """ Fit a single binary calibrator. Parameters ---------- calibrator X y classes Returns ------- """ # Sum probabilities of combined classes in calibration training data X cl = classes[1] X = np.column_stack([np.sum(np.delete(X, cl, axis=1), axis=1), X[:, cl]]) # Check whether only one label is present in training data unique_y = np.unique(y) if len(unique_y) == 1: if classes is not None: if y[0] == -1: c = 0 else: c = y[0] warnings.warn("Label %s is present in all training examples." % str(classes[c])) calibrator = _ConstantCalibrator().fit(X, unique_y) else: calibrator = clone(calibrator) calibrator.fit(X, y) return calibrator class _ConstantCalibrator(CalibrationMethod): def fit(self, X, y): self.y_ = y return self def predict(self, X): check_is_fitted(self, 'y_') return np.repeat(self.y_, X.shape[0]) def predict_proba(self, X): check_is_fitted(self, 'y_') return np.repeat([np.hstack([1 - self.y_, self.y_])], X.shape[0], axis=0) CALIBRATION_MODELS = { 'no_calibration': NoCalibration, 'temperature_scaling': TemperatureScaling, 'platt_scaling': PlattScaling, 'isotonic_regression': IsotonicRegression, 'histogram_binning': HistogramBinning, 'bayesian_binning_quantiles': BayesianBinningQuantiles }
[ "numpy.clip", "matplotlib.pyplot.ylabel", "numpy.hstack", "numpy.log", "numpy.column_stack", "numpy.equal", "numpy.array", "numpy.isfinite", "sklearn.utils._joblib.delayed", "numpy.arange", "sklearn.preprocessing.LabelBinarizer", "numpy.histogram", "numpy.repeat", "numpy.searchsorted", "...
[((3189, 3213), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(10000)'], {}), '(0, 1, 10000)\n', (3200, 3213), True, 'import numpy as np\n'), ((3314, 3338), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y, **kwargs)\n', (3322, 3338), True, 'import matplotlib.pyplot as plt\n'), ((3347, 3361), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xlim'], {}), '(xlim)\n', (3355, 3361), True, 'import matplotlib.pyplot as plt\n'), ((3370, 3392), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""p(y=1|x)"""'], {}), "('p(y=1|x)')\n", (3380, 3392), True, 'import matplotlib.pyplot as plt\n'), ((3401, 3426), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""f(p(y=1|x))"""'], {}), "('f(p(y=1|x))')\n", (3411, 3426), True, 'import matplotlib.pyplot as plt\n'), ((7150, 7176), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""T"""'], {}), "(self, 'T')\n", (7165, 7176), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((7681, 7707), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""T"""'], {}), "(self, 'T')\n", (7696, 7707), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((9797, 9843), 'sklearn.utils.check_random_state', 'sklearn.utils.check_random_state', (['random_state'], {}), '(random_state)\n', (9829, 9843), False, 'import sklearn\n'), ((23460, 23494), 'numpy.digitize', 'np.digitize', (['probs'], {'bins': 'partition'}), '(probs, bins=partition)\n', (23471, 23494), True, 'import numpy as np\n'), ((31419, 31453), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {'sparse_output': '(True)'}), '(sparse_output=True)\n', (31433, 31453), False, 'from sklearn.preprocessing import LabelBinarizer\n'), ((32681, 32732), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', "['classes_', 'calibrators_']"], {}), "(self, ['classes_', 'calibrators_'])\n", (32696, 32732), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((33468, 33555), 'sklearn.preprocessing.normalize', 'sklearn.preprocessing.normalize', (['Y'], {'norm': '"""l1"""', 'axis': '(1)', 'copy': '(True)', 'return_norm': '(False)'}), "(Y, norm='l1', axis=1, copy=True,\n return_norm=False)\n", (33499, 33555), False, 'import sklearn\n'), ((33567, 33595), 'numpy.clip', 'np.clip', (['Y'], {'a_min': '(0)', 'a_max': '(1)'}), '(Y, a_min=0, a_max=1)\n', (33574, 33595), True, 'import numpy as np\n'), ((34288, 34300), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (34297, 34300), True, 'import numpy as np\n'), ((34932, 34959), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""y_"""'], {}), "(self, 'y_')\n", (34947, 34959), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((34976, 35006), 'numpy.repeat', 'np.repeat', (['self.y_', 'X.shape[0]'], {}), '(self.y_, X.shape[0])\n', (34985, 35006), True, 'import numpy as np\n'), ((35048, 35075), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""y_"""'], {}), "(self, 'y_')\n", (35063, 35075), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((6092, 6105), 'numpy.exp', 'np.exp', (['(X / T)'], {}), '(X / T)\n', (6098, 6105), True, 'import numpy as np\n'), ((23400, 23435), 'numpy.histogram', 'np.histogram', (['probs'], {'bins': 'partition'}), '(probs, bins=partition)\n', (23412, 23435), True, 'import numpy as np\n'), ((23760, 23778), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (23768, 23778), True, 'import numpy as np\n'), ((24065, 24079), 'numpy.log', 'np.log', (['self.T'], {}), '(self.T)\n', (24071, 24079), True, 'import numpy as np\n'), ((27084, 27127), 'numpy.digitize', 'np.digitize', (['X[:, 1]'], {'bins': 'self.binnings[i]'}), '(X[:, 1], bins=self.binnings[i])\n', (27095, 27127), True, 'import numpy as np\n'), ((31878, 31906), 'sklearn.utils._joblib.Parallel', 'Parallel', ([], {'n_jobs': 'self.n_jobs'}), '(n_jobs=self.n_jobs)\n', (31886, 31906), False, 'from sklearn.utils._joblib import Parallel\n'), ((33167, 33201), 'numpy.concatenate', 'np.concatenate', (['(1 - Y, Y)'], {'axis': '(1)'}), '((1 - Y, Y), axis=1)\n', (33181, 33201), True, 'import numpy as np\n'), ((34706, 34723), 'sklearn.base.clone', 'clone', (['calibrator'], {}), '(calibrator)\n', (34711, 34723), False, 'from sklearn.base import clone\n'), ((3245, 3272), 'numpy.column_stack', 'np.column_stack', (['[1 - x, x]'], {}), '([1 - x, x])\n', (3260, 3272), True, 'import numpy as np\n'), ((5818, 5836), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (5826, 5836), True, 'import numpy as np\n'), ((6256, 6273), 'numpy.sum', 'np.sum', (['E'], {'axis': '(1)'}), '(E, axis=1)\n', (6262, 6273), True, 'import numpy as np\n'), ((10867, 10986), 'sklearn.linear_model.LogisticRegression', 'sklearn.linear_model.LogisticRegression', ([], {'C': '(1 / self.regularization)', 'solver': '"""lbfgs"""', 'random_state': 'self.random_state'}), "(C=1 / self.regularization, solver=\n 'lbfgs', random_state=self.random_state)\n", (10906, 10986), False, 'import sklearn\n'), ((12027, 12071), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""logistic_regressor_"""'], {}), "(self, 'logistic_regressor_')\n", (12042, 12071), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((14515, 14606), 'sklearn.isotonic.IsotonicRegression', 'sklearn.isotonic.IsotonicRegression', ([], {'increasing': '(True)', 'out_of_bounds': 'self.out_of_bounds'}), '(increasing=True, out_of_bounds=self.\n out_of_bounds)\n', (14550, 14606), False, 'import sklearn\n'), ((15548, 15592), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""isotonic_regressor_"""'], {}), "(self, 'isotonic_regressor_')\n", (15563, 15592), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((15671, 15700), 'numpy.column_stack', 'np.column_stack', (['[1 - p1, p1]'], {}), '([1 - p1, p1])\n', (15686, 15700), True, 'import numpy as np\n'), ((19298, 19337), 'numpy.digitize', 'np.digitize', (['X[:, 1]'], {'bins': 'self.binning'}), '(X[:, 1], bins=self.binning)\n', (19309, 19337), True, 'import numpy as np\n'), ((20188, 20238), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', "['binning', 'prob_class_1']"], {}), "(self, ['binning', 'prob_class_1'])\n", (20203, 20238), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((20301, 20340), 'numpy.digitize', 'np.digitize', (['X[:, 1]'], {'bins': 'self.binning'}), '(X[:, 1], bins=self.binning)\n', (20312, 20340), True, 'import numpy as np\n'), ((20545, 20600), 'numpy.array', 'np.array', (['[self.prob_class_1[j] for j in digitized - 1]'], {}), '([self.prob_class_1[j] for j in digitized - 1])\n', (20553, 20600), True, 'import numpy as np\n'), ((20827, 20856), 'numpy.column_stack', 'np.column_stack', (['[1 - p1, p1]'], {}), '([1 - p1, p1])\n', (20842, 20856), True, 'import numpy as np\n'), ((26044, 26075), 'numpy.floor', 'np.floor', (['(N ** (1 / 3) / self.C)'], {}), '(N ** (1 / 3) / self.C)\n', (26052, 26075), True, 'import numpy as np\n'), ((26105, 26119), 'numpy.ceil', 'np.ceil', (['(N / 5)'], {}), '(N / 5)\n', (26112, 26119), True, 'import numpy as np\n'), ((26121, 26151), 'numpy.ceil', 'np.ceil', (['(self.C * N ** (1 / 3))'], {}), '(self.C * N ** (1 / 3))\n', (26128, 26151), True, 'import numpy as np\n'), ((26828, 26862), 'numpy.maximum.accumulate', 'np.maximum.accumulate', (['binning_tmp'], {}), '(binning_tmp)\n', (26849, 26862), True, 'import numpy as np\n'), ((28492, 28562), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', "['binnings', 'log_scores', 'prob_class_1', 'T']"], {}), "(self, ['binnings', 'log_scores', 'prob_class_1', 'T'])\n", (28507, 28562), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((29236, 29290), 'numpy.sum', 'np.sum', (['(posterior_prob_binnings * norm_weights)'], {'axis': '(1)'}), '(posterior_prob_binnings * norm_weights, axis=1)\n', (29242, 29290), True, 'import numpy as np\n'), ((29361, 29414), 'numpy.column_stack', 'np.column_stack', (['[1 - posterior_prob, posterior_prob]'], {}), '([1 - posterior_prob, posterior_prob])\n', (29376, 29414), True, 'import numpy as np\n'), ((33274, 33285), 'numpy.shape', 'np.shape', (['Y'], {}), '(Y)\n', (33282, 33285), True, 'import numpy as np\n'), ((33292, 33303), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (33300, 33303), True, 'import numpy as np\n'), ((33338, 33349), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (33346, 33349), True, 'import numpy as np\n'), ((35103, 35136), 'numpy.hstack', 'np.hstack', (['[1 - self.y_, self.y_]'], {}), '([1 - self.y_, self.y_])\n', (35112, 35136), True, 'import numpy as np\n'), ((5903, 5921), 'numpy.log', 'np.log', (['(P_y + tiny)'], {}), '(P_y + tiny)\n', (5909, 5921), True, 'import numpy as np\n'), ((10807, 10818), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (10815, 10818), True, 'import numpy as np\n'), ((11994, 12005), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (12002, 12005), True, 'import numpy as np\n'), ((12199, 12245), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""onevsrest_calibrator_"""'], {}), "(self, 'onevsrest_calibrator_')\n", (12214, 12245), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((14455, 14466), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (14463, 14466), True, 'import numpy as np\n'), ((15515, 15526), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (15523, 15526), True, 'import numpy as np\n'), ((15746, 15792), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""onevsrest_calibrator_"""'], {}), "(self, 'onevsrest_calibrator_')\n", (15761, 15792), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((18195, 18206), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (18203, 18206), True, 'import numpy as np\n'), ((18675, 18689), 'numpy.equal', 'np.equal', (['(1)', 'y'], {}), '(1, y)\n', (18683, 18689), True, 'import numpy as np\n'), ((20155, 20166), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (20163, 20166), True, 'import numpy as np\n'), ((20699, 20714), 'numpy.isfinite', 'np.isfinite', (['p1'], {}), '(p1)\n', (20710, 20714), True, 'import numpy as np\n'), ((20755, 20770), 'numpy.isfinite', 'np.isfinite', (['p1'], {}), '(p1)\n', (20766, 20770), True, 'import numpy as np\n'), ((20902, 20948), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""onevsrest_calibrator_"""'], {}), "(self, 'onevsrest_calibrator_')\n", (20917, 20948), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((25535, 25546), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (25543, 25546), True, 'import numpy as np\n'), ((26537, 26602), 'numpy.linspace', 'np.linspace', (['self.input_range[0]', 'self.input_range[1]', '(n_bins + 1)'], {}), '(self.input_range[0], self.input_range[1], n_bins + 1)\n', (26548, 26602), True, 'import numpy as np\n'), ((28459, 28470), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (28467, 28470), True, 'import numpy as np\n'), ((28815, 28848), 'numpy.searchsorted', 'np.searchsorted', (['binning', 'X[:, 1]'], {}), '(binning, X[:, 1])\n', (28830, 28848), True, 'import numpy as np\n'), ((29460, 29506), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""onevsrest_calibrator_"""'], {}), "(self, 'onevsrest_calibrator_')\n", (29475, 29506), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((31920, 31960), 'sklearn.utils._joblib.delayed', 'delayed', (['OneVsRestCalibrator._fit_binary'], {}), '(OneVsRestCalibrator._fit_binary)\n', (31927, 31960), False, 'from sklearn.utils._joblib import delayed\n'), ((34155, 34179), 'numpy.delete', 'np.delete', (['X', 'cl'], {'axis': '(1)'}), '(X, cl, axis=1)\n', (34164, 34179), True, 'import numpy as np\n'), ((5769, 5793), 'numpy.arange', 'np.arange', (['(0)', 'X.shape[0]'], {}), '(0, X.shape[0])\n', (5778, 5793), True, 'import numpy as np\n'), ((11221, 11232), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (11229, 11232), True, 'import numpy as np\n'), ((12167, 12178), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (12175, 12178), True, 'import numpy as np\n'), ((14743, 14754), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (14751, 14754), True, 'import numpy as np\n'), ((15714, 15725), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (15722, 15725), True, 'import numpy as np\n'), ((18271, 18282), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (18279, 18282), True, 'import numpy as np\n'), ((19132, 19202), 'numpy.linspace', 'np.linspace', (['self.input_range[0]', 'self.input_range[1]', '(self.n_bins + 1)'], {}), '(self.input_range[0], self.input_range[1], self.n_bins + 1)\n', (19143, 19202), True, 'import numpy as np\n'), ((20870, 20881), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (20878, 20881), True, 'import numpy as np\n'), ((25733, 25744), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (25741, 25744), True, 'import numpy as np\n'), ((29137, 29162), 'numpy.array', 'np.array', (['self.log_scores'], {}), '(self.log_scores)\n', (29145, 29162), True, 'import numpy as np\n'), ((29428, 29439), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (29436, 29439), True, 'import numpy as np\n'), ((11313, 11324), 'sklearn.base.clone', 'clone', (['self'], {}), '(self)\n', (11318, 11324), False, 'from sklearn.base import clone\n'), ((14835, 14846), 'sklearn.base.clone', 'clone', (['self'], {}), '(self)\n', (14840, 14846), False, 'from sklearn.base import clone\n'), ((18363, 18374), 'sklearn.base.clone', 'clone', (['self'], {}), '(self)\n', (18368, 18374), False, 'from sklearn.base import clone\n'), ((25825, 25836), 'sklearn.base.clone', 'clone', (['self'], {}), '(self)\n', (25830, 25836), False, 'from sklearn.base import clone\n'), ((28696, 28707), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (28704, 28707), True, 'import numpy as np\n'), ((32880, 32907), 'numpy.delete', 'np.delete', (['X'], {'obj': 'i', 'axis': '(1)'}), '(X, obj=i, axis=1)\n', (32889, 32907), True, 'import numpy as np\n'), ((6177, 6201), 'numpy.arange', 'np.arange', (['(0)', 'X.shape[0]'], {}), '(0, X.shape[0])\n', (6186, 6201), True, 'import numpy as np\n')]
"""A class for microscope objects. Author: <NAME>, ANL, 20.Feb.2015. """ import numpy as np import scipy.constants as physcon import scipy.ndimage as ndimage class Microscope(object): '''Class for Microscope objects. A class that describes a microscope for image simulation and reconstruction purposes. Along with accelerating voltage, aberrations, and other parameters, this also contains methods for propagating the electron wave and simulating images. Notes: - When initializing a Microscope you can set verbose=True to get a printout of the parameters. - Unlike in TIE_reconstruct, here the qq frequency spectrum is expected to be shifted, i.e. rather than four dark corners it's a dark circle. Attributes: E (float): Accelerating voltage (V). Default 200kV. Cs (float): Spherical aberration (nm). Default 1mm. Cc (float): Chromatic aberration (nm). Default 5mm. theta_c (float): Beam coherence (rad). Default 0.6mrad. Ca (float): 2-fold astigmatism (nm). Default 0. phi_a (float): 2-fold astigmatism angle (rad). Default 0. def_spr (float): Defocus spread (nm). Default 120nm. defocus (float): Defocus of the microscope (nm). Default 0nm. lam (float): Electron wavelength (nm) calculated from E. Default 2.51pm. gamma (float): Relativistic factor (unitless) from E. Default 1.39. sigma (float): Interaction constant (1/(V*nm)) from E. Default 0.00729. ''' def __init__(self, E=200.0e3, Cs=1.0e6, Cc=5.0e6, theta_c=6.0e-4, Ca=0.0e6, phi_a=0, def_spr=120.0,verbose=False): """ Constructs the Microscope object. All arguments are optional. Set verbose=True to print microscope values. """ # properties that can be changed self.E = E self.Cs = Cs self.Cc = Cc self.theta_c = theta_c self.Ca = Ca self.phi_a = phi_a self.def_spr = def_spr self.defocus = 0.0 #nm self.aperture = 1.0 #properties that are derived and cannot be changed directly. epsilon = 0.5 * physcon.e / physcon.m_e / physcon.c**2 self.lam = physcon.h * 1.0e9 / np.sqrt(2.0 * physcon.m_e * physcon.e) / np.sqrt(self.E + epsilon * self.E**2) self.gamma = 1.0 + physcon.e * self.E / physcon.m_e / physcon.c**2 self.sigma = 2.0 * np.pi * physcon.m_e * self.gamma * physcon.e * self.lam * 1.0e-18 / physcon.h**2 if verbose: print( "Creating a new microscope object with the following properties:") print( "Quantities preceded by a star (*) can be changed using optional arguments at call.") print( "-------------------------------------------------------------------------") print( f"*Accelerating voltage E: [V] {self.E:.4g}") print( f"*Spherical Aberration Cs: [nm] {self.Cs:.4g}") print( f"*Chromatic Aberration Cc: [nm] {self.Cc:.4g}") print( f"*Beam Coherence theta_c: [rad] {self.theta_c:.4g}") print( f"*2-fold astigmatism Ca: [nm] {self.Ca:.4g}") print( f"*2-fold astigmatism angle phi_a: [rad] {self.phi_a:.4g}") print( f"*defocus spread def_spr: [nm] {self.def_spr:.4g}") print( f"Electron wavelength lambda: [nm] {self.lam:.4g}") print( f"Relativistic factor gamma: [-] {self.gamma:.4g}") print( f"Interaction constant sigma: [1/V/nm] {self.sigma:.4g}") print( "-------------------------------------------------------------------------") def getSchDef(self): """Calculate the Scherzer defocus""" return np.sqrt(1.5 * self.Cs * self.lam) def getOptDef(self,qq,del_px): """Calculate the Optimum or Lichte defocus (for holography). Args: qq (2D array): Frequency array del_px (float): Scale (nm/pixel) Returns: float: Optimum defocus (nm) """ qmax = np.amax(qq) lam = self.lam / del_px optdef = 3.0/4.0 * self.Cs * lam**2 * qmax**2 return optdef def setAperture(self,qq,del_px, sz): """ Set the objective aperture Args: qq (2D array): Frequency array del_px (float): Scale (nm/pixel) sz (float): Aperture size (nm). Returns: None: Sets self.aperture. """ ap = np.zeros(qq.shape) sz_q = qq.shape #Convert the size of aperture from nm to nm^-1 and then to px^-1 ap_sz = sz/del_px ap_sz /= float(sz_q[0]) ap[qq <= ap_sz] = 1.0 #Smooth the edge of the aperture ap = ndimage.gaussian_filter(ap,sigma=2) self.aperture = ap return 1 def getChiQ(self,qq,del_px): """Calculate the phase transfer function. Args: qq (2D array): Frequency array del_px (float): Scale (nm/pixel) Returns: ``ndarray``: 2D array same size as qq. """ #convert all the properties to pixel values lam = self.lam / del_px def_val = self.defocus / del_px cs = self.Cs / del_px ca = self.Ca / del_px dy, dx = np.shape(qq) ly = np.arange(dy) - dy//2 lx = np.arange(dx) - dx//2 lY,lX = np.meshgrid(ly, lx, indexing='ij') phi = np.arctan2(lY,lX) #compute the required prefactor terms p1 = np.pi * lam * (def_val + ca * np.cos(2.0 * (phi - self.phi_a))) p2 = np.pi * cs * lam**3 * 0.5 #compute the phase transfer function chiq = -p1 * qq**2 + p2 * qq**4 return chiq def getDampEnv(self,qq,del_px): """ Calculate the complete damping envelope: spatial + temporal Args: qq (2D array): Frequency array del_px (float): Scale (nm/pixel) Returns: ``ndarray``: Damping envelope. 2D array same size as qq. """ #convert all the properties to pixel values lam = self.lam / del_px def_val = self.defocus / del_px spread = self.def_spr / del_px cs = self.Cs / del_px #compute prefactors p3 = 2.0 * (np.pi * self.theta_c * spread)**2 p4 = (np.pi * lam * spread)**2 p5 = np.pi**2 * self.theta_c**2 / lam**2 p6 = cs * lam**3 p7 = def_val * lam #compute the damping envelope u = 1.0 + p3 * qq**2 arg = 1.0/u * ( (p4*qq**4)/2.0 + p5*(p6*qq**3 - p7*qq)**2) dampenv = np.exp(-arg) return dampenv def getTransferFunction(self,qq,del_px): """ Generate the full transfer function in reciprocal space Args: qq (2D array): Frequency array del_px (float): Scale (nm/pixel) Returns: ``ndarray``: Transfer function. 2D array same size as qq. """ chiq = self.getChiQ(qq,del_px) dampenv = self.getDampEnv(qq,del_px) tf = (np.cos(chiq) - 1j * np.sin(chiq)) * dampenv * self.aperture return tf def PropagateWave(self, ObjWave, qq, del_px): """ Propagate object wave function to image plane. This function will propagate the object wave function to the image plane by convolving with the transfer function of microscope, and returns the complex real-space ImgWave Args: ObjWave (2D array): Object wave function. qq (2D array): Frequency array del_px (float): Scale (nm/pixel) Returns: ``ndarray``: Realspace image wave function. Complex 2D array same size as ObjWave. """ #get the transfer function tf = self.getTransferFunction(qq, del_px) #Compute Fourier transform of ObjWave and convolve with tf f_ObjWave = np.fft.fftshift(np.fft.fftn(ObjWave)) f_ImgWave = f_ObjWave * tf ImgWave = np.fft.ifftn(np.fft.ifftshift(f_ImgWave)) return ImgWave def BackPropagateWave(self, ImgWave, qq, del_px): """ Back-propagate an image wave to get the object wave. This function will back-propagate the image wave function to the object wave plane by convolving with exp(+i*Chiq). The damping envelope is not used for back propagation. Returns ObjWave in real space. Args: ObjWave (2D array): Object wave function. qq (2D array): Frequency array del_px (float): Scale (nm/pixel) Returns: ``ndarray``: Realspace object wave function. Complex 2D array same size as ObjWave. """ #Get Chiq and then compute BackPropTF chiq = getChiQ(qq,del_px) backprop_tf = (np.cos(chiq) + 1j * np.sin(chiq)) #Convolve with ImgWave f_ImgWave = np.fft.fftshift(np.fft.fftn(ImgWave)) f_ObjWave = f_ImgWave * backprop_tf ObjWave = np.fft.ifftn(np.fft.ifftshift(f_ObjWave)) return ObjWave def getImage(self, ObjWave, qq, del_px): """ Produce the image at the set defocus using the methods in this class. Args: ObjWave (2D array): Object wave function. qq (2D array): Frequency array del_px (float): Scale (nm/pixel) Returns: ``ndarray``: Realspace image wave function. Real-valued 2D array same size as ObjWave. """ #Get the Propagated wave function ImgWave = self.PropagateWave(ObjWave, qq, del_px) Image = np.abs(ImgWave)**2 return Image def getBFPImage(self, ObjWave, qq, del_px): """ Produce the image in the backfocal plane (diffraction) Args: ObjWave (2D array): Object wave function. qq (2D array): Frequency array del_px (float): Scale (nm/pixel) Returns: ``ndarray``: Realspace image wave function. Real-valued 2D array same size as ObjWave. """ #get the transfer function tf = self.getTransferFunction(qq, del_px) #Compute Fourier transform of ObjWave and convolve with tf f_ObjWave = np.fft.fftshift(np.fft.fftn(ObjWave)) f_ImgWave = f_ObjWave * tf f_Img = np.abs(f_ImgWave)**2 return f_Img
[ "numpy.fft.ifftshift", "numpy.abs", "numpy.sqrt", "numpy.fft.fftn", "numpy.exp", "numpy.zeros", "numpy.arctan2", "numpy.cos", "scipy.ndimage.gaussian_filter", "numpy.sin", "numpy.meshgrid", "numpy.shape", "numpy.amax", "numpy.arange" ]
[((3882, 3915), 'numpy.sqrt', 'np.sqrt', (['(1.5 * self.Cs * self.lam)'], {}), '(1.5 * self.Cs * self.lam)\n', (3889, 3915), True, 'import numpy as np\n'), ((4211, 4222), 'numpy.amax', 'np.amax', (['qq'], {}), '(qq)\n', (4218, 4222), True, 'import numpy as np\n'), ((4643, 4661), 'numpy.zeros', 'np.zeros', (['qq.shape'], {}), '(qq.shape)\n', (4651, 4661), True, 'import numpy as np\n'), ((4901, 4937), 'scipy.ndimage.gaussian_filter', 'ndimage.gaussian_filter', (['ap'], {'sigma': '(2)'}), '(ap, sigma=2)\n', (4924, 4937), True, 'import scipy.ndimage as ndimage\n'), ((5471, 5483), 'numpy.shape', 'np.shape', (['qq'], {}), '(qq)\n', (5479, 5483), True, 'import numpy as np\n'), ((5570, 5604), 'numpy.meshgrid', 'np.meshgrid', (['ly', 'lx'], {'indexing': '"""ij"""'}), "(ly, lx, indexing='ij')\n", (5581, 5604), True, 'import numpy as np\n'), ((5619, 5637), 'numpy.arctan2', 'np.arctan2', (['lY', 'lX'], {}), '(lY, lX)\n', (5629, 5637), True, 'import numpy as np\n'), ((6798, 6810), 'numpy.exp', 'np.exp', (['(-arg)'], {}), '(-arg)\n', (6804, 6810), True, 'import numpy as np\n'), ((2284, 2323), 'numpy.sqrt', 'np.sqrt', (['(self.E + epsilon * self.E ** 2)'], {}), '(self.E + epsilon * self.E ** 2)\n', (2291, 2323), True, 'import numpy as np\n'), ((5497, 5510), 'numpy.arange', 'np.arange', (['dy'], {}), '(dy)\n', (5506, 5510), True, 'import numpy as np\n'), ((5532, 5545), 'numpy.arange', 'np.arange', (['dx'], {}), '(dx)\n', (5541, 5545), True, 'import numpy as np\n'), ((8134, 8154), 'numpy.fft.fftn', 'np.fft.fftn', (['ObjWave'], {}), '(ObjWave)\n', (8145, 8154), True, 'import numpy as np\n'), ((8222, 8249), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['f_ImgWave'], {}), '(f_ImgWave)\n', (8238, 8249), True, 'import numpy as np\n'), ((9028, 9040), 'numpy.cos', 'np.cos', (['chiq'], {}), '(chiq)\n', (9034, 9040), True, 'import numpy as np\n'), ((9130, 9150), 'numpy.fft.fftn', 'np.fft.fftn', (['ImgWave'], {}), '(ImgWave)\n', (9141, 9150), True, 'import numpy as np\n'), ((9227, 9254), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['f_ObjWave'], {}), '(f_ObjWave)\n', (9243, 9254), True, 'import numpy as np\n'), ((9835, 9850), 'numpy.abs', 'np.abs', (['ImgWave'], {}), '(ImgWave)\n', (9841, 9850), True, 'import numpy as np\n'), ((10499, 10519), 'numpy.fft.fftn', 'np.fft.fftn', (['ObjWave'], {}), '(ObjWave)\n', (10510, 10519), True, 'import numpy as np\n'), ((10572, 10589), 'numpy.abs', 'np.abs', (['f_ImgWave'], {}), '(f_ImgWave)\n', (10578, 10589), True, 'import numpy as np\n'), ((2243, 2281), 'numpy.sqrt', 'np.sqrt', (['(2.0 * physcon.m_e * physcon.e)'], {}), '(2.0 * physcon.m_e * physcon.e)\n', (2250, 2281), True, 'import numpy as np\n'), ((9048, 9060), 'numpy.sin', 'np.sin', (['chiq'], {}), '(chiq)\n', (9054, 9060), True, 'import numpy as np\n'), ((5727, 5759), 'numpy.cos', 'np.cos', (['(2.0 * (phi - self.phi_a))'], {}), '(2.0 * (phi - self.phi_a))\n', (5733, 5759), True, 'import numpy as np\n'), ((7251, 7263), 'numpy.cos', 'np.cos', (['chiq'], {}), '(chiq)\n', (7257, 7263), True, 'import numpy as np\n'), ((7271, 7283), 'numpy.sin', 'np.sin', (['chiq'], {}), '(chiq)\n', (7277, 7283), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf import sklearn as skl from modules.models.utils import parse_hooks, parse_layers, get_rate from modules.models.base import DeterministicTracker, ProbabilisticTracker from tensorflow.python.saved_model.signature_constants import ( DEFAULT_SERVING_SIGNATURE_DEF_KEY) from tensorflow.python.estimator.export.export_output import PredictOutput from tensorflow.python.ops.variable_scope import variable_scope as var_scope class SimpleTracker(DeterministicTracker): """docstring for ExampleTF""" def __init__(self, input_fn_config={"shuffle": True}, config={}, params={}): # noqa: E129 super(SimpleTracker, self).__init__(input_fn_config, config, params) def model_fn(self, features, labels, mode, params, config): blocks = tf.layers.flatten(features["blocks"]) incoming = tf.layers.flatten(features["incoming"]) concat = tf.concat([blocks, incoming], axis=1) unnormed = parse_layers( inputs=concat, layers=params["layers"], mode=mode, default_summaries=params["default_summaries"]) normed = tf.nn.l2_normalize(unnormed, dim=1) # ================================================================ if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec( mode=mode, predictions={"directions": normed}, export_outputs={ DEFAULT_SERVING_SIGNATURE_DEF_KEY: PredictOutput({ "directions": normed }) }) # ================================================================ loss = -tf.multiply(normed, labels) loss = tf.reduce_sum(loss, axis=1) loss = tf.reduce_mean(loss) optimizer = params["optimizer_class"]( learning_rate=params["learning_rate"]) gradients, variables = zip(*optimizer.compute_gradients(loss)) gradient_global_norm = tf.global_norm(gradients, name="global_norm") if "gradient_max_norm" in params: gradients, _ = tf.clip_by_global_norm(gradients, params["gradient_max_norm"], use_norm=gradient_global_norm) train_op = optimizer.apply_gradients(grads_and_vars=zip(gradients, variables), global_step=tf.train.get_global_step()) # ================================================================ training_hooks = parse_hooks(params, locals(), self.save_path) # ================================================================ if (mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL): # noqa: E129 return tf.estimator.EstimatorSpec( mode=mode, loss=loss, train_op=train_op, training_hooks=training_hooks) def score(self, X): pass class MaxEntropyTracker(ProbabilisticTracker): """Implementation of the maximimum entropy probabilistic tracking.""" def __init__(self, input_fn_config={"shuffle": True}, config={}, params={}): # noqa: E129 super(MaxEntropyTracker, self).__init__(input_fn_config, config, params) def model_fn(self, features, labels, mode, params, config): blocks = tf.layers.flatten(features["blocks"]) incoming = tf.layers.flatten(features["incoming"]) concat = tf.concat([blocks, incoming], axis=1) shared_layers = parse_layers( inputs=concat, layers=params["shared_layers"], mode=mode, default_summaries=params["default_summaries"]) mu_out = parse_layers( inputs=shared_layers, layers=params["mu_head"], mode=mode, default_summaries=params["default_summaries"]) k_out = parse_layers( inputs=shared_layers, layers=params["k_head"], mode=mode, default_summaries=params["default_summaries"]) # Normalize the mean vectors mu_normed = tf.nn.l2_normalize(mu_out, dim=1) predictions = { 'mean': mu_normed, 'concentration': k_out } # ================================================================ if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, export_outputs={ DEFAULT_SERVING_SIGNATURE_DEF_KEY: PredictOutput(predictions) }) # ================================================================ dot_products = tf.reduce_sum(tf.multiply(mu_normed, labels), axis=1) W = self.W_stabilized(k_out, 10**-12) H = self.H_stabilized(k_out, 10**-12) cost = -tf.multiply(W, dot_products) T_H = -get_rate(params["temp"]) * H loss = cost + T_H loss = tf.reduce_mean(loss) optimizer = params["optimizer_class"]( learning_rate=get_rate(params["learning_rate"])) gradients, variables = zip(*optimizer.compute_gradients(loss)) gradient_global_norm = tf.global_norm(gradients, name="global_norm") if "gradient_max_norm" in params: gradients, _ = tf.clip_by_global_norm(gradients, params["gradient_max_norm"], use_norm=gradient_global_norm) train_op = optimizer.apply_gradients(grads_and_vars=zip(gradients, variables), global_step=tf.train.get_global_step()) # ================================================================ training_hooks = parse_hooks(params, locals(), self.save_path) # ================================================================ if (mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL): # noqa: E129 return tf.estimator.EstimatorSpec( mode=mode, loss=loss, train_op=train_op, training_hooks=training_hooks) @staticmethod def max_entropy_loss(y, mu, k, T): """Compute the maximum entropy loss. Args: y: Ground-truth fiber direction vectors. mu: Predicted mean vectors. k: Concentration parameters. T: Temperature parameter. Returns: loss: The maximum entropy loss. """ dot_products = tf.reduce_sum(tf.multiply(mu, y), axis=1) W = tf.cosh(k) / (tf.sinh(k))- tf.reciprocal(k) cost = -tf.multiply(W, dot_products) entropy = 1 - k / tf.tanh(k) - tf.log(k / (4 * np.pi * tf.sinh(k))) loss = cost - T * entropy loss = tf.reduce_mean(loss) return loss @staticmethod def W_stabilized(k, eps): return (k * (1 + tf.exp(-2 * k)) - (1 - tf.exp(-2 * k))) / (eps + k * (1 - tf.exp(-2 * k))) @staticmethod def H_stabilized(k, eps): return (2 * k * tf.exp(-2 * k) / (1 + tf.exp(-2 * k)) - tf.log(k + eps) + tf.log1p(eps - tf.exp(-2 * k)) + tf.log(float(2 * np.pi * np.exp(1))) ) class BayesianTracker(MaxEntropyTracker): def model_fn(self, features, labels, mode, params, config): blocks = tf.layers.flatten(features["blocks"]) #incoming = tf.layers.flatten(features["incoming"]) #incoming = tf.slice(incoming, begin=[0, 0], size=[-1, 3]) incoming = features["incoming"][:, 0] shared_layers = parse_layers( inputs=blocks, layers=params["shared_layers"], mode=mode, default_summaries=params["default_summaries"]) mu_out = parse_layers( inputs=shared_layers, layers=params["mu_head"], mode=mode, default_summaries=params["default_summaries"]) k_out = parse_layers( inputs=shared_layers, layers=params["k_head"], mode=mode, default_summaries=params["default_summaries"]) mu_normed = tf.nn.l2_normalize(mu_out, dim=1) mu_tilde = k_out * (mu_normed + incoming) k_out = tf.norm(mu_tilde, axis=1, keep_dims=True) mean = tf.nn.l2_normalize(mu_tilde, dim=1) predictions = { 'mean': mean, 'concentration': k_out } # ================================================================ if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, export_outputs={ DEFAULT_SERVING_SIGNATURE_DEF_KEY: PredictOutput(predictions) }) # ================================================================ dot_products = tf.reduce_sum(tf.multiply(mean, labels), axis=1) W = self.W_stabilized(k_out, 10**-12) H = self.H_stabilized(k_out, 10**-12) cost = -tf.multiply(W, dot_products) T_H = -get_rate(params["temp"]) * H loss = cost + T_H loss = tf.reduce_mean(loss) optimizer = params["optimizer_class"]( learning_rate=params["learning_rate"]) gradients, variables = zip(*optimizer.compute_gradients(loss)) gradient_global_norm = tf.global_norm(gradients, name="global_norm") if "gradient_max_norm" in params: gradients, _ = tf.clip_by_global_norm(gradients, params["gradient_max_norm"], use_norm=gradient_global_norm) train_op = optimizer.apply_gradients(grads_and_vars=zip(gradients, variables), global_step=tf.train.get_global_step()) # ================================================================ training_hooks = parse_hooks(params, locals(), self.save_path) # ================================================================ if (mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL): # noqa: E129 return tf.estimator.EstimatorSpec( mode=mode, loss=loss, train_op=train_op, training_hooks=training_hooks)
[ "tensorflow.python.estimator.export.export_output.PredictOutput", "tensorflow.layers.flatten", "tensorflow.sinh", "tensorflow.reduce_sum", "tensorflow.tanh", "tensorflow.multiply", "tensorflow.estimator.EstimatorSpec", "tensorflow.reduce_mean", "tensorflow.cosh", "tensorflow.log", "tensorflow.cl...
[((819, 856), 'tensorflow.layers.flatten', 'tf.layers.flatten', (["features['blocks']"], {}), "(features['blocks'])\n", (836, 856), True, 'import tensorflow as tf\n'), ((877, 916), 'tensorflow.layers.flatten', 'tf.layers.flatten', (["features['incoming']"], {}), "(features['incoming'])\n", (894, 916), True, 'import tensorflow as tf\n'), ((935, 972), 'tensorflow.concat', 'tf.concat', (['[blocks, incoming]'], {'axis': '(1)'}), '([blocks, incoming], axis=1)\n', (944, 972), True, 'import tensorflow as tf\n'), ((993, 1107), 'modules.models.utils.parse_layers', 'parse_layers', ([], {'inputs': 'concat', 'layers': "params['layers']", 'mode': 'mode', 'default_summaries': "params['default_summaries']"}), "(inputs=concat, layers=params['layers'], mode=mode,\n default_summaries=params['default_summaries'])\n", (1005, 1107), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((1171, 1206), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['unnormed'], {'dim': '(1)'}), '(unnormed, dim=1)\n', (1189, 1206), True, 'import tensorflow as tf\n'), ((1804, 1831), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['loss'], {'axis': '(1)'}), '(loss, axis=1)\n', (1817, 1831), True, 'import tensorflow as tf\n'), ((1847, 1867), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (1861, 1867), True, 'import tensorflow as tf\n'), ((2071, 2116), 'tensorflow.global_norm', 'tf.global_norm', (['gradients'], {'name': '"""global_norm"""'}), "(gradients, name='global_norm')\n", (2085, 2116), True, 'import tensorflow as tf\n'), ((3564, 3601), 'tensorflow.layers.flatten', 'tf.layers.flatten', (["features['blocks']"], {}), "(features['blocks'])\n", (3581, 3601), True, 'import tensorflow as tf\n'), ((3622, 3661), 'tensorflow.layers.flatten', 'tf.layers.flatten', (["features['incoming']"], {}), "(features['incoming'])\n", (3639, 3661), True, 'import tensorflow as tf\n'), ((3680, 3717), 'tensorflow.concat', 'tf.concat', (['[blocks, incoming]'], {'axis': '(1)'}), '([blocks, incoming], axis=1)\n', (3689, 3717), True, 'import tensorflow as tf\n'), ((3743, 3864), 'modules.models.utils.parse_layers', 'parse_layers', ([], {'inputs': 'concat', 'layers': "params['shared_layers']", 'mode': 'mode', 'default_summaries': "params['default_summaries']"}), "(inputs=concat, layers=params['shared_layers'], mode=mode,\n default_summaries=params['default_summaries'])\n", (3755, 3864), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((3928, 4050), 'modules.models.utils.parse_layers', 'parse_layers', ([], {'inputs': 'shared_layers', 'layers': "params['mu_head']", 'mode': 'mode', 'default_summaries': "params['default_summaries']"}), "(inputs=shared_layers, layers=params['mu_head'], mode=mode,\n default_summaries=params['default_summaries'])\n", (3940, 4050), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((4113, 4234), 'modules.models.utils.parse_layers', 'parse_layers', ([], {'inputs': 'shared_layers', 'layers': "params['k_head']", 'mode': 'mode', 'default_summaries': "params['default_summaries']"}), "(inputs=shared_layers, layers=params['k_head'], mode=mode,\n default_summaries=params['default_summaries'])\n", (4125, 4234), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((4338, 4371), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['mu_out'], {'dim': '(1)'}), '(mu_out, dim=1)\n', (4356, 4371), True, 'import tensorflow as tf\n'), ((5248, 5268), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (5262, 5268), True, 'import tensorflow as tf\n'), ((5482, 5527), 'tensorflow.global_norm', 'tf.global_norm', (['gradients'], {'name': '"""global_norm"""'}), "(gradients, name='global_norm')\n", (5496, 5527), True, 'import tensorflow as tf\n'), ((7150, 7170), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (7164, 7170), True, 'import tensorflow as tf\n'), ((7733, 7770), 'tensorflow.layers.flatten', 'tf.layers.flatten', (["features['blocks']"], {}), "(features['blocks'])\n", (7750, 7770), True, 'import tensorflow as tf\n'), ((7970, 8091), 'modules.models.utils.parse_layers', 'parse_layers', ([], {'inputs': 'blocks', 'layers': "params['shared_layers']", 'mode': 'mode', 'default_summaries': "params['default_summaries']"}), "(inputs=blocks, layers=params['shared_layers'], mode=mode,\n default_summaries=params['default_summaries'])\n", (7982, 8091), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((8155, 8277), 'modules.models.utils.parse_layers', 'parse_layers', ([], {'inputs': 'shared_layers', 'layers': "params['mu_head']", 'mode': 'mode', 'default_summaries': "params['default_summaries']"}), "(inputs=shared_layers, layers=params['mu_head'], mode=mode,\n default_summaries=params['default_summaries'])\n", (8167, 8277), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((8340, 8461), 'modules.models.utils.parse_layers', 'parse_layers', ([], {'inputs': 'shared_layers', 'layers': "params['k_head']", 'mode': 'mode', 'default_summaries': "params['default_summaries']"}), "(inputs=shared_layers, layers=params['k_head'], mode=mode,\n default_summaries=params['default_summaries'])\n", (8352, 8461), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((8528, 8561), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['mu_out'], {'dim': '(1)'}), '(mu_out, dim=1)\n', (8546, 8561), True, 'import tensorflow as tf\n'), ((8630, 8671), 'tensorflow.norm', 'tf.norm', (['mu_tilde'], {'axis': '(1)', 'keep_dims': '(True)'}), '(mu_tilde, axis=1, keep_dims=True)\n', (8637, 8671), True, 'import tensorflow as tf\n'), ((8687, 8722), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['mu_tilde'], {'dim': '(1)'}), '(mu_tilde, dim=1)\n', (8705, 8722), True, 'import tensorflow as tf\n'), ((9589, 9609), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (9603, 9609), True, 'import tensorflow as tf\n'), ((9813, 9858), 'tensorflow.global_norm', 'tf.global_norm', (['gradients'], {'name': '"""global_norm"""'}), "(gradients, name='global_norm')\n", (9827, 9858), True, 'import tensorflow as tf\n'), ((1761, 1788), 'tensorflow.multiply', 'tf.multiply', (['normed', 'labels'], {}), '(normed, labels)\n', (1772, 1788), True, 'import tensorflow as tf\n'), ((2187, 2285), 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['gradients', "params['gradient_max_norm']"], {'use_norm': 'gradient_global_norm'}), "(gradients, params['gradient_max_norm'], use_norm=\n gradient_global_norm)\n", (2209, 2285), True, 'import tensorflow as tf\n'), ((2913, 3015), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'loss', 'train_op': 'train_op', 'training_hooks': 'training_hooks'}), '(mode=mode, loss=loss, train_op=train_op,\n training_hooks=training_hooks)\n', (2939, 3015), True, 'import tensorflow as tf\n'), ((4980, 5010), 'tensorflow.multiply', 'tf.multiply', (['mu_normed', 'labels'], {}), '(mu_normed, labels)\n', (4991, 5010), True, 'import tensorflow as tf\n'), ((5131, 5159), 'tensorflow.multiply', 'tf.multiply', (['W', 'dot_products'], {}), '(W, dot_products)\n', (5142, 5159), True, 'import tensorflow as tf\n'), ((5598, 5696), 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['gradients', "params['gradient_max_norm']"], {'use_norm': 'gradient_global_norm'}), "(gradients, params['gradient_max_norm'], use_norm=\n gradient_global_norm)\n", (5620, 5696), True, 'import tensorflow as tf\n'), ((6326, 6428), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'loss', 'train_op': 'train_op', 'training_hooks': 'training_hooks'}), '(mode=mode, loss=loss, train_op=train_op,\n training_hooks=training_hooks)\n', (6352, 6428), True, 'import tensorflow as tf\n'), ((6892, 6910), 'tensorflow.multiply', 'tf.multiply', (['mu', 'y'], {}), '(mu, y)\n', (6903, 6910), True, 'import tensorflow as tf\n'), ((6960, 6976), 'tensorflow.reciprocal', 'tf.reciprocal', (['k'], {}), '(k)\n', (6973, 6976), True, 'import tensorflow as tf\n'), ((6994, 7022), 'tensorflow.multiply', 'tf.multiply', (['W', 'dot_products'], {}), '(W, dot_products)\n', (7005, 7022), True, 'import tensorflow as tf\n'), ((9326, 9351), 'tensorflow.multiply', 'tf.multiply', (['mean', 'labels'], {}), '(mean, labels)\n', (9337, 9351), True, 'import tensorflow as tf\n'), ((9472, 9500), 'tensorflow.multiply', 'tf.multiply', (['W', 'dot_products'], {}), '(W, dot_products)\n', (9483, 9500), True, 'import tensorflow as tf\n'), ((9929, 10027), 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['gradients', "params['gradient_max_norm']"], {'use_norm': 'gradient_global_norm'}), "(gradients, params['gradient_max_norm'], use_norm=\n gradient_global_norm)\n", (9951, 10027), True, 'import tensorflow as tf\n'), ((10657, 10759), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'loss', 'train_op': 'train_op', 'training_hooks': 'training_hooks'}), '(mode=mode, loss=loss, train_op=train_op,\n training_hooks=training_hooks)\n', (10683, 10759), True, 'import tensorflow as tf\n'), ((2526, 2552), 'tensorflow.train.get_global_step', 'tf.train.get_global_step', ([], {}), '()\n', (2550, 2552), True, 'import tensorflow as tf\n'), ((5176, 5200), 'modules.models.utils.get_rate', 'get_rate', (["params['temp']"], {}), "(params['temp'])\n", (5184, 5200), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((5343, 5376), 'modules.models.utils.get_rate', 'get_rate', (["params['learning_rate']"], {}), "(params['learning_rate'])\n", (5351, 5376), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((5937, 5963), 'tensorflow.train.get_global_step', 'tf.train.get_global_step', ([], {}), '()\n', (5961, 5963), True, 'import tensorflow as tf\n'), ((6933, 6943), 'tensorflow.cosh', 'tf.cosh', (['k'], {}), '(k)\n', (6940, 6943), True, 'import tensorflow as tf\n'), ((6947, 6957), 'tensorflow.sinh', 'tf.sinh', (['k'], {}), '(k)\n', (6954, 6957), True, 'import tensorflow as tf\n'), ((9517, 9541), 'modules.models.utils.get_rate', 'get_rate', (["params['temp']"], {}), "(params['temp'])\n", (9525, 9541), False, 'from modules.models.utils import parse_hooks, parse_layers, get_rate\n'), ((10268, 10294), 'tensorflow.train.get_global_step', 'tf.train.get_global_step', ([], {}), '()\n', (10292, 10294), True, 'import tensorflow as tf\n'), ((7050, 7060), 'tensorflow.tanh', 'tf.tanh', (['k'], {}), '(k)\n', (7057, 7060), True, 'import tensorflow as tf\n'), ((7288, 7302), 'tensorflow.exp', 'tf.exp', (['(-2 * k)'], {}), '(-2 * k)\n', (7294, 7302), True, 'import tensorflow as tf\n'), ((7469, 7484), 'tensorflow.log', 'tf.log', (['(k + eps)'], {}), '(k + eps)\n', (7475, 7484), True, 'import tensorflow as tf\n'), ((1567, 1604), 'tensorflow.python.estimator.export.export_output.PredictOutput', 'PredictOutput', (["{'directions': normed}"], {}), "({'directions': normed})\n", (1580, 1604), False, 'from tensorflow.python.estimator.export.export_output import PredictOutput\n'), ((4821, 4847), 'tensorflow.python.estimator.export.export_output.PredictOutput', 'PredictOutput', (['predictions'], {}), '(predictions)\n', (4834, 4847), False, 'from tensorflow.python.estimator.export.export_output import PredictOutput\n'), ((7087, 7097), 'tensorflow.sinh', 'tf.sinh', (['k'], {}), '(k)\n', (7094, 7097), True, 'import tensorflow as tf\n'), ((7265, 7279), 'tensorflow.exp', 'tf.exp', (['(-2 * k)'], {}), '(-2 * k)\n', (7271, 7279), True, 'import tensorflow as tf\n'), ((7323, 7337), 'tensorflow.exp', 'tf.exp', (['(-2 * k)'], {}), '(-2 * k)\n', (7329, 7337), True, 'import tensorflow as tf\n'), ((7518, 7532), 'tensorflow.exp', 'tf.exp', (['(-2 * k)'], {}), '(-2 * k)\n', (7524, 7532), True, 'import tensorflow as tf\n'), ((7577, 7586), 'numpy.exp', 'np.exp', (['(1)'], {}), '(1)\n', (7583, 7586), True, 'import numpy as np\n'), ((9167, 9193), 'tensorflow.python.estimator.export.export_output.PredictOutput', 'PredictOutput', (['predictions'], {}), '(predictions)\n', (9180, 9193), False, 'from tensorflow.python.estimator.export.export_output import PredictOutput\n'), ((7413, 7427), 'tensorflow.exp', 'tf.exp', (['(-2 * k)'], {}), '(-2 * k)\n', (7419, 7427), True, 'import tensorflow as tf\n'), ((7435, 7449), 'tensorflow.exp', 'tf.exp', (['(-2 * k)'], {}), '(-2 * k)\n', (7441, 7449), True, 'import tensorflow as tf\n')]
import matplotlib.pyplot as plt import numpy as np import pathlib import f16 import casadi as ca import pytest from casadi.tools.graph import graph import os TRIM_TOL = 1e-5 def plot_table2D(title, path, x_grid, y_grid, x_label, y_label, f_table): X, Y = np.meshgrid(x_grid, y_grid) Z = np.zeros((len(x_grid), len(y_grid))) for i, x in enumerate(x_grid): for j, y in enumerate(y_grid): Z[i, j] = f_table(x, y) plt.figure() plt.contourf(X, Y, Z.T, levels=20) plt.colorbar() plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) plt.savefig(path.joinpath('{:s}.png'.format(title))) plt.close() def test_tables(): alpha_deg_grid = np.linspace(-15, 50, 20) beta_deg_grid = np.linspace(-35, 35, 20) elev_deg_grid = np.linspace(-30, 30, 20) ail_deg_grid = np.linspace(-30, 30, 20) mach_grid = np.linspace(0, 1.1, 20) alt_grid = np.linspace(-1e4, 6e4, 20) path = pathlib.Path('results') path.mkdir(parents=True, exist_ok=True) tables = f16.tables plot_table2D('Cl', path, alpha_deg_grid, beta_deg_grid, 'alpha_deg', 'beta_deg', tables['Cl']) plot_table2D('Cm', path, alpha_deg_grid, elev_deg_grid, 'alpha_deg', 'elev_deg', tables['Cm']) plot_table2D('Cn', path, alpha_deg_grid, beta_deg_grid, 'alpha_deg', 'beta_deg', tables['Cn']) plot_table2D('Cx', path, alpha_deg_grid, elev_deg_grid, 'alpha_deg', 'elev_deg', tables['Cx']) plot_table2D('Cy', path, beta_deg_grid, ail_deg_grid, 'beta_deg', 'ail_deg', lambda x, y: tables['Cy'](x, y, 0)) plot_table2D('Cz', path, alpha_deg_grid, beta_deg_grid, 'alpha_deg', 'beta_deg', lambda x, y: tables['Cz'](x, y, 0)) plot_table2D('thrust_idle', path, alt_grid, mach_grid, 'alt, ft', 'mach', tables['thrust_idle']) plot_table2D('thrust_mil', path, alt_grid, mach_grid, 'alt, ft', 'mach', tables['thrust_mil']) plot_table2D('thrust_max', path, alt_grid, mach_grid, 'alt, ft', 'mach', tables['thrust_max']) plt.figure() lift = [] for alpha in alpha_deg_grid: lift.append(-tables['Cz'](alpha, 0, 0)) plt.plot(alpha_deg_grid, lift) plt.xlabel('alpha, deg') plt.ylabel('CL') plt.savefig(path.joinpath('CL.png')) plt.close() plt.figure() plot_table2D('amach', path, np.linspace(0, 1000), np.linspace(0, 60000), 'VT, ft/s', 'alt, ft', tables['amach']) plt.close() names = ['CXq', 'CYr', 'CYp', 'CZq', 'Clr', 'Clp', 'Cmq', 'Cnr', 'Cnp'] for name in names: plt.figure() data = [tables[name](alpha) for alpha in alpha_deg_grid] plt.plot(alpha_deg_grid, data) plt.xlabel('alpha, deg') plt.ylabel(name) plt.savefig(path.joinpath('damp_{:s}.png'.format(name))) plt.close() def test_jacobian(): x_sym = ca.MX.sym('x', 16) u_sym = ca.MX.sym('u', 4) x = f16.State.from_casadi(x_sym) u = f16.Control.from_casadi(u_sym) p = f16.Parameters() dx = f16.dynamics(x, u, p) A = ca.jacobian(dx.to_casadi(), x_sym) B = ca.jacobian(dx.to_casadi(), u_sym) f_A = ca.Function('A', [x_sym, u_sym], [A]) f_B = ca.Function('B', [x_sym, u_sym], [B]) print('A', f_A(np.ones(16), np.ones(4))) print('B', f_B(np.ones(16), np.ones(4))) def test_trim1(): # pg 197 p = f16.Parameters() x = f16.State(VT=502, alpha=0.03691, theta=0.03691) u = f16.Control(thtl=0.1385, elv_cmd_deg=-0.7588) x = f16.trim_actuators(x, u) dx = f16.dynamics(x, u, p) print(dx) assert f16.trim_cost(dx) < TRIM_TOL def test_trim2(): # pg 197 p = f16.Parameters(xcg=0.3) x = f16.State(VT=502, alpha=0.03936, theta=0.03936) u = f16.Control(thtl=0.1485, elv_cmd_deg=-1.931) x = f16.trim_actuators(x, u) x.power = f16.tables['tgear'](u.thtl) dx = f16.dynamics(x, u, p) print(dx) assert f16.trim_cost(dx) < TRIM_TOL def test_trim3(): # pg 197 p = f16.Parameters(xcg=0.38) x = f16.State(VT=502, alpha=0.03544, theta=0.03544) u = f16.Control(thtl=0.1325, elv_cmd_deg=-0.0559) x = f16.trim_actuators(x, u) dx = f16.dynamics(x, u, p) assert f16.trim_cost(dx) < TRIM_TOL def test_trim4(): # pg 197 p = f16.Parameters(xcg=0.3) # psi_dot = 0.3 x = f16.State(VT=502, alpha=0.2485, beta=4.8e-4, phi=1.367, theta=0.05185, P=-0.0155, Q=0.2934, R=0.06071) u = f16.Control( thtl=0.8499, elv_cmd_deg=-6.256, ail_cmd_deg=0.09891, rdr_cmd_deg=-0.4218) x = f16.trim_actuators(x, u) dx = f16.dynamics(x, u, p) print(dx) assert f16.trim_cost(dx) < TRIM_TOL def test_trim5(): # pg 197 p = f16.Parameters(xcg=0.3) # listed as -0.3, must be typo # theta_dot = 0.3 x = f16.State(VT=502, alpha=0.3006, beta=4.1e-5, theta=0.3006, Q=0.3) u = f16.Control( thtl=1.023, elv_cmd_deg=-7.082, ail_cmd_deg=-6.2e-4, rdr_cmd_deg=0.01655) x = f16.trim_actuators(x, u) dx = f16.dynamics(x, u, p) print(dx) assert f16.trim_cost(dx) < 2e-2 # doesn't converge as close def test_trim6(): # pg 195 p = f16.Parameters() x = f16.State(VT=502, alpha=2.392628e-1, beta=5.061803e-4, phi=1.366289, theta=5.000808e-2, psi=2.340769e-1, P=-1.499617e-2, Q=2.933811e-1, R=6.084932e-2, p_N=0, p_E=0, alt=0, power=6.412363e1) u = f16.Control(thtl=8.349601e-1, elv_cmd_deg=-1.481766, ail_cmd_deg=9.553108e-2, rdr_cmd_deg=-4.118124e-1) x = f16.trim_actuators(x, u) dx = f16.dynamics(x, u, p) print(dx) assert f16.trim_cost(dx) < TRIM_TOL def test_trim_and_linearize(): p = f16.Parameters() x = f16.State(VT=502) x0, u0 = f16.trim(x=x, p=p, phi_dot=0, theta_dot=0, psi_dot=0, gam=0) dx = f16.dynamics(x0, u0, p) assert f16.trim_cost(dx) < TRIM_TOL print(dx) sys = f16.linearize(x0, u0, p) sys.sub_system(['VT', 'elv_deg', 'alpha', 'Q'], ['elv_cmd_deg'], ['alpha', 'Q']) print(sys) ss = sys.to_control() def test_table_3_5_2(): # pg 187 p = f16.Parameters(xcg=0.4) x = f16.State( VT=500, alpha=0.5, beta=-0.2, phi=-1, theta=1, psi=-1, P=0.7, Q=-0.8, R=0.9, p_N=1000, p_E=900, alt=10000) u = f16.Control( thtl=0.9, elv_cmd_deg=20, ail_cmd_deg=-15, rdr_cmd_deg=-20) x = f16.trim_actuators(x, u) x.power = 90 dx = f16.dynamics(x, u, p) dx_compute = np.array(dx.to_casadi())[:, 0] dx_check = np.array([ -75.23724, -0.8813491, -0.4759990, 2.505734, 0.3250820, 2.145926, 12.62679, 0.9649671, 0.5809759, 342.4439, -266.7707, 248.1241, -58.68999, 0, 0, 0 ]) print('\nexpected:\n\t', dx_check) print('\nactual:\n\t', dx_compute) print('\nerror:\n\t', dx_check - dx_compute) assert np.allclose(dx_compute, dx_check, 1e-3) def test_simulate(): f_control = lambda t, x: f16.Control() f16.simulate(x0=f16.State(VT=502), f_control= f_control, p=f16.Parameters(), t0=0, tf=10, dt=0.01)
[ "f16.State.from_casadi", "matplotlib.pyplot.ylabel", "f16.Parameters", "numpy.array", "f16.linearize", "f16.dynamics", "matplotlib.pyplot.contourf", "pathlib.Path", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "numpy.linspace", "numpy.meshgrid", "f16.tri...
[((263, 290), 'numpy.meshgrid', 'np.meshgrid', (['x_grid', 'y_grid'], {}), '(x_grid, y_grid)\n', (274, 290), True, 'import numpy as np\n'), ((450, 462), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (460, 462), True, 'import matplotlib.pyplot as plt\n'), ((467, 501), 'matplotlib.pyplot.contourf', 'plt.contourf', (['X', 'Y', 'Z.T'], {'levels': '(20)'}), '(X, Y, Z.T, levels=20)\n', (479, 501), True, 'import matplotlib.pyplot as plt\n'), ((506, 520), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (518, 520), True, 'import matplotlib.pyplot as plt\n'), ((525, 544), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {}), '(x_label)\n', (535, 544), True, 'import matplotlib.pyplot as plt\n'), ((549, 568), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {}), '(y_label)\n', (559, 568), True, 'import matplotlib.pyplot as plt\n'), ((573, 589), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (582, 589), True, 'import matplotlib.pyplot as plt\n'), ((651, 662), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (660, 662), True, 'import matplotlib.pyplot as plt\n'), ((705, 729), 'numpy.linspace', 'np.linspace', (['(-15)', '(50)', '(20)'], {}), '(-15, 50, 20)\n', (716, 729), True, 'import numpy as np\n'), ((750, 774), 'numpy.linspace', 'np.linspace', (['(-35)', '(35)', '(20)'], {}), '(-35, 35, 20)\n', (761, 774), True, 'import numpy as np\n'), ((795, 819), 'numpy.linspace', 'np.linspace', (['(-30)', '(30)', '(20)'], {}), '(-30, 30, 20)\n', (806, 819), True, 'import numpy as np\n'), ((839, 863), 'numpy.linspace', 'np.linspace', (['(-30)', '(30)', '(20)'], {}), '(-30, 30, 20)\n', (850, 863), True, 'import numpy as np\n'), ((880, 903), 'numpy.linspace', 'np.linspace', (['(0)', '(1.1)', '(20)'], {}), '(0, 1.1, 20)\n', (891, 903), True, 'import numpy as np\n'), ((919, 953), 'numpy.linspace', 'np.linspace', (['(-10000.0)', '(60000.0)', '(20)'], {}), '(-10000.0, 60000.0, 20)\n', (930, 953), True, 'import numpy as np\n'), ((958, 981), 'pathlib.Path', 'pathlib.Path', (['"""results"""'], {}), "('results')\n", (970, 981), False, 'import pathlib\n'), ((2023, 2035), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2033, 2035), True, 'import matplotlib.pyplot as plt\n'), ((2135, 2165), 'matplotlib.pyplot.plot', 'plt.plot', (['alpha_deg_grid', 'lift'], {}), '(alpha_deg_grid, lift)\n', (2143, 2165), True, 'import matplotlib.pyplot as plt\n'), ((2170, 2194), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""alpha, deg"""'], {}), "('alpha, deg')\n", (2180, 2194), True, 'import matplotlib.pyplot as plt\n'), ((2199, 2215), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""CL"""'], {}), "('CL')\n", (2209, 2215), True, 'import matplotlib.pyplot as plt\n'), ((2261, 2272), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2270, 2272), True, 'import matplotlib.pyplot as plt\n'), ((2278, 2290), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2288, 2290), True, 'import matplotlib.pyplot as plt\n'), ((2412, 2423), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2421, 2423), True, 'import matplotlib.pyplot as plt\n'), ((2827, 2845), 'casadi.MX.sym', 'ca.MX.sym', (['"""x"""', '(16)'], {}), "('x', 16)\n", (2836, 2845), True, 'import casadi as ca\n'), ((2858, 2875), 'casadi.MX.sym', 'ca.MX.sym', (['"""u"""', '(4)'], {}), "('u', 4)\n", (2867, 2875), True, 'import casadi as ca\n'), ((2884, 2912), 'f16.State.from_casadi', 'f16.State.from_casadi', (['x_sym'], {}), '(x_sym)\n', (2905, 2912), False, 'import f16\n'), ((2921, 2951), 'f16.Control.from_casadi', 'f16.Control.from_casadi', (['u_sym'], {}), '(u_sym)\n', (2944, 2951), False, 'import f16\n'), ((2960, 2976), 'f16.Parameters', 'f16.Parameters', ([], {}), '()\n', (2974, 2976), False, 'import f16\n'), ((2986, 3007), 'f16.dynamics', 'f16.dynamics', (['x', 'u', 'p'], {}), '(x, u, p)\n', (2998, 3007), False, 'import f16\n'), ((3104, 3141), 'casadi.Function', 'ca.Function', (['"""A"""', '[x_sym, u_sym]', '[A]'], {}), "('A', [x_sym, u_sym], [A])\n", (3115, 3141), True, 'import casadi as ca\n'), ((3152, 3189), 'casadi.Function', 'ca.Function', (['"""B"""', '[x_sym, u_sym]', '[B]'], {}), "('B', [x_sym, u_sym], [B])\n", (3163, 3189), True, 'import casadi as ca\n'), ((3321, 3337), 'f16.Parameters', 'f16.Parameters', ([], {}), '()\n', (3335, 3337), False, 'import f16\n'), ((3346, 3393), 'f16.State', 'f16.State', ([], {'VT': '(502)', 'alpha': '(0.03691)', 'theta': '(0.03691)'}), '(VT=502, alpha=0.03691, theta=0.03691)\n', (3355, 3393), False, 'import f16\n'), ((3402, 3447), 'f16.Control', 'f16.Control', ([], {'thtl': '(0.1385)', 'elv_cmd_deg': '(-0.7588)'}), '(thtl=0.1385, elv_cmd_deg=-0.7588)\n', (3413, 3447), False, 'import f16\n'), ((3456, 3480), 'f16.trim_actuators', 'f16.trim_actuators', (['x', 'u'], {}), '(x, u)\n', (3474, 3480), False, 'import f16\n'), ((3490, 3511), 'f16.dynamics', 'f16.dynamics', (['x', 'u', 'p'], {}), '(x, u, p)\n', (3502, 3511), False, 'import f16\n'), ((3607, 3630), 'f16.Parameters', 'f16.Parameters', ([], {'xcg': '(0.3)'}), '(xcg=0.3)\n', (3621, 3630), False, 'import f16\n'), ((3639, 3686), 'f16.State', 'f16.State', ([], {'VT': '(502)', 'alpha': '(0.03936)', 'theta': '(0.03936)'}), '(VT=502, alpha=0.03936, theta=0.03936)\n', (3648, 3686), False, 'import f16\n'), ((3695, 3739), 'f16.Control', 'f16.Control', ([], {'thtl': '(0.1485)', 'elv_cmd_deg': '(-1.931)'}), '(thtl=0.1485, elv_cmd_deg=-1.931)\n', (3706, 3739), False, 'import f16\n'), ((3748, 3772), 'f16.trim_actuators', 'f16.trim_actuators', (['x', 'u'], {}), '(x, u)\n', (3766, 3772), False, 'import f16\n'), ((3824, 3845), 'f16.dynamics', 'f16.dynamics', (['x', 'u', 'p'], {}), '(x, u, p)\n', (3836, 3845), False, 'import f16\n'), ((3941, 3965), 'f16.Parameters', 'f16.Parameters', ([], {'xcg': '(0.38)'}), '(xcg=0.38)\n', (3955, 3965), False, 'import f16\n'), ((3974, 4021), 'f16.State', 'f16.State', ([], {'VT': '(502)', 'alpha': '(0.03544)', 'theta': '(0.03544)'}), '(VT=502, alpha=0.03544, theta=0.03544)\n', (3983, 4021), False, 'import f16\n'), ((4030, 4075), 'f16.Control', 'f16.Control', ([], {'thtl': '(0.1325)', 'elv_cmd_deg': '(-0.0559)'}), '(thtl=0.1325, elv_cmd_deg=-0.0559)\n', (4041, 4075), False, 'import f16\n'), ((4084, 4108), 'f16.trim_actuators', 'f16.trim_actuators', (['x', 'u'], {}), '(x, u)\n', (4102, 4108), False, 'import f16\n'), ((4118, 4139), 'f16.dynamics', 'f16.dynamics', (['x', 'u', 'p'], {}), '(x, u, p)\n', (4130, 4139), False, 'import f16\n'), ((4221, 4244), 'f16.Parameters', 'f16.Parameters', ([], {'xcg': '(0.3)'}), '(xcg=0.3)\n', (4235, 4244), False, 'import f16\n'), ((4273, 4381), 'f16.State', 'f16.State', ([], {'VT': '(502)', 'alpha': '(0.2485)', 'beta': '(0.00048)', 'phi': '(1.367)', 'theta': '(0.05185)', 'P': '(-0.0155)', 'Q': '(0.2934)', 'R': '(0.06071)'}), '(VT=502, alpha=0.2485, beta=0.00048, phi=1.367, theta=0.05185, P=-\n 0.0155, Q=0.2934, R=0.06071)\n', (4282, 4381), False, 'import f16\n'), ((4402, 4492), 'f16.Control', 'f16.Control', ([], {'thtl': '(0.8499)', 'elv_cmd_deg': '(-6.256)', 'ail_cmd_deg': '(0.09891)', 'rdr_cmd_deg': '(-0.4218)'}), '(thtl=0.8499, elv_cmd_deg=-6.256, ail_cmd_deg=0.09891,\n rdr_cmd_deg=-0.4218)\n', (4413, 4492), False, 'import f16\n'), ((4514, 4538), 'f16.trim_actuators', 'f16.trim_actuators', (['x', 'u'], {}), '(x, u)\n', (4532, 4538), False, 'import f16\n'), ((4548, 4569), 'f16.dynamics', 'f16.dynamics', (['x', 'u', 'p'], {}), '(x, u, p)\n', (4560, 4569), False, 'import f16\n'), ((4665, 4688), 'f16.Parameters', 'f16.Parameters', ([], {'xcg': '(0.3)'}), '(xcg=0.3)\n', (4679, 4688), False, 'import f16\n'), ((4751, 4817), 'f16.State', 'f16.State', ([], {'VT': '(502)', 'alpha': '(0.3006)', 'beta': '(4.1e-05)', 'theta': '(0.3006)', 'Q': '(0.3)'}), '(VT=502, alpha=0.3006, beta=4.1e-05, theta=0.3006, Q=0.3)\n', (4760, 4817), False, 'import f16\n'), ((4825, 4915), 'f16.Control', 'f16.Control', ([], {'thtl': '(1.023)', 'elv_cmd_deg': '(-7.082)', 'ail_cmd_deg': '(-0.00062)', 'rdr_cmd_deg': '(0.01655)'}), '(thtl=1.023, elv_cmd_deg=-7.082, ail_cmd_deg=-0.00062,\n rdr_cmd_deg=0.01655)\n', (4836, 4915), False, 'import f16\n'), ((4936, 4960), 'f16.trim_actuators', 'f16.trim_actuators', (['x', 'u'], {}), '(x, u)\n', (4954, 4960), False, 'import f16\n'), ((4970, 4991), 'f16.dynamics', 'f16.dynamics', (['x', 'u', 'p'], {}), '(x, u, p)\n', (4982, 4991), False, 'import f16\n'), ((5112, 5128), 'f16.Parameters', 'f16.Parameters', ([], {}), '()\n', (5126, 5128), False, 'import f16\n'), ((5137, 5325), 'f16.State', 'f16.State', ([], {'VT': '(502)', 'alpha': '(0.2392628)', 'beta': '(0.0005061803)', 'phi': '(1.366289)', 'theta': '(0.05000808)', 'psi': '(0.2340769)', 'P': '(-0.01499617)', 'Q': '(0.2933811)', 'R': '(0.06084932)', 'p_N': '(0)', 'p_E': '(0)', 'alt': '(0)', 'power': '(64.12363)'}), '(VT=502, alpha=0.2392628, beta=0.0005061803, phi=1.366289, theta=\n 0.05000808, psi=0.2340769, P=-0.01499617, Q=0.2933811, R=0.06084932,\n p_N=0, p_E=0, alt=0, power=64.12363)\n', (5146, 5325), False, 'import f16\n'), ((5389, 5491), 'f16.Control', 'f16.Control', ([], {'thtl': '(0.8349601)', 'elv_cmd_deg': '(-1.481766)', 'ail_cmd_deg': '(0.09553108)', 'rdr_cmd_deg': '(-0.4118124)'}), '(thtl=0.8349601, elv_cmd_deg=-1.481766, ail_cmd_deg=0.09553108,\n rdr_cmd_deg=-0.4118124)\n', (5400, 5491), False, 'import f16\n'), ((5521, 5545), 'f16.trim_actuators', 'f16.trim_actuators', (['x', 'u'], {}), '(x, u)\n', (5539, 5545), False, 'import f16\n'), ((5555, 5576), 'f16.dynamics', 'f16.dynamics', (['x', 'u', 'p'], {}), '(x, u, p)\n', (5567, 5576), False, 'import f16\n'), ((5672, 5688), 'f16.Parameters', 'f16.Parameters', ([], {}), '()\n', (5686, 5688), False, 'import f16\n'), ((5697, 5714), 'f16.State', 'f16.State', ([], {'VT': '(502)'}), '(VT=502)\n', (5706, 5714), False, 'import f16\n'), ((5728, 5788), 'f16.trim', 'f16.trim', ([], {'x': 'x', 'p': 'p', 'phi_dot': '(0)', 'theta_dot': '(0)', 'psi_dot': '(0)', 'gam': '(0)'}), '(x=x, p=p, phi_dot=0, theta_dot=0, psi_dot=0, gam=0)\n', (5736, 5788), False, 'import f16\n'), ((5798, 5821), 'f16.dynamics', 'f16.dynamics', (['x0', 'u0', 'p'], {}), '(x0, u0, p)\n', (5810, 5821), False, 'import f16\n'), ((5886, 5910), 'f16.linearize', 'f16.linearize', (['x0', 'u0', 'p'], {}), '(x0, u0, p)\n', (5899, 5910), False, 'import f16\n'), ((6084, 6107), 'f16.Parameters', 'f16.Parameters', ([], {'xcg': '(0.4)'}), '(xcg=0.4)\n', (6098, 6107), False, 'import f16\n'), ((6116, 6237), 'f16.State', 'f16.State', ([], {'VT': '(500)', 'alpha': '(0.5)', 'beta': '(-0.2)', 'phi': '(-1)', 'theta': '(1)', 'psi': '(-1)', 'P': '(0.7)', 'Q': '(-0.8)', 'R': '(0.9)', 'p_N': '(1000)', 'p_E': '(900)', 'alt': '(10000)'}), '(VT=500, alpha=0.5, beta=-0.2, phi=-1, theta=1, psi=-1, P=0.7, Q=-\n 0.8, R=0.9, p_N=1000, p_E=900, alt=10000)\n', (6125, 6237), False, 'import f16\n'), ((6274, 6345), 'f16.Control', 'f16.Control', ([], {'thtl': '(0.9)', 'elv_cmd_deg': '(20)', 'ail_cmd_deg': '(-15)', 'rdr_cmd_deg': '(-20)'}), '(thtl=0.9, elv_cmd_deg=20, ail_cmd_deg=-15, rdr_cmd_deg=-20)\n', (6285, 6345), False, 'import f16\n'), ((6371, 6395), 'f16.trim_actuators', 'f16.trim_actuators', (['x', 'u'], {}), '(x, u)\n', (6389, 6395), False, 'import f16\n'), ((6422, 6443), 'f16.dynamics', 'f16.dynamics', (['x', 'u', 'p'], {}), '(x, u, p)\n', (6434, 6443), False, 'import f16\n'), ((6507, 6674), 'numpy.array', 'np.array', (['[-75.23724, -0.8813491, -0.475999, 2.505734, 0.325082, 2.145926, 12.62679, \n 0.9649671, 0.5809759, 342.4439, -266.7707, 248.1241, -58.68999, 0, 0, 0]'], {}), '([-75.23724, -0.8813491, -0.475999, 2.505734, 0.325082, 2.145926, \n 12.62679, 0.9649671, 0.5809759, 342.4439, -266.7707, 248.1241, -\n 58.68999, 0, 0, 0])\n', (6515, 6674), True, 'import numpy as np\n'), ((6843, 6883), 'numpy.allclose', 'np.allclose', (['dx_compute', 'dx_check', '(0.001)'], {}), '(dx_compute, dx_check, 0.001)\n', (6854, 6883), True, 'import numpy as np\n'), ((2323, 2343), 'numpy.linspace', 'np.linspace', (['(0)', '(1000)'], {}), '(0, 1000)\n', (2334, 2343), True, 'import numpy as np\n'), ((2345, 2366), 'numpy.linspace', 'np.linspace', (['(0)', '(60000)'], {}), '(0, 60000)\n', (2356, 2366), True, 'import numpy as np\n'), ((2532, 2544), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2542, 2544), True, 'import matplotlib.pyplot as plt\n'), ((2618, 2648), 'matplotlib.pyplot.plot', 'plt.plot', (['alpha_deg_grid', 'data'], {}), '(alpha_deg_grid, data)\n', (2626, 2648), True, 'import matplotlib.pyplot as plt\n'), ((2657, 2681), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""alpha, deg"""'], {}), "('alpha, deg')\n", (2667, 2681), True, 'import matplotlib.pyplot as plt\n'), ((2690, 2706), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['name'], {}), '(name)\n', (2700, 2706), True, 'import matplotlib.pyplot as plt\n'), ((2780, 2791), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2789, 2791), True, 'import matplotlib.pyplot as plt\n'), ((3537, 3554), 'f16.trim_cost', 'f16.trim_cost', (['dx'], {}), '(dx)\n', (3550, 3554), False, 'import f16\n'), ((3871, 3888), 'f16.trim_cost', 'f16.trim_cost', (['dx'], {}), '(dx)\n', (3884, 3888), False, 'import f16\n'), ((4151, 4168), 'f16.trim_cost', 'f16.trim_cost', (['dx'], {}), '(dx)\n', (4164, 4168), False, 'import f16\n'), ((4595, 4612), 'f16.trim_cost', 'f16.trim_cost', (['dx'], {}), '(dx)\n', (4608, 4612), False, 'import f16\n'), ((5017, 5034), 'f16.trim_cost', 'f16.trim_cost', (['dx'], {}), '(dx)\n', (5030, 5034), False, 'import f16\n'), ((5602, 5619), 'f16.trim_cost', 'f16.trim_cost', (['dx'], {}), '(dx)\n', (5615, 5619), False, 'import f16\n'), ((5833, 5850), 'f16.trim_cost', 'f16.trim_cost', (['dx'], {}), '(dx)\n', (5846, 5850), False, 'import f16\n'), ((6935, 6948), 'f16.Control', 'f16.Control', ([], {}), '()\n', (6946, 6948), False, 'import f16\n'), ((3209, 3220), 'numpy.ones', 'np.ones', (['(16)'], {}), '(16)\n', (3216, 3220), True, 'import numpy as np\n'), ((3222, 3232), 'numpy.ones', 'np.ones', (['(4)'], {}), '(4)\n', (3229, 3232), True, 'import numpy as np\n'), ((3254, 3265), 'numpy.ones', 'np.ones', (['(16)'], {}), '(16)\n', (3261, 3265), True, 'import numpy as np\n'), ((3267, 3277), 'numpy.ones', 'np.ones', (['(4)'], {}), '(4)\n', (3274, 3277), True, 'import numpy as np\n'), ((6969, 6986), 'f16.State', 'f16.State', ([], {'VT': '(502)'}), '(VT=502)\n', (6978, 6986), False, 'import f16\n'), ((7020, 7036), 'f16.Parameters', 'f16.Parameters', ([], {}), '()\n', (7034, 7036), False, 'import f16\n')]
import torch import torch.optim as optim from torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR import numpy as np import pandas as pd from collections import Counter import time, os, platform, sys, re import torch.backends.cudnn as cudnn def metric(probability, truth, threshold=0.5, reduction='none'): '''Calculates dice of positive and negative images seperately''' '''probability and truth must be torch tensors''' batch_size = len(truth) with torch.no_grad(): probability = probability.view(batch_size, -1) truth = truth.view(batch_size, -1) assert (probability.shape == truth.shape) p = (probability > threshold).float() t = (truth > 0.5).float() t_sum = t.sum(-1) p_sum = p.sum(-1) neg_index = torch.nonzero(t_sum == 0) pos_index = torch.nonzero(t_sum >= 1) dice_neg = (p_sum == 0).float() dice_pos = 2 * (p * t).sum(-1) / ((p + t).sum(-1)) dice_neg = dice_neg[neg_index] dice_pos = dice_pos[pos_index] dice = torch.cat([dice_pos, dice_neg]) num_neg = len(neg_index) num_pos = len(pos_index) return dice, dice_neg, dice_pos, num_neg, num_pos class Meter: '''A meter to keep track of iou and dice scores throughout an epoch''' def __init__(self, phase, epoch): self.base_threshold = 0.5 # <<<<<<<<<<< here's the threshold self.base_dice_scores = [] self.dice_neg_scores = [] self.dice_pos_scores = [] self.iou_scores = [] def predict(self, X, threshold): '''X is sigmoid output of the model''' X_p = np.copy(X) preds = (X_p > threshold).astype('uint8') return preds def update(self, targets, outputs): probs = torch.sigmoid(outputs) dice, dice_neg, dice_pos, _, _ = metric(probs, targets, self.base_threshold) self.base_dice_scores.extend(dice.tolist()) self.dice_pos_scores.extend(dice_pos.tolist()) self.dice_neg_scores.extend(dice_neg.tolist()) preds = self.predict(probs, self.base_threshold) iou = compute_iou_batch(preds, targets, classes=[1]) self.iou_scores.append(iou) def get_metrics(self): dice = np.nanmean(self.base_dice_scores) dice_neg = np.nanmean(self.dice_neg_scores) dice_pos = np.nanmean(self.dice_pos_scores) dices = [dice, dice_neg, dice_pos] iou = np.nanmean(self.iou_scores) return dices, iou def epoch_log(phase, epoch, epoch_loss, meter, start): '''logging the metrics at the end of an epoch''' dices, iou = meter.get_metrics() dice, dice_neg, dice_pos = dices print("Loss: %0.4f | IoU: %0.4f | dice: %0.4f | dice_neg: %0.4f | dice_pos: %0.4f" % ( epoch_loss, iou, dice, dice_neg, dice_pos)) return dice, iou def compute_ious(pred, label, classes, ignore_index=255, only_present=True): '''computes iou for one ground truth mask and predicted mask''' pred[label == ignore_index] = 0 ious = [] for c in classes: label_c = label == c if only_present and np.sum(label_c) == 0: ious.append(np.nan) continue pred_c = pred == c intersection = np.logical_and(pred_c, label_c).sum() union = np.logical_or(pred_c, label_c).sum() if union != 0: ious.append(intersection / union) return ious if ious else [1] def compute_iou_batch(outputs, labels, classes=None): '''computes mean iou for a batch of ground truth masks and predicted masks''' ious = [] preds = np.copy(outputs) # copy is imp labels = np.array(labels) # tensor to np for pred, label in zip(preds, labels): ious.append(np.nanmean(compute_ious(pred, label, classes))) iou = np.nanmean(ious) return iou class Seg_Trainer(object): '''This class takes care of training and validation of our model''' def __init__(self, dataloaders, model, criterion, out_dir, lr=5e-4, batch_size=8, epochs=20, use_sam=False): self.batch_size = {"train": batch_size, "val": 4 * batch_size} if self.batch_size["train"] < 24: self.accumulation_steps = 24 // self.batch_size["train"] else: self.accumulation_steps = 1 # print(self.accumulation_steps) self.out_dir = out_dir self.lr = lr self.num_epochs = epochs self.best_loss = float("inf") self.phases = ["train", "val"] self.cuda = torch.cuda.is_available() if self.cuda: # torch.set_default_tensor_type("torch.cuda.FloatTensor") cudnn.benchmark = True # else: # torch.set_default_tensor_type("torch.FloatTensor") self.net = model self.criterion = criterion self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr, weight_decay=1e-4, amsgrad=True) self.scheduler = StepLR(self.optimizer, step_size=10, gamma=0.2) self.dataloaders = dataloaders self.losses = {phase: [] for phase in self.phases} self.iou_scores = {phase: [] for phase in self.phases} self.dice_scores = {phase: [] for phase in self.phases} self.use_sam = use_sam def forward(self, images, targets, usmasks=None): if self.cuda: images = images.cuda() masks = targets.cuda() if self.use_sam: usmasks = usmasks.cuda() if self.use_sam: outputs = self.net(images, usmasks) else: outputs = self.net(images) # masks=masks.unsqueeze(1) loss = self.criterion(outputs, masks) # print(loss) return loss, outputs def iterate(self, epoch, phase): meter = Meter(phase, epoch) start = time.strftime("%H:%M:%S") print(f"Starting epoch: {epoch} | phase: {phase} | ⏰: {start}") batch_size = self.batch_size[phase] self.net.train(phase == "train") dataloader = self.dataloaders[phase] running_loss = 0.0 total_batches = len(dataloader) # tk0 = tqdm(dataloader, total=total_batches) self.optimizer.zero_grad() if self.use_sam: for itr, (images, targets, usmasks) in enumerate(dataloader): loss, outputs = self.forward(images, targets, usmasks) loss = loss / self.accumulation_steps if phase == "train": loss.backward() if (itr + 1) % self.accumulation_steps == 0: self.optimizer.step() self.optimizer.zero_grad() running_loss += loss.item() outputs = outputs.detach().cpu() meter.update(targets, outputs) else: for itr, (images, targets) in enumerate(dataloader): loss, outputs = self.forward(images, targets) loss = loss / self.accumulation_steps if phase == "train": loss.backward() if (itr + 1) % self.accumulation_steps == 0: self.optimizer.step() self.optimizer.zero_grad() running_loss += loss.item() outputs = outputs.detach().cpu() meter.update(targets, outputs) # tk0.set_postfix(loss=(running_loss / ((itr + 1)))) epoch_loss = (running_loss * self.accumulation_steps) / total_batches dice, iou = epoch_log(phase, epoch, epoch_loss, meter, start) self.losses[phase].append(epoch_loss) self.dice_scores[phase].append(dice) self.iou_scores[phase].append(iou) torch.cuda.empty_cache() return epoch_loss def start(self): for epoch in range(self.num_epochs): self.iterate(epoch, "train") state = { "epoch": epoch, "best_loss": self.best_loss, "state_dict": self.net.state_dict(), "optimizer": self.optimizer.state_dict(), } with torch.no_grad(): val_loss = self.iterate(epoch, "val") # self.scheduler.step(val_loss) restart = self.scheduler.step() if val_loss < self.best_loss: print("******** New optimal found, saving state ********") state["best_loss"] = self.best_loss = val_loss torch.save(state, self.out_dir + '/model_lowest_loss.pth') with open(self.out_dir + '/train_log.txt', 'a') as acc_file: acc_file.write('New optimal found (loss %s), state saved.\n' % val_loss) with open(self.out_dir + '/train_log.txt', 'a') as acc_file: acc_file.write('Epoch: %2d, Loss: %.8f, Dice: %.8f, IoU: %.8f.\n ' % (epoch, self.losses['val'][-1], self.dice_scores['val'][-1], self.iou_scores['val'][-1])) if restart: with open(self.out_dir + '/train_log.txt', 'a') as acc_file: acc_file.write('At Epoch: %2d, Optim Restart. Got Loss: %.8f, Dice: %.8f, IoU: %.8f.\n ' % (epoch, self.losses[ 'val'][ -1], self.dice_scores[ 'val'][ -1], self.iou_scores[ 'val'][ -1])) print()
[ "numpy.copy", "numpy.logical_and", "torch.sigmoid", "time.strftime", "torch.optim.lr_scheduler.StepLR", "numpy.logical_or", "torch.nonzero", "numpy.array", "numpy.nanmean", "torch.cuda.is_available", "numpy.sum", "torch.save", "torch.no_grad", "torch.cuda.empty_cache", "torch.cat" ]
[((3604, 3620), 'numpy.copy', 'np.copy', (['outputs'], {}), '(outputs)\n', (3611, 3620), True, 'import numpy as np\n'), ((3649, 3665), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (3657, 3665), True, 'import numpy as np\n'), ((3803, 3819), 'numpy.nanmean', 'np.nanmean', (['ious'], {}), '(ious)\n', (3813, 3819), True, 'import numpy as np\n'), ((474, 489), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (487, 489), False, 'import torch\n'), ((793, 818), 'torch.nonzero', 'torch.nonzero', (['(t_sum == 0)'], {}), '(t_sum == 0)\n', (806, 818), False, 'import torch\n'), ((839, 864), 'torch.nonzero', 'torch.nonzero', (['(t_sum >= 1)'], {}), '(t_sum >= 1)\n', (852, 864), False, 'import torch\n'), ((1059, 1090), 'torch.cat', 'torch.cat', (['[dice_pos, dice_neg]'], {}), '([dice_pos, dice_neg])\n', (1068, 1090), False, 'import torch\n'), ((1643, 1653), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (1650, 1653), True, 'import numpy as np\n'), ((1782, 1804), 'torch.sigmoid', 'torch.sigmoid', (['outputs'], {}), '(outputs)\n', (1795, 1804), False, 'import torch\n'), ((2249, 2282), 'numpy.nanmean', 'np.nanmean', (['self.base_dice_scores'], {}), '(self.base_dice_scores)\n', (2259, 2282), True, 'import numpy as np\n'), ((2302, 2334), 'numpy.nanmean', 'np.nanmean', (['self.dice_neg_scores'], {}), '(self.dice_neg_scores)\n', (2312, 2334), True, 'import numpy as np\n'), ((2354, 2386), 'numpy.nanmean', 'np.nanmean', (['self.dice_pos_scores'], {}), '(self.dice_pos_scores)\n', (2364, 2386), True, 'import numpy as np\n'), ((2444, 2471), 'numpy.nanmean', 'np.nanmean', (['self.iou_scores'], {}), '(self.iou_scores)\n', (2454, 2471), True, 'import numpy as np\n'), ((4509, 4534), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4532, 4534), False, 'import torch\n'), ((4932, 4979), 'torch.optim.lr_scheduler.StepLR', 'StepLR', (['self.optimizer'], {'step_size': '(10)', 'gamma': '(0.2)'}), '(self.optimizer, step_size=10, gamma=0.2)\n', (4938, 4979), False, 'from torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR\n'), ((5802, 5827), 'time.strftime', 'time.strftime', (['"""%H:%M:%S"""'], {}), "('%H:%M:%S')\n", (5815, 5827), False, 'import time, os, platform, sys, re\n'), ((7719, 7743), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (7741, 7743), False, 'import torch\n'), ((3122, 3137), 'numpy.sum', 'np.sum', (['label_c'], {}), '(label_c)\n', (3128, 3137), True, 'import numpy as np\n'), ((3247, 3278), 'numpy.logical_and', 'np.logical_and', (['pred_c', 'label_c'], {}), '(pred_c, label_c)\n', (3261, 3278), True, 'import numpy as np\n'), ((3301, 3331), 'numpy.logical_or', 'np.logical_or', (['pred_c', 'label_c'], {}), '(pred_c, label_c)\n', (3314, 3331), True, 'import numpy as np\n'), ((8120, 8135), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8133, 8135), False, 'import torch\n'), ((8483, 8541), 'torch.save', 'torch.save', (['state', "(self.out_dir + '/model_lowest_loss.pth')"], {}), "(state, self.out_dir + '/model_lowest_loss.pth')\n", (8493, 8541), False, 'import torch\n')]
""" Operations on trees (dependency parse tree) """ import numpy as np from collections import defaultdict import torch from torch.autograd import Variable class Tree(object): """ Modified from tree.py from 'Graph Convolution over Pruned Dependency Trees for Relation Extraction' """ def __init__(self): self.parent = None self.num_children = 0 self.children = list() def add_child(self,child): child.parent = self self.num_children += 1 self.children.append(child) def size(self): if getattr(self,'_size'): return self._size count = 1 for i in xrange(self.num_children): count += self.children[i].size() self._size = count return self._size def depth(self): if getattr(self,'_depth'): return self._depth count = 0 if self.num_children>0: for i in xrange(self.num_children): child_depth = self.children[i].depth() if child_depth>count: count = child_depth count += 1 self._depth = count return self._depth def __iter__(self): yield self for c in self.children: for x in c: yield x def tree_to_adj(sent_len, tree, directed=True, self_loop=False): """ Convert a tree object to a adjacency matrix. """ ret = np.zeros((sent_len, sent_len), dtype=np.float32) if tree is not None: queue = [tree] idx = [] while len(queue) > 0: t, queue = queue[0], queue[1:] idx += [t.idx] for c in t.children: ret[t.idx, c.idx] = 1 queue += t.children if not directed: ret = ret + ret.T if self_loop: for i in idx: ret[i, i] = 1 else: print('this is None') return ret def head_to_tree(head, tokens, len_, prune, trigger_pos, entity_pos): """ Convert a sequence of head indexes (from dependency parse information) into a tree object. """ tokens = tokens[:len_].tolist() head = head[:len_].tolist() root = None if prune < 0: ### keep the whole dependency tree - no pruning nodes = [Tree() for _ in head] for i in range(len(nodes)): h = head[i] nodes[i].idx = i nodes[i].dist = -1 # just a filler if h == 0: root = nodes[i] else: nodes[h-1].add_child(nodes[i]) else: # find dependency path trigger_pos = [i for i in range(len_) if trigger_pos[i] == 0] entity_pos = [i for i in range(len_) if entity_pos[i] == 0] cas = None trigger_ancestors = set(trigger_pos) for t in trigger_pos: h = head[t] tmp = [t] while h > 0: tmp += [h-1] if len(tmp) == len_ : break trigger_ancestors.add(h-1) h = head[h-1] if cas is None: cas = set(tmp) else: cas.intersection_update(tmp) entity_ancestors = set(entity_pos) for e in entity_pos: h = head[e] tmp = [e] while h > 0: tmp += [h-1] if len(tmp) == len_ : break entity_ancestors.add(h-1) h = head[h-1] cas.intersection_update(tmp) # find lowest common ancestor lca = -1 if len(cas) == 1: lca = list(cas)[0] else: child_count = {k:0 for k in cas} for ca in cas: if head[ca] > 0 and head[ca] - 1 in cas: child_count[head[ca] - 1] += 1 # the LCA has no child in the CA set for ca in cas: if child_count[ca] == 0: lca = ca break path_nodes = trigger_ancestors.union(entity_ancestors).difference(cas) if lca != -1: path_nodes.add(lca) # compute distance to path_nodes dist = [-1 if i not in path_nodes else 0 for i in range(len_)] for i in range(len_): if dist[i] < 0: ## not in path_nodes stack = [i] if stack[-1] >= 0 and stack[-1] not in path_nodes: stack.append(head[stack[-1]] - 1) if stack[-1] in path_nodes: for d, j in enumerate(reversed(stack)): dist[j] = d else: for j in stack: if j >= 0 and dist[j] < 0: dist[j] = int(1e4) # aka infinity highest_node = lca nodes = [Tree() if dist[i] <= prune else None for i in range(len_)] for i in range(len(nodes)): if nodes[i] is None: continue h = head[i] nodes[i].idx = i nodes[i].dist = dist[i] if h > 0 and i != highest_node: if nodes[h-1] is not None: assert nodes[h-1] is not None nodes[h-1].add_child(nodes[i]) root = nodes[highest_node] return root def tokens_tree_adjmatrix(words_in_path, head, words, l, prune, trigger_pos, entity_pos, maxlen): """ Convert tokens to tree structure then to adjacency matrix """ head, words, trigger_pos, entity_pos = head.cpu().numpy(), words.cpu().detach().numpy(), trigger_pos.cpu().numpy(), entity_pos.cpu().numpy() trees = [head_to_tree(head[i], words[i], l[i], prune, trigger_pos[i], entity_pos[i]) for i in range(len(l))] adj = [tree_to_adj(maxlen, tree, directed=False, self_loop=True).reshape(1, maxlen, maxlen) for tree in trees] adj = np.concatenate(adj, axis=0) adj = torch.from_numpy(adj) ### for investigating / troubleshooting purpose #for i in range(len(l)): # print_words_from_adj(words_in_path[i], adj[i]) return Variable(adj.cuda()) def print_words_from_adj(words_in_path, adj): """ For printing sub-dependency parse tree """ words = [] for rows in adj: for col_idx, column in enumerate(rows): if column == 1: words.append(col_idx) words = set(words) print(words) for word_index in words: print(tokenizer.convert_ids_to_tokens(words_in_path[word_index]))
[ "numpy.zeros", "torch.from_numpy", "numpy.concatenate" ]
[((1445, 1493), 'numpy.zeros', 'np.zeros', (['(sent_len, sent_len)'], {'dtype': 'np.float32'}), '((sent_len, sent_len), dtype=np.float32)\n', (1453, 1493), True, 'import numpy as np\n'), ((5991, 6018), 'numpy.concatenate', 'np.concatenate', (['adj'], {'axis': '(0)'}), '(adj, axis=0)\n', (6005, 6018), True, 'import numpy as np\n'), ((6029, 6050), 'torch.from_numpy', 'torch.from_numpy', (['adj'], {}), '(adj)\n', (6045, 6050), False, 'import torch\n')]
#!/usr/bin/env python import rospy import sys import time import numpy as np from numpy import linalg as LA import random from realtimepseudoAstar import plan from globaltorobotcoords import transform from std_msgs.msg import String from nubot_common.msg import ActionCmd, VelCmd, OminiVisionInfo, BallInfo, ObstaclesInfo, RobotInfo, BallIsHolding ROBOT_NAME = 'NuBot' + str(sys.argv[1]) if str(sys.argv[2]) == '1': ROBOT_NAME = 'rival' + str(sys.argv[1]) opponent_goal = np.array([1100.0, 0.0]) isdribble = 0 #Init ball handlers ball_handler1 = (0, "NuBot1") ball_handler2 = (0, "NuBot2") ball_handler3 = (0, "NuBot3") ball_handler4 = (0, "rival1") ball_handler5 = (0, "rival2") ball_handler6 = (0, "rival3") ball_handler_current = "nobody" shoot_range = 500 #Bare minimum is 50 obstacle_radius = 75 plan_radius = 300 random_obstacle_clipping = True if str(sys.argv[1]) == '2': my_id = 1 mate_id = 2 if str(sys.argv[1]) == '3': my_id = 2 mate_id = 1 # For plotting # import math # import matplotlib.pyplot as plt # Initialize publisher and rate pub = rospy.Publisher('/' + str(ROBOT_NAME)+'/nubotcontrol/actioncmd', ActionCmd, queue_size=1) rospy.init_node(str(ROBOT_NAME) + '_brain', anonymous=False) hertz = 10 rate = rospy.Rate(hertz) #rate2 = rospy.Rate(1) # #For plotting path and path plan # targets_generated_x = [] # targets_generated_y = [] # robot_position_x = [] # robot_position_y = [] # def plot_circle(x, y, size, color="-b"): # pragma: no cover # deg = list(range(0, 360, 5)) # deg.append(0) # xl = [x + size * math.cos(np.deg2rad(d)) for d in deg] # yl = [y + size * math.sin(np.deg2rad(d)) for d in deg] # plt.plot(xl, yl, color) def callback(data): def in_range(pos_1, pos_2, dist=300): val = np.linalg.norm(pos_1 - pos_2) return val < dist def exists_clear_path(goal_pos, current_pos, obstacles): AB = goal_pos - current_pos for o in obstacles: AC = o[:2] - current_pos AD = AB * np.dot(AC, AB) / np.dot(AB, AB) D = current_pos + AD if np.linalg.norm(D - o[:2]) <= o[2]: return False return True action = ActionCmd() #Get ball position in global frame b = data.ballinfo ball_pos = np.array([b.pos.x, b.pos.y]) if np.abs(ball_pos[0]) > 1100 and np.abs(ball_pos[1]) < 125: action = ActionCmd() action.target.x = 0 action.target.y = 0 action.maxvel = 0 pub.publish(action) #print('sleeping') time.sleep(1.5) #rate2.sleep() #Get robot position and heading in global frame r = data.robotinfo[my_id] my_pos = np.array([r.pos.x, r.pos.y]) my_theta = r.heading.theta #Get teammate position and heading in global frame r_2 = data.robotinfo[mate_id] mate_pos = np.array([r_2.pos.x, r_2.pos.y]) mate_theta = r.heading.theta #Get obstacle positions in global frame obstacles = data.obstacleinfo obstacle_list = np.empty((0,3), float) for p in obstacles.pos: obstacle_list = np.concatenate((obstacle_list, np.array([[p.x, p.y, 75]]))) # In range to pass passing = False if isdribble and in_range(my_pos, mate_pos, dist=500): dist_to_teammate = LA.norm(my_pos - mate_pos) dist_to_goal = LA.norm(my_pos - opponent_goal) ang_to_teammate = np.arctan2(mate_pos[1] - my_pos[1], mate_pos[0] - my_pos[0]) - my_theta obstructed_goal = not exists_clear_path(opponent_goal, my_pos, obstacle_list) obstructed_mate = not exists_clear_path(mate_pos, my_pos, obstacle_list) if ((dist_to_teammate < dist_to_goal) \ or (obstructed_goal and not obstructed_mate)) \ and (dist_to_teammate > 200) \ and (ang_to_teammate-np.pi/30 < my_theta and my_theta < ang_to_teammate+np.pi/30): target = my_pos thetaDes = ang_to_teammate action.maxvel = 250 action.shootPos = 1 action.strength = dist_to_teammate / 50 passing = True def has_ball_priority(my_pos, mate_pos): my_dist_to_ball = LA.norm(my_pos - ball_pos) mate_dist_to_ball = LA.norm(mate_pos - ball_pos) return my_dist_to_ball < mate_dist_to_ball def team_has_ball(): return ball_handler_current[0:5] == ROBOT_NAME[0:5] # WINGMAN: GET OPEN if not passing and not has_ball_priority(my_pos, mate_pos) and team_has_ball(): target = [mate_pos[0]+(opponent_goal[0]-mate_pos[0])/2, 100-mate_pos[1]/2] thetaDes = np.arctan2(mate_pos[1] - my_pos[1], mate_pos[0] - my_pos[0]) - my_theta target = transform(target[0], target[1], my_pos[0], my_pos[1], my_theta) action.maxvel = 300 elif not passing and not has_ball_priority(my_pos, mate_pos): target = plan(ball_pos, my_pos, obstacle_list, obstacle_radius, 400) thetaDes = np.arctan2(target[1] - my_pos[1], target[0] - my_pos[0]) - my_theta target = transform(target[0], target[1], my_pos[0], my_pos[1], my_theta) action.maxvel = 300 # AGGRESSOR: GET BALL if not passing and has_ball_priority(my_pos, mate_pos): action.maxvel = 250 #print(obstacle_list) #print(r.isdribble) target = plan(ball_pos, my_pos, obstacle_list, obstacle_radius, 400) thetaDes = np.arctan2(target[1] - my_pos[1], target[0] - my_pos[0]) - my_theta #print(isdribble) clear_shot = exists_clear_path(opponent_goal, my_pos, obstacle_list) if isdribble and np.linalg.norm(opponent_goal - my_pos) > shoot_range: target = plan(opponent_goal, my_pos, obstacle_list, obstacle_radius, 400) thetaDes = np.arctan2(opponent_goal[1] - my_pos[1], opponent_goal[0] - my_pos[0]) - my_theta elif clear_shot and isdribble and np.linalg.norm(opponent_goal - my_pos) < shoot_range: thetaDes = np.arctan2(opponent_goal[1] - my_pos[1], opponent_goal[0] - my_pos[0]) - my_theta target = my_pos action.shootPos = 1 action.strength = 200 elif isdribble and np.linalg.norm(opponent_goal - my_pos) < shoot_range: dist_to_teammate = LA.norm(my_pos - mate_pos) dist_to_goal = LA.norm(my_pos - opponent_goal) ang_to_teammate = np.arctan2(mate_pos[1] - my_pos[1], mate_pos[0] - my_pos[0]) - my_theta obstructed_goal = not exists_clear_path(opponent_goal, my_pos, obstacle_list) obstructed_mate = not exists_clear_path(mate_pos, my_pos, obstacle_list) target = my_pos thetaDes = ang_to_teammate action.maxvel = 250 action.shootPos = 1 action.strength = dist_to_teammate / 50 passing = True target = transform(target[0], target[1], my_pos[0], my_pos[1], my_theta) #Generate target position and heading in global frame from real-time psuedo A-star path planning algorithm # target = plan(ball_pos, my_pos, obstacle_list, 100, 400) # thetaDes = np.arctan2(target[1] - my_pos[1], target[0] - my_pos[0]) # For plotting # my_position_x.append(my_pos[0]) # my_position_y.append(my_pos[1]) # targets_generated_x.append(target[0]) # targets_generated_y.append(target[1]) #Convert target from global coordinate frame to robot coordinate frame for use by hwcontroller #Generate ActionCmd() and publish to hwcontroller action.target.x = target[0] action.target.y = target[1] action.maxw = 300 action.handle_enable = 1 action.target_ori = thetaDes pub.publish(action) rate.sleep() # # For plotting path and path plan of robot, after 100 pathing iterations # if len(targets_generated_x) > 100: # plt.plot(targets_generated_x, targets_generated_y, 'g*--', label='Dynamically Generated Path Plan') # plt.plot(robot_position_x, robot_position_y, 'xr-', label='Actual Robot Path') # plt.legend() # # fig, ax = plt.subplots() # # ax.scatter(targets_generated_x, targets_generated_y) # # ax.scatter(robot_position_x, robot_position_y) # # for i in range(len(targets_generated_x)): # # ax.annotate(i, (targets_generated_x[i], targets_generated_y[i])) # # ax.annotate(i, (robot_position_x[i], robot_position_y[i])) # # for o in obstacle_list: # # plot_circle(o[0], o[1], o[2]) # #print(targets_generated) # plt.show() # time.sleep(100) def holdingballcallback(data): global isdribble isdribble = data.BallIsHolding def update_holder1(data): global ball_handler1 ball_handler1 = (data.BallIsHolding, "NuBot1") update_holder_consolidate() def update_holder2(data): global ball_handler2 ball_handler2 = (data.BallIsHolding, "NuBot2") update_holder_consolidate() def update_holder3(data): global ball_handler3 ball_handler3 = (data.BallIsHolding, "NuBot3") update_holder_consolidate() def update_holder4(data): global ball_handler4 ball_handler4 = (data.BallIsHolding, "rival1") update_holder_consolidate() def update_holder5(data): global ball_handler5 ball_handler5 = (data.BallIsHolding, "rival2") update_holder_consolidate() def update_holder6(data): global ball_handler6 ball_handler6 = (data.BallIsHolding, "rival3") update_holder_consolidate() def update_holder_consolidate(): global ball_handler_current l = [ball_handler1, ball_handler2, ball_handler3, ball_handler4, ball_handler5, ball_handler6] for i in range(6): a = l[i] data, name = a if int(data) == 1: ball_handler_current = name return ball_handler_current = "nobody" def listener(): rospy.Subscriber("/" + str(ROBOT_NAME) + "/omnivision/OmniVisionInfo", OminiVisionInfo, callback, queue_size=1) rospy.Subscriber("/" + str(ROBOT_NAME) + "/ballisholding/BallIsHolding", BallIsHolding, holdingballcallback, queue_size=1) rospy.Subscriber("/NuBot1/ballisholding/BallIsHolding", BallIsHolding, update_holder1, queue_size=1) rospy.Subscriber("/NuBot2/ballisholding/BallIsHolding", BallIsHolding, update_holder2, queue_size=1) rospy.Subscriber("/NuBot3/ballisholding/BallIsHolding", BallIsHolding, update_holder3, queue_size=1) rospy.Subscriber("/rival1/ballisholding/BallIsHolding", BallIsHolding, update_holder4, queue_size=1) rospy.Subscriber("/rival2/ballisholding/BallIsHolding", BallIsHolding, update_holder5, queue_size=1) rospy.Subscriber("/rival3/ballisholding/BallIsHolding", BallIsHolding, update_holder6, queue_size=1) rospy.spin() if __name__ == '__main__': try: listener() except rospy.ROSInterruptException: pass
[ "numpy.abs", "nubot_common.msg.ActionCmd", "time.sleep", "numpy.array", "numpy.dot", "numpy.empty", "rospy.Rate", "rospy.spin", "numpy.linalg.norm", "realtimepseudoAstar.plan", "globaltorobotcoords.transform", "numpy.arctan2", "rospy.Subscriber" ]
[((477, 500), 'numpy.array', 'np.array', (['[1100.0, 0.0]'], {}), '([1100.0, 0.0])\n', (485, 500), True, 'import numpy as np\n'), ((1251, 1268), 'rospy.Rate', 'rospy.Rate', (['hertz'], {}), '(hertz)\n', (1261, 1268), False, 'import rospy\n'), ((2218, 2229), 'nubot_common.msg.ActionCmd', 'ActionCmd', ([], {}), '()\n', (2227, 2229), False, 'from nubot_common.msg import ActionCmd, VelCmd, OminiVisionInfo, BallInfo, ObstaclesInfo, RobotInfo, BallIsHolding\n'), ((2307, 2335), 'numpy.array', 'np.array', (['[b.pos.x, b.pos.y]'], {}), '([b.pos.x, b.pos.y])\n', (2315, 2335), True, 'import numpy as np\n'), ((2710, 2738), 'numpy.array', 'np.array', (['[r.pos.x, r.pos.y]'], {}), '([r.pos.x, r.pos.y])\n', (2718, 2738), True, 'import numpy as np\n'), ((2875, 2907), 'numpy.array', 'np.array', (['[r_2.pos.x, r_2.pos.y]'], {}), '([r_2.pos.x, r_2.pos.y])\n', (2883, 2907), True, 'import numpy as np\n'), ((3040, 3063), 'numpy.empty', 'np.empty', (['(0, 3)', 'float'], {}), '((0, 3), float)\n', (3048, 3063), True, 'import numpy as np\n'), ((10101, 10205), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/NuBot1/ballisholding/BallIsHolding"""', 'BallIsHolding', 'update_holder1'], {'queue_size': '(1)'}), "('/NuBot1/ballisholding/BallIsHolding', BallIsHolding,\n update_holder1, queue_size=1)\n", (10117, 10205), False, 'import rospy\n'), ((10206, 10310), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/NuBot2/ballisholding/BallIsHolding"""', 'BallIsHolding', 'update_holder2'], {'queue_size': '(1)'}), "('/NuBot2/ballisholding/BallIsHolding', BallIsHolding,\n update_holder2, queue_size=1)\n", (10222, 10310), False, 'import rospy\n'), ((10311, 10415), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/NuBot3/ballisholding/BallIsHolding"""', 'BallIsHolding', 'update_holder3'], {'queue_size': '(1)'}), "('/NuBot3/ballisholding/BallIsHolding', BallIsHolding,\n update_holder3, queue_size=1)\n", (10327, 10415), False, 'import rospy\n'), ((10416, 10520), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/rival1/ballisholding/BallIsHolding"""', 'BallIsHolding', 'update_holder4'], {'queue_size': '(1)'}), "('/rival1/ballisholding/BallIsHolding', BallIsHolding,\n update_holder4, queue_size=1)\n", (10432, 10520), False, 'import rospy\n'), ((10521, 10625), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/rival2/ballisholding/BallIsHolding"""', 'BallIsHolding', 'update_holder5'], {'queue_size': '(1)'}), "('/rival2/ballisholding/BallIsHolding', BallIsHolding,\n update_holder5, queue_size=1)\n", (10537, 10625), False, 'import rospy\n'), ((10626, 10730), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/rival3/ballisholding/BallIsHolding"""', 'BallIsHolding', 'update_holder6'], {'queue_size': '(1)'}), "('/rival3/ballisholding/BallIsHolding', BallIsHolding,\n update_holder6, queue_size=1)\n", (10642, 10730), False, 'import rospy\n'), ((10736, 10748), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (10746, 10748), False, 'import rospy\n'), ((1799, 1828), 'numpy.linalg.norm', 'np.linalg.norm', (['(pos_1 - pos_2)'], {}), '(pos_1 - pos_2)\n', (1813, 1828), True, 'import numpy as np\n'), ((2418, 2429), 'nubot_common.msg.ActionCmd', 'ActionCmd', ([], {}), '()\n', (2427, 2429), False, 'from nubot_common.msg import ActionCmd, VelCmd, OminiVisionInfo, BallInfo, ObstaclesInfo, RobotInfo, BallIsHolding\n'), ((2575, 2590), 'time.sleep', 'time.sleep', (['(1.5)'], {}), '(1.5)\n', (2585, 2590), False, 'import time\n'), ((3305, 3331), 'numpy.linalg.norm', 'LA.norm', (['(my_pos - mate_pos)'], {}), '(my_pos - mate_pos)\n', (3312, 3331), True, 'from numpy import linalg as LA\n'), ((3355, 3386), 'numpy.linalg.norm', 'LA.norm', (['(my_pos - opponent_goal)'], {}), '(my_pos - opponent_goal)\n', (3362, 3386), True, 'from numpy import linalg as LA\n'), ((4181, 4207), 'numpy.linalg.norm', 'LA.norm', (['(my_pos - ball_pos)'], {}), '(my_pos - ball_pos)\n', (4188, 4207), True, 'from numpy import linalg as LA\n'), ((4236, 4264), 'numpy.linalg.norm', 'LA.norm', (['(mate_pos - ball_pos)'], {}), '(mate_pos - ball_pos)\n', (4243, 4264), True, 'from numpy import linalg as LA\n'), ((4706, 4769), 'globaltorobotcoords.transform', 'transform', (['target[0]', 'target[1]', 'my_pos[0]', 'my_pos[1]', 'my_theta'], {}), '(target[0], target[1], my_pos[0], my_pos[1], my_theta)\n', (4715, 4769), False, 'from globaltorobotcoords import transform\n'), ((5328, 5387), 'realtimepseudoAstar.plan', 'plan', (['ball_pos', 'my_pos', 'obstacle_list', 'obstacle_radius', '(400)'], {}), '(ball_pos, my_pos, obstacle_list, obstacle_radius, 400)\n', (5332, 5387), False, 'from realtimepseudoAstar import plan\n'), ((6855, 6918), 'globaltorobotcoords.transform', 'transform', (['target[0]', 'target[1]', 'my_pos[0]', 'my_pos[1]', 'my_theta'], {}), '(target[0], target[1], my_pos[0], my_pos[1], my_theta)\n', (6864, 6918), False, 'from globaltorobotcoords import transform\n'), ((2343, 2362), 'numpy.abs', 'np.abs', (['ball_pos[0]'], {}), '(ball_pos[0])\n', (2349, 2362), True, 'import numpy as np\n'), ((2374, 2393), 'numpy.abs', 'np.abs', (['ball_pos[1]'], {}), '(ball_pos[1])\n', (2380, 2393), True, 'import numpy as np\n'), ((3413, 3473), 'numpy.arctan2', 'np.arctan2', (['(mate_pos[1] - my_pos[1])', '(mate_pos[0] - my_pos[0])'], {}), '(mate_pos[1] - my_pos[1], mate_pos[0] - my_pos[0])\n', (3423, 3473), True, 'import numpy as np\n'), ((4617, 4677), 'numpy.arctan2', 'np.arctan2', (['(mate_pos[1] - my_pos[1])', '(mate_pos[0] - my_pos[0])'], {}), '(mate_pos[1] - my_pos[1], mate_pos[0] - my_pos[0])\n', (4627, 4677), True, 'import numpy as np\n'), ((4881, 4940), 'realtimepseudoAstar.plan', 'plan', (['ball_pos', 'my_pos', 'obstacle_list', 'obstacle_radius', '(400)'], {}), '(ball_pos, my_pos, obstacle_list, obstacle_radius, 400)\n', (4885, 4940), False, 'from realtimepseudoAstar import plan\n'), ((5045, 5108), 'globaltorobotcoords.transform', 'transform', (['target[0]', 'target[1]', 'my_pos[0]', 'my_pos[1]', 'my_theta'], {}), '(target[0], target[1], my_pos[0], my_pos[1], my_theta)\n', (5054, 5108), False, 'from globaltorobotcoords import transform\n'), ((5407, 5463), 'numpy.arctan2', 'np.arctan2', (['(target[1] - my_pos[1])', '(target[0] - my_pos[0])'], {}), '(target[1] - my_pos[1], target[0] - my_pos[0])\n', (5417, 5463), True, 'import numpy as np\n'), ((5679, 5743), 'realtimepseudoAstar.plan', 'plan', (['opponent_goal', 'my_pos', 'obstacle_list', 'obstacle_radius', '(400)'], {}), '(opponent_goal, my_pos, obstacle_list, obstacle_radius, 400)\n', (5683, 5743), False, 'from realtimepseudoAstar import plan\n'), ((2057, 2071), 'numpy.dot', 'np.dot', (['AB', 'AB'], {}), '(AB, AB)\n', (2063, 2071), True, 'import numpy as np\n'), ((2120, 2145), 'numpy.linalg.norm', 'np.linalg.norm', (['(D - o[:2])'], {}), '(D - o[:2])\n', (2134, 2145), True, 'import numpy as np\n'), ((3146, 3172), 'numpy.array', 'np.array', (['[[p.x, p.y, 75]]'], {}), '([[p.x, p.y, 75]])\n', (3154, 3172), True, 'import numpy as np\n'), ((4960, 5016), 'numpy.arctan2', 'np.arctan2', (['(target[1] - my_pos[1])', '(target[0] - my_pos[0])'], {}), '(target[1] - my_pos[1], target[0] - my_pos[0])\n', (4970, 5016), True, 'import numpy as np\n'), ((5604, 5642), 'numpy.linalg.norm', 'np.linalg.norm', (['(opponent_goal - my_pos)'], {}), '(opponent_goal - my_pos)\n', (5618, 5642), True, 'import numpy as np\n'), ((5767, 5837), 'numpy.arctan2', 'np.arctan2', (['(opponent_goal[1] - my_pos[1])', '(opponent_goal[0] - my_pos[0])'], {}), '(opponent_goal[1] - my_pos[1], opponent_goal[0] - my_pos[0])\n', (5777, 5837), True, 'import numpy as np\n'), ((2040, 2054), 'numpy.dot', 'np.dot', (['AC', 'AB'], {}), '(AC, AB)\n', (2046, 2054), True, 'import numpy as np\n'), ((5891, 5929), 'numpy.linalg.norm', 'np.linalg.norm', (['(opponent_goal - my_pos)'], {}), '(opponent_goal - my_pos)\n', (5905, 5929), True, 'import numpy as np\n'), ((5968, 6038), 'numpy.arctan2', 'np.arctan2', (['(opponent_goal[1] - my_pos[1])', '(opponent_goal[0] - my_pos[0])'], {}), '(opponent_goal[1] - my_pos[1], opponent_goal[0] - my_pos[0])\n', (5978, 6038), True, 'import numpy as np\n'), ((6256, 6282), 'numpy.linalg.norm', 'LA.norm', (['(my_pos - mate_pos)'], {}), '(my_pos - mate_pos)\n', (6263, 6282), True, 'from numpy import linalg as LA\n'), ((6310, 6341), 'numpy.linalg.norm', 'LA.norm', (['(my_pos - opponent_goal)'], {}), '(my_pos - opponent_goal)\n', (6317, 6341), True, 'from numpy import linalg as LA\n'), ((6171, 6209), 'numpy.linalg.norm', 'np.linalg.norm', (['(opponent_goal - my_pos)'], {}), '(opponent_goal - my_pos)\n', (6185, 6209), True, 'import numpy as np\n'), ((6372, 6432), 'numpy.arctan2', 'np.arctan2', (['(mate_pos[1] - my_pos[1])', '(mate_pos[0] - my_pos[0])'], {}), '(mate_pos[1] - my_pos[1], mate_pos[0] - my_pos[0])\n', (6382, 6432), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 6 10:02:22 2019 @author: roshanprakash """ import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') class Trader: def __init__(self, **kwargs): """ A class that helps formulate the trading decision-making problem with a Discrete Time Markov Chain. PARAMETERS ---------- A dictionary with keys indicating the name of the stock (str) and value indicating the path name to the csv file that contains historical data for the stock (str). RETURNS ------- None """ self.source_data = {} self.train_data = {} self.validation_data = {} self.trigger_states = {} self.state_ranges = {} self.transition_matrix = {} self.portfolio = {'balance':2500000.0} self.transaction_volume=1000 self.commission = 0.0012 self.max_buys = {} self.buys = {} for key, path in kwargs.items(): df = pd.read_csv(path, usecols=['Date', 'Close', 'Open']).sort_values('Date') df['delta'] = df.Close.pct_change() df['EMA'] = self.compute_EMA(df.Close) df['LT_MA'] = self.compute_MA(df.Close, long_term=True) df['ST_MA'] = self.compute_MA(df.Close, long_term=False) df['MACD'], df['signal_line'] = self.compute_momentum_signals(df.Close) df['ST_tau'] = (df.Close - df.ST_MA) df['LT_tau'] = (df.Close - df.LT_MA) df['state'], self.state_ranges[key], trigger_state = self.get_state_representations(df.ST_tau) temp = df.dropna().reset_index(drop=True) self.source_data[key] = temp.loc[:int(0.7*len(temp))] self.train_data[key] = temp.loc[int(0.7*len(temp)):int(0.85*len(temp))].reset_index(drop=True) self.validation_data[key] = temp.loc[int(0.85*len(temp)):].reset_index(drop=True) self.trigger_states[key] = trigger_state ## param 'lookahead' should be tuned ; previously done for all stocks being considered if key=='TSLA': lookahead = 30 elif key=='GOOGL': lookahead = 3 elif key=='PFE': lookahead = 50 elif key=='FCSC': lookahead = 75 elif key=='FLKS': lookahead = 180 elif key=='EFII': lookahead = 50 self.transition_matrix[key] = self.compute_transition_matrix(key, lookahead=lookahead) # setup a starting portfolio for the trader self.portfolio[key] = {'holdings': 0} if key=='PFE': self.max_buys[key] = 35 elif key=='FCSC': self.max_buys[key] = 30 elif key=='FLKS': self.max_buys[key] = 5 elif key=='EFII': self.max_buys[key] = 25 elif key=='GOOGL': self.max_buys[key] = 10 elif key=='TSLA': self.max_buys[key] = 10 else: self.max_buys[key] = 10 self.buys[key] = 0.0 def reset(self): """ Resets trader's portfolio for another run of the simulation """ for key in self.portfolio.keys(): self.portfolio[key] = {'holdings': 0} self.buys[key] = 0 self.portfolio['balance'] = 2500000.0 def compute_EMA(self, series, num_days=50): """ Computes Exponential Moving Averages of prices for every timestamp in the data. PARAMETERS ---------- - series (pandas Series) : the (training) timeseries data - num_days (int, default=20) : the smoothing period RETURNS ------- - A pandas series containing EMA's for every timestamp (row index). """ temp = series.copy().reset_index(drop=True) # DO NOT MODIFY THE ORIGINAL DATAFRAME! smoothing_factor = 2/(num_days+1) EMA_prev = 0.0 for idx in range(len(temp)): EMA_current = (temp[idx]*smoothing_factor)+EMA_prev*(1-smoothing_factor) # update values for next iteration temp[idx] = EMA_current EMA_prev = EMA_current return temp def compute_momentum_signals(self, series): """ Computes Moving Average Convergence Divergence and signal line for entries in data. PARAMETERS ---------- - series (pandas Series) : the (training) timeseries data RETURNS ------- - Two pandas series containing MACD and it's associated signal line for every timestamp (row index). """ temp = series.copy().reset_index(drop=True) # DO NOT MODIFY THE ORIGINAL DATAFRAME! t1 = self.compute_EMA(temp, num_days=12) t2 = self.compute_EMA(temp, num_days=26) MACD = t1-t2 signal_line = self.compute_EMA(MACD, num_days=9) return MACD, signal_line def compute_MA(self, series, long_term=True): """ Computes long-term/short-term Moving Averages for the entries in the data. PARAMETERS ---------- - series (pandas Series) : the (training) timeseries data - long_term (bool, default=True) : If True, uses a longer lag time (200 days) RETURNS ------- - A pandas series containing the MA's for every timestamp (row index). """ temp = series.copy().reset_index(drop=True) # DO NOT MODIFY THE ORIGINAL DATAFRAME! if long_term: lag = 200 else: lag = 50 assert len(temp)>lag, 'Not enough data points in this timeseries!' for idx in range(lag, len(temp)): temp[idx] = series[idx-lag:idx].mean() temp[:lag] = None return temp def map_to_states(self, series, state_ranges): """ Helper function to map parameter values to states. PARAMETERS ---------- - series (pandas Series) : the (training) timeseries data - state_ranges (dictionary) : contains the percentile ranges for every state RETURNS ------- - A pandas series containing the state for every timestamp (row index). """ states = series.copy().reset_index(drop=True) l_st = list(state_ranges.keys())[0] # extreme left r_st = list(state_ranges.keys())[-1] # extreme right for idx, val in enumerate(series): # first check if value is located at the tails of the distribution if val<=state_ranges[l_st][0]: states[idx] = l_st elif val>=state_ranges[r_st][0]: states[idx] = r_st else: # find the range for state_idx, percentile_range in enumerate(state_ranges): l, r = percentile_range[0], percentile_range[1] if val>=l and val<r: states[idx] = state_idx break return states def get_state_representations(self, series, k=25): """ Maps the values of the parameter of interest to states. (Based on the percentiles in the distribution of the parameter.) PARAMETERS ---------- - series (pandas Series) : the (training) timeseries data - k (int, default=True) : the number of states RETURNS ------- - A pandas series containing the state for every timestamp (row index) and a scalar indicating the 'trigger state'. (point of change from 'undesirable' to 'desirable') """ # first, compute the 'k' percentiles assert 100%k==0, 'Invalid value for the number of states. Try again with another value!' delta = (100/k)/100 idxs = [delta*idx for idx in range(1,k+1)] temp = series.loc[:int(0.7*len(series))] # use only the source data to generate transition matrix percentiles = pd.Series({key+1:temp.quantile(val) for \ key,val in enumerate(idxs)}) trigger_state = np.max(np.argwhere(percentiles<0))+1 # compute the ranges for each state using the percentiles percentiles = pd.Series(list(zip(percentiles.shift().fillna \ (series.min()), percentiles))) # map values into states states = self.map_to_states(series, percentiles) return states, percentiles, trigger_state def compute_transition_matrix(self, key, lookahead=1): """ Computes the state transition probabilities, between successive days. PARAMETERS ---------- - key (str) : the keyword for the company's data, used in the records. - lookahead(int, default=1) : the number of timesteps to look ahead while fetching the destination state. RETURNS ------- - A numpy array of transition probabilities between states ; shape-->(k*k) where 'k' is the number of states. """ assert key in self.source_data.keys(), \ 'Company data not found in records! Try again after storing records.' num_states = int(self.source_data[key].state.max()+1) Q = np.zeros((num_states, num_states)) temp = self.source_data[key] freqs = [0.0]*num_states for idx in range(len(temp.loc[:int(0.7*len(temp))].index)-lookahead+1): # use only the source data to generate transition matrix current_ = self.source_data[key].iloc[idx]['state'] next_ = self.source_data[key].iloc[idx+lookahead]['state'] Q[int(current_), int(next_)]+=1.0 freqs[int(current_)]+=1.0 for idx in range(num_states): assert np.sum(Q[idx,:])==freqs[idx], 'Transition matrix computational error!' if freqs[idx]!=0.0: Q[idx,:]/=freqs[idx] else: Q[idx,:] = 0.0 return Q def choose_action(self, d, name): """ Chooses an action for the the input observation. PARAMETERS ---------- - d (pandas Series instance) : the input observation - name (str) : the name of the company, used while searching transition information RETURNS ------- - 'buy', 'sell' or 'hold'. """ # some initializations current_state = d.state caution = False confidence = False buy_rules = [0,0,0,0] next_vec = self.transition_matrix[name][int(current_state)] num_undesirable_states = (self.trigger_states[name]+1) num_desirable_states = (next_vec.size-num_undesirable_states) if num_undesirable_states<5: left_basket_max = 2 else: left_basket_max = num_undesirable_states//3 if num_desirable_states<5: right_basket_min = next_vec.size-2 else: right_basket_min = next_vec.size-num_undesirable_states//3 # check if rules are satisfied # rule-1 m1 = np.max(next_vec[:self.trigger_states[name]+1]) m1_idx = np.argmax(next_vec[:self.trigger_states[name]+1]) m2 = np.max(next_vec[self.trigger_states[name]+1:]) m2_idx = np.argmax(next_vec[self.trigger_states[name]+1:])+\ next_vec[:self.trigger_states[name]+1].size if m2-m1>=0.1: # threshold #print('Rule #1 satisfied.') buy_rules[0]=1 # rule-2 if np.sum(next_vec[self.trigger_states[name]+1:])-\ np.sum(next_vec[:self.trigger_states[name]+1])>=0.25: # threshold #print('Rule #2 satisfied.') buy_rules[1]=1 # rule-3 if m1_idx<left_basket_max: if buy_rules[0]!=1: caution=True #print('Predicted state is very undesirable.') # rule-3 if m2_idx>=right_basket_min: if buy_rules[0]==1: confidence=True #print('Predicted state is very desirable.') if d.MACD>d.signal_line: #print('Rule #3 satisfied.') buy_rules[2] = True # sum of k most undesirable vs k most desirable temp_1 = np.sort(next_vec[self.trigger_states[name]+1:]) temp_2 = np.sort(next_vec[:self.trigger_states[name]+1]) size = 3 if temp_1.size<size or temp_2.size<size: size = min(temp_1.size, temp_2.size) k1 = np.sum(temp_1[::-size]) k2 = np.sum(temp_2[::-size]) if k1-k2>0.25: #print('Rule #4 satisfied.') buy_rules[3] = True # finally, make a call using the rules if confidence or sum(buy_rules)>=3: return 'buy' elif caution or (buy_rules[0]==0 and sum(buy_rules)<=2 and m1-m2>0.05): return 'sell' else: return 'hold' def simulate_trader(self, validate=False, sell_all=False): """ Simulates the trader's actions on the test data. PARAMETERS ---------- - override (bool, default=False) : if True, previous actions will not be considered while choosing current action RETURNS ------- - The results of the simulation run containing the history of profits made during the simulation. (dict) """ if validate: data = self.validation_data else: data = self.train_data results = {} for name in data.keys(): # reset actions = [] profits = [] prev_action = None buy_record = [] for idx in range(len(data[name])-1): observation = data[name].iloc[idx] next_price = data[name].iloc[idx+1].Open action = self.choose_action(observation, name) if action=='buy' and self.portfolio['balance']>=(1+self.commission)*\ (self.transaction_volume*next_price): if self.buys[name]<self.max_buys[name]: # buy at next day's opening price self.portfolio['balance']-=(1+self.commission)*\ (self.transaction_volume*next_price) self.portfolio[name]['holdings']+=self.transaction_volume # update system characteristics buy_record.append(next_price) self.buys[name]+=1 actions.append('buy') prev_action = 'buy' else: prev_action = 'hold' actions.append('hold') elif action=='sell' and prev_action!='sell' and self.portfolio[name]['holdings']>=self.transaction_volume: if sell_all: # sell all holdings at next day's opening price for bought_price in buy_record: profits.append((1-self.commission)*self.transaction_volume*(next_price-bought_price)) self.portfolio[name]['holdings']-=self.transaction_volume self.portfolio['balance']+=(1-self.commission)*self.transaction_volume*next_price self.buys[name]-=1 # sanity check assert self.portfolio[name]['holdings']==0, 'Implementation error in "sell"!' assert self.buys[name]==0, 'Implementation error in "buy"!' buy_record = [] actions.append('sell') prev_action = 'sell' else: # sell only profitable holdings at next day's opening price sells = 0 temp = buy_record.copy() for bought_price in buy_record: if next_price>=bought_price: profits.append((1-self.commission)*self.transaction_volume*(next_price-bought_price)) self.portfolio[name]['holdings']-=self.transaction_volume self.portfolio['balance']+=(1-self.commission)*self.transaction_volume*next_price self.buys[name]-=1 # remove the 'bought prices' of disposed stocks from buy record temp.remove(bought_price) sells+=1 buy_record = temp if sells>0: actions.append('sell') prev_action = 'sell' else: actions.append('hold') prev_action = 'hold' else: # hold actions.append('hold') prev_action = 'hold' # sell remaining holdings temp = buy_record.copy() for bought_price in buy_record: profits.append((1-self.commission)*self.transaction_volume*(next_price-bought_price)) self.portfolio[name]['holdings']-=self.transaction_volume self.portfolio['balance']+=(1-self.commission)*self.transaction_volume*next_price self.buys[name]-=1 # remove the 'bought prices' of disposed stocks from buy record temp.remove(bought_price) #================= PRINT SIMULATION STATS ================# print() print('---- Post-simulation portfolio characteristics ----') print('Company : {}'.format(name)) print('Account Balance : {} USD'.format(self.portfolio['balance'])) print('Holdings : {}'.format(self.portfolio[name]['holdings'])) print('Next Price : {}'.format(next_price)) print('Net Present Value : {}'.format(\ self.portfolio['balance']+self.portfolio[name]['holdings']*next_price)) print('Net Profits : {}'.format(sum(profits))) #=========================================================# results[name] = profits #===================== OPTIONAL PLOT =====================# once_buy = False once_sell = False temp = data[name].iloc[:-1].copy() temp['action'] = actions plt.figure(figsize=(13, 7)) ax = temp.Open.plot(color='green', label='Price(USD)') ax.grid(color='orange', alpha=0.35) ax.set_facecolor('xkcd:black') ymin, ymax = ax.get_ylim() for idx in range(len(temp)): if temp.iloc[idx].action=='buy': if once_buy: ax.vlines(x=idx, ymin=ymin, ymax=ymax, linestyles='dotted', color='blue', alpha=0.88) else: ax.vlines(x=idx, ymin=ymin, ymax=ymax, linestyles='dotted', color='blue', alpha=0.88, label='buy') once_buy = True elif temp.iloc[idx].action=='sell': if once_sell: ax.vlines(x=idx, ymin=ymin, ymax=ymax, color='red', alpha=0.75) else: ax.vlines(x=idx, ymin=ymin, ymax=ymax, color='red', alpha=0.75, label='sell') once_sell = True plt.xlabel('Simulated Day (#)') plt.ylabel('Price in USD') plt.title('Trade Simulation Plot : {}'.format(name)) plt.legend() plt.show() #=========================================================# self.reset() # reset for next stock return results if __name__=='__main__': trader = Trader(PFE='../data/PFE.csv', FLKS='../data/FLKS.csv', FCSC='../data/FCSC.csv', GOOGL='../data/GOOGL.csv', TSLA='../data/TSLA.csv', EFII='../data/EFII.csv') #trader = Trader(FLKS='../data/FLKS.csv') print() print('====================================== Training-time Stats ======================================') print() training_results = trader.simulate_trader() trader.reset() print() print('=================================== Validation-time Stats ===================================') print() validation_results = trader.simulate_trader(validate=True) print() print('============================================= END ===========================================')
[ "pandas.read_csv", "matplotlib.pyplot.ylabel", "numpy.sort", "matplotlib.pyplot.xlabel", "numpy.argmax", "matplotlib.pyplot.style.use", "numpy.max", "numpy.sum", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.argwhere", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((186, 209), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (199, 209), True, 'import matplotlib.pyplot as plt\n'), ((9579, 9613), 'numpy.zeros', 'np.zeros', (['(num_states, num_states)'], {}), '((num_states, num_states))\n', (9587, 9613), True, 'import numpy as np\n'), ((11422, 11470), 'numpy.max', 'np.max', (['next_vec[:self.trigger_states[name] + 1]'], {}), '(next_vec[:self.trigger_states[name] + 1])\n', (11428, 11470), True, 'import numpy as np\n'), ((11486, 11537), 'numpy.argmax', 'np.argmax', (['next_vec[:self.trigger_states[name] + 1]'], {}), '(next_vec[:self.trigger_states[name] + 1])\n', (11495, 11537), True, 'import numpy as np\n'), ((11549, 11597), 'numpy.max', 'np.max', (['next_vec[self.trigger_states[name] + 1:]'], {}), '(next_vec[self.trigger_states[name] + 1:])\n', (11555, 11597), True, 'import numpy as np\n'), ((12591, 12640), 'numpy.sort', 'np.sort', (['next_vec[self.trigger_states[name] + 1:]'], {}), '(next_vec[self.trigger_states[name] + 1:])\n', (12598, 12640), True, 'import numpy as np\n'), ((12656, 12705), 'numpy.sort', 'np.sort', (['next_vec[:self.trigger_states[name] + 1]'], {}), '(next_vec[:self.trigger_states[name] + 1])\n', (12663, 12705), True, 'import numpy as np\n'), ((12832, 12855), 'numpy.sum', 'np.sum', (['temp_1[::-size]'], {}), '(temp_1[::-size])\n', (12838, 12855), True, 'import numpy as np\n'), ((12869, 12892), 'numpy.sum', 'np.sum', (['temp_2[::-size]'], {}), '(temp_2[::-size])\n', (12875, 12892), True, 'import numpy as np\n'), ((11613, 11664), 'numpy.argmax', 'np.argmax', (['next_vec[self.trigger_states[name] + 1:]'], {}), '(next_vec[self.trigger_states[name] + 1:])\n', (11622, 11664), True, 'import numpy as np\n'), ((19122, 19149), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(13, 7)'}), '(figsize=(13, 7))\n', (19132, 19149), True, 'import matplotlib.pyplot as plt\n'), ((20136, 20167), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Simulated Day (#)"""'], {}), "('Simulated Day (#)')\n", (20146, 20167), True, 'import matplotlib.pyplot as plt\n'), ((20180, 20206), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price in USD"""'], {}), "('Price in USD')\n", (20190, 20206), True, 'import matplotlib.pyplot as plt\n'), ((20284, 20296), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20294, 20296), True, 'import matplotlib.pyplot as plt\n'), ((20309, 20319), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20317, 20319), True, 'import matplotlib.pyplot as plt\n'), ((8420, 8448), 'numpy.argwhere', 'np.argwhere', (['(percentiles < 0)'], {}), '(percentiles < 0)\n', (8431, 8448), True, 'import numpy as np\n'), ((10097, 10114), 'numpy.sum', 'np.sum', (['Q[idx, :]'], {}), '(Q[idx, :])\n', (10103, 10114), True, 'import numpy as np\n'), ((11864, 11912), 'numpy.sum', 'np.sum', (['next_vec[self.trigger_states[name] + 1:]'], {}), '(next_vec[self.trigger_states[name] + 1:])\n', (11870, 11912), True, 'import numpy as np\n'), ((11929, 11977), 'numpy.sum', 'np.sum', (['next_vec[:self.trigger_states[name] + 1]'], {}), '(next_vec[:self.trigger_states[name] + 1])\n', (11935, 11977), True, 'import numpy as np\n'), ((1108, 1160), 'pandas.read_csv', 'pd.read_csv', (['path'], {'usecols': "['Date', 'Close', 'Open']"}), "(path, usecols=['Date', 'Close', 'Open'])\n", (1119, 1160), True, 'import pandas as pd\n')]
# coding=utf-8 # Author: <NAME> # email : <EMAIL> / <EMAIL> # # magdynlab # Rutinas de analisis para los datos medidos con: # experiments/MI # # TODO: # Make documentation import numpy import matplotlib import matplotlib.pyplot as plt class _MI(object): ''' Broadband MI measurement ''' def getHi(self, h): return numpy.argmin(numpy.abs(self.h - h)) def getFi(self, f): return numpy.argmin(numpy.abs(self.f - f)) def getOutH(self, h): hi = numpy.argmin(numpy.abs(self.h - h)) return self.ColorMapData[hi] def getOutF(self, f): fi = numpy.argmin(numpy.abs(self.f - f)) return self.ColorMapData[:,fi] def Calc(self, Sfunct, *args, **kargs): Sfunct(self, *args, **kargs) def plot_ColorMap(self, fig='Auto'): if fig == 'Auto': fig = self.file.split('/')[-1] + '_CM' data = self.ColorMapData if self.sweepDir == '-1': data = data[::-1] extent = self.extent if self.ColorMapData.dtype != 'complex': fig = plt.figure(fig, (4,4)) fig.clear() plt.xlim(*extent[[0,1]]) plt.ylim(*extent[[2,3]]) plt.xlabel('Field (Oe)') plt.ylabel('Freq (MHz)') plt.imshow(data.T, aspect = 'auto', origin = 'lower', extent = extent) fig.tight_layout() fig.canvas.draw() else: fig = plt.figure(fig, (7,4)) fig.clear() for pl in [121, 122]: plt.subplot(pl) plt.xlim(*extent[[0,1]]) plt.ylim(*extent[[2,3]]) plt.xlabel('Field (Oe)') plt.ylabel('Freq (MHz)') ax = fig.axes[0] ax.imshow(data.real.T, aspect = 'auto', origin = 'lower', extent = extent) ax = fig.axes[1] ax.imshow(data.imag.T, aspect = 'auto', origin = 'lower', extent = extent) fig.tight_layout() fig.canvas.draw() def plotH(self, h, fig='Auto'): if fig == 'Auto': fig = self.file.split('/')[-1] + '_H' data = self.getOutH(h) fig = plt.figure(fig, (4, 3)) plt.plot(self.f/1E6, data.real, '-') plt.grid(True) plt.xlabel('Freq (MHz)') if data.dtype == 'complex': plt.plot(self.f/1E6, data.imag, '--') fig.tight_layout() def plotF(self, f, fig='Auto'): if fig == 'Auto': fig = self.file.split('/')[-1] + '_F' data = self.getOutF(f) fig = plt.figure(fig, (4, 3)) plt.plot(self.h, data.real, '-') plt.grid(True) plt.xlabel('Field (Oe)') if data.dtype == 'complex': plt.plot(self.h, data.imag, '--') fig.tight_layout() def To_PowSpectra(self, file_name, info=''): numpy.savez_compressed(file_name + '.PowerSpectra', info=info, outArray=self.ColorMapData.real, h=self.h, f=self.f) @property def extent(self): return numpy.array([self.h.min(), self.h.max(), self.f.min()/1E6, self.f.max()/1E6]) class MI(_MI): ''' Broadband MI measurement port ''' def __init__(self, file_name): npz_file = numpy.load(file_name+'.ZxH_Raw.npz') self.Info = str(npz_file['Info']) self.f = npz_file['f'] self.h = npz_file['h'] self.Z = npz_file['Z'] self.Ref = npz_file['Ref'] self.file = file_name self.sweepDir = '+1' if self.h[0]>self.h[-1]: self.sweepDir = '-1' self.ColorMapData = numpy.abs(self.Z)[:,:] - numpy.abs(self.Ref)[None,:] class MI_t(_MI): ''' Broadband FMR measurement 1 port ''' def __init__(self, file_name): npz_file = numpy.load(file_name+'.Zxt_Raw.npz') self.Info = str(npz_file['Info']) self.f = npz_file['f'] self.t = npz_file['t'] self.t -= self.t[0] self.t[self.t>1E6] = numpy.nan self.t[self.t<-1E6] = numpy.nan self.Z = npz_file['Z'] self.file = file_name self.ColorMapData = self.Z def get_ti(self, t): return numpy.argmin(numpy.abs(self.t - t)) def getOut_t(self, t): ti = numpy.argmin(numpy.abs(self.t - t)) return self.ColorMapData[ti] @property def extent(self): return numpy.array([self.t.min(), self.t.max(), self.f.min()/1E6, self.f.max()/1E6]) def plot_ColorMap(self, fig='Auto'): if fig == 'Auto': fig = self.file.split('/')[-1] + '_CM' data = self.ColorMapData extent = self.extent if self.ColorMapData.dtype != 'complex': fig = plt.figure(fig, (4,4)) fig.clear() plt.xlim(*extent[[0,1]]) plt.ylim(*extent[[2,3]]) plt.xlabel('time (s)') plt.ylabel('Freq (MHz)') plt.imshow(data.T, aspect = 'auto', origin = 'lower', extent = extent) fig.tight_layout() fig.canvas.draw() else: fig = plt.figure(fig, (7,4)) fig.clear() for pl in [121, 122]: plt.subplot(pl) plt.xlim(*extent[[0,1]]) plt.ylim(*extent[[2,3]]) plt.xlabel('time (s)') plt.ylabel('Freq (MHz)') ax = fig.axes[0] ax.imshow(data.real.T, aspect = 'auto', origin = 'lower', extent = extent) ax = fig.axes[1] ax.imshow(data.imag.T, aspect = 'auto', origin = 'lower', extent = extent) fig.tight_layout() fig.canvas.draw()
[ "matplotlib.pyplot.imshow", "numpy.abs", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlim", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylim", "numpy.savez_compressed", "numpy.load", "matplotlib.pyplot.subplo...
[((2382, 2405), 'matplotlib.pyplot.figure', 'plt.figure', (['fig', '(4, 3)'], {}), '(fig, (4, 3))\n', (2392, 2405), True, 'import matplotlib.pyplot as plt\n'), ((2415, 2459), 'matplotlib.pyplot.plot', 'plt.plot', (['(self.f / 1000000.0)', 'data.real', '"""-"""'], {}), "(self.f / 1000000.0, data.real, '-')\n", (2423, 2459), True, 'import matplotlib.pyplot as plt\n'), ((2460, 2474), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2468, 2474), True, 'import matplotlib.pyplot as plt\n'), ((2483, 2507), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Freq (MHz)"""'], {}), "('Freq (MHz)')\n", (2493, 2507), True, 'import matplotlib.pyplot as plt\n'), ((2779, 2802), 'matplotlib.pyplot.figure', 'plt.figure', (['fig', '(4, 3)'], {}), '(fig, (4, 3))\n', (2789, 2802), True, 'import matplotlib.pyplot as plt\n'), ((2812, 2844), 'matplotlib.pyplot.plot', 'plt.plot', (['self.h', 'data.real', '"""-"""'], {}), "(self.h, data.real, '-')\n", (2820, 2844), True, 'import matplotlib.pyplot as plt\n'), ((2853, 2867), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2861, 2867), True, 'import matplotlib.pyplot as plt\n'), ((2876, 2900), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Field (Oe)"""'], {}), "('Field (Oe)')\n", (2886, 2900), True, 'import matplotlib.pyplot as plt\n'), ((3068, 3188), 'numpy.savez_compressed', 'numpy.savez_compressed', (["(file_name + '.PowerSpectra')"], {'info': 'info', 'outArray': 'self.ColorMapData.real', 'h': 'self.h', 'f': 'self.f'}), "(file_name + '.PowerSpectra', info=info, outArray=\n self.ColorMapData.real, h=self.h, f=self.f)\n", (3090, 3188), False, 'import numpy\n'), ((3558, 3596), 'numpy.load', 'numpy.load', (["(file_name + '.ZxH_Raw.npz')"], {}), "(file_name + '.ZxH_Raw.npz')\n", (3568, 3596), False, 'import numpy\n'), ((4100, 4138), 'numpy.load', 'numpy.load', (["(file_name + '.Zxt_Raw.npz')"], {}), "(file_name + '.Zxt_Raw.npz')\n", (4110, 4138), False, 'import numpy\n'), ((357, 378), 'numpy.abs', 'numpy.abs', (['(self.h - h)'], {}), '(self.h - h)\n', (366, 378), False, 'import numpy\n'), ((433, 454), 'numpy.abs', 'numpy.abs', (['(self.f - f)'], {}), '(self.f - f)\n', (442, 454), False, 'import numpy\n'), ((509, 530), 'numpy.abs', 'numpy.abs', (['(self.h - h)'], {}), '(self.h - h)\n', (518, 530), False, 'import numpy\n'), ((622, 643), 'numpy.abs', 'numpy.abs', (['(self.f - f)'], {}), '(self.f - f)\n', (631, 643), False, 'import numpy\n'), ((1082, 1105), 'matplotlib.pyplot.figure', 'plt.figure', (['fig', '(4, 4)'], {}), '(fig, (4, 4))\n', (1092, 1105), True, 'import matplotlib.pyplot as plt\n'), ((1141, 1166), 'matplotlib.pyplot.xlim', 'plt.xlim', (['*extent[[0, 1]]'], {}), '(*extent[[0, 1]])\n', (1149, 1166), True, 'import matplotlib.pyplot as plt\n'), ((1178, 1203), 'matplotlib.pyplot.ylim', 'plt.ylim', (['*extent[[2, 3]]'], {}), '(*extent[[2, 3]])\n', (1186, 1203), True, 'import matplotlib.pyplot as plt\n'), ((1215, 1239), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Field (Oe)"""'], {}), "('Field (Oe)')\n", (1225, 1239), True, 'import matplotlib.pyplot as plt\n'), ((1252, 1276), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Freq (MHz)"""'], {}), "('Freq (MHz)')\n", (1262, 1276), True, 'import matplotlib.pyplot as plt\n'), ((1289, 1353), 'matplotlib.pyplot.imshow', 'plt.imshow', (['data.T'], {'aspect': '"""auto"""', 'origin': '"""lower"""', 'extent': 'extent'}), "(data.T, aspect='auto', origin='lower', extent=extent)\n", (1299, 1353), True, 'import matplotlib.pyplot as plt\n'), ((1522, 1545), 'matplotlib.pyplot.figure', 'plt.figure', (['fig', '(7, 4)'], {}), '(fig, (7, 4))\n', (1532, 1545), True, 'import matplotlib.pyplot as plt\n'), ((2556, 2601), 'matplotlib.pyplot.plot', 'plt.plot', (['(self.f / 1000000.0)', 'data.imag', '"""--"""'], {}), "(self.f / 1000000.0, data.imag, '--')\n", (2564, 2601), True, 'import matplotlib.pyplot as plt\n'), ((2949, 2982), 'matplotlib.pyplot.plot', 'plt.plot', (['self.h', 'data.imag', '"""--"""'], {}), "(self.h, data.imag, '--')\n", (2957, 2982), True, 'import matplotlib.pyplot as plt\n'), ((4499, 4520), 'numpy.abs', 'numpy.abs', (['(self.t - t)'], {}), '(self.t - t)\n', (4508, 4520), False, 'import numpy\n'), ((4576, 4597), 'numpy.abs', 'numpy.abs', (['(self.t - t)'], {}), '(self.t - t)\n', (4585, 4597), False, 'import numpy\n'), ((5045, 5068), 'matplotlib.pyplot.figure', 'plt.figure', (['fig', '(4, 4)'], {}), '(fig, (4, 4))\n', (5055, 5068), True, 'import matplotlib.pyplot as plt\n'), ((5104, 5129), 'matplotlib.pyplot.xlim', 'plt.xlim', (['*extent[[0, 1]]'], {}), '(*extent[[0, 1]])\n', (5112, 5129), True, 'import matplotlib.pyplot as plt\n'), ((5141, 5166), 'matplotlib.pyplot.ylim', 'plt.ylim', (['*extent[[2, 3]]'], {}), '(*extent[[2, 3]])\n', (5149, 5166), True, 'import matplotlib.pyplot as plt\n'), ((5178, 5200), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time (s)"""'], {}), "('time (s)')\n", (5188, 5200), True, 'import matplotlib.pyplot as plt\n'), ((5213, 5237), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Freq (MHz)"""'], {}), "('Freq (MHz)')\n", (5223, 5237), True, 'import matplotlib.pyplot as plt\n'), ((5250, 5314), 'matplotlib.pyplot.imshow', 'plt.imshow', (['data.T'], {'aspect': '"""auto"""', 'origin': '"""lower"""', 'extent': 'extent'}), "(data.T, aspect='auto', origin='lower', extent=extent)\n", (5260, 5314), True, 'import matplotlib.pyplot as plt\n'), ((5483, 5506), 'matplotlib.pyplot.figure', 'plt.figure', (['fig', '(7, 4)'], {}), '(fig, (7, 4))\n', (5493, 5506), True, 'import matplotlib.pyplot as plt\n'), ((1619, 1634), 'matplotlib.pyplot.subplot', 'plt.subplot', (['pl'], {}), '(pl)\n', (1630, 1634), True, 'import matplotlib.pyplot as plt\n'), ((1651, 1676), 'matplotlib.pyplot.xlim', 'plt.xlim', (['*extent[[0, 1]]'], {}), '(*extent[[0, 1]])\n', (1659, 1676), True, 'import matplotlib.pyplot as plt\n'), ((1692, 1717), 'matplotlib.pyplot.ylim', 'plt.ylim', (['*extent[[2, 3]]'], {}), '(*extent[[2, 3]])\n', (1700, 1717), True, 'import matplotlib.pyplot as plt\n'), ((1733, 1757), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Field (Oe)"""'], {}), "('Field (Oe)')\n", (1743, 1757), True, 'import matplotlib.pyplot as plt\n'), ((1774, 1798), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Freq (MHz)"""'], {}), "('Freq (MHz)')\n", (1784, 1798), True, 'import matplotlib.pyplot as plt\n'), ((3920, 3937), 'numpy.abs', 'numpy.abs', (['self.Z'], {}), '(self.Z)\n', (3929, 3937), False, 'import numpy\n'), ((3945, 3964), 'numpy.abs', 'numpy.abs', (['self.Ref'], {}), '(self.Ref)\n', (3954, 3964), False, 'import numpy\n'), ((5580, 5595), 'matplotlib.pyplot.subplot', 'plt.subplot', (['pl'], {}), '(pl)\n', (5591, 5595), True, 'import matplotlib.pyplot as plt\n'), ((5612, 5637), 'matplotlib.pyplot.xlim', 'plt.xlim', (['*extent[[0, 1]]'], {}), '(*extent[[0, 1]])\n', (5620, 5637), True, 'import matplotlib.pyplot as plt\n'), ((5653, 5678), 'matplotlib.pyplot.ylim', 'plt.ylim', (['*extent[[2, 3]]'], {}), '(*extent[[2, 3]])\n', (5661, 5678), True, 'import matplotlib.pyplot as plt\n'), ((5694, 5716), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time (s)"""'], {}), "('time (s)')\n", (5704, 5716), True, 'import matplotlib.pyplot as plt\n'), ((5733, 5757), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Freq (MHz)"""'], {}), "('Freq (MHz)')\n", (5743, 5757), True, 'import matplotlib.pyplot as plt\n')]
import sys import numpy as np from plyfile import PlyData from matplotlib import pyplot as plt from tomasi_kanade import TomasiKanade from visualization import plot3d, plot_result import rigid_motion def read_object(filename): """Read a 3D object from a PLY file""" ply = PlyData.read(filename) vertex = ply['vertex'] x, y, z = [vertex[t] for t in ('x', 'y', 'z')] return np.vstack((x, y, z)).T def normalize_object_size(X): """ Noramlize object size so that for each object point :math:`\mathbf{x} \in X` .. math:: \\frac{1}{|X|} \sum_{\mathbf{x} \in X} ||\mathbf{x}|| = 1 """ return X / np.linalg.norm(X, axis=1).mean() class Camera(object): """ Camera class Args: intrinsic_parameters: Intrinsic camera matrix :math:`K \in R^{3 \times 3}` """ def __init__(self, intrinsic_parameters: np.ndarray): self.intrinsic_parameters = intrinsic_parameters self.rotation = np.eye(3) self.translation = np.zeros(3) def set_pose(self, rotation, translation): self.rotation = rotation self.translation = translation class Object3D(object): """ 3D object class. This class wraps the observation process from a view point Args: points: Points of the 3D object """ def __init__(self, points: np.ndarray): self.X = points @property def n_points(self): """The number of points in the object""" return self.X.shape[0] def observed(self, camera_rotation: np.ndarray, camera_translation: np.ndarray): """ Return 2D points projected onto the image plane Args: camera_rotation: Rotation matrix which represents the camera rotation camera_translation: Translation vector which represents the camera position """ R = camera_rotation t = camera_translation return rigid_motion.transform(1, R, t, self.X) def take_picture(target_object: Object3D, camera: Camera, noise_std=0.0): """ Project 3D points in ``target_object`` onto the image plane defined by `camera` Args: target_object: Object to be seen from the ``camera`` camera: Camera object which observes the target object noise_std: Standard deviation of noise added in the observation process """ # Y: points seen from the camera coordinate Y = target_object.observed(camera.rotation, camera.translation) K = camera.intrinsic_parameters image_points = np.dot(K, Y.T).T # project onto the image plane if noise_std == 0.0: return image_points noise = np.random.normal(0, noise_std, size=image_points.shape) return image_points + noise def to_viewpoints(M): x = np.array([1, 0, 0]) def to_viewpoint(M): m = np.cross(M[0], M[1]) R = np.vstack((M, m)) return np.dot(R, x) F = M.shape[0] // 2 return np.array([to_viewpoint(M_) for M_ in np.split(M, F)]) def main(): np.random.seed(1234) if len(sys.argv) < 2: print("Usage: $python3 run_reconstruction.py <path to PLY file>") exit(0) filename = sys.argv[1] # Camera intrinsic matrix # In this case, the image coordinate is represented in a non-homogeneous 2D # vector, therefore the intrinsic matrix is represented in a 2x3 matrix. # In this script, we assume the orthogonal projection as a camera # projection model intrinsic_parameters = np.array([ [1, 0, 0], [0, 1, 0] ]) # Load the 3D object from the file X_true = read_object(filename) X_true = normalize_object_size(X_true) # Number of viewpoints to be used for reconstruction n_views = 128 # Standard deviation of noise noise_std = 0.0 target_object = Object3D(X_true) # Create the target object camera = Camera(intrinsic_parameters) # Camera object to observe the target # The ground truth object `X_true` is passed to the TomasiKanade method, # though, this is used only for the evaluation, not reconstruction tomasi_kanade = TomasiKanade(X_eval=X_true, learning_rate=0.0027) for i in range(n_views): # Generate a random camera pose R = rigid_motion.random_rotation_matrix_3d() t = rigid_motion.random_vector_3d() camera.set_pose(R, t) # Observe the 3D object by projecting it onto the image plane image_points = take_picture(target_object, camera, noise_std) tomasi_kanade.add_image_points(image_points) # Run reconstruction # M is a stacked motion matrices # X contains the reconstructed object M, X = tomasi_kanade.run() V = to_viewpoints(M) plot3d(X, azim=180, elev=90) plot_result(X, V) plt.show() if __name__ == '__main__': main()
[ "numpy.random.normal", "tomasi_kanade.TomasiKanade", "numpy.eye", "numpy.cross", "rigid_motion.random_rotation_matrix_3d", "numpy.linalg.norm", "visualization.plot_result", "numpy.array", "numpy.zeros", "rigid_motion.transform", "numpy.dot", "numpy.random.seed", "numpy.vstack", "rigid_moti...
[((286, 308), 'plyfile.PlyData.read', 'PlyData.read', (['filename'], {}), '(filename)\n', (298, 308), False, 'from plyfile import PlyData\n'), ((2729, 2784), 'numpy.random.normal', 'np.random.normal', (['(0)', 'noise_std'], {'size': 'image_points.shape'}), '(0, noise_std, size=image_points.shape)\n', (2745, 2784), True, 'import numpy as np\n'), ((2849, 2868), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (2857, 2868), True, 'import numpy as np\n'), ((3094, 3114), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (3108, 3114), True, 'import numpy as np\n'), ((3568, 3600), 'numpy.array', 'np.array', (['[[1, 0, 0], [0, 1, 0]]'], {}), '([[1, 0, 0], [0, 1, 0]])\n', (3576, 3600), True, 'import numpy as np\n'), ((4188, 4237), 'tomasi_kanade.TomasiKanade', 'TomasiKanade', ([], {'X_eval': 'X_true', 'learning_rate': '(0.0027)'}), '(X_eval=X_true, learning_rate=0.0027)\n', (4200, 4237), False, 'from tomasi_kanade import TomasiKanade\n'), ((4797, 4825), 'visualization.plot3d', 'plot3d', (['X'], {'azim': '(180)', 'elev': '(90)'}), '(X, azim=180, elev=90)\n', (4803, 4825), False, 'from visualization import plot3d, plot_result\n'), ((4830, 4847), 'visualization.plot_result', 'plot_result', (['X', 'V'], {}), '(X, V)\n', (4841, 4847), False, 'from visualization import plot3d, plot_result\n'), ((4852, 4862), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4860, 4862), True, 'from matplotlib import pyplot as plt\n'), ((401, 421), 'numpy.vstack', 'np.vstack', (['(x, y, z)'], {}), '((x, y, z))\n', (410, 421), True, 'import numpy as np\n'), ((998, 1007), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (1004, 1007), True, 'import numpy as np\n'), ((1035, 1046), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1043, 1046), True, 'import numpy as np\n'), ((2005, 2044), 'rigid_motion.transform', 'rigid_motion.transform', (['(1)', 'R', 't', 'self.X'], {}), '(1, R, t, self.X)\n', (2027, 2044), False, 'import rigid_motion\n'), ((2613, 2627), 'numpy.dot', 'np.dot', (['K', 'Y.T'], {}), '(K, Y.T)\n', (2619, 2627), True, 'import numpy as np\n'), ((2907, 2927), 'numpy.cross', 'np.cross', (['M[0]', 'M[1]'], {}), '(M[0], M[1])\n', (2915, 2927), True, 'import numpy as np\n'), ((2940, 2957), 'numpy.vstack', 'np.vstack', (['(M, m)'], {}), '((M, m))\n', (2949, 2957), True, 'import numpy as np\n'), ((2973, 2985), 'numpy.dot', 'np.dot', (['R', 'x'], {}), '(R, x)\n', (2979, 2985), True, 'import numpy as np\n'), ((4320, 4360), 'rigid_motion.random_rotation_matrix_3d', 'rigid_motion.random_rotation_matrix_3d', ([], {}), '()\n', (4358, 4360), False, 'import rigid_motion\n'), ((4373, 4404), 'rigid_motion.random_vector_3d', 'rigid_motion.random_vector_3d', ([], {}), '()\n', (4402, 4404), False, 'import rigid_motion\n'), ((662, 687), 'numpy.linalg.norm', 'np.linalg.norm', (['X'], {'axis': '(1)'}), '(X, axis=1)\n', (676, 687), True, 'import numpy as np\n'), ((3059, 3073), 'numpy.split', 'np.split', (['M', 'F'], {}), '(M, F)\n', (3067, 3073), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.optim as optim from torchvision.transforms import ToTensor from model_super_resolution import Net from super_resolution_data_loader import * import os from os import listdir from math import log10 from PIL import Image device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def super_resolve(input_image, upscale_factor): test_img = Image.open(input_image).convert('YCbCr') y, cb, cr = test_img.split() test_img = np.array(test_img) model = Net(upscale_factor = upscale_factor).to(device) if upscale_factor == 2: model = torch.load("trained_models/super_res_model_epoch_500_64.pth") elif upscale_factor == 4: model = torch.load("trained_models/super_res_model_epoch_300_32.pth") else: raise Exception('Scaling factor must be at the moment 2 or 4!') img_to_tensor = ToTensor() input_ = img_to_tensor(y).view(1, -1, y.size[1], y.size[0]) model = model.cuda() input_ = input_.cuda() out = model(input_) out = out.cpu() out_img_y = out[0].detach().numpy() out_img_y *= 255.0 out_img_y = out_img_y.clip(0, 255) out_img_y = Image.fromarray(np.uint8(out_img_y[0]), mode='L') out_img_cb = cb.resize(out_img_y.size, Image.BICUBIC) out_img_cr = cr.resize(out_img_y.size, Image.BICUBIC) out_img = Image.merge('YCbCr', [out_img_y, out_img_cb, out_img_cr]).convert('RGB') return np.array(out_img)
[ "numpy.uint8", "PIL.Image.open", "torch.load", "model_super_resolution.Net", "numpy.array", "torch.cuda.is_available", "torchvision.transforms.ToTensor", "PIL.Image.merge" ]
[((550, 568), 'numpy.array', 'np.array', (['test_img'], {}), '(test_img)\n', (558, 568), True, 'import numpy as np\n'), ((964, 974), 'torchvision.transforms.ToTensor', 'ToTensor', ([], {}), '()\n', (972, 974), False, 'from torchvision.transforms import ToTensor\n'), ((1531, 1548), 'numpy.array', 'np.array', (['out_img'], {}), '(out_img)\n', (1539, 1548), True, 'import numpy as np\n'), ((353, 378), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (376, 378), False, 'import torch\n'), ((683, 744), 'torch.load', 'torch.load', (['"""trained_models/super_res_model_epoch_500_64.pth"""'], {}), "('trained_models/super_res_model_epoch_500_64.pth')\n", (693, 744), False, 'import torch\n'), ((1277, 1299), 'numpy.uint8', 'np.uint8', (['out_img_y[0]'], {}), '(out_img_y[0])\n', (1285, 1299), True, 'import numpy as np\n'), ((460, 483), 'PIL.Image.open', 'Image.open', (['input_image'], {}), '(input_image)\n', (470, 483), False, 'from PIL import Image\n'), ((586, 620), 'model_super_resolution.Net', 'Net', ([], {'upscale_factor': 'upscale_factor'}), '(upscale_factor=upscale_factor)\n', (589, 620), False, 'from model_super_resolution import Net\n'), ((791, 852), 'torch.load', 'torch.load', (['"""trained_models/super_res_model_epoch_300_32.pth"""'], {}), "('trained_models/super_res_model_epoch_300_32.pth')\n", (801, 852), False, 'import torch\n'), ((1442, 1499), 'PIL.Image.merge', 'Image.merge', (['"""YCbCr"""', '[out_img_y, out_img_cb, out_img_cr]'], {}), "('YCbCr', [out_img_y, out_img_cb, out_img_cr])\n", (1453, 1499), False, 'from PIL import Image\n')]
# PyVot Python Variational Optimal Transportation # Author: <NAME> <<EMAIL>> # Date: April 28th 2020 # Licence: MIT import os import sys import time import numpy as np import matplotlib.pyplot as plt sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from vot_numpy import VOT, VOTREG import utils # -------------------------------------- # # --------- w/o regularization --------- # # -------------------------------------- # N0 = 1000 mean1, cov1 = [-0.5, 0.25], [[0.02, 0], [0, 0.02]] mean2, cov2 = [ 0.5, 0.25], [[0.02, 0], [0, 0.02]] x11, x12 = np.random.multivariate_normal(mean1, cov1, N0).T x21, x22 = np.random.multivariate_normal(mean2, cov2, N0).T x = np.concatenate([np.stack((x11, x12), axis=1), np.stack((x21, x22), axis=1)], axis=0).clip(-0.99, 0.99) K = 50 mean3, cov3 = [0.0, 0.0], [[0.02, 0], [0, 0.02]] mean4, cov4 = [0.5, -0.5], [[0.02, 0], [0, 0.02]] y11, y12 = np.random.multivariate_normal(mean3, cov3, K).T y21, y22 = np.random.multivariate_normal(mean4, cov4, K).T y = np.concatenate((np.stack((y11, y12), axis=1), np.stack((y21, y22), axis=1)), axis=0).clip(-0.99, 0.99) labels = np.concatenate((np.zeros(50, dtype=np.int64), np.ones(50, dtype=np.int64)), axis=0) # ----- plot before ----- # xmin, xmax, ymin, ymax = -1.0, 1.0, -1.0, 1.0 cxs_base = np.array((utils.COLOR_LIGHT_BLUE, utils.COLOR_LIGHT_RED)) cys_base = np.array((utils.COLOR_BLUE, utils.COLOR_RED)) cys = cys_base[labels] ys, xs = 15, 3 plt.figure(figsize=(12, 8)) plt.subplot(231) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.grid(True) plt.title('w/o reg before') plt.scatter(x[:, 0], x[:, 1], s=xs, color=utils.COLOR_LIGHT_GREY) for p, cy in zip(y, cys): plt.scatter(p[0], p[1], s=ys, color=cy) # ------- run WM -------- # vot = VOT(y.copy(), [x.copy()], label_y=labels, verbose=False) print("running Wasserstein clustering...") tick = time.time() vot.cluster(max_iter_y=1) tock = time.time() print("total running time : {0:g} seconds".format(tock-tick)) cxs = cxs_base[vot.label_x[0]] # ------ plot map ------- # fig232 = plt.subplot(232) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.grid(True) plt.title('w/o reg map') for p, p0 in zip(vot.y, vot.y_original): plt.plot([p[0], p0[0]], [p[1], p0[1]], color=np.append(utils.COLOR_LIGHT_GREY, 0.5), zorder=4) for p, cy in zip(vot.y, cys): plt.scatter(p[0], p[1], s=ys, color=cy, facecolor='none', zorder=3) for p, cy in zip(vot.y_original, cys): plt.scatter(p[0], p[1], s=ys, color=cy, zorder=2) # ------ plot after ----- # plt.subplot(233) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.grid(True) plt.title('w/o reg after') for px, cx in zip(vot.x[0], cxs): plt.scatter(px[0], px[1], s=xs, color=cx, zorder=2) for py, cy in zip(vot.y, cys): plt.scatter(py[0], py[1], s=ys, color=cy, facecolor='none', zorder=3) # -------------------------------------- # # --------- w/ regularization ---------- # # -------------------------------------- # # ------- run RWM ------- # vot_reg = VOTREG(y.copy(), [x.copy()], label_y=labels, verbose=False) print("running regularized Wasserstein clustering...") tick = time.time() vot_reg.map(reg_type='potential', reg=0.01, max_iter_y=5) tock = time.time() print("total running time : {0:g} seconds".format(tock-tick)) # cxs = cxs_base[vot_reg.label_x[0]] # Compute OT one more time to disperse the centroids into the empirical domain. # This does not change the correspondence but can give better visual. # This is optional. print("[optional] distribute centroids into target domain...") vot = VOT(vot_reg.y, vot_reg.x, label_y=labels, verbose=False) vot.cluster(max_iter_y=1) cxs = cxs_base[vot.label_x[0]] # ------ plot map ------- # plt.subplot(235) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.grid(True) plt.title('w/ reg map') for p, p0 in zip(vot.y, vot_reg.y_original): plt.plot([p[0], p0[0]], [p[1], p0[1]], color=np.append(utils.COLOR_LIGHT_GREY, 0.5), zorder=4) for p, cy in zip(vot.y, cys): plt.scatter(p[0], p[1], s=ys, color=cy, facecolor='none', zorder=3) for p, cy in zip(vot_reg.y_original, cys): plt.scatter(p[0], p[1], s=ys, color=cy, zorder=2) # ------ plot after ----- # plt.subplot(236) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.grid(True) plt.title('w/ reg after') for px, cx in zip(vot.x[0], cxs): plt.scatter(px[0], px[1], s=xs, color=cx, zorder=2) for py, cy in zip(vot.y, cys): plt.scatter(py[0], py[1], s=ys, color=cy, facecolor='none', zorder=3) # ---- plot and save ---- # plt.tight_layout(pad=1.0, w_pad=1.5, h_pad=0.5) plt.savefig("potential.png") plt.show()
[ "matplotlib.pyplot.grid", "numpy.array", "numpy.stack", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylim", "matplotlib.pyplot.savefig", "numpy.ones", "numpy.random.multivariate_normal", "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "time.time", "matplotlib.pyplot.show", "numpy.app...
[((1306, 1363), 'numpy.array', 'np.array', (['(utils.COLOR_LIGHT_BLUE, utils.COLOR_LIGHT_RED)'], {}), '((utils.COLOR_LIGHT_BLUE, utils.COLOR_LIGHT_RED))\n', (1314, 1363), True, 'import numpy as np\n'), ((1375, 1420), 'numpy.array', 'np.array', (['(utils.COLOR_BLUE, utils.COLOR_RED)'], {}), '((utils.COLOR_BLUE, utils.COLOR_RED))\n', (1383, 1420), True, 'import numpy as np\n'), ((1460, 1487), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (1470, 1487), True, 'import matplotlib.pyplot as plt\n'), ((1488, 1504), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(231)'], {}), '(231)\n', (1499, 1504), True, 'import matplotlib.pyplot as plt\n'), ((1505, 1525), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xmin', 'xmax'], {}), '(xmin, xmax)\n', (1513, 1525), True, 'import matplotlib.pyplot as plt\n'), ((1526, 1546), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ymin', 'ymax'], {}), '(ymin, ymax)\n', (1534, 1546), True, 'import matplotlib.pyplot as plt\n'), ((1547, 1561), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (1555, 1561), True, 'import matplotlib.pyplot as plt\n'), ((1562, 1589), 'matplotlib.pyplot.title', 'plt.title', (['"""w/o reg before"""'], {}), "('w/o reg before')\n", (1571, 1589), True, 'import matplotlib.pyplot as plt\n'), ((1591, 1656), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x[:, 0]', 'x[:, 1]'], {'s': 'xs', 'color': 'utils.COLOR_LIGHT_GREY'}), '(x[:, 0], x[:, 1], s=xs, color=utils.COLOR_LIGHT_GREY)\n', (1602, 1656), True, 'import matplotlib.pyplot as plt\n'), ((1870, 1881), 'time.time', 'time.time', ([], {}), '()\n', (1879, 1881), False, 'import time\n'), ((1915, 1926), 'time.time', 'time.time', ([], {}), '()\n', (1924, 1926), False, 'import time\n'), ((2058, 2074), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(232)'], {}), '(232)\n', (2069, 2074), True, 'import matplotlib.pyplot as plt\n'), ((2075, 2095), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xmin', 'xmax'], {}), '(xmin, xmax)\n', (2083, 2095), True, 'import matplotlib.pyplot as plt\n'), ((2096, 2116), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ymin', 'ymax'], {}), '(ymin, ymax)\n', (2104, 2116), True, 'import matplotlib.pyplot as plt\n'), ((2117, 2131), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2125, 2131), True, 'import matplotlib.pyplot as plt\n'), ((2132, 2156), 'matplotlib.pyplot.title', 'plt.title', (['"""w/o reg map"""'], {}), "('w/o reg map')\n", (2141, 2156), True, 'import matplotlib.pyplot as plt\n'), ((2523, 2539), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(233)'], {}), '(233)\n', (2534, 2539), True, 'import matplotlib.pyplot as plt\n'), ((2540, 2560), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xmin', 'xmax'], {}), '(xmin, xmax)\n', (2548, 2560), True, 'import matplotlib.pyplot as plt\n'), ((2561, 2581), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ymin', 'ymax'], {}), '(ymin, ymax)\n', (2569, 2581), True, 'import matplotlib.pyplot as plt\n'), ((2582, 2596), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2590, 2596), True, 'import matplotlib.pyplot as plt\n'), ((2597, 2623), 'matplotlib.pyplot.title', 'plt.title', (['"""w/o reg after"""'], {}), "('w/o reg after')\n", (2606, 2623), True, 'import matplotlib.pyplot as plt\n'), ((3112, 3123), 'time.time', 'time.time', ([], {}), '()\n', (3121, 3123), False, 'import time\n'), ((3189, 3200), 'time.time', 'time.time', ([], {}), '()\n', (3198, 3200), False, 'import time\n'), ((3540, 3596), 'vot_numpy.VOT', 'VOT', (['vot_reg.y', 'vot_reg.x'], {'label_y': 'labels', 'verbose': '(False)'}), '(vot_reg.y, vot_reg.x, label_y=labels, verbose=False)\n', (3543, 3596), False, 'from vot_numpy import VOT, VOTREG\n'), ((3684, 3700), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(235)'], {}), '(235)\n', (3695, 3700), True, 'import matplotlib.pyplot as plt\n'), ((3701, 3721), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xmin', 'xmax'], {}), '(xmin, xmax)\n', (3709, 3721), True, 'import matplotlib.pyplot as plt\n'), ((3722, 3742), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ymin', 'ymax'], {}), '(ymin, ymax)\n', (3730, 3742), True, 'import matplotlib.pyplot as plt\n'), ((3743, 3757), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (3751, 3757), True, 'import matplotlib.pyplot as plt\n'), ((3758, 3781), 'matplotlib.pyplot.title', 'plt.title', (['"""w/ reg map"""'], {}), "('w/ reg map')\n", (3767, 3781), True, 'import matplotlib.pyplot as plt\n'), ((4156, 4172), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(236)'], {}), '(236)\n', (4167, 4172), True, 'import matplotlib.pyplot as plt\n'), ((4173, 4193), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xmin', 'xmax'], {}), '(xmin, xmax)\n', (4181, 4193), True, 'import matplotlib.pyplot as plt\n'), ((4194, 4214), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ymin', 'ymax'], {}), '(ymin, ymax)\n', (4202, 4214), True, 'import matplotlib.pyplot as plt\n'), ((4215, 4229), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (4223, 4229), True, 'import matplotlib.pyplot as plt\n'), ((4230, 4255), 'matplotlib.pyplot.title', 'plt.title', (['"""w/ reg after"""'], {}), "('w/ reg after')\n", (4239, 4255), True, 'import matplotlib.pyplot as plt\n'), ((4481, 4528), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'pad': '(1.0)', 'w_pad': '(1.5)', 'h_pad': '(0.5)'}), '(pad=1.0, w_pad=1.5, h_pad=0.5)\n', (4497, 4528), True, 'import matplotlib.pyplot as plt\n'), ((4529, 4557), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""potential.png"""'], {}), "('potential.png')\n", (4540, 4557), True, 'import matplotlib.pyplot as plt\n'), ((4558, 4568), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4566, 4568), True, 'import matplotlib.pyplot as plt\n'), ((578, 624), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean1', 'cov1', 'N0'], {}), '(mean1, cov1, N0)\n', (607, 624), True, 'import numpy as np\n'), ((638, 684), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean2', 'cov2', 'N0'], {}), '(mean2, cov2, N0)\n', (667, 684), True, 'import numpy as np\n'), ((913, 958), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean3', 'cov3', 'K'], {}), '(mean3, cov3, K)\n', (942, 958), True, 'import numpy as np\n'), ((972, 1017), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean4', 'cov4', 'K'], {}), '(mean4, cov4, K)\n', (1001, 1017), True, 'import numpy as np\n'), ((1687, 1726), 'matplotlib.pyplot.scatter', 'plt.scatter', (['p[0]', 'p[1]'], {'s': 'ys', 'color': 'cy'}), '(p[0], p[1], s=ys, color=cy)\n', (1698, 1726), True, 'import matplotlib.pyplot as plt\n'), ((2332, 2399), 'matplotlib.pyplot.scatter', 'plt.scatter', (['p[0]', 'p[1]'], {'s': 'ys', 'color': 'cy', 'facecolor': '"""none"""', 'zorder': '(3)'}), "(p[0], p[1], s=ys, color=cy, facecolor='none', zorder=3)\n", (2343, 2399), True, 'import matplotlib.pyplot as plt\n'), ((2443, 2492), 'matplotlib.pyplot.scatter', 'plt.scatter', (['p[0]', 'p[1]'], {'s': 'ys', 'color': 'cy', 'zorder': '(2)'}), '(p[0], p[1], s=ys, color=cy, zorder=2)\n', (2454, 2492), True, 'import matplotlib.pyplot as plt\n'), ((2663, 2714), 'matplotlib.pyplot.scatter', 'plt.scatter', (['px[0]', 'px[1]'], {'s': 'xs', 'color': 'cx', 'zorder': '(2)'}), '(px[0], px[1], s=xs, color=cx, zorder=2)\n', (2674, 2714), True, 'import matplotlib.pyplot as plt\n'), ((2750, 2819), 'matplotlib.pyplot.scatter', 'plt.scatter', (['py[0]', 'py[1]'], {'s': 'ys', 'color': 'cy', 'facecolor': '"""none"""', 'zorder': '(3)'}), "(py[0], py[1], s=ys, color=cy, facecolor='none', zorder=3)\n", (2761, 2819), True, 'import matplotlib.pyplot as plt\n'), ((3961, 4028), 'matplotlib.pyplot.scatter', 'plt.scatter', (['p[0]', 'p[1]'], {'s': 'ys', 'color': 'cy', 'facecolor': '"""none"""', 'zorder': '(3)'}), "(p[0], p[1], s=ys, color=cy, facecolor='none', zorder=3)\n", (3972, 4028), True, 'import matplotlib.pyplot as plt\n'), ((4076, 4125), 'matplotlib.pyplot.scatter', 'plt.scatter', (['p[0]', 'p[1]'], {'s': 'ys', 'color': 'cy', 'zorder': '(2)'}), '(p[0], p[1], s=ys, color=cy, zorder=2)\n', (4087, 4125), True, 'import matplotlib.pyplot as plt\n'), ((4295, 4346), 'matplotlib.pyplot.scatter', 'plt.scatter', (['px[0]', 'px[1]'], {'s': 'xs', 'color': 'cx', 'zorder': '(2)'}), '(px[0], px[1], s=xs, color=cx, zorder=2)\n', (4306, 4346), True, 'import matplotlib.pyplot as plt\n'), ((4382, 4451), 'matplotlib.pyplot.scatter', 'plt.scatter', (['py[0]', 'py[1]'], {'s': 'ys', 'color': 'cy', 'facecolor': '"""none"""', 'zorder': '(3)'}), "(py[0], py[1], s=ys, color=cy, facecolor='none', zorder=3)\n", (4393, 4451), True, 'import matplotlib.pyplot as plt\n'), ((1152, 1180), 'numpy.zeros', 'np.zeros', (['(50)'], {'dtype': 'np.int64'}), '(50, dtype=np.int64)\n', (1160, 1180), True, 'import numpy as np\n'), ((1182, 1209), 'numpy.ones', 'np.ones', (['(50)'], {'dtype': 'np.int64'}), '(50, dtype=np.int64)\n', (1189, 1209), True, 'import numpy as np\n'), ((249, 274), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (264, 274), False, 'import os\n'), ((2248, 2286), 'numpy.append', 'np.append', (['utils.COLOR_LIGHT_GREY', '(0.5)'], {}), '(utils.COLOR_LIGHT_GREY, 0.5)\n', (2257, 2286), True, 'import numpy as np\n'), ((3877, 3915), 'numpy.append', 'np.append', (['utils.COLOR_LIGHT_GREY', '(0.5)'], {}), '(utils.COLOR_LIGHT_GREY, 0.5)\n', (3886, 3915), True, 'import numpy as np\n'), ((707, 735), 'numpy.stack', 'np.stack', (['(x11, x12)'], {'axis': '(1)'}), '((x11, x12), axis=1)\n', (715, 735), True, 'import numpy as np\n'), ((737, 765), 'numpy.stack', 'np.stack', (['(x21, x22)'], {'axis': '(1)'}), '((x21, x22), axis=1)\n', (745, 765), True, 'import numpy as np\n'), ((1040, 1068), 'numpy.stack', 'np.stack', (['(y11, y12)'], {'axis': '(1)'}), '((y11, y12), axis=1)\n', (1048, 1068), True, 'import numpy as np\n'), ((1070, 1098), 'numpy.stack', 'np.stack', (['(y21, y22)'], {'axis': '(1)'}), '((y21, y22), axis=1)\n', (1078, 1098), True, 'import numpy as np\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core import caffe2.python.hypothesis_test_util as hu import caffe2.python.serialized_test.serialized_test_util as serial from hypothesis import given, settings import hypothesis.strategies as st import numpy as np class TestMarginRankingCriterion(serial.SerializedTestCase): @given(N=st.integers(min_value=10, max_value=20), seed=st.integers(min_value=0, max_value=65535), margin=st.floats(min_value=-0.5, max_value=0.5), **hu.gcs) @settings(deadline=1000) def test_margin_ranking_criterion(self, N, seed, margin, gc, dc): np.random.seed(seed) X1 = np.random.randn(N).astype(np.float32) X2 = np.random.randn(N).astype(np.float32) Y = np.random.choice([-1, 1], size=N).astype(np.int32) op = core.CreateOperator( "MarginRankingCriterion", ["X1", "X2", "Y"], ["loss"], margin=margin) def ref_cec(X1, X2, Y): result = np.maximum(-Y * (X1 - X2) + margin, 0) return (result, ) inputs = [X1, X2, Y] # This checks the op implementation against a reference function in # python. self.assertReferenceChecks(gc, op, inputs, ref_cec) # This checks the op implementation over multiple device options (e.g. # CPU and CUDA). [0] means that the 0-th output is checked. self.assertDeviceChecks(dc, op, inputs, [0]) # Make singular points less sensitive X1[np.abs(margin - Y * (X1 - X2)) < 0.1] += 0.1 X2[np.abs(margin - Y * (X1 - X2)) < 0.1] -= 0.1 # Check dX1 self.assertGradientChecks(gc, op, inputs, 0, [0]) # Check dX2 self.assertGradientChecks(gc, op, inputs, 1, [0]) if __name__ == "__main__": import unittest unittest.main()
[ "numpy.abs", "hypothesis.strategies.integers", "numpy.random.choice", "hypothesis.strategies.floats", "numpy.random.seed", "hypothesis.settings", "caffe2.python.core.CreateOperator", "unittest.main", "numpy.maximum", "numpy.random.randn" ]
[((653, 676), 'hypothesis.settings', 'settings', ([], {'deadline': '(1000)'}), '(deadline=1000)\n', (661, 676), False, 'from hypothesis import given, settings\n'), ((1944, 1959), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1957, 1959), False, 'import unittest\n'), ((755, 775), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (769, 775), True, 'import numpy as np\n'), ((954, 1047), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""MarginRankingCriterion"""', "['X1', 'X2', 'Y']", "['loss']"], {'margin': 'margin'}), "('MarginRankingCriterion', ['X1', 'X2', 'Y'], ['loss'],\n margin=margin)\n", (973, 1047), False, 'from caffe2.python import core\n'), ((1123, 1161), 'numpy.maximum', 'np.maximum', (['(-Y * (X1 - X2) + margin)', '(0)'], {}), '(-Y * (X1 - X2) + margin, 0)\n', (1133, 1161), True, 'import numpy as np\n'), ((467, 506), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(10)', 'max_value': '(20)'}), '(min_value=10, max_value=20)\n', (478, 506), True, 'import hypothesis.strategies as st\n'), ((524, 565), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(65535)'}), '(min_value=0, max_value=65535)\n', (535, 565), True, 'import hypothesis.strategies as st\n'), ((585, 625), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(-0.5)', 'max_value': '(0.5)'}), '(min_value=-0.5, max_value=0.5)\n', (594, 625), True, 'import hypothesis.strategies as st\n'), ((789, 807), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (804, 807), True, 'import numpy as np\n'), ((840, 858), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (855, 858), True, 'import numpy as np\n'), ((890, 923), 'numpy.random.choice', 'np.random.choice', (['[-1, 1]'], {'size': 'N'}), '([-1, 1], size=N)\n', (906, 923), True, 'import numpy as np\n'), ((1634, 1664), 'numpy.abs', 'np.abs', (['(margin - Y * (X1 - X2))'], {}), '(margin - Y * (X1 - X2))\n', (1640, 1664), True, 'import numpy as np\n'), ((1690, 1720), 'numpy.abs', 'np.abs', (['(margin - Y * (X1 - X2))'], {}), '(margin - Y * (X1 - X2))\n', (1696, 1720), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # @Author: 红白黑 # @Date: 2021-08-04 18:12:59 # @Last Modified by: 红白黑 # @Last Modified time: 2021-08-04 18:15:41 import cv2 import numpy as np from PIL import Image class Resize(object): '''图像缩放 Args: target_size: [int]缩放的目标大小 ''' def __init__(self, target_size=448): self.target_size=target_size def _apply_img(self, img): '''对图片的操作 Args: img: [np.ndarray]图像数据: (h, w, c)/(h, w) Return: img_map: [np.ndarray]缩放后的图像数据: (h, w, c)/(h, w) img_scale: [float]xy统一缩放的比例 offset_x, offset_y: [int]缩放过程中,原图填充的偏移值——也是边界框缩放后需要调整xy偏移值 ''' if len(img.shape)<3: img_map=np.zeros((self.target_size, self.target_size)).astype(np.float32) img_map.fill(255.) elif len(img.shape)==3: img_map=np.zeros((self.target_size, self.target_size, 3)).astype(np.float32) img_map.fill(255.) h,w=img.shape[0:2] dist_=max(h, w) img_scale=self.target_size/dist_ img=cv2.resize(img, None, fx=img_scale, fy=img_scale) offset_x=(self.target_size-img.shape[1])//2 offset_y=(self.target_size-img.shape[0])//2 img_map[offset_y:(self.target_size-offset_y), offset_x:(self.target_size-offset_x)]=img return img_map, [img_scale, [offset_x, offset_y]] def _apply_bbox(self, bboxs, scale, offsets): '''对边界框的操作 Args: bboxs: [np.ndarray]边界框数据: B, 4(xyxy/xywh) scale: [float]xy统一缩放的比例 offsets: [list:offset_x, offset_y]边界框缩放后需要调整xy偏移值 Return: bboxs: [np.ndarray]缩放调整后的边界框数据: B, 4(xyxy/xywh) ''' offset_x, offset_y=offsets bboxs[:, 0::2] = bboxs[:, 0::2] * scale + offset_x bboxs[:, 1::2] = bboxs[:, 1::2] * scale + offset_y bboxs[:, 0::2] = np.clip(bboxs[:, 0::2], 0., self.target_size) bboxs[:, 1::2] = np.clip(bboxs[:, 1::2], 0., self.target_size) return bboxs def __call__(self, img, bbox): '''执行缩放 Args: img: [np.ndarray]图片数据: (h, w, c)/(h, w) bbox: [np.ndarray]边界框数据: B, 4(xyxy/xywh) Return: new_img: [np.ndarray]缩放调整后的图片数据: (h, w, c)/(h, w) new_bboxs: [np.ndarray]缩放调整后的边界框数据: B, 4(xyxy/xywh) ''' new_img, [img_scale, [offset_x, offset_y]] = self._apply_img(img) # 执行图片缩放 new_bboxs = self._apply_bbox(bbox, img_scale, [offset_x, offset_y]) # 执行边界框缩放 return new_img, new_bboxs
[ "numpy.clip", "cv2.resize", "numpy.zeros" ]
[((1143, 1192), 'cv2.resize', 'cv2.resize', (['img', 'None'], {'fx': 'img_scale', 'fy': 'img_scale'}), '(img, None, fx=img_scale, fy=img_scale)\n', (1153, 1192), False, 'import cv2\n'), ((2005, 2051), 'numpy.clip', 'np.clip', (['bboxs[:, 0::2]', '(0.0)', 'self.target_size'], {}), '(bboxs[:, 0::2], 0.0, self.target_size)\n', (2012, 2051), True, 'import numpy as np\n'), ((2077, 2123), 'numpy.clip', 'np.clip', (['bboxs[:, 1::2]', '(0.0)', 'self.target_size'], {}), '(bboxs[:, 1::2], 0.0, self.target_size)\n', (2084, 2123), True, 'import numpy as np\n'), ((782, 828), 'numpy.zeros', 'np.zeros', (['(self.target_size, self.target_size)'], {}), '((self.target_size, self.target_size))\n', (790, 828), True, 'import numpy as np\n'), ((934, 983), 'numpy.zeros', 'np.zeros', (['(self.target_size, self.target_size, 3)'], {}), '((self.target_size, self.target_size, 3))\n', (942, 983), True, 'import numpy as np\n')]
import cmath import numpy as np from collections import OrderedDict from objects.seismic.rays import Ray1D from objects.Data.WavePlaceholder import get_down_up_vel_types from objects.seismic.waves import OWT from fmodeling.seismic.ray_tracing.case_1D.bound_strateg import strategy_1D def eq_to_solve(p, vd, vu, h, x_2): assert (len(vd) == len(vu)) number_of_layers = len(vd) xx = 0 for i in range(2 * (number_of_layers - 1)): if i > number_of_layers - 2: jj = 2 * number_of_layers - 3 - i v = vu else: jj = i v = vd xx = xx + (p * v[jj] * h[jj]) / cmath.sqrt(1 - p * p * v[jj] * v[jj]) res = xx - x_2 return res def deriv_eq_to_solve(p, vd, vu, h): assert (len(vd) == len(vu)) number_of_layers = len(vd) xx = 0 for i in range(2 * (number_of_layers - 1)): if i > number_of_layers - 2: j = 2 * number_of_layers - 3 - i v = vu else: j = i v = vd a1 = (v[j] * h[j]) a2 = cmath.sqrt(pow((1 - p * p * v[j] * v[j]), 3)) xx = xx + a1 / a2 res = xx return res def solve_for_p(p_start, vd, vu, h, x_2, tol=0.001): pn = p_start while True: if pn.imag != 0: alpha = cmath.asin(pn * vd[0]) alpha = alpha / 100 pn = cmath.sin(alpha) / vd[0] pn1 = pn - eq_to_solve(pn, vd, vu, h, x_2) / deriv_eq_to_solve(pn, vd, vu, h) res = abs(eq_to_solve(pn1, vd, vu, h, x_2)) if res < tol: break else: pn = pn1 p = pn1 return p.real def forward_rtrc(vd, vu, h, p): assert(len(vd) == len(vu)) number_of_layers = len(vd) x = np.zeros(2 * number_of_layers - 1) z = np.zeros(2 * number_of_layers - 1) t = 0 for i in range(2 * (number_of_layers - 1)): if i > number_of_layers - 2: jj = 2 * number_of_layers - 3 - i dz = -h[jj] v = vu else: jj = i dz = h[jj] v = vd dx = (p * v[jj] * h[jj]) / (np.sqrt(1 - p * p * v[jj] * v[jj])) x[i + 1] = x[i] + dx z[i + 1] = z[i] + dz t = t + np.sqrt(dx * dx + dz * dz) / v[jj] return x, z, t def calculate_rays_for_layer(model, observ, owt, layer_index): rays = [] vel_types = get_down_up_vel_types(owt) p = np.sin(np.pi / 4) / model.get_single_param(vel_types['down'], index_start=0, index_finish=1)[0] for receiver in observ.receivers: p_start = p p = solve_for_p(p_start, model.get_single_param(vel_types['down'], index_finish=layer_index + 1), model.get_single_param(vel_types['up'], index_finish=layer_index + 1), model.get_single_param('h', index_finish=layer_index), receiver.x) x, z, t = forward_rtrc(model.get_single_param(vel_types['down'], index_finish=layer_index + 1), model.get_single_param(vel_types['up'], index_finish=layer_index + 1), model.get_single_param('h', index_finish=layer_index), p) rays.append(Ray1D(owt, x, z, t, p, receiver.x)) rays[-1].create_boundaries(*strategy_1D(z, owt)) return rays def calculate_rays_for_layer_mp_helper(args): return calculate_rays_for_layer(*args) def calculate_rays(observ, model, owt): rays = OrderedDict() refl_flags = model.get_reflection_flags() # TODO check multiwaves condition for i, refl in zip(range(1, model.nlayers), refl_flags): if refl: rays[i] = calculate_rays_for_layer(model, observ, owt, i) return rays
[ "collections.OrderedDict", "numpy.sqrt", "cmath.sqrt", "objects.seismic.rays.Ray1D", "cmath.asin", "cmath.sin", "numpy.zeros", "fmodeling.seismic.ray_tracing.case_1D.bound_strateg.strategy_1D", "numpy.sin", "objects.Data.WavePlaceholder.get_down_up_vel_types" ]
[((1785, 1819), 'numpy.zeros', 'np.zeros', (['(2 * number_of_layers - 1)'], {}), '(2 * number_of_layers - 1)\n', (1793, 1819), True, 'import numpy as np\n'), ((1828, 1862), 'numpy.zeros', 'np.zeros', (['(2 * number_of_layers - 1)'], {}), '(2 * number_of_layers - 1)\n', (1836, 1862), True, 'import numpy as np\n'), ((2421, 2447), 'objects.Data.WavePlaceholder.get_down_up_vel_types', 'get_down_up_vel_types', (['owt'], {}), '(owt)\n', (2442, 2447), False, 'from objects.Data.WavePlaceholder import get_down_up_vel_types\n'), ((3553, 3566), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3564, 3566), False, 'from collections import OrderedDict\n'), ((2456, 2473), 'numpy.sin', 'np.sin', (['(np.pi / 4)'], {}), '(np.pi / 4)\n', (2462, 2473), True, 'import numpy as np\n'), ((1337, 1359), 'cmath.asin', 'cmath.asin', (['(pn * vd[0])'], {}), '(pn * vd[0])\n', (1347, 1359), False, 'import cmath\n'), ((2161, 2195), 'numpy.sqrt', 'np.sqrt', (['(1 - p * p * v[jj] * v[jj])'], {}), '(1 - p * p * v[jj] * v[jj])\n', (2168, 2195), True, 'import numpy as np\n'), ((3298, 3332), 'objects.seismic.rays.Ray1D', 'Ray1D', (['owt', 'x', 'z', 't', 'p', 'receiver.x'], {}), '(owt, x, z, t, p, receiver.x)\n', (3303, 3332), False, 'from objects.seismic.rays import Ray1D\n'), ((670, 707), 'cmath.sqrt', 'cmath.sqrt', (['(1 - p * p * v[jj] * v[jj])'], {}), '(1 - p * p * v[jj] * v[jj])\n', (680, 707), False, 'import cmath\n'), ((1409, 1425), 'cmath.sin', 'cmath.sin', (['alpha'], {}), '(alpha)\n', (1418, 1425), False, 'import cmath\n'), ((2271, 2297), 'numpy.sqrt', 'np.sqrt', (['(dx * dx + dz * dz)'], {}), '(dx * dx + dz * dz)\n', (2278, 2297), True, 'import numpy as np\n'), ((3371, 3390), 'fmodeling.seismic.ray_tracing.case_1D.bound_strateg.strategy_1D', 'strategy_1D', (['z', 'owt'], {}), '(z, owt)\n', (3382, 3390), False, 'from fmodeling.seismic.ray_tracing.case_1D.bound_strateg import strategy_1D\n')]
import os # Workaround for PyTorch spawning too many threads os.environ['OMP_NUM_THREADS'] = '1' import argparse import sys import math import time import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from torch.nn import DataParallel try: from tqdm import tqdm except ImportError: print('Warning: tqdm not found. Install it to see the progress bar.') def tqdm(x): return x import cv2 cv2.setNumThreads(0) # Prevent opencv from spawning too many threads in the data loaders import kaolin as kal from rendering.renderer import Renderer from rendering.utils import qrot, qmul, circpad, symmetrize_texture, adjust_poles from rendering.mesh_template import MeshTemplate from utils.losses import loss_flat from models.reconstruction import ReconstructionNetwork, DatasetParams from models.classification_network import ClassificationNetwork from models.pnet import pointMLP parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, required=True) parser.add_argument('--dataset', type=str, required=True, help='(p3d|cub)') parser.add_argument('--mesh_path', type=str, default='autodetect') parser.add_argument('--batch_size', type=int, default=50) parser.add_argument('--image_resolution', type=int, default=256) parser.add_argument('--symmetric', type=bool, default=True) parser.add_argument('--texture_resolution', type=int, default=128) parser.add_argument('--mesh_resolution', type=int, default=32) parser.add_argument('--loss', type=str, default='mse', help='(mse|l1)') parser.add_argument('--checkpoint_freq', type=int, default=100) # Epochs parser.add_argument('--evaluate_freq', type=int, default=10) # Epochs parser.add_argument('--save_freq', type=int, default=10) # Epochs parser.add_argument('--tensorboard', action='store_true') # Epochs parser.add_argument('--image_freq', type=int, default=10) # Epochs parser.add_argument('--no_augmentation', action='store_true') parser.add_argument('--optimize_deltas', type=bool, default=True) parser.add_argument('--optimize_z0', action='store_true') parser.add_argument('--generate_pseudogt', action='store_true') parser.add_argument('--pseudogt_resolution', type=int, default=512) # Output texture resolution parser.add_argument('--evaluate', action='store_true') parser.add_argument('--continue_train', action='store_true') # Resume from checkpoint parser.add_argument('--which_epoch', type=str, default='latest') # Epoch from which to resume (or evaluate) parser.add_argument('--mesh_regularization', type=float, default=0.00005) parser.add_argument('--epochs', type=int, default=1000) parser.add_argument('--lr', type=float, default=0.0001) parser.add_argument('--lr_dataset', type=float, default=0.0001) parser.add_argument('--lr_decay_every', type=int, default=250) parser.add_argument('--num_workers', type=int, default=4) parser.add_argument('--f', action='store_true') parser.add_argument('--pretrained_class_net', action='store_true') parser.add_argument('--use_texture', action='store_true') parser.add_argument('--use_pnet', action='store_true') args = parser.parse_args() if args.mesh_path == 'autodetect': if args.dataset == 'p3d': args.mesh_path = 'mesh_templates/uvsphere_31rings.obj' elif args.dataset == 'cub': args.mesh_path = 'mesh_templates/uvsphere_16rings.obj' else: raise print('Using autodetected mesh', args.mesh_path) mesh_template = MeshTemplate(args.mesh_path, is_symmetric=args.symmetric) if args.generate_pseudogt: # Ideally, the renderer should run at a higher resolution than the input image, # or a sufficiently high resolution at the very least. renderer_res = max(1024, 2*args.pseudogt_resolution) else: # Match neural network input resolution renderer_res = args.image_resolution renderer = Renderer(renderer_res, renderer_res) class ImageDataset(torch.utils.data.Dataset): def __init__(self, cmr_dataset, img_size): self.cmr_dataset = cmr_dataset self.paths = cmr_dataset.get_paths() self.extra_img_keys = [] if isinstance(img_size, list): for res in img_size[1:]: self.extra_img_keys.append(f'img_{res}') def __len__(self): return len(self.cmr_dataset) def __getitem__(self, idx): item = self.cmr_dataset[idx] # Rescale img to [-1, 1] img = item['img'].astype('float32')*2 - 1 mask = item['mask'].astype('float32') img *= mask[np.newaxis, :, :] img = torch.FloatTensor(img) mask = torch.FloatTensor(mask).unsqueeze(0) ind = torch.LongTensor([idx]) if item['mirrored']: # Indices from 0 to N-1 are straight, from N to 2N-1 are mirrored ind += len(self.cmr_dataset) scale = torch.FloatTensor(item['sfm_pose'][:1]) translation = torch.FloatTensor([item['sfm_pose'][1], item['sfm_pose'][2], 0]) rot = torch.FloatTensor(item['sfm_pose'][-4:]) output = torch.cat((img, mask), dim=0) extra_imgs = [] for k in self.extra_img_keys: img_k, mask_k = item[k] img_k = img_k.astype('float32')*2 - 1 mask_k = mask_k.astype('float32') img_k *= mask_k[np.newaxis, :, :] img_k = torch.FloatTensor(img_k) extra_imgs.append(img_k) lab = item['target'] return (output, *extra_imgs, scale, translation, rot, ind,lab) dataset_type = args.dataset if not args.generate_pseudogt: dataloader_resolution = args.image_resolution dataloader_resolution_val = args.image_resolution else: # We need images at different scales inception_resolution = 299 dataloader_resolution = [args.image_resolution, inception_resolution, renderer_res] dataloader_resolution_val = inception_resolution is_train = not (args.no_augmentation or args.evaluate or args.generate_pseudogt) if dataset_type == 'p3d': from cmr_data.p3d import P3dDataset cmr_ds_train = P3dDataset('train', is_train, dataloader_resolution) mesh_ds_train = ImageDataset(cmr_ds_train, dataloader_resolution) if not args.generate_pseudogt: cmr_ds_val = P3dDataset('val', False, dataloader_resolution_val) mesh_ds_val = ImageDataset(cmr_ds_val, dataloader_resolution_val) else: mesh_ds_val = None debug_ids = [6, 9, 16, 23, 34, 39, 40, 54, 60, 61, 64, 66, 67, 75, 77, 84] # For TensorBoard elif dataset_type == 'cub': from cmr_data.cub import CUBDataset cmr_ds_train = CUBDataset('train', is_train, dataloader_resolution) mesh_ds_train = ImageDataset(cmr_ds_train, dataloader_resolution) cmr_ds_val = CUBDataset('testval', False, dataloader_resolution_val) mesh_ds_val = ImageDataset(cmr_ds_val, dataloader_resolution_val) debug_ids = [0, 1, 12, 18, 20, 42, 72, 100, 101, 115, 123, 125, 142, 158, 188, 203] # For TensorBoard else: raise batch_size = args.batch_size shuffle = not (args.generate_pseudogt or args.evaluate) train_loader = torch.utils.data.DataLoader(mesh_ds_train, batch_size=batch_size, shuffle=shuffle, num_workers=args.num_workers, pin_memory=True) if mesh_ds_val is not None: val_loader = torch.utils.data.DataLoader(mesh_ds_val, batch_size=batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) def render_multiview(raw_vtx, pred_tex, idx=0): angles = [0, 45, 90, 135, 180, 225, 270, 315] with torch.no_grad(): # Render from multiple viewpoints rad = -90 / 180 * np.pi q0 = torch.Tensor([np.cos(-rad/2), 0, 0, np.sin(-rad/2)]).cuda() rad = 110 / 180 * np.pi q1 = torch.Tensor([np.cos(-rad/2), 0, np.sin(-rad/2), 0]).cuda() q0 = qmul(q0, q1) rot = [] for angle in angles: rad = angle / 180 *np.pi * 0.8 q = torch.Tensor([np.cos(-rad/2), 0, 0, np.sin(-rad/2)]).cuda() q = qmul(q0, q) rot.append(q) rot = torch.stack(rot, dim=0) raw_vtx = raw_vtx[idx:idx+1].expand(rot.shape[0], -1, -1) pred_tex = pred_tex[idx:idx+1].expand(rot.shape[0], -1, -1, -1) vtx = qrot(rot, raw_vtx)*0.9 vtx[:, :, 1:] *= -1 pred_view, _ = mesh_template.forward_renderer(renderer, vtx, pred_tex) pred_view = pred_view.cpu() nrows = 2 ncols= 4 pred_view = pred_view.view(nrows, ncols, pred_view.shape[1], pred_view.shape[2], pred_view.shape[3]) pred_view = pred_view.permute(0, 2, 1, 3, 4).contiguous() pred_view = pred_view.view(args.image_resolution*nrows, args.image_resolution*ncols, 3) render = (pred_view.cpu().numpy() + 1)/2 return render def mean_iou(alpha_pred, alpha_real): alpha_pred = alpha_pred > 0.5 alpha_real = alpha_real > 0.5 intersection = (alpha_pred & alpha_real).float().sum(dim=[1, 2]) union = (alpha_pred | alpha_real).float().sum(dim=[1, 2]) iou = intersection / union return torch.mean(iou) def to_grid(x): return torchvision.utils.make_grid((x[:16, :3]+1)/2, nrow=4) def transform_vertices(vtx, gt_scale, gt_translation, gt_rot, gt_idx): if args.optimize_deltas: translation_delta, scale_delta = dataset_params(gt_idx, 'deltas') else: scale_delta = 0 translation_delta = 0 vtx = qrot(gt_rot, (gt_scale + scale_delta).unsqueeze(-1)*vtx) + (gt_translation + translation_delta).unsqueeze(1) vtx = vtx * torch.Tensor([1, -1, -1]).to(vtx.device) if args.optimize_z0: z0 = dataset_params(gt_idx, 'z0').unsqueeze(-1) z = vtx[:, :, 2:] factor = (z0 + z/2)/(z0 - z/2) vtx = torch.cat((vtx[:, :, :2]*factor, z), dim=2) else: assert 'ds_z0' not in dataset_params.__dict__, 'Model was trained with --optimize_z0' return vtx # Full test def evaluate_all(loader, writer=None, it=0): with torch.no_grad(): generator.eval() classNet.eval() N = 0 total_recon_loss = 0 total_flat_loss = 0 total_class_loss = 0 total_miou = 0 total_accuracy=0 debug_images_real = [] debug_images_fake = [] debug_images_render = [] for i, (X, gt_scale, gt_translation, gt_rot, _,target) in enumerate(loader): target = target.cuda() X_real = X.cuda() gt_scale = gt_scale.cuda() gt_translation = gt_translation.cuda() gt_rot = gt_rot.cuda() pred_tex, mesh_map = generator(X_real) raw_vtx = mesh_template.get_vertex_positions(mesh_map) vtx = transform_vertices(raw_vtx, gt_scale, gt_translation, gt_rot, None) image_pred, alpha_pred = mesh_template.forward_renderer(renderer, vtx, pred_tex) X_fake = torch.cat((image_pred, alpha_pred), dim=3).permute(0, 3, 1, 2) if not args.use_texture: output = classNet(vtx) #vtx or raw_vtx ? else: text_graph = mesh_template.get_texture_graph(pred_tex) output = classNet(vtx,x=text_graph) class_loss = criterion_class(output,target) acc = (output.argmax(dim=-1) == target).float().mean() recon_loss = criterion(X_fake, X_real) flat_loss = loss_flat(mesh_template.mesh, mesh_template.compute_normals(raw_vtx)) miou = mean_iou(X_fake[:, 3], X_real[:, 3]) # Done on alpha channel total_recon_loss += X.shape[0] * recon_loss.item() total_flat_loss += X.shape[0] * flat_loss.item() total_class_loss += X.shape[0]*class_loss total_accuracy += X.shape[0]*acc total_miou += X.shape[0] * miou.item() N += X.shape[0] if writer is not None: # Save images dbg_ids = np.array(debug_ids) min_idx = i * args.batch_size max_idx = (i+1) * args.batch_size dbg_ids = dbg_ids[(dbg_ids >= min_idx) & (dbg_ids < max_idx)] - min_idx if len(dbg_ids) > 0: debug_images_real.append(X_real[dbg_ids].cpu()) debug_images_fake.append(X_fake[dbg_ids].cpu()) for idx in dbg_ids: if len(debug_images_render) >= 4: break debug_images_render.append(render_multiview(raw_vtx, pred_tex, idx)) total_recon_loss /= N total_flat_loss /= N total_class_loss /= N total_accuracy /= N total_miou /= N if writer is not None: writer.add_scalar(args.loss + '/val', total_recon_loss, it) writer.add_scalar('flat/val', total_flat_loss, it) writer.add_scalar('iou/val', total_miou, it) writer.add_scalar('acc/val', total_accuracy.item(), total_it) writer.add_scalar('class_loss/val', total_class_loss.item(), total_it) log('[TEST] recon_loss {:.5f}, flat_loss {:.5f}, mIoU {:.5f}, total_accuracy{:.5f}, class_loss {:.5f}, N {}'.format( total_recon_loss, total_flat_loss, total_miou, total_accuracy,total_class_loss,N )) if writer is not None: writer.add_image('image_val/real', to_grid(torch.cat(debug_images_real, dim=0)), it) writer.add_image('image_val/fake', to_grid(torch.cat(debug_images_fake, dim=0)), it) debug_images_render = torch.FloatTensor(debug_images_render).permute(0, 3, 1, 2) render_grid = torchvision.utils.make_grid(debug_images_render, nrow=1) writer.add_image('image_val/render', render_grid, it) def log_image(X_fake, X_real, writer, it): writer.add_image('image_train/real', to_grid(X_real), it) writer.add_image('image_train/fake', to_grid(X_fake), it) import pathlib import os if args.tensorboard: import shutil from torch.utils.tensorboard import SummaryWriter import torchvision generator = ReconstructionNetwork(symmetric=args.symmetric, texture_res=args.texture_resolution, mesh_res=args.mesh_resolution, ).cuda() generator.load_state_dict(torch.load("checkpoints_recon/pretrained_reconstruction_cub/checkpoint_latest.pth")["generator"]) print("Loaded from checkpoints_recon/pretrained_reconstruction_cub/checkpoint_latest.pth") if args.use_pnet: classNet = pointMLP(200,args.pretrained_class_net,args.use_texture).cuda() else: classNet = ClassificationNetwork(200,args.pretrained_class_net,args.use_texture).cuda() classNet = DataParallel(classNet) optimizer = optim.Adam(classNet.parameters(), lr=args.lr) if args.optimize_deltas or args.optimize_z0: dataset_params = DatasetParams(args, len(train_loader.dataset)).cuda() optimizer_dataset = optim.Adam(dataset_params.parameters(), lr=args.lr_dataset) else: dataset_params = None optimizer_dataset = None criteria = { 'mse': nn.MSELoss(), 'l1': nn.L1Loss(), } criterion = criteria[args.loss] criterion_class = torch.nn.CrossEntropyLoss() g_curve = [] total_it = 0 epoch = 0 flat_warmup = 10 checkpoint_dir = 'checkpoints_recon/' + args.name if args.evaluate or args.generate_pseudogt: # Load last checkpoint chk = torch.load(os.path.join(checkpoint_dir, f'checkpoint_{args.which_epoch}.pth'), map_location=lambda storage, loc: storage) if 'epoch' in chk: epoch = chk['epoch'] total_it = chk['iteration'] generator.load_state_dict(chk['generator']) if dataset_params is not None: dataset_params.load_state_dict(chk['dataset_params']) else: assert 'dataset_params' not in chk or chk['dataset_params'] is None if args.continue_train: optimizer.load_state_dict(chk['optimizer']) if optimizer_dataset is not None: optimizer_dataset.load_state_dict(chk['optimizer_dataset_params']) print(f'Resuming from epoch {epoch}') else: if 'epoch' in chk: print(f'Evaluating epoch {epoch}') args.epochs = -1 # Disable training chk = None if args.tensorboard and not (args.evaluate or args.generate_pseudogt): log_dir = 'tensorboard_recon/' + args.name shutil.rmtree(log_dir, ignore_errors=True) # Delete logs writer = SummaryWriter(log_dir) else: writer = None if not (args.generate_pseudogt or args.evaluate): pathlib.Path(checkpoint_dir).mkdir(parents=True, exist_ok=True) log_file = open(os.path.join(checkpoint_dir, 'log.txt'), 'a' if args.continue_train else 'w', buffering=1) # Line buffering print(' '.join(sys.argv), file=log_file) else: log_file = None def log(text): if log_file is not None: print(text, file=log_file) print(text) try: while epoch < args.epochs: generator.train() start_time = time.time() for i, (X, gt_scale, gt_translation, gt_rot, gt_idx,target) in enumerate(train_loader): target = target.cuda() X_real = X.cuda() gt_scale = gt_scale.cuda() gt_translation = gt_translation.cuda() gt_rot = gt_rot.cuda() if args.optimize_deltas or args.optimize_z0: gt_idx = gt_idx.squeeze(-1).cuda() else: gt_idx = None optimizer.zero_grad() if optimizer_dataset is not None: optimizer_dataset.zero_grad() with torch.no_grad(): pred_tex, mesh_map = generator(X_real) raw_vtx = mesh_template.get_vertex_positions(mesh_map) vtx = transform_vertices(raw_vtx, gt_scale, gt_translation, gt_rot, gt_idx) image_pred, alpha_pred = mesh_template.forward_renderer(renderer, vtx, pred_tex) X_fake = torch.cat((image_pred, alpha_pred), dim=3).permute(0, 3, 1, 2) recon_loss = criterion(X_fake, X_real) flat_loss = loss_flat(mesh_template.mesh, mesh_template.compute_normals(raw_vtx)) if not args.use_texture: output = classNet(vtx) #vtx or raw_vtx ? else: text_graph = mesh_template.get_texture_graph(pred_tex) output = classNet(vtx,x=text_graph) class_loss = criterion_class(output,target) # Test losses with torch.no_grad(): miou = mean_iou(X_fake[:, 3], X_real[:, 3]) # Done on alpha channel acc = (output.argmax(dim=-1) == target).float().mean() flat_coeff = args.mesh_regularization*flat_warmup flat_warmup = max(flat_warmup - 0.1, 1) #loss = recon_loss + flat_coeff*flat_loss loss = class_loss loss.backward() optimizer.step() if optimizer_dataset is not None: optimizer_dataset.step() g_curve.append(loss.item()) if total_it % 10 == 0: log('[{}] epoch {}, {}/{}, recon_loss {:.5f} flat_loss {:.5f} class_loss {:.5f} acc {:.5f} iou {:.5f}'.format( total_it, epoch, i, len(train_loader), recon_loss.item(), flat_loss.item(), loss.item(), acc.item(),miou.item(), )) if args.tensorboard: writer.add_scalar(args.loss + '/train', recon_loss.item(), total_it) writer.add_scalar('flat/train', flat_loss.item(), total_it) writer.add_scalar('iou/train', miou.item(), total_it) writer.add_scalar('acc/train', acc.item(), total_it) writer.add_scalar('class_loss/train', class_loss.item(), total_it) total_it += 1 epoch += 1 log('Time per epoch: {:.3f} s'.format(time.time() - start_time)) if epoch % args.lr_decay_every == 0: for param_group in optimizer.param_groups: param_group['lr'] *= 0.5 def save_checkpoint(it): torch.save({ 'optimizer': optimizer.state_dict(), 'generator': generator.state_dict(), 'optimizer_dataset_params': optimizer_dataset.state_dict() if optimizer_dataset is not None else None, 'dataset_params': dataset_params.state_dict() if dataset_params is not None else None, 'epoch': epoch, 'iteration': total_it, 'args': vars(args), }, os.path.join(checkpoint_dir, f'checkpoint_{it}.pth')) if epoch % args.save_freq == 0: save_checkpoint('latest') if epoch % args.checkpoint_freq == 0: save_checkpoint(str(epoch)) if args.tensorboard and epoch % args.image_freq == 0: log_image(X_fake, X_real, writer, total_it) if epoch % args.evaluate_freq == 0: evaluate_all(val_loader, writer, total_it) except KeyboardInterrupt: print('Aborted.') if not (args.generate_pseudogt or args.evaluate): save_checkpoint('latest') elif args.evaluate: evaluate_all(val_loader, writer, total_it) elif args.generate_pseudogt: from utils.fid import calculate_stats, init_inception, forward_inception_batch inception_model = init_inception().cuda().eval() print('Exporting pseudo-ground-truth data...') class InverseRenderer(nn.Module): def __init__(self, mesh, res_h, res_w): super().__init__() self.res = (res_h, res_w) self.inverse_renderer = Renderer(res_h, res_w) self.mesh = mesh def forward(self, predicted_vertices, target): with torch.no_grad(): tex = target # The texture is the target image uvs = (predicted_vertices[..., :2] + 1)/2 vertices = self.mesh.uvs.unsqueeze(0)*2 - 1 vertices = torch.cat((vertices, torch.zeros_like(vertices[..., :1])), dim=-1) image_pred, alpha_pred, _ = self.inverse_renderer(points=[vertices.expand(target.shape[0], -1, -1), self.mesh.face_textures], uv_bxpx2=uvs, texture_bx3xthxtw=tex, ft_fx3=self.mesh.faces, return_hardmask=True, ) return image_pred, alpha_pred inverse_renderer = InverseRenderer(mesh_template.mesh, args.pseudogt_resolution, args.pseudogt_resolution) cache_dir = os.path.join('cache', args.dataset) pseudogt_dir = os.path.join(cache_dir, f'pseudogt_{args.pseudogt_resolution}x{args.pseudogt_resolution}') pathlib.Path(pseudogt_dir).mkdir(parents=True, exist_ok=True) all_path = [] all_gt_scale = [] all_gt_translation = [] all_gt_rotation = [] all_inception_activation = [] generator.eval() for net_image, inception_image, hd_image, gt_scale, gt_translation, gt_rot, indices in tqdm(train_loader): # Compute visibility mask with torch.no_grad(): net_image = net_image.cuda() gt_scale = gt_scale.cuda() gt_translation = gt_translation.cuda() gt_rot = gt_rot.cuda() if args.optimize_deltas or args.optimize_z0: gt_idx = indices.squeeze(-1).cuda() else: gt_idx = indices.cuda() pred_tex, mesh_map = generator(net_image) raw_vtx = mesh_template.get_vertex_positions(mesh_map) vtx = transform_vertices(raw_vtx, gt_scale, gt_translation, gt_rot, gt_idx) if pred_tex.shape[2] > renderer_res//8: # To reduce aliasing in the gradients from the renderer, # the rendering resolution must be much higher than the texture resolution. # As a rule of thumb, we came up with render_res >= 8*texture_res # This is already ensured by the default hyperparameters (1024 and 128). # If not, the texture is resized. pred_tex = F.interpolate(pred_tex, size=(renderer_res//8, renderer_res//8), mode='bilinear', align_corners=False) pred_tex.requires_grad_() image_pred, alpha_pred = mesh_template.forward_renderer(renderer, vtx, pred_tex) # Compute gradient visibility_mask, = torch.autograd.grad(image_pred, pred_tex, torch.ones_like(image_pred)) with torch.no_grad(): # Compute inception activations all_inception_activation.append(forward_inception_batch(inception_model, inception_image.cuda()/2 + 0.5)) # Project ground-truth image onto the UV map inverse_tex, inverse_alpha = inverse_renderer(vtx, hd_image.cuda()) # Mask projection using the visibility mask mask = F.interpolate(visibility_mask, args.pseudogt_resolution, mode='bilinear', align_corners=False).permute(0, 2, 3, 1).cuda() mask = (mask > 0).any(dim=3, keepdim=True).float() inverse_tex *= mask inverse_alpha *= mask inverse_tex = inverse_tex.permute(0, 3, 1, 2) inverse_alpha = inverse_alpha.permute(0, 3, 1, 2) # Convert to half to save disk space inverse_tex = inverse_tex.half().cpu() inverse_alpha = inverse_alpha.half().cpu() all_gt_scale.append(gt_scale.cpu().clone()) all_gt_translation.append(gt_translation.cpu().clone()) all_gt_rotation.append(gt_rot.cpu().clone()) for i, idx in enumerate(indices): idx = idx.item() all_path.append(train_loader.dataset.paths[idx]) pseudogt = { 'mesh': mesh_map[i].cpu().clone(), 'texture': inverse_tex[i].clone(), 'texture_alpha': inverse_alpha[i].clone(), 'image': inception_image[i].half().clone(), } np.savez_compressed(os.path.join(pseudogt_dir, f'{idx}'), data=pseudogt, ) print('Saving pose metadata...') poses_metadata = { 'scale': torch.cat(all_gt_scale, dim=0), 'translation': torch.cat(all_gt_translation, dim=0), 'rotation': torch.cat(all_gt_rotation, dim=0), 'path': all_path, } np.savez_compressed(os.path.join(cache_dir, 'poses_metadata'), data=poses_metadata, ) print('Saving precomputed FID statistics (train)...') all_inception_activation = np.concatenate(all_inception_activation, axis=0) if args.dataset == 'p3d': # For Pascal3D+, we only use images that are part of the ImageNet subset imagenet_indices = [i for i, p in enumerate(all_path) if p.startswith('car_imagenet')] all_inception_activation = all_inception_activation[imagenet_indices] m_real, s_real = calculate_stats(all_inception_activation) fid_save_path = os.path.join(cache_dir, f'precomputed_fid_{inception_resolution}x{inception_resolution}_train') np.savez_compressed(fid_save_path, stats_m=m_real, stats_s=np.tril(s_real.astype(np.float32)), # The matrix is symmetric, we only store half of it num_images=len(all_inception_activation), resolution=inception_resolution, ) if args.dataset == 'cub': print('Saving precomputed FID statistics (testval)...') val_inception_activation = [] for inception_image, _, _, _, _ in tqdm(val_loader): with torch.no_grad(): val_inception_activation.append( forward_inception_batch(inception_model, inception_image[:, :3].cuda()/2 + 0.5)) val_inception_activation = np.concatenate(val_inception_activation, axis=0) m_real, s_real = calculate_stats(val_inception_activation) fid_save_path = os.path.join(cache_dir, f'precomputed_fid_{inception_resolution}x{inception_resolution}_testval') np.savez_compressed(fid_save_path, stats_m=m_real, stats_s=np.tril(s_real.astype(np.float32)), # The matrix is symmetric, we only store half of it num_images=len(val_inception_activation), resolution=inception_resolution, ) print('Done.') if writer is not None: writer.close()
[ "torch.nn.CrossEntropyLoss", "rendering.mesh_template.MeshTemplate", "torch.utils.data.DataLoader", "torch.LongTensor", "torch.nn.L1Loss", "models.pnet.pointMLP", "torch.nn.MSELoss", "numpy.array", "rendering.utils.qrot", "torch.nn.functional.interpolate", "numpy.sin", "torchvision.utils.make_...
[((462, 482), 'cv2.setNumThreads', 'cv2.setNumThreads', (['(0)'], {}), '(0)\n', (479, 482), False, 'import cv2\n'), ((958, 983), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (981, 983), False, 'import argparse\n'), ((3455, 3512), 'rendering.mesh_template.MeshTemplate', 'MeshTemplate', (['args.mesh_path'], {'is_symmetric': 'args.symmetric'}), '(args.mesh_path, is_symmetric=args.symmetric)\n', (3467, 3512), False, 'from rendering.mesh_template import MeshTemplate\n'), ((3848, 3884), 'rendering.renderer.Renderer', 'Renderer', (['renderer_res', 'renderer_res'], {}), '(renderer_res, renderer_res)\n', (3856, 3884), False, 'from rendering.renderer import Renderer\n'), ((7086, 7220), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['mesh_ds_train'], {'batch_size': 'batch_size', 'shuffle': 'shuffle', 'num_workers': 'args.num_workers', 'pin_memory': '(True)'}), '(mesh_ds_train, batch_size=batch_size, shuffle=\n shuffle, num_workers=args.num_workers, pin_memory=True)\n', (7113, 7220), False, 'import torch\n'), ((14985, 15007), 'torch.nn.DataParallel', 'DataParallel', (['classNet'], {}), '(classNet)\n', (14997, 15007), False, 'from torch.nn import DataParallel\n'), ((15448, 15475), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (15473, 15475), False, 'import torch\n'), ((6043, 6095), 'cmr_data.p3d.P3dDataset', 'P3dDataset', (['"""train"""', 'is_train', 'dataloader_resolution'], {}), "('train', is_train, dataloader_resolution)\n", (6053, 6095), False, 'from cmr_data.p3d import P3dDataset\n'), ((7305, 7435), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['mesh_ds_val'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'args.num_workers', 'pin_memory': '(True)'}), '(mesh_ds_val, batch_size=batch_size, shuffle=\n False, num_workers=args.num_workers, pin_memory=True)\n', (7332, 7435), False, 'import torch\n'), ((9127, 9142), 'torch.mean', 'torch.mean', (['iou'], {}), '(iou)\n', (9137, 9142), False, 'import torch\n'), ((9172, 9229), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['((x[:16, :3] + 1) / 2)'], {'nrow': '(4)'}), '((x[:16, :3] + 1) / 2, nrow=4)\n', (9199, 9229), False, 'import torchvision\n'), ((15358, 15370), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (15368, 15370), True, 'import torch.nn as nn\n'), ((15382, 15393), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (15391, 15393), True, 'import torch.nn as nn\n'), ((16642, 16684), 'shutil.rmtree', 'shutil.rmtree', (['log_dir'], {'ignore_errors': '(True)'}), '(log_dir, ignore_errors=True)\n', (16655, 16684), False, 'import shutil\n'), ((16712, 16734), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['log_dir'], {}), '(log_dir)\n', (16725, 16734), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((4548, 4570), 'torch.FloatTensor', 'torch.FloatTensor', (['img'], {}), '(img)\n', (4565, 4570), False, 'import torch\n'), ((4637, 4660), 'torch.LongTensor', 'torch.LongTensor', (['[idx]'], {}), '([idx])\n', (4653, 4660), False, 'import torch\n'), ((4826, 4865), 'torch.FloatTensor', 'torch.FloatTensor', (["item['sfm_pose'][:1]"], {}), "(item['sfm_pose'][:1])\n", (4843, 4865), False, 'import torch\n'), ((4888, 4952), 'torch.FloatTensor', 'torch.FloatTensor', (["[item['sfm_pose'][1], item['sfm_pose'][2], 0]"], {}), "([item['sfm_pose'][1], item['sfm_pose'][2], 0])\n", (4905, 4952), False, 'import torch\n'), ((4967, 5007), 'torch.FloatTensor', 'torch.FloatTensor', (["item['sfm_pose'][-4:]"], {}), "(item['sfm_pose'][-4:])\n", (4984, 5007), False, 'import torch\n'), ((5025, 5054), 'torch.cat', 'torch.cat', (['(img, mask)'], {'dim': '(0)'}), '((img, mask), dim=0)\n', (5034, 5054), False, 'import torch\n'), ((6227, 6278), 'cmr_data.p3d.P3dDataset', 'P3dDataset', (['"""val"""', '(False)', 'dataloader_resolution_val'], {}), "('val', False, dataloader_resolution_val)\n", (6237, 6278), False, 'from cmr_data.p3d import P3dDataset\n'), ((6585, 6637), 'cmr_data.cub.CUBDataset', 'CUBDataset', (['"""train"""', 'is_train', 'dataloader_resolution'], {}), "('train', is_train, dataloader_resolution)\n", (6595, 6637), False, 'from cmr_data.cub import CUBDataset\n'), ((6730, 6785), 'cmr_data.cub.CUBDataset', 'CUBDataset', (['"""testval"""', '(False)', 'dataloader_resolution_val'], {}), "('testval', False, dataloader_resolution_val)\n", (6740, 6785), False, 'from cmr_data.cub import CUBDataset\n'), ((7585, 7600), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7598, 7600), False, 'import torch\n'), ((7867, 7879), 'rendering.utils.qmul', 'qmul', (['q0', 'q1'], {}), '(q0, q1)\n', (7871, 7879), False, 'from rendering.utils import qrot, qmul, circpad, symmetrize_texture, adjust_poles\n'), ((8114, 8137), 'torch.stack', 'torch.stack', (['rot'], {'dim': '(0)'}), '(rot, dim=0)\n', (8125, 8137), False, 'import torch\n'), ((9801, 9846), 'torch.cat', 'torch.cat', (['(vtx[:, :, :2] * factor, z)'], {'dim': '(2)'}), '((vtx[:, :, :2] * factor, z), dim=2)\n', (9810, 9846), False, 'import torch\n'), ((10031, 10046), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10044, 10046), False, 'import torch\n'), ((14335, 14455), 'models.reconstruction.ReconstructionNetwork', 'ReconstructionNetwork', ([], {'symmetric': 'args.symmetric', 'texture_res': 'args.texture_resolution', 'mesh_res': 'args.mesh_resolution'}), '(symmetric=args.symmetric, texture_res=args.\n texture_resolution, mesh_res=args.mesh_resolution)\n', (14356, 14455), False, 'from models.reconstruction import ReconstructionNetwork, DatasetParams\n'), ((14588, 14676), 'torch.load', 'torch.load', (['"""checkpoints_recon/pretrained_reconstruction_cub/checkpoint_latest.pth"""'], {}), "(\n 'checkpoints_recon/pretrained_reconstruction_cub/checkpoint_latest.pth')\n", (14598, 14676), False, 'import torch\n'), ((15676, 15742), 'os.path.join', 'os.path.join', (['checkpoint_dir', 'f"""checkpoint_{args.which_epoch}.pth"""'], {}), "(checkpoint_dir, f'checkpoint_{args.which_epoch}.pth')\n", (15688, 15742), False, 'import os\n'), ((16898, 16937), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""log.txt"""'], {}), "(checkpoint_dir, 'log.txt')\n", (16910, 16937), False, 'import os\n'), ((17263, 17274), 'time.time', 'time.time', ([], {}), '()\n', (17272, 17274), False, 'import time\n'), ((5324, 5348), 'torch.FloatTensor', 'torch.FloatTensor', (['img_k'], {}), '(img_k)\n', (5341, 5348), False, 'import torch\n'), ((8062, 8073), 'rendering.utils.qmul', 'qmul', (['q0', 'q'], {}), '(q0, q)\n', (8066, 8073), False, 'from rendering.utils import qrot, qmul, circpad, symmetrize_texture, adjust_poles\n'), ((8300, 8318), 'rendering.utils.qrot', 'qrot', (['rot', 'raw_vtx'], {}), '(rot, raw_vtx)\n', (8304, 8318), False, 'from rendering.utils import qrot, qmul, circpad, symmetrize_texture, adjust_poles\n'), ((13881, 13937), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['debug_images_render'], {'nrow': '(1)'}), '(debug_images_render, nrow=1)\n', (13908, 13937), False, 'import torchvision\n'), ((14812, 14870), 'models.pnet.pointMLP', 'pointMLP', (['(200)', 'args.pretrained_class_net', 'args.use_texture'], {}), '(200, args.pretrained_class_net, args.use_texture)\n', (14820, 14870), False, 'from models.pnet import pointMLP\n'), ((14897, 14968), 'models.classification_network.ClassificationNetwork', 'ClassificationNetwork', (['(200)', 'args.pretrained_class_net', 'args.use_texture'], {}), '(200, args.pretrained_class_net, args.use_texture)\n', (14918, 14968), False, 'from models.classification_network import ClassificationNetwork\n'), ((16814, 16842), 'pathlib.Path', 'pathlib.Path', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (16826, 16842), False, 'import pathlib\n'), ((23140, 23175), 'os.path.join', 'os.path.join', (['"""cache"""', 'args.dataset'], {}), "('cache', args.dataset)\n", (23152, 23175), False, 'import os\n'), ((23195, 23289), 'os.path.join', 'os.path.join', (['cache_dir', 'f"""pseudogt_{args.pseudogt_resolution}x{args.pseudogt_resolution}"""'], {}), "(cache_dir,\n f'pseudogt_{args.pseudogt_resolution}x{args.pseudogt_resolution}')\n", (23207, 23289), False, 'import os\n'), ((23601, 23619), 'tqdm.tqdm', 'tqdm', (['train_loader'], {}), '(train_loader)\n', (23605, 23619), False, 'from tqdm import tqdm\n'), ((27423, 27471), 'numpy.concatenate', 'np.concatenate', (['all_inception_activation'], {'axis': '(0)'}), '(all_inception_activation, axis=0)\n', (27437, 27471), True, 'import numpy as np\n'), ((27787, 27828), 'utils.fid.calculate_stats', 'calculate_stats', (['all_inception_activation'], {}), '(all_inception_activation)\n', (27802, 27828), False, 'from utils.fid import calculate_stats, init_inception, forward_inception_batch\n'), ((27849, 27948), 'os.path.join', 'os.path.join', (['cache_dir', 'f"""precomputed_fid_{inception_resolution}x{inception_resolution}_train"""'], {}), "(cache_dir,\n f'precomputed_fid_{inception_resolution}x{inception_resolution}_train')\n", (27861, 27948), False, 'import os\n'), ((4586, 4609), 'torch.FloatTensor', 'torch.FloatTensor', (['mask'], {}), '(mask)\n', (4603, 4609), False, 'import torch\n'), ((9600, 9625), 'torch.Tensor', 'torch.Tensor', (['[1, -1, -1]'], {}), '([1, -1, -1])\n', (9612, 9625), False, 'import torch\n'), ((12001, 12020), 'numpy.array', 'np.array', (['debug_ids'], {}), '(debug_ids)\n', (12009, 12020), True, 'import numpy as np\n'), ((17863, 17878), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (17876, 17878), False, 'import torch\n'), ((18785, 18800), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (18798, 18800), False, 'import torch\n'), ((21098, 21150), 'os.path.join', 'os.path.join', (['checkpoint_dir', 'f"""checkpoint_{it}.pth"""'], {}), "(checkpoint_dir, f'checkpoint_{it}.pth')\n", (21110, 21150), False, 'import os\n'), ((27012, 27042), 'torch.cat', 'torch.cat', (['all_gt_scale'], {'dim': '(0)'}), '(all_gt_scale, dim=0)\n', (27021, 27042), False, 'import torch\n'), ((27067, 27103), 'torch.cat', 'torch.cat', (['all_gt_translation'], {'dim': '(0)'}), '(all_gt_translation, dim=0)\n', (27076, 27103), False, 'import torch\n'), ((27125, 27158), 'torch.cat', 'torch.cat', (['all_gt_rotation'], {'dim': '(0)'}), '(all_gt_rotation, dim=0)\n', (27134, 27158), False, 'import torch\n'), ((27216, 27257), 'os.path.join', 'os.path.join', (['cache_dir', '"""poses_metadata"""'], {}), "(cache_dir, 'poses_metadata')\n", (27228, 27257), False, 'import os\n'), ((28473, 28489), 'tqdm.tqdm', 'tqdm', (['val_loader'], {}), '(val_loader)\n', (28477, 28489), False, 'from tqdm import tqdm\n'), ((28719, 28767), 'numpy.concatenate', 'np.concatenate', (['val_inception_activation'], {'axis': '(0)'}), '(val_inception_activation, axis=0)\n', (28733, 28767), True, 'import numpy as np\n'), ((28793, 28834), 'utils.fid.calculate_stats', 'calculate_stats', (['val_inception_activation'], {}), '(val_inception_activation)\n', (28808, 28834), False, 'from utils.fid import calculate_stats, init_inception, forward_inception_batch\n'), ((28859, 28960), 'os.path.join', 'os.path.join', (['cache_dir', 'f"""precomputed_fid_{inception_resolution}x{inception_resolution}_testval"""'], {}), "(cache_dir,\n f'precomputed_fid_{inception_resolution}x{inception_resolution}_testval')\n", (28871, 28960), False, 'import os\n'), ((10957, 10999), 'torch.cat', 'torch.cat', (['(image_pred, alpha_pred)'], {'dim': '(3)'}), '((image_pred, alpha_pred), dim=3)\n', (10966, 10999), False, 'import torch\n'), ((13623, 13658), 'torch.cat', 'torch.cat', (['debug_images_real'], {'dim': '(0)'}), '(debug_images_real, dim=0)\n', (13632, 13658), False, 'import torch\n'), ((13720, 13755), 'torch.cat', 'torch.cat', (['debug_images_fake'], {'dim': '(0)'}), '(debug_images_fake, dim=0)\n', (13729, 13755), False, 'import torch\n'), ((13796, 13834), 'torch.FloatTensor', 'torch.FloatTensor', (['debug_images_render'], {}), '(debug_images_render)\n', (13813, 13834), False, 'import torch\n'), ((20419, 20430), 'time.time', 'time.time', ([], {}), '()\n', (20428, 20430), False, 'import time\n'), ((22170, 22192), 'rendering.renderer.Renderer', 'Renderer', (['res_h', 'res_w'], {}), '(res_h, res_w)\n', (22178, 22192), False, 'from rendering.renderer import Renderer\n'), ((23290, 23316), 'pathlib.Path', 'pathlib.Path', (['pseudogt_dir'], {}), '(pseudogt_dir)\n', (23302, 23316), False, 'import pathlib\n'), ((23668, 23683), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (23681, 23683), False, 'import torch\n'), ((25071, 25098), 'torch.ones_like', 'torch.ones_like', (['image_pred'], {}), '(image_pred)\n', (25086, 25098), False, 'import torch\n'), ((25122, 25137), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (25135, 25137), False, 'import torch\n'), ((7703, 7719), 'numpy.cos', 'np.cos', (['(-rad / 2)'], {}), '(-rad / 2)\n', (7709, 7719), True, 'import numpy as np\n'), ((7725, 7741), 'numpy.sin', 'np.sin', (['(-rad / 2)'], {}), '(-rad / 2)\n', (7731, 7741), True, 'import numpy as np\n'), ((7808, 7824), 'numpy.cos', 'np.cos', (['(-rad / 2)'], {}), '(-rad / 2)\n', (7814, 7824), True, 'import numpy as np\n'), ((7827, 7843), 'numpy.sin', 'np.sin', (['(-rad / 2)'], {}), '(-rad / 2)\n', (7833, 7843), True, 'import numpy as np\n'), ((18221, 18263), 'torch.cat', 'torch.cat', (['(image_pred, alpha_pred)'], {'dim': '(3)'}), '((image_pred, alpha_pred), dim=3)\n', (18230, 18263), False, 'import torch\n'), ((22295, 22310), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (22308, 22310), False, 'import torch\n'), ((24698, 24809), 'torch.nn.functional.interpolate', 'F.interpolate', (['pred_tex'], {'size': '(renderer_res // 8, renderer_res // 8)', 'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(pred_tex, size=(renderer_res // 8, renderer_res // 8), mode=\n 'bilinear', align_corners=False)\n", (24711, 24809), True, 'import torch.nn.functional as F\n'), ((28508, 28523), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (28521, 28523), False, 'import torch\n'), ((8000, 8016), 'numpy.cos', 'np.cos', (['(-rad / 2)'], {}), '(-rad / 2)\n', (8006, 8016), True, 'import numpy as np\n'), ((8022, 8038), 'numpy.sin', 'np.sin', (['(-rad / 2)'], {}), '(-rad / 2)\n', (8028, 8038), True, 'import numpy as np\n'), ((21886, 21902), 'utils.fid.init_inception', 'init_inception', ([], {}), '()\n', (21900, 21902), False, 'from utils.fid import calculate_stats, init_inception, forward_inception_batch\n'), ((26804, 26840), 'os.path.join', 'os.path.join', (['pseudogt_dir', 'f"""{idx}"""'], {}), "(pseudogt_dir, f'{idx}')\n", (26816, 26840), False, 'import os\n'), ((22541, 22576), 'torch.zeros_like', 'torch.zeros_like', (['vertices[..., :1]'], {}), '(vertices[..., :1])\n', (22557, 22576), False, 'import torch\n'), ((25527, 25625), 'torch.nn.functional.interpolate', 'F.interpolate', (['visibility_mask', 'args.pseudogt_resolution'], {'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(visibility_mask, args.pseudogt_resolution, mode='bilinear',\n align_corners=False)\n", (25540, 25625), True, 'import torch.nn.functional as F\n')]
from __future__ import print_function from ipywidgets import interact, interactive, fixed, interact_manual from ipywidgets import GridspecLayout import ipywidgets as widgets from IPython.display import display from IPython.display import clear_output from plotly.subplots import make_subplots import plotly.express as px import plotly.offline as pyo import plotly.io as pio import plotly.express as px import plotly.graph_objects as go import matplotlib.pyplot as plt from matplotlib import colors,ticker,cm import matplotlib from sklearn import datasets, linear_model from _plotly_future_ import v4_subplots import plotly.offline as pyo import plotly.graph_objs as go import plotly import numpy as np from scipy.stats import gaussian_kde from scipy import stats import pandas as pd from pyLPM import utils import math ############################################################################################################# def plot_experimental_variogram(dfs, azm,dip): size_row = 1 if len(azm) < 4 else int(math.ceil(len(azm)/4)) size_cols = 4 if len(azm) >= 4 else int(len(azm)) titles = ["Azimuth {} - Dip {}".format(azm[j], dip[j]) for j in range(len(azm))] fig = make_subplots(rows=size_row, cols=size_cols, subplot_titles=titles) count_row = 1 count_cols = 1 for j, i in enumerate(dfs): fig.add_trace(go.Scatter(x=i['Average distance'], y=i['Spatial continuity'], mode='markers', name='Experimental' , marker= dict(color =i['Number of pairs']), text =i['Number of pairs'], textposition='bottom center') , row=count_row, col=count_cols) fig.update_xaxes(title_text="Distance", row=count_row, col=count_cols, automargin = True) fig.update_yaxes(title_text="Variogram", row=count_row, col=count_cols, automargin=True) fig.update_layout(autosize=True) count_cols += 1 if count_cols > 4: count_cols = 1 count_row += 1 fig.show() return (dfs) ############################################################################################################# def plot_hscat(store, lagsize, lagmultiply, figsize): """Plots h scatterplot Args: store ([type]): [description] lagsize (float): lag size lagmultiply (int): how many lags to plot """ distance =[i*lagsize for i in lagmultiply] fig = go.Figure() statitics = "" annotations = [] for j, i in enumerate(store): # Create linear regression object if len(i[0]) != 0: slope, intercept, r_value, p_value, std_err = stats.linregress(i[0],i[1]) statitics = statitics +''' rho ({}) / distance {} <br />'''.format(str(np.round(r_value,2)), str(distance[j])) x_val = np.linspace(0, np.max(i[0]), 100) y_val = slope*x_val + intercept else: x_val = [] y_val =[] fig.add_trace(go.Scatter(x=i[0], y=i[1], mode='markers', name='Hscatter - distance {}'.format(str(distance[j])))) fig.add_trace(go.Scatter(x=x_val, y=y_val, mode= 'lines', name = 'Regression - distance {}'.format(str(distance[j])), line= dict(width=3))) fig.layout = { 'title':'Hscatter plots', 'xaxis':{'title':'Z(x)','zeroline':True,'autorange':True}, 'yaxis':{'title':'Z(x+h)','zeroline':True,'autorange':True}, 'annotations':[{'text':statitics,'showarrow':False,'x':0.98,'y':0.98,'xref':'paper','yref':'paper','align':'left','yanchor':'top','bgcolor':'white','bordercolor':'black'}], 'width':figsize[0], 'height':figsize[1], } fig['layout'].update(annotations =annotations) fig.show() ############################################################################################################# def weighted_avg_and_var(values, weights): """Calculates weighted average and variance Args: values (array): data values array weights (array): weight values array Returns: array: average, variance """ average = np.average(values, weights=weights) # Fast and numerically precise: variance = np.average((values-average)**2, weights=weights) return average, variance def isotopic_arrays(arrays): """Extract isotopic group from arrays Args: arrays (array): data values nd array Returns: arrays: nd idotopic arrays """ masks = [] for array in arrays: masks.append(np.isnan(array)) mask = sum(masks) masked_arrays = [] for array in arrays: masked_var = np.ma.array(array, mask=mask).compressed() masked_arrays.append(masked_var) return masked_arrays ############################################################################################################# def locmap(x, y, variable, categorical=False, title='', x_axis='Easting (m)', y_axis='Northing (m)', pointsize=8, colorscale='Jet', colorbartitle='', figsize=(700,700)): """Plots a location map for samples Args: x (array): x values array y (array): y values array variable (array): variables values array categorical (bool, optional): Categorical variable flag. Defaults to False. title (str, optional): Plot title. Defaults to ''. x_axis (str, optional): x axis title. Defaults to 'Easting (m)'. y_axis (str, optional): y axis title. Defaults to 'Northing (m)'. pointsize (int, optional): point size. Defaults to 8. colorscale (str, optional): color scale. Defaults to 'Jet'. colorbartitle (str, optional): colorbar title. Defaults to ''. figsize (tuple, optional): figure size. Defaults to (700,700). Returns: iplot: Location map """ variable = np.where(variable == -999.0, float('nan'), variable) traces = [] if categorical == True: cats = np.unique(variable[~np.isnan(variable)]) for cat in cats: mask = variable == cat trace = { 'type':'scatter', 'mode':'markers', 'x':x[mask], 'y':y[mask], 'marker':{'size':pointsize}, 'text':variable[mask], 'name':str(int(cat)), } traces.append(trace) else: trace = { 'type':'scatter', 'mode':'markers', 'x':x, 'y':y, 'marker':{'size':pointsize,'color':variable,'colorscale':colorscale,'showscale':True,'colorbar':{'title':colorbartitle}}, 'text':variable } traces.append(trace) layout = { 'title':title, 'xaxis':{'title':x_axis,'scaleanchor':'y','zeroline':False}, 'yaxis':{'title':y_axis,'zeroline':False}, 'width':figsize[0], 'height':figsize[1], } fig = go.Figure(traces, layout) return pyo.iplot(fig) def histogram(data, n_bins=20, wt=None, title='', x_axis='', y_axis='', cdf=False, figsize=(700,700)): """Histogram plot Args: data (array): data values array n_bins (int, optional): number of bins. Defaults to 20. wt (array, optional): weights values array. Defaults to None. title (str, optional): plot title. Defaults to ''. x_axis (str, optional): x axis title. Defaults to ''. y_axis (str, optional): y axis title. Defaults to ''. cdf (bool, optional): cdf flag. Defaults to False. figsize (tuple, optional): figure size. Defaults to (700,700). Returns: iplot: histogram plot """ dataf = np.where(data == -999.0, float('nan'), data) dataf = data[~np.isnan(data)] statistics = ''' n {} <br /> min {} <br /> max {} <br /> mean {} <br /> stdev {} <br /> cv {} '''.format(round(len(dataf),0), round(dataf.min(),2), round(dataf.max(),2), round(dataf.mean(),2), round(np.sqrt(dataf.var()),2), round(np.sqrt(dataf.var())/dataf.mean(),2)) if wt is not None: mean, var = weighted_avg_and_var(dataf, wt) statistics = ''' n {} <br /> min {} <br /> max {} <br /> mean {} <br /> stdev {} <br /> cv {} <br /> weighted '''.format(round(len(dataf),0), round(dataf.min(),2), round(dataf.max(),2), round(mean,2), round(np.sqrt(var),2), round(np.sqrt(var)/mean),2) traces = [] hist, bin_edges = np.histogram(dataf, bins=n_bins, weights=wt, density=True) hist = hist*np.diff(bin_edges) trace = { 'type':'bar', 'x':bin_edges, 'y':hist, 'name':'pdf' } traces.append(trace) if cdf == True: hist = np.cumsum(hist) trace = { 'type':'bar', 'x':bin_edges, 'y':hist, 'name':'cdf' } traces.append(trace) layout = { 'title':title, 'xaxis':{'title':x_axis}, 'yaxis':{'title':y_axis}, 'width':figsize[0], 'height':figsize[1], 'barmode':'group', 'annotations':[{'text':statistics,'showarrow':False,'x':0.98,'y':0.98,'xref':'paper','yref':'paper','align':'left','yanchor':'top','bgcolor':'white','bordercolor':'black'}] } fig = go.Figure(traces, layout) return pyo.iplot(fig) def scatter2d(x, y, variable='kernel density', xy_line = True, best_fit_line=True, title='', x_axis='', y_axis='', pointsize=8, colorscale='Viridis', colorbartitle='', figsize=(700,700)): """2D scatter plot Args: x (array): x variable data array y (array): y variable data array variable (str, optional): variable to color points. Defaults to 'kernel density'. xy_line (bool, optional): x=y line flag. Defaults to True. best_fit_line (bool, optional): best fit line flag. Defaults to True. title (str, optional): plot title. Defaults to ''. x_axis (str, optional): x axis title. Defaults to ''. y_axis (str, optional): y axis title. Defaults to ''. pointsize (int, optional): point size. Defaults to 8. colorscale (str, optional): color scale. Defaults to 'Viridis'. colorbartitle (str, optional): color bar title. Defaults to ''. figsize (tuple, optional): figure size. Defaults to (700,700). Returns: iplot: 2D scatter plot """ x = np.where(x == -999.0, float('nan'), x) y = np.where(y == -999.0, float('nan'), y) x, y = isotopic_arrays([x,y])[0], isotopic_arrays([x,y])[1] statistics = ''' n {} <br /> rho {} '''.format(round(len(x),0), round(np.corrcoef([x,y])[1,0],2)) if best_fit_line == True: slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) statistics = ''' n {} <br /> rho {} <br /> slope {} <br /> intercept {} '''.format(round(len(x),0), round(np.corrcoef([x,y])[1,0],2), round(slope,2), round(intercept,2)) if type(variable) is not str: variable = np.where(variable == -999.0, float('nan'), variable) else: xy = np.vstack([x,y]) variable = gaussian_kde(xy)(xy) traces = [] trace = { 'type':'scatter', 'mode':'markers', 'x':x, 'y':y, 'marker':{'size':pointsize,'color':variable,'colorscale':colorscale,'showscale':False,'colorbar':{'title':colorbartitle}}, 'text':variable, 'name':'Scatter' } traces.append(trace) if xy_line == True: maxxy = [max(x), max(y)] trace = { 'type':'scatter', 'mode':'lines', 'x':[0,max(maxxy)], 'y':[0,max(maxxy)], 'name':'x=y line', 'line':{'dash':'dot','color':'red'} } traces.append(trace) if best_fit_line == True: maxxy = [max(x), max(y)] minxy = [min(x), min(y)] vals = np.arange(min(minxy),max(maxxy)) trace = { 'type':'scatter', 'mode':'lines', 'x':vals, 'y':slope*vals+intercept, 'name':'best fit line', 'line':{'dash':'dot','color':'grey'} } traces.append(trace) layout = { 'title':title, 'xaxis':{'title':x_axis,'zeroline':True,'autorange':True}, 'yaxis':{'title':y_axis,'zeroline':True,'autorange':True}, 'width':figsize[0], 'height':figsize[1], 'annotations':[{'text':statistics,'showarrow':False,'x':0.98,'y':0.98,'xref':'paper','yref':'paper','align':'left','yanchor':'top','bgcolor':'white','bordercolor':'black'}], } fig = go.Figure(traces, layout) return pyo.iplot(fig) def cell_declus_sum(cell_size, mean, title='Cell declus summary', pointsize=8, figsize=(600,600)): """Cell declustering summary plot Args: cell_size (array): cell sizes values array mean (array): mean values array title (str, optional): plt title. Defaults to 'Cell declus summary'. pointsize (int, optional): point size. Defaults to 8. figsize (tuple, optional): figure size. Defaults to (600,600). Returns: iplot: cell declus summary plot """ index = np.where(mean == min(mean))[0][0] text_annotation = ''' cell size {} <br /> mean {} '''.format(round(cell_size[index],2), round(min(mean),2)) trace = { 'type':'scatter', 'mode':'markers', 'x':cell_size, 'y':mean, 'marker':{'size':pointsize}, } layout = { 'title':title, 'xaxis':{'title':'cell size','zeroline':True,'autorange':True}, 'yaxis':{'title':'mean','zeroline':True,'autorange':True}, 'width':figsize[0], 'height':figsize[1], 'annotations':[{'text':text_annotation,'showarrow':True,'arrowhead':7,'ax':0,'ay':-0.5*min(mean),'x':cell_size[index],'y':min(mean),'xref':'x','yref':'y','align':'left','yanchor':'top','bgcolor':'white','bordercolor':'black'}], } fig = go.Figure([trace], layout) return pyo.iplot(fig) def pixelplot(grid_dic, variable, categorical=False, points=None, gap=0, title='', x_axis='Easting (m)', y_axis='Northing (m)', colorscale='Jet', colorbartitle='', figsize=(700,700)): """Pixel plot for gridded data Args: grid_dic (dict): grid definitions dictionary variable (array): data values array categorical (bool, optional): categorical data flag. Defaults to False. points (lst, optional): [x,y,z,var] list to plot points on top of grid. Defaults to None. gap (int, optional): gap between blocks. Defaults to 0. title (str, optional): plt title. Defaults to ''. x_axis (str, optional): x axis title. Defaults to 'Easting (m)'. y_axis (str, optional): y axis title. Defaults to 'Northing (m)'. colorscale (str, optional): color scale. Defaults to 'Jet'. colorbartitle (str, optional): color bar title. Defaults to ''. figsize (tuple, optional):figure size. Defaults to (700,700). Returns: iplot: pixel plot """ variable = np.where(variable == -999, float('nan'), variable) traces = [] x = np.array([(grid_dic['ox']+i*grid_dic['sx']) for i in range(grid_dic['nx'])]) y = np.array([(grid_dic['oy']+j*grid_dic['sy']) for j in range(grid_dic['ny'])]) trace = { 'type':'heatmap', 'z':variable.reshape(grid_dic['ny'], grid_dic['nx']), 'x':x, 'y':y, 'colorscale':colorscale, 'xgap':gap, 'ygap':gap } traces.append(trace) if points is not None: trace = { 'type':'scatter', 'mode':'markers', 'x':points[0], 'y':points[1], 'marker':{'colorscale':colorscale,'size':6,'color':points[2],'line':{'color':'black','width':1}}, 'text':variable} traces.append(trace) layout = { 'title':title, 'xaxis':{'title':x_axis,'zeroline':False,'scaleanchor':'y'}, 'yaxis':{'title':y_axis,'zeroline':False}, 'width':figsize[0], 'height':figsize[1], } fig = go.Figure(traces, layout) return pyo.iplot(fig) def qqplot(x,y, dicretization=100, title='', x_axis='', y_axis='', pointsize=8, figsize=(700,700)): """QQ plot Args: x (array): x variable data array y (array): y variable data array dicretization (int, optional): number of quantiles to plot. Defaults to 100. title (str, optional): plot title. Defaults to ''. x_axis (str, optional): x axis title. Defaults to ''. y_axis (str, optional): y axis title. Defaults to ''. pointsize (int, optional): point size. Defaults to 8. figsize (tuple, optional): figure size. Defaults to (700,700). Returns: iplot: QQ plot """ x = np.where(x == -999.0, float('nan'), x) y = np.where(y == -999.0, float('nan'), y) x_quant = [np.nanquantile(np.array(x), q) for q in np.linspace(0,1,dicretization)] y_quant = [np.nanquantile(np.array(y), q) for q in np.linspace(0,1,dicretization)] traces = [] maxxy = [max(x_quant), max(y_quant)] minxy = [min(x_quant), min(y_quant)] trace = { 'type':'scatter', 'mode':'lines', 'x':[min(minxy),max(maxxy)], 'y':[min(minxy),max(maxxy)], 'name':'reference', 'line':{'dash':'dot','color':'grey'} } traces.append(trace) trace = { 'type':'scatter', 'mode':'lines', 'x':x_quant, 'y':y_quant, 'name':'qq', #'line':{'dash':'dot','color':'grey'} } traces.append(trace) layout = { 'title':title, 'xaxis':{'title':x_axis,'zeroline':True,'autorange':False,'range':[min(minxy),max(maxxy)]}, 'yaxis':{'title':y_axis,'zeroline':True,'autorange':False,'range':[min(minxy),max(maxxy)]}, 'width':figsize[0], 'height':figsize[1], #'annotations':[{'text':statistics,'showarrow':False,'x':0.98,'y':0.98,'xref':'paper','yref':'paper','align':'left','yanchor':'top','bgcolor':'white','bordercolor':'black'}], } fig = go.Figure(traces, layout) return pyo.iplot(fig) def xval(real, estimate, error, pointsize=8, figsize=(500,900)): """Cross validation results summary Args: real (array): true values array estimate (array): estimated values array error (array): real - estimates array pointsize (int, optional): point size. Defaults to 8. figsize (tuple, optional): figure size. Defaults to (500,900). Returns: iplot: cross validation summary """ fig = plotly.subplots.make_subplots(rows=1, cols=3) real = np.where(real == -999.0, float('nan'), real) estimate = np.where(estimate == -999.0, float('nan'), estimate) slope, intercept, r_value, p_value, std_err = stats.linregress(real,estimate) trace = { 'type':'scatter', 'mode':'markers', 'x':real, 'y':estimate, 'marker':{'size':pointsize}, 'name':'True x Estimates' } fig.append_trace(trace, 1, 1) maxxy = [max(real), max(estimate)] minxy = [min(real), min(estimate)] vals = np.arange(min(minxy),max(maxxy)) trace = { 'type':'scatter', 'mode':'lines', 'x':vals, 'y':slope*vals+intercept, 'name':'best fit line', 'line':{'dash':'dot','color':'grey'} } fig.append_trace(trace, 1, 1) maxxy = [max(real), max(estimate)] trace = { 'type':'scatter', 'mode':'lines', 'x':[0,max(maxxy)], 'y':[0,max(maxxy)], 'name':'x=y line', 'line':{'dash':'dot','color':'red'} } fig.append_trace(trace, 1, 1) hist, bin_edges = np.histogram(error, bins=20, density=True) hist = hist*np.diff(bin_edges) trace = { 'type':'bar', 'x':bin_edges, 'y':hist, 'name':'error histogram' } fig.append_trace(trace, 1, 2) trace = { 'type':'scatter', 'mode':'markers', 'x':real, 'y':error, 'marker':{'size':pointsize}, 'name':'True x Error' } fig.append_trace(trace, 1, 3) statistics = ''' n {} <br /> min {} <br /> max {} <br /> mean {} <br /> stdev {} <br /> cv {} <br /> rho {} <br /> slope {} '''.format(round(len(error),0), round(error.min(),2), round(error.max(),2), round(error.mean(),2), round(np.sqrt(error.var()),2), round(np.sqrt(error.var())/error.mean(),2), round(np.corrcoef([real,estimate])[1,0],2), round(slope,2)) fig.layout.update(annotations=[{'text':statistics,'showarrow':False,'x':0.98,'y':0.98,'xref':'paper','yref':'paper','align':'left','yanchor':'top','bgcolor':'white','bordercolor':'black'}]) fig.layout.update(title='Cross validation results') return pyo.iplot(fig) def swath_plots(x,y,z,point_var,grid,grid_var,n_bins=10): """Swath plots in x, y and z Args: x (array): x coordinates array y (array): y coordinates array z (array): z coordinates array point_var (array): point variable array grid (dict): grid definitions dictionary grid_var (array): gridded variable array n_bins (int, optional): number of bins. Defaults to 10. Returns: iplot: swath plots """ mask_pt = np.isfinite(point_var) mask_grid = np.isfinite(grid_var) if z is None: z = np.zeros(len(x)) x, y, z = np.array(x)[mask_pt], np.array(y)[mask_pt], np.array(z)[mask_pt] point_var, grid_var = np.array(point_var)[mask_pt], np.array(grid_var)[mask_grid] points_df = pd.DataFrame(columns=['x','y','z','var']) points_df['x'], points_df['y'], points_df['z'], points_df['var'] = x, y, z, point_var grid_df = pd.DataFrame(columns=['x','y','z'], data=utils.add_coord(grid)) #grid_df.sort_values(by=['z','y','x'], inplace=True) grid_df['var'] = grid_var x_linspace, y_linspace, z_linspace = np.linspace(min(grid_df['x']), max(grid_df['x']), n_bins), np.linspace(min(grid_df['y']), max(grid_df['y']), n_bins), np.linspace(min(grid_df['z']), max(grid_df['z']), n_bins) x_grades_pts = [] x_grades_grid = [] x_n_pts = [] for idx, slice in enumerate(x_linspace): if idx != 0: pts_df_filter = (points_df['x'] >= x_linspace[idx-1]) & (points_df['x'] <= x_linspace[idx]) grid_df_filter = (grid_df['x'] >= x_linspace[idx-1]) & (grid_df['x'] <= x_linspace[idx]) x_grades_pts.append(np.mean(points_df[pts_df_filter]['var'])) x_grades_grid.append(np.mean(grid_df[grid_df_filter]['var'])) x_n_pts.append(len(points_df[pts_df_filter]['var'])) y_grades_pts = [] y_grades_grid = [] y_n_pts = [] for idx, slice in enumerate(y_linspace): if idx != 0: pts_df_filter = (points_df['y'] >= y_linspace[idx-1]) & (points_df['y'] <= y_linspace[idx]) grid_df_filter = (grid_df['y'] >= y_linspace[idx-1]) & (grid_df['y'] <= y_linspace[idx]) y_grades_pts.append(np.mean(points_df[pts_df_filter]['var'])) y_grades_grid.append(np.mean(grid_df[grid_df_filter]['var'])) y_n_pts.append(len(points_df[pts_df_filter]['var'])) z_grades_pts = [] z_grades_grid = [] z_n_pts = [] for idx, slice in enumerate(z_linspace): if idx != 0: pts_df_filter = (points_df['z'] >= z_linspace[idx-1]) & (points_df['z'] <= z_linspace[idx]) grid_df_filter = (grid_df['z'] >= z_linspace[idx-1]) & (grid_df['z'] <= z_linspace[idx]) z_grades_pts.append(np.mean(points_df[pts_df_filter]['var'])) z_grades_grid.append(np.mean(grid_df[grid_df_filter]['var'])) z_n_pts.append(len(points_df[pts_df_filter]['var'])) if sum(z) == 0: fig = plotly.subplots.make_subplots(rows=2, cols=1) tracepts = { 'type':'scatter', 'mode':'lines', 'x':x_linspace, 'y':x_grades_pts, 'name':'points in x', 'line':{'dash':'solid','color':'red'}, } tracegrid = { 'type':'scatter', 'mode':'lines', 'x':x_linspace, 'y':x_grades_grid, 'name':'grid in x', 'line':{'dash':'solid','color':'blue'}, } tracenpts = { 'type':'bar', 'x':x_linspace, 'y':np.array(x_n_pts)/max(x_n_pts)*max(x_grades_grid), 'name':'number of points in x', 'hovertext':x_n_pts } fig.append_trace(tracepts, 1, 1) fig.append_trace(tracegrid, 1, 1) fig.append_trace(tracenpts, 1, 1) tracepts = { 'type':'scatter', 'mode':'lines', 'x':y_linspace, 'y':y_grades_pts, 'name':'points in y', 'line':{'dash':'solid','color':'red'}, } tracegrid = { 'type':'scatter', 'mode':'lines', 'x':y_linspace, 'y':y_grades_grid, 'name':'grid in y', 'line':{'dash':'solid','color':'blue'}, } tracenpts = { 'type':'bar', 'x':y_linspace, 'y':np.array(y_n_pts)/max(y_n_pts)*max(y_grades_grid), 'name':'number of points in y', 'hovertext':y_n_pts } fig.append_trace(tracepts, 2, 1) fig.append_trace(tracegrid, 2, 1) fig.append_trace(tracenpts, 2, 1) fig.layout.update(title='Swath plots') return pyo.iplot(fig)
[ "scipy.stats.linregress", "numpy.sqrt", "plotly.offline.iplot", "numpy.array", "numpy.isfinite", "numpy.mean", "numpy.histogram", "scipy.stats.gaussian_kde", "numpy.diff", "numpy.max", "numpy.linspace", "numpy.vstack", "pandas.DataFrame", "plotly.graph_objs.Figure", "numpy.round", "plo...
[((1199, 1266), 'plotly.subplots.make_subplots', 'make_subplots', ([], {'rows': 'size_row', 'cols': 'size_cols', 'subplot_titles': 'titles'}), '(rows=size_row, cols=size_cols, subplot_titles=titles)\n', (1212, 1266), False, 'from plotly.subplots import make_subplots\n'), ((2456, 2467), 'plotly.graph_objs.Figure', 'go.Figure', ([], {}), '()\n', (2465, 2467), True, 'import plotly.graph_objs as go\n'), ((4238, 4273), 'numpy.average', 'np.average', (['values'], {'weights': 'weights'}), '(values, weights=weights)\n', (4248, 4273), True, 'import numpy as np\n'), ((4325, 4377), 'numpy.average', 'np.average', (['((values - average) ** 2)'], {'weights': 'weights'}), '((values - average) ** 2, weights=weights)\n', (4335, 4377), True, 'import numpy as np\n'), ((7053, 7078), 'plotly.graph_objs.Figure', 'go.Figure', (['traces', 'layout'], {}), '(traces, layout)\n', (7062, 7078), True, 'import plotly.graph_objs as go\n'), ((7091, 7105), 'plotly.offline.iplot', 'pyo.iplot', (['fig'], {}), '(fig)\n', (7100, 7105), True, 'import plotly.offline as pyo\n'), ((8636, 8694), 'numpy.histogram', 'np.histogram', (['dataf'], {'bins': 'n_bins', 'weights': 'wt', 'density': '(True)'}), '(dataf, bins=n_bins, weights=wt, density=True)\n', (8648, 8694), True, 'import numpy as np\n'), ((9466, 9491), 'plotly.graph_objs.Figure', 'go.Figure', (['traces', 'layout'], {}), '(traces, layout)\n', (9475, 9491), True, 'import plotly.graph_objs as go\n'), ((9504, 9518), 'plotly.offline.iplot', 'pyo.iplot', (['fig'], {}), '(fig)\n', (9513, 9518), True, 'import plotly.offline as pyo\n'), ((12868, 12893), 'plotly.graph_objs.Figure', 'go.Figure', (['traces', 'layout'], {}), '(traces, layout)\n', (12877, 12893), True, 'import plotly.graph_objs as go\n'), ((12906, 12920), 'plotly.offline.iplot', 'pyo.iplot', (['fig'], {}), '(fig)\n', (12915, 12920), True, 'import plotly.offline as pyo\n'), ((14208, 14234), 'plotly.graph_objs.Figure', 'go.Figure', (['[trace]', 'layout'], {}), '([trace], layout)\n', (14217, 14234), True, 'import plotly.graph_objs as go\n'), ((14247, 14261), 'plotly.offline.iplot', 'pyo.iplot', (['fig'], {}), '(fig)\n', (14256, 14261), True, 'import plotly.offline as pyo\n'), ((16338, 16363), 'plotly.graph_objs.Figure', 'go.Figure', (['traces', 'layout'], {}), '(traces, layout)\n', (16347, 16363), True, 'import plotly.graph_objs as go\n'), ((16376, 16390), 'plotly.offline.iplot', 'pyo.iplot', (['fig'], {}), '(fig)\n', (16385, 16390), True, 'import plotly.offline as pyo\n'), ((18301, 18326), 'plotly.graph_objs.Figure', 'go.Figure', (['traces', 'layout'], {}), '(traces, layout)\n', (18310, 18326), True, 'import plotly.graph_objs as go\n'), ((18339, 18353), 'plotly.offline.iplot', 'pyo.iplot', (['fig'], {}), '(fig)\n', (18348, 18353), True, 'import plotly.offline as pyo\n'), ((18820, 18865), 'plotly.subplots.make_subplots', 'plotly.subplots.make_subplots', ([], {'rows': '(1)', 'cols': '(3)'}), '(rows=1, cols=3)\n', (18849, 18865), False, 'import plotly\n'), ((19041, 19073), 'scipy.stats.linregress', 'stats.linregress', (['real', 'estimate'], {}), '(real, estimate)\n', (19057, 19073), False, 'from scipy import stats\n'), ((19874, 19916), 'numpy.histogram', 'np.histogram', (['error'], {'bins': '(20)', 'density': '(True)'}), '(error, bins=20, density=True)\n', (19886, 19916), True, 'import numpy as np\n'), ((20948, 20962), 'plotly.offline.iplot', 'pyo.iplot', (['fig'], {}), '(fig)\n', (20957, 20962), True, 'import plotly.offline as pyo\n'), ((21465, 21487), 'numpy.isfinite', 'np.isfinite', (['point_var'], {}), '(point_var)\n', (21476, 21487), True, 'import numpy as np\n'), ((21504, 21525), 'numpy.isfinite', 'np.isfinite', (['grid_var'], {}), '(grid_var)\n', (21515, 21525), True, 'import numpy as np\n'), ((21755, 21799), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['x', 'y', 'z', 'var']"}), "(columns=['x', 'y', 'z', 'var'])\n", (21767, 21799), True, 'import pandas as pd\n'), ((8711, 8729), 'numpy.diff', 'np.diff', (['bin_edges'], {}), '(bin_edges)\n', (8718, 8729), True, 'import numpy as np\n'), ((8902, 8917), 'numpy.cumsum', 'np.cumsum', (['hist'], {}), '(hist)\n', (8911, 8917), True, 'import numpy as np\n'), ((10941, 10963), 'scipy.stats.linregress', 'stats.linregress', (['x', 'y'], {}), '(x, y)\n', (10957, 10963), False, 'from scipy import stats\n'), ((11318, 11335), 'numpy.vstack', 'np.vstack', (['[x, y]'], {}), '([x, y])\n', (11327, 11335), True, 'import numpy as np\n'), ((19933, 19951), 'numpy.diff', 'np.diff', (['bin_edges'], {}), '(bin_edges)\n', (19940, 19951), True, 'import numpy as np\n'), ((23957, 24002), 'plotly.subplots.make_subplots', 'plotly.subplots.make_subplots', ([], {'rows': '(2)', 'cols': '(1)'}), '(rows=2, cols=1)\n', (23986, 24002), False, 'import plotly\n'), ((25577, 25591), 'plotly.offline.iplot', 'pyo.iplot', (['fig'], {}), '(fig)\n', (25586, 25591), True, 'import plotly.offline as pyo\n'), ((2675, 2703), 'scipy.stats.linregress', 'stats.linregress', (['i[0]', 'i[1]'], {}), '(i[0], i[1])\n', (2691, 2703), False, 'from scipy import stats\n'), ((4657, 4672), 'numpy.isnan', 'np.isnan', (['array'], {}), '(array)\n', (4665, 4672), True, 'import numpy as np\n'), ((7866, 7880), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (7874, 7880), True, 'import numpy as np\n'), ((11354, 11370), 'scipy.stats.gaussian_kde', 'gaussian_kde', (['xy'], {}), '(xy)\n', (11366, 11370), False, 'from scipy.stats import gaussian_kde\n'), ((17184, 17195), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (17192, 17195), True, 'import numpy as np\n'), ((17209, 17241), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'dicretization'], {}), '(0, 1, dicretization)\n', (17220, 17241), True, 'import numpy as np\n'), ((17271, 17282), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (17279, 17282), True, 'import numpy as np\n'), ((17296, 17328), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'dicretization'], {}), '(0, 1, dicretization)\n', (17307, 17328), True, 'import numpy as np\n'), ((21587, 21598), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (21595, 21598), True, 'import numpy as np\n'), ((21609, 21620), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (21617, 21620), True, 'import numpy as np\n'), ((21631, 21642), 'numpy.array', 'np.array', (['z'], {}), '(z)\n', (21639, 21642), True, 'import numpy as np\n'), ((21678, 21697), 'numpy.array', 'np.array', (['point_var'], {}), '(point_var)\n', (21686, 21697), True, 'import numpy as np\n'), ((21708, 21726), 'numpy.array', 'np.array', (['grid_var'], {}), '(grid_var)\n', (21716, 21726), True, 'import numpy as np\n'), ((21943, 21964), 'pyLPM.utils.add_coord', 'utils.add_coord', (['grid'], {}), '(grid)\n', (21958, 21964), False, 'from pyLPM import utils\n'), ((2867, 2879), 'numpy.max', 'np.max', (['i[0]'], {}), '(i[0])\n', (2873, 2879), True, 'import numpy as np\n'), ((4765, 4794), 'numpy.ma.array', 'np.ma.array', (['array'], {'mask': 'mask'}), '(array, mask=mask)\n', (4776, 4794), True, 'import numpy as np\n'), ((8551, 8563), 'numpy.sqrt', 'np.sqrt', (['var'], {}), '(var)\n', (8558, 8563), True, 'import numpy as np\n'), ((10828, 10847), 'numpy.corrcoef', 'np.corrcoef', (['[x, y]'], {}), '([x, y])\n', (10839, 10847), True, 'import numpy as np\n'), ((20630, 20659), 'numpy.corrcoef', 'np.corrcoef', (['[real, estimate]'], {}), '([real, estimate])\n', (20641, 20659), True, 'import numpy as np\n'), ((22639, 22679), 'numpy.mean', 'np.mean', (["points_df[pts_df_filter]['var']"], {}), "(points_df[pts_df_filter]['var'])\n", (22646, 22679), True, 'import numpy as np\n'), ((22714, 22753), 'numpy.mean', 'np.mean', (["grid_df[grid_df_filter]['var']"], {}), "(grid_df[grid_df_filter]['var'])\n", (22721, 22753), True, 'import numpy as np\n'), ((23189, 23229), 'numpy.mean', 'np.mean', (["points_df[pts_df_filter]['var']"], {}), "(points_df[pts_df_filter]['var'])\n", (23196, 23229), True, 'import numpy as np\n'), ((23264, 23303), 'numpy.mean', 'np.mean', (["grid_df[grid_df_filter]['var']"], {}), "(grid_df[grid_df_filter]['var'])\n", (23271, 23303), True, 'import numpy as np\n'), ((23739, 23779), 'numpy.mean', 'np.mean', (["points_df[pts_df_filter]['var']"], {}), "(points_df[pts_df_filter]['var'])\n", (23746, 23779), True, 'import numpy as np\n'), ((23814, 23853), 'numpy.mean', 'np.mean', (["grid_df[grid_df_filter]['var']"], {}), "(grid_df[grid_df_filter]['var'])\n", (23821, 23853), True, 'import numpy as np\n'), ((6105, 6123), 'numpy.isnan', 'np.isnan', (['variable'], {}), '(variable)\n', (6113, 6123), True, 'import numpy as np\n'), ((8574, 8586), 'numpy.sqrt', 'np.sqrt', (['var'], {}), '(var)\n', (8581, 8586), True, 'import numpy as np\n'), ((11119, 11138), 'numpy.corrcoef', 'np.corrcoef', (['[x, y]'], {}), '([x, y])\n', (11130, 11138), True, 'import numpy as np\n'), ((24503, 24520), 'numpy.array', 'np.array', (['x_n_pts'], {}), '(x_n_pts)\n', (24511, 24520), True, 'import numpy as np\n'), ((25258, 25275), 'numpy.array', 'np.array', (['y_n_pts'], {}), '(y_n_pts)\n', (25266, 25275), True, 'import numpy as np\n'), ((2790, 2810), 'numpy.round', 'np.round', (['r_value', '(2)'], {}), '(r_value, 2)\n', (2798, 2810), True, 'import numpy as np\n')]
import numpy as np from tensorgraph.graph import Placeholder from tensorgraph.graph import Operation from tensorgraph.graph import Variable class Session: """Represents a particular execution of a computational graph. """ @staticmethod def run(operation, feed_dict={}): """Computes the output of an operation Args: operation: The operation whose output we'd like to compute. feed_dict: A dictionary that maps placeholders to values for this session """ nodes_post_order = traverse_post_order(operation) for node in nodes_post_order: if type(node) == Placeholder: node.output = feed_dict[node] elif type(node) == Variable: node.output = node.value else: node.inputs = [input_node.output for input_node in node.input_nodes] node.output = node.compute(*node.inputs) # print(type(node), node.output) # print(type(node), node.output) if type(node.output) == list: node.output = np.array(node.output) return operation.output def traverse_post_order(operation): """Performs a post-order traversal, returning a list of nodes in the order in which they have to be computed Args: operation: The operation to start traversal at """ nodes_post_order = [] def recurse(node): if isinstance(node, Operation): for input_node in node.input_nodes: recurse(input_node) # if node.name is not None: # print(node.name) nodes_post_order.append(node) recurse(operation) return nodes_post_order
[ "numpy.array" ]
[((1116, 1137), 'numpy.array', 'np.array', (['node.output'], {}), '(node.output)\n', (1124, 1137), True, 'import numpy as np\n')]
import os import pandas as pd import numpy as np import seaborn as sns from matplotlib import pyplot as plt import warnings warnings.filterwarnings("ignore") def read_p1(problem_name): x = pd.read_csv(os.path.join("data", "p1", f"p1_{problem_name}_X.dat"), sep=" ", header=None, engine='python') y = pd.read_csv(os.path.join("data", "p1", f"p1_{problem_name}_y.dat"), header=None) y = y.values.reshape((-1,)) x = x.values return x, y def plot_points(x, y): sns.scatterplot( x=x[:, 0], y=x[:, 1], hue=y, palette=sns.color_palette("muted", n_colors=2) ) def plot_separator(w, bias): slope = -w[0] / w[1] intercept = -bias / w[1] limits = plt.axes().get_xlim() x = np.arange(limits[0], limits[1]) plt.plot(x, x * slope + intercept, 'k-') theta = np.degrees(np.arctan(slope)) plt.title(rf"$\theta = {theta:.2f}$") plt.legend(loc='best') def plot_svm_margin(w): margin = 1.0 / np.linalg.norm(w) title = plt.axes().get_title() plt.title(rf"{title} margin={margin:2f}") def plot_perceptron_margin(x, w, epochs): distances = [np.dot(entry, w) / np.linalg.norm(w) for entry in x] min_positive_distance = abs(min([d for d in distances if d > 0])) max_negative_distance = abs(max([d for d in distances if d < 0])) title = plt.axes().get_title() plt.title(rf"{title} + margin {min_positive_distance:2f}, - margin {max_negative_distance:2f} epochs {epochs}") def plot_support_vectors(x, support_vectors): sns.scatterplot( x=x[support_vectors, 0], y=x[support_vectors, 1], marker="P", s=100, c=['C8'], label='support vectors' ) plt.legend(loc='best') def save_plot(filename, extension="eps"): file_path = os.path.join("plots", f"{filename}.{extension}") with open(file_path, 'w') as f: plt.savefig(file_path)
[ "matplotlib.pyplot.savefig", "seaborn.color_palette", "numpy.arange", "matplotlib.pyplot.plot", "os.path.join", "numpy.dot", "matplotlib.pyplot.axes", "seaborn.scatterplot", "numpy.linalg.norm", "matplotlib.pyplot.title", "warnings.filterwarnings", "matplotlib.pyplot.legend", "numpy.arctan" ...
[((127, 160), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (150, 160), False, 'import warnings\n'), ((753, 784), 'numpy.arange', 'np.arange', (['limits[0]', 'limits[1]'], {}), '(limits[0], limits[1])\n', (762, 784), True, 'import numpy as np\n'), ((789, 829), 'matplotlib.pyplot.plot', 'plt.plot', (['x', '(x * slope + intercept)', '"""k-"""'], {}), "(x, x * slope + intercept, 'k-')\n", (797, 829), True, 'from matplotlib import pyplot as plt\n'), ((876, 913), 'matplotlib.pyplot.title', 'plt.title', (['f"""$\\\\theta = {theta:.2f}$"""'], {}), "(f'$\\\\theta = {theta:.2f}$')\n", (885, 913), True, 'from matplotlib import pyplot as plt\n'), ((919, 941), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (929, 941), True, 'from matplotlib import pyplot as plt\n'), ((1045, 1085), 'matplotlib.pyplot.title', 'plt.title', (['f"""{title} margin={margin:2f}"""'], {}), "(f'{title} margin={margin:2f}')\n", (1054, 1085), True, 'from matplotlib import pyplot as plt\n'), ((1383, 1503), 'matplotlib.pyplot.title', 'plt.title', (['f"""{title} + margin {min_positive_distance:2f}, - margin {max_negative_distance:2f} epochs {epochs}"""'], {}), "(\n f'{title} + margin {min_positive_distance:2f}, - margin {max_negative_distance:2f} epochs {epochs}'\n )\n", (1392, 1503), True, 'from matplotlib import pyplot as plt\n'), ((1547, 1671), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': 'x[support_vectors, 0]', 'y': 'x[support_vectors, 1]', 'marker': '"""P"""', 's': '(100)', 'c': "['C8']", 'label': '"""support vectors"""'}), "(x=x[support_vectors, 0], y=x[support_vectors, 1], marker=\n 'P', s=100, c=['C8'], label='support vectors')\n", (1562, 1671), True, 'import seaborn as sns\n'), ((1726, 1748), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (1736, 1748), True, 'from matplotlib import pyplot as plt\n'), ((1809, 1857), 'os.path.join', 'os.path.join', (['"""plots"""', 'f"""{filename}.{extension}"""'], {}), "('plots', f'{filename}.{extension}')\n", (1821, 1857), False, 'import os\n'), ((210, 264), 'os.path.join', 'os.path.join', (['"""data"""', '"""p1"""', 'f"""p1_{problem_name}_X.dat"""'], {}), "('data', 'p1', f'p1_{problem_name}_X.dat')\n", (222, 264), False, 'import os\n'), ((327, 381), 'os.path.join', 'os.path.join', (['"""data"""', '"""p1"""', 'f"""p1_{problem_name}_y.dat"""'], {}), "('data', 'p1', f'p1_{problem_name}_y.dat')\n", (339, 381), False, 'import os\n'), ((854, 870), 'numpy.arctan', 'np.arctan', (['slope'], {}), '(slope)\n', (863, 870), True, 'import numpy as np\n'), ((987, 1004), 'numpy.linalg.norm', 'np.linalg.norm', (['w'], {}), '(w)\n', (1001, 1004), True, 'import numpy as np\n'), ((1902, 1924), 'matplotlib.pyplot.savefig', 'plt.savefig', (['file_path'], {}), '(file_path)\n', (1913, 1924), True, 'from matplotlib import pyplot as plt\n'), ((578, 616), 'seaborn.color_palette', 'sns.color_palette', (['"""muted"""'], {'n_colors': '(2)'}), "('muted', n_colors=2)\n", (595, 616), True, 'import seaborn as sns\n'), ((722, 732), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (730, 732), True, 'from matplotlib import pyplot as plt\n'), ((1017, 1027), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (1025, 1027), True, 'from matplotlib import pyplot as plt\n'), ((1148, 1164), 'numpy.dot', 'np.dot', (['entry', 'w'], {}), '(entry, w)\n', (1154, 1164), True, 'import numpy as np\n'), ((1167, 1184), 'numpy.linalg.norm', 'np.linalg.norm', (['w'], {}), '(w)\n', (1181, 1184), True, 'import numpy as np\n'), ((1355, 1365), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (1363, 1365), True, 'from matplotlib import pyplot as plt\n')]
from typing import Iterable, Sequence import numpy as np from ..layout import Flat from ..io import PathLike @np.deprecate(message='This function is deprecated in favor of `dpipe.layout.Flat`') def flat(split: Iterable[Sequence], config_path: PathLike, experiment_path: PathLike, prefixes: Sequence[str] = ('train', 'val', 'test')): """ Generates an experiment with a 'flat' structure. Creates a subdirectory of ``experiment_path`` for the each entry of ``split``. The subdirectory contains corresponding structure of identifiers. Also, the config file from ``config_path`` is copied to ``experiment_path/resources.config``. Parameters ---------- split: Iterable[Sequence] an iterable with groups of ids. config_path: PathLike the path to the config file. experiment_path: PathLike the path where the experiment will be created. prefixes: Sequence[str] the corresponding prefixes for each identifier group of ``split``. Default is ``('train', 'val', 'test')``. Examples -------- >>> ids = [ >>> [[1, 2, 3], [4, 5, 6], [7, 8]], >>> [[1, 4, 8], [7, 5, 2], [6, 3]], >>> ] >>> flat(ids, 'some_path.config', 'experiments/base') # resulting folder structure: # experiments/base: # - resources.config # - experiment_0: # - train_ids.json # 1, 2, 3 # - val_ids.json # 4, 5, 6 # - test_ids.json # 7, 8 # - experiment_1: # - train_ids.json # 1, 4, 8 # - val_ids.json # 7, 5, 2 # - test_ids.json # 6, 3 """ Flat(split, prefixes=prefixes).build(config_path, experiment_path)
[ "numpy.deprecate" ]
[((114, 202), 'numpy.deprecate', 'np.deprecate', ([], {'message': '"""This function is deprecated in favor of `dpipe.layout.Flat`"""'}), "(message=\n 'This function is deprecated in favor of `dpipe.layout.Flat`')\n", (126, 202), True, 'import numpy as np\n')]
import numpy as np from statsmodels.tools.testing import MarginTableTestBunch est = dict( rank=7, N=17, ic=6, k=7, k_eq=1, k_dv=1, converged=1, rc=0, k_autoCns=0, ll=-28.46285727296058, k_eq_model=1, ll_0=-101.6359341820935, df_m=6, chi2=146.3461538182658, p=4.58013206701e-29, r2_p=.719952814897477, properties="b V", depvar="sexecutions", which="max", technique="nr", singularHmethod="m-marquardt", ml_method="e2", crittype="log likelihood", user="poiss_lf", title="Poisson regression", vce="oim", opt="moptimize", chi2type="LR", gof="poiss_g", estat_cmd="poisson_estat", predict="poisso_p", cmd="poisson", cmdline="poisson sexecutions sincome sperpoverty sperblack LN_VC100k96 south sdegree", # noqa:E501 ) margins_table = np.array([ 47.514189267677, 12.722695157081, 3.7346009380122, .000188013074, 22.578164973516, 72.450213561838, np.nan, 1.9599639845401, 0, 2.3754103372885, 7.6314378245266, .31126642081184, .75559809249357, -12.58193294904, 17.332753623617, np.nan, 1.9599639845401, 0, -11.583732327397, 3.8511214886273, -3.007885459237, .00263072269737, -19.131791745195, -4.0356729095995, np.nan, 1.9599639845401, 0, -1.807106397978, 14.19277372084, -.12732580914219, .89868253380624, -29.624431731551, 26.010218935595, np.nan, 1.9599639845401, 0, 10.852916363139, 2.6197368291491, 4.1427506161617, .00003431650408, 5.7183265290336, 15.987506197244, np.nan, 1.9599639845401, 0, -26.588397789444, 7.6315578612519, -3.4840065780596, .00049396734722, -41.545976343431, -11.630819235457, np.nan, 1.9599639845401, 0]).reshape(6, 9) margins_table_colnames = 'b se z pvalue ll ul df crit eform'.split() margins_table_rownames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', 'south', 'sdegree'] margins_cov = np.array([ 10.87507957467, 3.4816608831283, .87483487811437, 3.1229403520191, -.87306122632875, -2.2870394487277, -12.321063650937, 3.4816608831283, 5.1715652306254, .27473956091394, 1.7908952063684, -.92880259796684, 1.8964947971413, -9.0063087868006, .87483487811437, .27473956091394, 1.1098392181639, -.99390727840297, -.34477731736542, -.98869834020742, .41772084541889, 3.1229403520191, 1.7908952063684, -.99390727840297, 17.912620004361, -.30763138390107, 2.8490197200257, -21.269786576194, -.87306122632875, -.92880259796684, -.34477731736542, -.30763138390107, .42666000427673, .05265352402592, 1.461997775289, -2.2870394487277, 1.8964947971413, -.98869834020742, 2.8490197200257, .05265352402592, 4.0773252373088, -4.46154120848, -12.321063650937, -9.0063087868006, .41772084541889, -21.269786576194, 1.461997775289, -4.46154120848, 37.559994394326]).reshape(7, 7) margins_cov_colnames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', 'south', 'sdegree', '_cons'] margins_cov_rownames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', 'south', 'sdegree', '_cons'] results_poisson_margins_cont = MarginTableTestBunch( margins_table=margins_table, margins_table_colnames=margins_table_colnames, margins_table_rownames=margins_table_rownames, margins_cov=margins_cov, margins_cov_colnames=margins_cov_colnames, margins_cov_rownames=margins_cov_rownames, **est ) est = dict( alpha=1.1399915663048, rank=8, N=17, ic=6, k=8, k_eq=2, k_dv=1, converged=1, rc=0, k_autoCns=0, ll=-27.58269157281191, k_eq_model=1, ll_0=-32.87628220135203, rank0=2, df_m=6, chi2=10.58718125708024, p=.1020042170100994, ll_c=-28.46285727296058, chi2_c=1.760331400297339, r2_p=.1610154881905236, k_aux=1, properties="b V", depvar="sexecutions", which="max", technique="nr", singularHmethod="m-marquardt", ml_method="e2", crittype="log likelihood", user="nbreg_lf", diparm1="lnalpha, exp label(", title="Negative binomial regression", vce="oim", opt="moptimize", chi2type="LR", chi2_ct="LR", diparm_opt2="noprob", dispers="mean", predict="nbreg_p", cmd="nbreg", cmdline="nbreg sexecutions sincome sperpoverty sperblack LN_VC100k96 south sdegree", # noqa:E501 ) margins_table = np.array([ 38.76996449636, 35.863089953808, 1.0810547709719, .27967275079666, -31.520400187424, 109.06032918014, np.nan, 1.9599639845401, 0, 2.5208248279391, 11.710699937092, .21525825454332, .82956597472339, -20.431725282518, 25.473374938396, np.nan, 1.9599639845401, 0, -8.225606184332, 9.557721280021, -.86062419517573, .38944505570119, -26.958395667445, 10.507183298781, np.nan, 1.9599639845401, 0, -4.4150939806524, 28.010544627225, -.15762256819387, .87475421903252, -59.314752637366, 50.484564676062, np.nan, 1.9599639845401, 0, 7.0049476220304, 6.3399264323903, 1.1048941492826, .26920545789466, -5.4210798500881, 19.430975094149, np.nan, 1.9599639845401, 0, -25.128303596214, 23.247820190364, -1.0808885904335, .279746674501, -70.693193888391, 20.436586695964, np.nan, 1.9599639845401, 0]).reshape(6, 9) margins_table_colnames = 'b se z pvalue ll ul df crit eform'.split() margins_table_rownames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', 'south', 'sdegree'] margins_cov = np.array([ 44.468037032422, 13.291812805254, .84306554343753, -.38095027773819, -2.1265212254924, -18.06714825989, -30.427077474507, .36347806905257, 13.291812805254, 15.093124820143, 3.3717840254072, -7.6860995498613, -3.3867901970823, -1.4200645173727, -12.979849717094, .51706617429388, .84306554343753, 3.3717840254072, 5.6928040093481, -12.140553562993, -2.5831646721297, -1.8071496111137, 7.961664784177, .27439267406128, -.38095027773819, -7.6860995498613, -12.140553562993, 91.950706114029, 6.6107070350689, 9.5470604840407, -82.665769963947, -1.1433180909155, -2.1265212254924, -3.3867901970823, -2.5831646721297, 6.6107070350689, 2.0499053083335, 1.7094543055869, -3.029543334606, -.34297224102579, -18.06714825989, -1.4200645173727, -1.8071496111137, 9.5470604840407, 1.7094543055869, 18.442703265156, -6.5839965105886, -.61952491151176, -30.427077474507, -12.979849717094, 7.961664784177, -82.665769963947, -3.029543334606, -6.5839965105886, 111.12618806587, .88600743091011, .36347806905257, .51706617429388, .27439267406128, -1.1433180909155, -.34297224102579, -.61952491151176, .88600743091011, .71851239110057 ]).reshape(8, 8) margins_cov_colnames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', 'south', 'sdegree', '_cons', '_cons'] margins_cov_rownames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', 'south', 'sdegree', '_cons', '_cons'] results_negbin_margins_cont = MarginTableTestBunch( margins_table=margins_table, margins_table_colnames=margins_table_colnames, margins_table_rownames=margins_table_rownames, margins_cov=margins_cov, margins_cov_colnames=margins_cov_colnames, margins_cov_rownames=margins_cov_rownames, **est ) est = dict( rank=7, N=17, ic=6, k=8, k_eq=1, k_dv=1, converged=1, rc=0, k_autoCns=1, ll=-28.46285727296058, k_eq_model=1, ll_0=-101.6359341820935, df_m=6, chi2=146.3461538182658, p=4.58013206701e-29, r2_p=.719952814897477, properties="b V", depvar="sexecutions", which="max", technique="nr", singularHmethod="m-marquardt", ml_method="e2", crittype="log likelihood", user="poiss_lf", title="Poisson regression", vce="oim", opt="moptimize", chi2type="LR", gof="poiss_g", estat_cmd="poisson_estat", predict="poisso_p", cmd="poisson", cmdline="poisson sexecutions sincome sperpoverty sperblack LN_VC100k96 i.south sdegree", # noqa:E501 ) margins_table = np.array([ 47.514189267677, 12.72269515678, 3.7346009381004, .00018801307393, 22.578164974105, 72.450213561249, np.nan, 1.9599639845401, 0, 2.3754103372885, 7.6314378245485, .31126642081095, .75559809249425, -12.581932949083, 17.33275362366, np.nan, 1.9599639845401, 0, -11.583732327397, 3.8511214887188, -3.0078854591656, .00263072269799, -19.131791745374, -4.0356729094203, np.nan, 1.9599639845401, 0, -1.807106397978, 14.192773720841, -.12732580914219, .89868253380624, -29.624431731552, 26.010218935596, np.nan, 1.9599639845401, 0, 0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 1.9599639845401, 0, 12.894515685772, 5.7673506886042, 2.2357779822979, .02536631788468, 1.5907160498956, 24.198315321648, np.nan, 1.9599639845401, 0, -26.588397789444, 7.6315578608763, -3.4840065782311, .00049396734691, -41.545976342695, -11.630819236193, np.nan, 1.9599639845401, 0]).reshape(7, 9) margins_table_colnames = 'b se z pvalue ll ul df crit eform'.split() margins_table_rownames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', '0b.south', '1.south', 'sdegree'] margins_cov = np.array([ 10.875079574674, 3.4816608831298, .87483487811447, 3.1229403520208, 0, -.873061226329, -2.2870394487282, -12.321063650942, 3.4816608831298, 5.1715652306252, .27473956091396, 1.7908952063684, 0, -.92880259796679, 1.8964947971405, -9.0063087868012, .87483487811447, .27473956091396, 1.109839218164, -.9939072784041, 0, -.34477731736544, -.98869834020768, .41772084541996, 3.1229403520208, 1.7908952063684, -.9939072784041, 17.912620004373, 0, -.30763138390086, 2.8490197200274, -21.269786576207, 0, 0, 0, 0, 0, 0, 0, 0, -.873061226329, -.92880259796679, -.34477731736544, -.30763138390086, 0, .42666000427672, .05265352402609, 1.4619977752889, -2.2870394487282, 1.8964947971405, -.98869834020768, 2.8490197200274, 0, .05265352402609, 4.0773252373089, -4.4615412084808, -12.321063650942, -9.0063087868012, .41772084541996, -21.269786576207, 0, 1.4619977752889, -4.4615412084808, 37.559994394343 ]).reshape(8, 8) margins_cov_colnames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', '0b.south', '1.south', 'sdegree', '_cons'] margins_cov_rownames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', '0b.south', '1.south', 'sdegree', '_cons'] results_poisson_margins_dummy = MarginTableTestBunch( margins_table=margins_table, margins_table_colnames=margins_table_colnames, margins_table_rownames=margins_table_rownames, margins_cov=margins_cov, margins_cov_colnames=margins_cov_colnames, margins_cov_rownames=margins_cov_rownames, **est ) est = dict( alpha=1.139991566304804, rank=8, N=17, ic=6, k=9, k_eq=2, k_dv=1, converged=1, rc=0, k_autoCns=1, ll=-27.58269157281191, k_eq_model=1, ll_0=-32.87628220135203, rank0=2, df_m=6, chi2=10.58718125708025, p=.1020042170100991, ll_c=-28.46285727296058, chi2_c=1.760331400297339, r2_p=.1610154881905237, k_aux=1, properties="b V", depvar="sexecutions", which="max", technique="nr", singularHmethod="m-marquardt", ml_method="e2", crittype="log likelihood", user="nbreg_lf", diparm1="lnalpha, exp label(", title="Negative binomial regression", vce="oim", opt="moptimize", chi2type="LR", chi2_ct="LR", diparm_opt2="noprob", dispers="mean", predict="nbreg_p", cmd="nbreg", cmdline="nbreg sexecutions sincome sperpoverty sperblack LN_VC100k96 i.south sdegree", # noqa:E501 ) margins_table = np.array([ 38.769964496355, 35.863089979665, 1.0810547701924, .27967275114341, -31.520400238107, 109.06032923082, np.nan, 1.9599639845401, 0, 2.5208248279388, 11.710699937639, .21525825453324, .82956597473124, -20.43172528359, 25.473374939467, np.nan, 1.9599639845401, 0, -8.2256061843309, 9.5577212853699, -.86062419469397, .38944505596662, -26.958395677928, 10.507183309266, np.nan, 1.9599639845401, 0, -4.4150939806521, 28.010544626815, -.15762256819618, .87475421903071, -59.314752636561, 50.484564675257, np.nan, 1.9599639845401, 0, 0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 1.9599639845401, 0, 8.0380552593041, 8.8634487485248, .90687671214231, .36447199739385, -9.3339850666211, 25.410095585229, np.nan, 1.9599639845401, 0, -25.12830359621, 23.247820207656, -1.0808885896294, .27974667485873, -70.693193922279, 20.436586729858, np.nan, 1.9599639845401, 0]).reshape(7, 9) margins_table_colnames = 'b se z pvalue ll ul df crit eform'.split() margins_table_rownames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', '0b.south', '1.south', 'sdegree'] margins_cov = np.array([ 44.468037032424, 13.291812805256, .84306554343906, -.38095027774827, 0, -2.1265212254934, -18.067148259892, -30.427077474499, .36347806905277, 13.291812805256, 15.093124820144, 3.3717840254072, -7.6860995498609, 0, -3.3867901970823, -1.4200645173736, -12.979849717095, .51706617429393, .84306554343906, 3.3717840254072, 5.6928040093478, -12.14055356299, 0, -2.5831646721296, -1.8071496111144, 7.9616647841741, .27439267406129, -.38095027774827, -7.6860995498609, -12.14055356299, 91.950706114005, 0, 6.6107070350678, 9.5470604840447, -82.665769963921, -1.1433180909154, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2.1265212254934, -3.3867901970823, -2.5831646721296, 6.6107070350678, 0, 2.0499053083335, 1.7094543055874, -3.0295433346046, -.34297224102581, -18.067148259892, -1.4200645173736, -1.8071496111144, 9.5470604840447, 0, 1.7094543055874, 18.442703265157, -6.5839965105912, -.61952491151187, -30.427077474499, -12.979849717095, 7.9616647841741, -82.665769963921, 0, -3.0295433346046, -6.5839965105912, 111.12618806584, .88600743090998, .36347806905277, .51706617429393, .27439267406129, -1.1433180909154, 0, -.34297224102581, -.61952491151187, .88600743090998, .71851239110059]).reshape(9, 9) margins_cov_colnames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', '0b.south', '1.south', 'sdegree', '_cons', '_cons'] margins_cov_rownames = ['sincome', 'sperpoverty', 'sperblack', 'LN_VC100k96', '0b.south', '1.south', 'sdegree', '_cons', '_cons'] results_negbin_margins_dummy = MarginTableTestBunch( margins_table=margins_table, margins_table_colnames=margins_table_colnames, margins_table_rownames=margins_table_rownames, margins_cov=margins_cov, margins_cov_colnames=margins_cov_colnames, margins_cov_rownames=margins_cov_rownames, **est )
[ "numpy.array", "statsmodels.tools.testing.MarginTableTestBunch" ]
[((3512, 3786), 'statsmodels.tools.testing.MarginTableTestBunch', 'MarginTableTestBunch', ([], {'margins_table': 'margins_table', 'margins_table_colnames': 'margins_table_colnames', 'margins_table_rownames': 'margins_table_rownames', 'margins_cov': 'margins_cov', 'margins_cov_colnames': 'margins_cov_colnames', 'margins_cov_rownames': 'margins_cov_rownames'}), '(margins_table=margins_table, margins_table_colnames=\n margins_table_colnames, margins_table_rownames=margins_table_rownames,\n margins_cov=margins_cov, margins_cov_colnames=margins_cov_colnames,\n margins_cov_rownames=margins_cov_rownames, **est)\n', (3532, 3786), False, 'from statsmodels.tools.testing import MarginTableTestBunch\n'), ((7861, 8135), 'statsmodels.tools.testing.MarginTableTestBunch', 'MarginTableTestBunch', ([], {'margins_table': 'margins_table', 'margins_table_colnames': 'margins_table_colnames', 'margins_table_rownames': 'margins_table_rownames', 'margins_cov': 'margins_cov', 'margins_cov_colnames': 'margins_cov_colnames', 'margins_cov_rownames': 'margins_cov_rownames'}), '(margins_table=margins_table, margins_table_colnames=\n margins_table_colnames, margins_table_rownames=margins_table_rownames,\n margins_cov=margins_cov, margins_cov_colnames=margins_cov_colnames,\n margins_cov_rownames=margins_cov_rownames, **est)\n', (7881, 8135), False, 'from statsmodels.tools.testing import MarginTableTestBunch\n'), ((11988, 12262), 'statsmodels.tools.testing.MarginTableTestBunch', 'MarginTableTestBunch', ([], {'margins_table': 'margins_table', 'margins_table_colnames': 'margins_table_colnames', 'margins_table_rownames': 'margins_table_rownames', 'margins_cov': 'margins_cov', 'margins_cov_colnames': 'margins_cov_colnames', 'margins_cov_rownames': 'margins_cov_rownames'}), '(margins_table=margins_table, margins_table_colnames=\n margins_table_colnames, margins_table_rownames=margins_table_rownames,\n margins_cov=margins_cov, margins_cov_colnames=margins_cov_colnames,\n margins_cov_rownames=margins_cov_rownames, **est)\n', (12008, 12262), False, 'from statsmodels.tools.testing import MarginTableTestBunch\n'), ((16731, 17005), 'statsmodels.tools.testing.MarginTableTestBunch', 'MarginTableTestBunch', ([], {'margins_table': 'margins_table', 'margins_table_colnames': 'margins_table_colnames', 'margins_table_rownames': 'margins_table_rownames', 'margins_cov': 'margins_cov', 'margins_cov_colnames': 'margins_cov_colnames', 'margins_cov_rownames': 'margins_cov_rownames'}), '(margins_table=margins_table, margins_table_colnames=\n margins_table_colnames, margins_table_rownames=margins_table_rownames,\n margins_cov=margins_cov, margins_cov_colnames=margins_cov_colnames,\n margins_cov_rownames=margins_cov_rownames, **est)\n', (16751, 17005), False, 'from statsmodels.tools.testing import MarginTableTestBunch\n'), ((1103, 1960), 'numpy.array', 'np.array', (['[47.514189267677, 12.722695157081, 3.7346009380122, 0.000188013074, \n 22.578164973516, 72.450213561838, np.nan, 1.9599639845401, 0, \n 2.3754103372885, 7.6314378245266, 0.31126642081184, 0.75559809249357, -\n 12.58193294904, 17.332753623617, np.nan, 1.9599639845401, 0, -\n 11.583732327397, 3.8511214886273, -3.007885459237, 0.00263072269737, -\n 19.131791745195, -4.0356729095995, np.nan, 1.9599639845401, 0, -\n 1.807106397978, 14.19277372084, -0.12732580914219, 0.89868253380624, -\n 29.624431731551, 26.010218935595, np.nan, 1.9599639845401, 0, \n 10.852916363139, 2.6197368291491, 4.1427506161617, 3.431650408e-05, \n 5.7183265290336, 15.987506197244, np.nan, 1.9599639845401, 0, -\n 26.588397789444, 7.6315578612519, -3.4840065780596, 0.00049396734722, -\n 41.545976343431, -11.630819235457, np.nan, 1.9599639845401, 0]'], {}), '([47.514189267677, 12.722695157081, 3.7346009380122, 0.000188013074,\n 22.578164973516, 72.450213561838, np.nan, 1.9599639845401, 0, \n 2.3754103372885, 7.6314378245266, 0.31126642081184, 0.75559809249357, -\n 12.58193294904, 17.332753623617, np.nan, 1.9599639845401, 0, -\n 11.583732327397, 3.8511214886273, -3.007885459237, 0.00263072269737, -\n 19.131791745195, -4.0356729095995, np.nan, 1.9599639845401, 0, -\n 1.807106397978, 14.19277372084, -0.12732580914219, 0.89868253380624, -\n 29.624431731551, 26.010218935595, np.nan, 1.9599639845401, 0, \n 10.852916363139, 2.6197368291491, 4.1427506161617, 3.431650408e-05, \n 5.7183265290336, 15.987506197244, np.nan, 1.9599639845401, 0, -\n 26.588397789444, 7.6315578612519, -3.4840065780596, 0.00049396734722, -\n 41.545976343431, -11.630819235457, np.nan, 1.9599639845401, 0])\n', (1111, 1960), True, 'import numpy as np\n'), ((2267, 3202), 'numpy.array', 'np.array', (['[10.87507957467, 3.4816608831283, 0.87483487811437, 3.1229403520191, -\n 0.87306122632875, -2.2870394487277, -12.321063650937, 3.4816608831283, \n 5.1715652306254, 0.27473956091394, 1.7908952063684, -0.92880259796684, \n 1.8964947971413, -9.0063087868006, 0.87483487811437, 0.27473956091394, \n 1.1098392181639, -0.99390727840297, -0.34477731736542, -\n 0.98869834020742, 0.41772084541889, 3.1229403520191, 1.7908952063684, -\n 0.99390727840297, 17.912620004361, -0.30763138390107, 2.8490197200257, \n -21.269786576194, -0.87306122632875, -0.92880259796684, -\n 0.34477731736542, -0.30763138390107, 0.42666000427673, 0.05265352402592,\n 1.461997775289, -2.2870394487277, 1.8964947971413, -0.98869834020742, \n 2.8490197200257, 0.05265352402592, 4.0773252373088, -4.46154120848, -\n 12.321063650937, -9.0063087868006, 0.41772084541889, -21.269786576194, \n 1.461997775289, -4.46154120848, 37.559994394326]'], {}), '([10.87507957467, 3.4816608831283, 0.87483487811437, \n 3.1229403520191, -0.87306122632875, -2.2870394487277, -12.321063650937,\n 3.4816608831283, 5.1715652306254, 0.27473956091394, 1.7908952063684, -\n 0.92880259796684, 1.8964947971413, -9.0063087868006, 0.87483487811437, \n 0.27473956091394, 1.1098392181639, -0.99390727840297, -0.34477731736542,\n -0.98869834020742, 0.41772084541889, 3.1229403520191, 1.7908952063684, \n -0.99390727840297, 17.912620004361, -0.30763138390107, 2.8490197200257,\n -21.269786576194, -0.87306122632875, -0.92880259796684, -\n 0.34477731736542, -0.30763138390107, 0.42666000427673, 0.05265352402592,\n 1.461997775289, -2.2870394487277, 1.8964947971413, -0.98869834020742, \n 2.8490197200257, 0.05265352402592, 4.0773252373088, -4.46154120848, -\n 12.321063650937, -9.0063087868006, 0.41772084541889, -21.269786576194, \n 1.461997775289, -4.46154120848, 37.559994394326])\n', (2275, 3202), True, 'import numpy as np\n'), ((5144, 6006), 'numpy.array', 'np.array', (['[38.76996449636, 35.863089953808, 1.0810547709719, 0.27967275079666, -\n 31.520400187424, 109.06032918014, np.nan, 1.9599639845401, 0, \n 2.5208248279391, 11.710699937092, 0.21525825454332, 0.82956597472339, -\n 20.431725282518, 25.473374938396, np.nan, 1.9599639845401, 0, -\n 8.225606184332, 9.557721280021, -0.86062419517573, 0.38944505570119, -\n 26.958395667445, 10.507183298781, np.nan, 1.9599639845401, 0, -\n 4.4150939806524, 28.010544627225, -0.15762256819387, 0.87475421903252, \n -59.314752637366, 50.484564676062, np.nan, 1.9599639845401, 0, \n 7.0049476220304, 6.3399264323903, 1.1048941492826, 0.26920545789466, -\n 5.4210798500881, 19.430975094149, np.nan, 1.9599639845401, 0, -\n 25.128303596214, 23.247820190364, -1.0808885904335, 0.279746674501, -\n 70.693193888391, 20.436586695964, np.nan, 1.9599639845401, 0]'], {}), '([38.76996449636, 35.863089953808, 1.0810547709719, \n 0.27967275079666, -31.520400187424, 109.06032918014, np.nan, \n 1.9599639845401, 0, 2.5208248279391, 11.710699937092, 0.21525825454332,\n 0.82956597472339, -20.431725282518, 25.473374938396, np.nan, \n 1.9599639845401, 0, -8.225606184332, 9.557721280021, -0.86062419517573,\n 0.38944505570119, -26.958395667445, 10.507183298781, np.nan, \n 1.9599639845401, 0, -4.4150939806524, 28.010544627225, -\n 0.15762256819387, 0.87475421903252, -59.314752637366, 50.484564676062,\n np.nan, 1.9599639845401, 0, 7.0049476220304, 6.3399264323903, \n 1.1048941492826, 0.26920545789466, -5.4210798500881, 19.430975094149,\n np.nan, 1.9599639845401, 0, -25.128303596214, 23.247820190364, -\n 1.0808885904335, 0.279746674501, -70.693193888391, 20.436586695964, np.\n nan, 1.9599639845401, 0])\n', (5152, 6006), True, 'import numpy as np\n'), ((6309, 7530), 'numpy.array', 'np.array', (['[44.468037032422, 13.291812805254, 0.84306554343753, -0.38095027773819, -\n 2.1265212254924, -18.06714825989, -30.427077474507, 0.36347806905257, \n 13.291812805254, 15.093124820143, 3.3717840254072, -7.6860995498613, -\n 3.3867901970823, -1.4200645173727, -12.979849717094, 0.51706617429388, \n 0.84306554343753, 3.3717840254072, 5.6928040093481, -12.140553562993, -\n 2.5831646721297, -1.8071496111137, 7.961664784177, 0.27439267406128, -\n 0.38095027773819, -7.6860995498613, -12.140553562993, 91.950706114029, \n 6.6107070350689, 9.5470604840407, -82.665769963947, -1.1433180909155, -\n 2.1265212254924, -3.3867901970823, -2.5831646721297, 6.6107070350689, \n 2.0499053083335, 1.7094543055869, -3.029543334606, -0.34297224102579, -\n 18.06714825989, -1.4200645173727, -1.8071496111137, 9.5470604840407, \n 1.7094543055869, 18.442703265156, -6.5839965105886, -0.61952491151176, \n -30.427077474507, -12.979849717094, 7.961664784177, -82.665769963947, -\n 3.029543334606, -6.5839965105886, 111.12618806587, 0.88600743091011, \n 0.36347806905257, 0.51706617429388, 0.27439267406128, -1.1433180909155,\n -0.34297224102579, -0.61952491151176, 0.88600743091011, 0.71851239110057]'], {}), '([44.468037032422, 13.291812805254, 0.84306554343753, -\n 0.38095027773819, -2.1265212254924, -18.06714825989, -30.427077474507, \n 0.36347806905257, 13.291812805254, 15.093124820143, 3.3717840254072, -\n 7.6860995498613, -3.3867901970823, -1.4200645173727, -12.979849717094, \n 0.51706617429388, 0.84306554343753, 3.3717840254072, 5.6928040093481, -\n 12.140553562993, -2.5831646721297, -1.8071496111137, 7.961664784177, \n 0.27439267406128, -0.38095027773819, -7.6860995498613, -12.140553562993,\n 91.950706114029, 6.6107070350689, 9.5470604840407, -82.665769963947, -\n 1.1433180909155, -2.1265212254924, -3.3867901970823, -2.5831646721297, \n 6.6107070350689, 2.0499053083335, 1.7094543055869, -3.029543334606, -\n 0.34297224102579, -18.06714825989, -1.4200645173727, -1.8071496111137, \n 9.5470604840407, 1.7094543055869, 18.442703265156, -6.5839965105886, -\n 0.61952491151176, -30.427077474507, -12.979849717094, 7.961664784177, -\n 82.665769963947, -3.029543334606, -6.5839965105886, 111.12618806587, \n 0.88600743091011, 0.36347806905257, 0.51706617429388, 0.27439267406128,\n -1.1433180909155, -0.34297224102579, -0.61952491151176, \n 0.88600743091011, 0.71851239110057])\n', (6317, 7530), True, 'import numpy as np\n'), ((9279, 10218), 'numpy.array', 'np.array', (['[47.514189267677, 12.72269515678, 3.7346009381004, 0.00018801307393, \n 22.578164974105, 72.450213561249, np.nan, 1.9599639845401, 0, \n 2.3754103372885, 7.6314378245485, 0.31126642081095, 0.75559809249425, -\n 12.581932949083, 17.33275362366, np.nan, 1.9599639845401, 0, -\n 11.583732327397, 3.8511214887188, -3.0078854591656, 0.00263072269799, -\n 19.131791745374, -4.0356729094203, np.nan, 1.9599639845401, 0, -\n 1.807106397978, 14.192773720841, -0.12732580914219, 0.89868253380624, -\n 29.624431731552, 26.010218935596, np.nan, 1.9599639845401, 0, 0, np.nan,\n np.nan, np.nan, np.nan, np.nan, np.nan, 1.9599639845401, 0, \n 12.894515685772, 5.7673506886042, 2.2357779822979, 0.02536631788468, \n 1.5907160498956, 24.198315321648, np.nan, 1.9599639845401, 0, -\n 26.588397789444, 7.6315578608763, -3.4840065782311, 0.00049396734691, -\n 41.545976342695, -11.630819236193, np.nan, 1.9599639845401, 0]'], {}), '([47.514189267677, 12.72269515678, 3.7346009381004, \n 0.00018801307393, 22.578164974105, 72.450213561249, np.nan, \n 1.9599639845401, 0, 2.3754103372885, 7.6314378245485, 0.31126642081095,\n 0.75559809249425, -12.581932949083, 17.33275362366, np.nan, \n 1.9599639845401, 0, -11.583732327397, 3.8511214887188, -3.0078854591656,\n 0.00263072269799, -19.131791745374, -4.0356729094203, np.nan, \n 1.9599639845401, 0, -1.807106397978, 14.192773720841, -0.12732580914219,\n 0.89868253380624, -29.624431731552, 26.010218935596, np.nan, \n 1.9599639845401, 0, 0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, \n 1.9599639845401, 0, 12.894515685772, 5.7673506886042, 2.2357779822979, \n 0.02536631788468, 1.5907160498956, 24.198315321648, np.nan, \n 1.9599639845401, 0, -26.588397789444, 7.6315578608763, -3.4840065782311,\n 0.00049396734691, -41.545976342695, -11.630819236193, np.nan, \n 1.9599639845401, 0])\n', (9287, 10218), True, 'import numpy as np\n'), ((10556, 11539), 'numpy.array', 'np.array', (['[10.875079574674, 3.4816608831298, 0.87483487811447, 3.1229403520208, 0, -\n 0.873061226329, -2.2870394487282, -12.321063650942, 3.4816608831298, \n 5.1715652306252, 0.27473956091396, 1.7908952063684, 0, -\n 0.92880259796679, 1.8964947971405, -9.0063087868012, 0.87483487811447, \n 0.27473956091396, 1.109839218164, -0.9939072784041, 0, -\n 0.34477731736544, -0.98869834020768, 0.41772084541996, 3.1229403520208,\n 1.7908952063684, -0.9939072784041, 17.912620004373, 0, -\n 0.30763138390086, 2.8490197200274, -21.269786576207, 0, 0, 0, 0, 0, 0, \n 0, 0, -0.873061226329, -0.92880259796679, -0.34477731736544, -\n 0.30763138390086, 0, 0.42666000427672, 0.05265352402609, \n 1.4619977752889, -2.2870394487282, 1.8964947971405, -0.98869834020768, \n 2.8490197200274, 0, 0.05265352402609, 4.0773252373089, -4.4615412084808,\n -12.321063650942, -9.0063087868012, 0.41772084541996, -21.269786576207,\n 0, 1.4619977752889, -4.4615412084808, 37.559994394343]'], {}), '([10.875079574674, 3.4816608831298, 0.87483487811447, \n 3.1229403520208, 0, -0.873061226329, -2.2870394487282, -12.321063650942,\n 3.4816608831298, 5.1715652306252, 0.27473956091396, 1.7908952063684, 0,\n -0.92880259796679, 1.8964947971405, -9.0063087868012, 0.87483487811447,\n 0.27473956091396, 1.109839218164, -0.9939072784041, 0, -\n 0.34477731736544, -0.98869834020768, 0.41772084541996, 3.1229403520208,\n 1.7908952063684, -0.9939072784041, 17.912620004373, 0, -\n 0.30763138390086, 2.8490197200274, -21.269786576207, 0, 0, 0, 0, 0, 0, \n 0, 0, -0.873061226329, -0.92880259796679, -0.34477731736544, -\n 0.30763138390086, 0, 0.42666000427672, 0.05265352402609, \n 1.4619977752889, -2.2870394487282, 1.8964947971405, -0.98869834020768, \n 2.8490197200274, 0, 0.05265352402609, 4.0773252373089, -4.4615412084808,\n -12.321063650942, -9.0063087868012, 0.41772084541996, -21.269786576207,\n 0, 1.4619977752889, -4.4615412084808, 37.559994394343])\n', (10564, 11539), True, 'import numpy as np\n'), ((13624, 14564), 'numpy.array', 'np.array', (['[38.769964496355, 35.863089979665, 1.0810547701924, 0.27967275114341, -\n 31.520400238107, 109.06032923082, np.nan, 1.9599639845401, 0, \n 2.5208248279388, 11.710699937639, 0.21525825453324, 0.82956597473124, -\n 20.43172528359, 25.473374939467, np.nan, 1.9599639845401, 0, -\n 8.2256061843309, 9.5577212853699, -0.86062419469397, 0.38944505596662, \n -26.958395677928, 10.507183309266, np.nan, 1.9599639845401, 0, -\n 4.4150939806521, 28.010544626815, -0.15762256819618, 0.87475421903071, \n -59.314752636561, 50.484564675257, np.nan, 1.9599639845401, 0, 0, np.\n nan, np.nan, np.nan, np.nan, np.nan, np.nan, 1.9599639845401, 0, \n 8.0380552593041, 8.8634487485248, 0.90687671214231, 0.36447199739385, -\n 9.3339850666211, 25.410095585229, np.nan, 1.9599639845401, 0, -\n 25.12830359621, 23.247820207656, -1.0808885896294, 0.27974667485873, -\n 70.693193922279, 20.436586729858, np.nan, 1.9599639845401, 0]'], {}), '([38.769964496355, 35.863089979665, 1.0810547701924, \n 0.27967275114341, -31.520400238107, 109.06032923082, np.nan, \n 1.9599639845401, 0, 2.5208248279388, 11.710699937639, 0.21525825453324,\n 0.82956597473124, -20.43172528359, 25.473374939467, np.nan, \n 1.9599639845401, 0, -8.2256061843309, 9.5577212853699, -\n 0.86062419469397, 0.38944505596662, -26.958395677928, 10.507183309266,\n np.nan, 1.9599639845401, 0, -4.4150939806521, 28.010544626815, -\n 0.15762256819618, 0.87475421903071, -59.314752636561, 50.484564675257,\n np.nan, 1.9599639845401, 0, 0, np.nan, np.nan, np.nan, np.nan, np.nan,\n np.nan, 1.9599639845401, 0, 8.0380552593041, 8.8634487485248, \n 0.90687671214231, 0.36447199739385, -9.3339850666211, 25.410095585229,\n np.nan, 1.9599639845401, 0, -25.12830359621, 23.247820207656, -\n 1.0808885896294, 0.27974667485873, -70.693193922279, 20.436586729858,\n np.nan, 1.9599639845401, 0])\n', (13632, 14564), True, 'import numpy as np\n'), ((14903, 16179), 'numpy.array', 'np.array', (['[44.468037032424, 13.291812805256, 0.84306554343906, -0.38095027774827, 0, \n -2.1265212254934, -18.067148259892, -30.427077474499, 0.36347806905277,\n 13.291812805256, 15.093124820144, 3.3717840254072, -7.6860995498609, 0,\n -3.3867901970823, -1.4200645173736, -12.979849717095, 0.51706617429393,\n 0.84306554343906, 3.3717840254072, 5.6928040093478, -12.14055356299, 0,\n -2.5831646721296, -1.8071496111144, 7.9616647841741, 0.27439267406129, \n -0.38095027774827, -7.6860995498609, -12.14055356299, 91.950706114005, \n 0, 6.6107070350678, 9.5470604840447, -82.665769963921, -1.1433180909154,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, -2.1265212254934, -3.3867901970823, -\n 2.5831646721296, 6.6107070350678, 0, 2.0499053083335, 1.7094543055874, \n -3.0295433346046, -0.34297224102581, -18.067148259892, -1.4200645173736,\n -1.8071496111144, 9.5470604840447, 0, 1.7094543055874, 18.442703265157,\n -6.5839965105912, -0.61952491151187, -30.427077474499, -12.979849717095,\n 7.9616647841741, -82.665769963921, 0, -3.0295433346046, -\n 6.5839965105912, 111.12618806584, 0.88600743090998, 0.36347806905277, \n 0.51706617429393, 0.27439267406129, -1.1433180909154, 0, -\n 0.34297224102581, -0.61952491151187, 0.88600743090998, 0.71851239110059]'], {}), '([44.468037032424, 13.291812805256, 0.84306554343906, -\n 0.38095027774827, 0, -2.1265212254934, -18.067148259892, -\n 30.427077474499, 0.36347806905277, 13.291812805256, 15.093124820144, \n 3.3717840254072, -7.6860995498609, 0, -3.3867901970823, -\n 1.4200645173736, -12.979849717095, 0.51706617429393, 0.84306554343906, \n 3.3717840254072, 5.6928040093478, -12.14055356299, 0, -2.5831646721296,\n -1.8071496111144, 7.9616647841741, 0.27439267406129, -0.38095027774827,\n -7.6860995498609, -12.14055356299, 91.950706114005, 0, 6.6107070350678,\n 9.5470604840447, -82.665769963921, -1.1433180909154, 0, 0, 0, 0, 0, 0, \n 0, 0, 0, -2.1265212254934, -3.3867901970823, -2.5831646721296, \n 6.6107070350678, 0, 2.0499053083335, 1.7094543055874, -3.0295433346046,\n -0.34297224102581, -18.067148259892, -1.4200645173736, -1.8071496111144,\n 9.5470604840447, 0, 1.7094543055874, 18.442703265157, -6.5839965105912,\n -0.61952491151187, -30.427077474499, -12.979849717095, 7.9616647841741,\n -82.665769963921, 0, -3.0295433346046, -6.5839965105912, \n 111.12618806584, 0.88600743090998, 0.36347806905277, 0.51706617429393, \n 0.27439267406129, -1.1433180909154, 0, -0.34297224102581, -\n 0.61952491151187, 0.88600743090998, 0.71851239110059])\n', (14911, 16179), True, 'import numpy as np\n')]
############################ # Imports ############################ import os from pathlib import Path import argparse import torch import torch.utils.data import numpy as np from torch import nn, optim from torch.nn import functional as F from torch.nn import DataParallel from torchvision import datasets, transforms from torchvision.utils import save_image from dataset import * from model import * from tqdm import tqdm from fid import get_fid from logger import Logger from envsetter import EnvSetter from helper_functions import * ############################ # Globals # function to add to JSON opt = EnvSetter("vaegan").get_parser() os.environ["CUDA_VISIBLE_DEVICES"] = opt.use_gpus logger = Logger(opt.log_path, opt) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") torch.manual_seed(opt.seed) # Load data train_loader, val_loader, test_loader = get_data_loader(opt) netEG = VAE(opt=opt) netEG = DataParallel(netEG.to(device)) netD = Discriminator_celeba(opt) netD = DataParallel(netD.to(device)) netEG.apply(weights_init) netD.apply(weights_init) optimizerEG = optim.Adam(netEG.parameters(), lr=1e-3) optimizerD = optim.Adam(netD.parameters(), lr=1e-3) # Initialize BCELoss function criterion = nn.BCELoss() ############################# # Reconstruction + KL divergence losses summed over all elements and batch # def reconstruction_loss(recon_x, x, mu, logvar): # MSE = F.mse_loss(recon_x, x, reduction='sum') # KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) # return MSE + opt.beta * KLD def KLD(mu, logvar): return opt.beta * (-0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())) def SIM(sim_recon, sim_real): SIM = F.mse_loss(sim_recon, sim_real, reduction='sum') return 0.5 * SIM def reconstruction_loss(recon_x, x): MSE = F.mse_loss(recon_x, x, reduction='sum') return MSE def train(epoch): netD.train() netEG.train() recon_enc_loss = 0 train_recon_enc_loss = 0 train_recon_dec_loss = 0 avg_dis_loss = 0 avg_Dx = 0 for batch_idx, (data, _) in tqdm(enumerate(train_loader)): # create labels fake_label = np.random.choice(a=[0.1,0.9], p=[0.95, 0.05]) real_label = np.random.choice(a=[0.1,0.9], p=[0.05, 0.95]) data = data.to(device) ### Discriminator ### netD.zero_grad() label = torch.full((data.size()[0],), real_label, device=device) # Forward pass real batch through D output, sim_real = netD(data) # Calculate loss on all-real batch errD_real = criterion(output, label) # Calculate gradients for D in backward pass errD_real.backward() D_x = output.mean().item() avg_dis_loss += output.mean().item() ## Train with all-fake batch # Generate batch of latent vectors noise = torch.randn(data.size()[0], 128, device=device) # Generate fake image batch with G fake = netEG.module.decode(noise) label.fill_(fake_label) # Classify all fake batch with D output, _ = netD(fake.detach()) # Calculate D's loss on the all-fake batch errD_fake = criterion(output, label) # Calculate the gradients for this batch errD_fake.backward() # Update D optimizerD.step() ### Decoder ### netEG.zero_grad() label.fill_(real_label) # fake labels are real for generator cost output, sim_real = netD(data) # encoder to reuires grad = False netEG.module.features.requires_grad = False netEG.module.x_to_mu.requires_grad = False netEG.module.x_to_logvar.requires_grad = False netEG.module.preprocess.requires_grad = True netEG.module.deconv1.requires_grad = True netEG.module.act1.requires_grad = True netEG.module.deconv2.requires_grad = True netEG.module.act2.requires_grad = True netEG.module.deconv3.requires_grad = True netEG.module.act3.requires_grad = True netEG.module.deconv4.requires_grad = True netEG.module.activation.requires_grad = True recon_batch, mu, logvar = netEG(data) # Since we just updated D, perform another forward pass of all-fake batch through D output_fake, _ = netD(fake) # should add this too output_recon, sim_recon = netD(recon_batch) # Calculate G's loss based on this output errG_fake = criterion(output_fake, label) errG_recon = criterion(output_recon, label) # Calculate gradients for G errG_fake.backward(retain_graph=True) errG_recon.backward(retain_graph=True) sim_loss = SIM(sim_real=sim_real.to(device), sim_recon=sim_recon.to(device)) sim_loss.backward(retain_graph=True) loss = reconstruction_loss(recon_x=recon_batch.to(device), x=data) loss.backward() optimizerEG.step() ### Encoder ### netEG.zero_grad() netEG.module.features.requires_grad = True netEG.module.x_to_mu.requires_grad = True netEG.module.x_to_logvar.requires_grad = True netEG.module.preprocess.requires_grad = False netEG.module.deconv1.requires_grad = False netEG.module.act1.requires_grad = False netEG.module.deconv2.requires_grad = False netEG.module.act2.requires_grad = False netEG.module.deconv3.requires_grad = False netEG.module.act3.requires_grad = False netEG.module.deconv4.requires_grad = False netEG.module.activation.requires_grad = False recon_batch, mu, logvar = netEG(data) kld = KLD(mu.to(device), logvar.to(device)) kld.backward(retain_graph=True) loss = reconstruction_loss(recon_x=recon_batch.to(device), x=data) loss.backward() train_recon_enc_loss += loss.item() train_recon_dec_loss += loss.item() avg_Dx+= D_x optimizerEG.step() avg_recon_enc_loss = train_recon_enc_loss / len(train_loader.dataset) avg_recon_dec_loss = train_recon_dec_loss / len(train_loader.dataset) avg_dis_loss = avg_dis_loss / len(train_loader.dataset) avg_Dx = avg_Dx / len(train_loader.dataset) return avg_recon_enc_loss, avg_recon_dec_loss, avg_dis_loss, avg_Dx def load_model(path): checkpoint = torch.load(path) netEG.module.load_state_dict(checkpoint['encoder_decoder_model']) netD.load_state_dict(checkpoint['discriminator_model']) optimizerEG.load_state_dict(checkpoint['encoder_decoder_optimizer']) optimizerD.load_state_dict(checkpoint['discriminator_optimizer']) return checkpoint['epoch'] if __name__ == "__main__": # set_up_globals() start_epoch = 0 if opt.load_path and len(opt.load_path) < 2: start_epoch = load_model(opt.load_path[0]) if opt.to_train: for epoch in tqdm(range(start_epoch, opt.epochs)): enc_loss, dec_loss, dis_loss, Dx = train(epoch) with torch.no_grad(): torch.save({ 'epoch': epoch + 1, "encoder_decoder_model": netEG.module.state_dict(), "discriminator_model": netD.state_dict(), 'encoder_decoder_optimizer': optimizerEG.state_dict(), 'discriminator_optimizer': optimizerD.state_dict(), }, opt.model_path + f"/model_{str(epoch+1)}.tar") # Calculate FID score fid = "N/A" if opt.calc_fid: fn = lambda x: netEG.module.decode(x).cpu() generate_fid_samples(fn, epoch, opt.n_samples, opt.n_hidden, opt.fid_path_recons, device=device) fid = get_fid(opt.fid_path_recons, opt.fid_path_pretrained) print('====> Epoch: {} Avg Encoder Loss: {:.4f} Avg Decoder Loss: {:.4f} Avg Discriminator Loss: {:.4f} FID: {} Dx: {:.4f}'.format( epoch, enc_loss, dec_loss, dis_loss, fid, Dx)) # Log epoch statistics logger.log({ "Epoch":epoch, "Avg Eec Loss": enc_loss, "Avg Dnc Loss": dec_loss, "Avg Dis Loss": dis_loss, "FID":fid}) tmp_epoch = 0 for m in opt.load_path: epoch = load_model(m) # Quick fix to load multiple models and not have overwriting happening epoch = epoch if epoch is not tmp_epoch and tmp_epoch < epoch else tmp_epoch + 1 tmp_epoch = epoch if opt.calc_fid: fn = lambda x: netEG.module.decode(x).cpu() generate_fid_samples(fn, epoch, opt.n_samples, opt.n_hidden, opt.fid_path_samples, device=device) fid = get_fid(opt.fid_path_samples, opt.fid_path_pretrained) if opt.test_recons: fn = lambda x: netEG(x.to(device))[0] gen_reconstructions(fn, test_loader, epoch, opt.test_results_path_recons, nrow=1, path_for_originals=opt.test_results_path_originals) print("Generated reconstructions") if opt.test_samples: fn = lambda x: netEG.module.decode(x).cpu() generate_samples(fn, start_epoch, 5, opt.n_hidden, opt.test_results_path_samples, nrow=1, device=device) print("Generated samples")
[ "torch.manual_seed", "torch.nn.functional.mse_loss", "numpy.random.choice", "torch.load", "envsetter.EnvSetter", "torch.nn.BCELoss", "torch.cuda.is_available", "fid.get_fid", "logger.Logger", "torch.no_grad" ]
[((707, 732), 'logger.Logger', 'Logger', (['opt.log_path', 'opt'], {}), '(opt.log_path, opt)\n', (713, 732), False, 'from logger import Logger\n'), ((806, 833), 'torch.manual_seed', 'torch.manual_seed', (['opt.seed'], {}), '(opt.seed)\n', (823, 833), False, 'import torch\n'), ((1242, 1254), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (1252, 1254), False, 'from torch import nn, optim\n'), ((1711, 1759), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['sim_recon', 'sim_real'], {'reduction': '"""sum"""'}), "(sim_recon, sim_real, reduction='sum')\n", (1721, 1759), True, 'from torch.nn import functional as F\n'), ((1830, 1869), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['recon_x', 'x'], {'reduction': '"""sum"""'}), "(recon_x, x, reduction='sum')\n", (1840, 1869), True, 'from torch.nn import functional as F\n'), ((6393, 6409), 'torch.load', 'torch.load', (['path'], {}), '(path)\n', (6403, 6409), False, 'import torch\n'), ((615, 634), 'envsetter.EnvSetter', 'EnvSetter', (['"""vaegan"""'], {}), "('vaegan')\n", (624, 634), False, 'from envsetter import EnvSetter\n'), ((768, 793), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (791, 793), False, 'import torch\n'), ((2173, 2219), 'numpy.random.choice', 'np.random.choice', ([], {'a': '[0.1, 0.9]', 'p': '[0.95, 0.05]'}), '(a=[0.1, 0.9], p=[0.95, 0.05])\n', (2189, 2219), True, 'import numpy as np\n'), ((2240, 2286), 'numpy.random.choice', 'np.random.choice', ([], {'a': '[0.1, 0.9]', 'p': '[0.05, 0.95]'}), '(a=[0.1, 0.9], p=[0.05, 0.95])\n', (2256, 2286), True, 'import numpy as np\n'), ((8832, 8886), 'fid.get_fid', 'get_fid', (['opt.fid_path_samples', 'opt.fid_path_pretrained'], {}), '(opt.fid_path_samples, opt.fid_path_pretrained)\n', (8839, 8886), False, 'from fid import get_fid\n'), ((7043, 7058), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7056, 7058), False, 'import torch\n'), ((7803, 7856), 'fid.get_fid', 'get_fid', (['opt.fid_path_recons', 'opt.fid_path_pretrained'], {}), '(opt.fid_path_recons, opt.fid_path_pretrained)\n', (7810, 7856), False, 'from fid import get_fid\n')]
from typing import Optional, Union from typing_extensions import Literal from anndata import AnnData import numpy as np import pandas as pd from pandas import DataFrame from scipy.sparse import csr_matrix from scipy.sparse.csgraph import minimum_spanning_tree from scipy.sparse.csgraph import shortest_path import igraph from tqdm import tqdm import sys import igraph import warnings import itertools import math from scipy import sparse import simpleppt from ..plot.trajectory import graph as plot_graph from .. import logging as logg from .. import settings from .utils import get_X def curve( adata: AnnData, Nodes: int = None, use_rep: str = None, ndims_rep: Optional[int] = None, init: Optional[DataFrame] = None, epg_lambda: Optional[Union[float, int]] = 0.01, epg_mu: Optional[Union[float, int]] = 0.1, epg_trimmingradius: Optional = np.inf, epg_initnodes: Optional[int] = 2, epg_verbose: bool = False, device: Literal["cpu", "gpu"] = "cpu", plot: bool = False, basis: Optional[str] = "umap", seed: Optional[int] = None, copy: bool = False, ): """\ Generate a principal curve. Learn a curved representation on any space, composed of nodes, approximating the position of the cells on a given space such as gene expression, pca, diffusion maps, ... Uses ElpiGraph algorithm. Parameters ---------- adata Annotated data matrix. Nodes Number of nodes composing the principial tree, use a range of 10 to 100 for ElPiGraph approach and 100 to 2000 for PPT approach. use_rep Choose the space to be learned by the principal tree. ndims_rep Number of dimensions to use for the inference. init Initialise the point positions. epg_lambda Parameter for ElPiGraph, coefficient of ‘stretching’ elasticity [Albergante20]_. epg_mu Parameter for ElPiGraph, coefficient of ‘bending’ elasticity [Albergante20]_. epg_trimmingradius Parameter for ElPiGraph, trimming radius for MSE-based data approximation term [Albergante20]_. epg_initnodes numerical 2D matrix, the k-by-m matrix with k m-dimensional positions of the nodes in the initial step epg_verbose show verbose output of epg algorithm device Run method on either `cpu` or on `gpu` plot Plot the resulting tree. basis Basis onto which the resulting tree should be projected. seed A numpy random seed. copy Return a copy instead of writing to adata. Returns ------- adata : anndata.AnnData if `copy=True` it returns or else add fields to `adata`: `.uns['epg']` dictionnary containing information from elastic principal curve `.obsm['X_R']` hard assignment of cells to principal points `.uns['graph']['B']` adjacency matrix of the principal points `.uns['graph']['F']` coordinates of principal points in representation space """ logg.info( "inferring a principal curve", reset=True, end=" " if settings.verbosity > 2 else "\n", ) adata = adata.copy() if copy else adata if Nodes is None: if adata.shape[0] * 2 > 100: Nodes = 100 else: Nodes = int(adata.shape[0] / 2) logg.hint( "parameters used \n" " " + str(Nodes) + " principal points, mu = " + str(epg_mu) + ", lambda = " + str(epg_lambda) ) curve_epg( adata, Nodes, use_rep, ndims_rep, init, epg_lambda, epg_mu, epg_trimmingradius, epg_initnodes, device, seed, epg_verbose, ) if plot: plot_graph(adata, basis) return adata if copy else None def tree( adata: AnnData, Nodes: int = None, use_rep: str = None, ndims_rep: Optional[int] = None, weight_rep: str = None, method: Literal["ppt", "epg"] = "ppt", init: Optional[DataFrame] = None, ppt_sigma: Optional[Union[float, int]] = 0.1, ppt_lambda: Optional[Union[float, int]] = 1, ppt_metric: str = "euclidean", ppt_nsteps: int = 50, ppt_err_cut: float = 5e-3, ppt_gpu_tpb: int = 16, epg_lambda: Optional[Union[float, int]] = 0.01, epg_mu: Optional[Union[float, int]] = 0.1, epg_trimmingradius: Optional = np.inf, epg_initnodes: Optional[int] = 2, epg_verbose: bool = False, device: Literal["cpu", "gpu"] = "cpu", plot: bool = False, basis: Optional[str] = "umap", seed: Optional[int] = None, copy: bool = False, ): """\ Generate a principal tree. Learn a simplified representation on any space, compsed of nodes, approximating the position of the cells on a given space such as gene expression, pca, diffusion maps, ... If `method=='ppt'`, uses simpleppt implementation from [Soldatov19]_. If `method=='epg'`, uses Elastic Principal Graph approach from [Albergante20]_. Parameters ---------- adata Annotated data matrix. Nodes Number of nodes composing the principial tree, use a range of 10 to 100 for ElPiGraph approach and 100 to 2000 for PPT approach. use_rep Choose the space to be learned by the principal tree. ndims_rep Number of dimensions to use for the inference. weight_rep If `ppt`, use a weight matrix for learning the tree. method If `ppt`, uses simpleppt approach, `ppt_lambda` and `ppt_sigma` are the parameters controlling the algorithm. If `epg`, uses ComputeElasticPrincipalTree function from elpigraph python package, `epg_lambda` `epg_mu` and `epg_trimmingradius` are the parameters controlling the algorithm. init Initialise the point positions. ppt_sigma Regularization parameter for simpleppt [Mao15]_. ppt_lambda Parameter for simpleppt, penalty for the tree length [Mao15]_. ppt_metric The metric to use to compute distances in high dimensional space. For compatible metrics, check the documentation of sklearn.metrics.pairwise_distances if using cpu or cuml.metrics.pairwise_distances if using gpu. ppt_nsteps Number of steps for the optimisation process of simpleppt. ppt_err_cut Stop simpleppt algorithm if proximity of principal points between iterations less than defiend value. ppt_gpu_tpb Threads per block parameter for cuda computations. epg_lambda Parameter for ElPiGraph, coefficient of ‘stretching’ elasticity [Albergante20]_. epg_mu Parameter for ElPiGraph, coefficient of ‘bending’ elasticity [Albergante20]_. epg_trimmingradius Parameter for ElPiGraph, trimming radius for MSE-based data approximation term [Albergante20]_. epg_initnodes numerical 2D matrix, the k-by-m matrix with k m-dimensional positions of the nodes in the initial step epg_verbose show verbose output of epg algorithm device Run either mehtod on `cpu` or on `gpu` plot Plot the resulting tree. basis Basis onto which the resulting tree should be projected. seed A numpy random seed. copy Return a copy instead of writing to adata. Returns ------- adata : anndata.AnnData if `copy=True` it returns or else add fields to `adata`: `.uns['ppt']` dictionnary containing information from simpelppt tree if method='ppt' `.uns['epg']` dictionnary containing information from elastic principal tree if method='epg' `.obsm['R']` soft assignment of cells to principal points `.uns['graph']['B']` adjacency matrix of the principal points `.uns['graph']['F']` coordinates of principal points in representation space """ logg.info( "inferring a principal tree", reset=True, end=" " if settings.verbosity > 2 else "\n", ) adata = adata.copy() if copy else adata X, use_rep = get_data(adata, use_rep, ndims_rep) W = get_data(adata, weight_rep, ndims_rep)[0] if weight_rep is not None else None if Nodes is None: if adata.shape[0] * 2 > 2000: Nodes = 2000 else: Nodes = int(adata.shape[0] / 2) if method == "ppt": simpleppt.settings.verbosity = settings.verbosity ppt = simpleppt.ppt( X, W, Nodes=Nodes, init=init, sigma=ppt_sigma, lam=ppt_lambda, metric=ppt_metric, nsteps=ppt_nsteps, err_cut=ppt_err_cut, device=device, gpu_tbp=ppt_gpu_tpb, seed=seed, progress=settings.verbosity > 1, ) ppt = vars(ppt) graph = { "B": ppt["B"], "F": ppt["F"], "tips": ppt["tips"], "forks": ppt["forks"], "metrics": ppt["metric"], "use_rep": use_rep, "ndims_rep": ndims_rep, } adata.uns["graph"] = graph adata.uns["ppt"] = ppt adata.obsm["X_R"] = ppt["R"] elif method == "epg": graph, epg = tree_epg( X, Nodes, init, epg_lambda, epg_mu, epg_trimmingradius, epg_initnodes, device, seed, epg_verbose, ) graph["use_rep"] = use_rep graph["ndims_rep"] = ndims_rep adata.obsm["X_R"] = graph["R"] del graph["R"] adata.uns["graph"] = graph adata.uns["epg"] = epg if plot: plot_graph(adata, basis) logg.hint( "added \n" " .uns['" + method + "'], dictionnary containing inferred tree.\n" " .obsm['X_R'] soft assignment of cells to principal points.\n" " .uns['graph']['B'] adjacency matrix of the principal points.\n" " .uns['graph']['F'] coordinates of principal points in representation space." ) return adata if copy else None def circle( adata: AnnData, Nodes: int = None, use_rep: str = None, ndims_rep: Optional[int] = None, init: Optional[DataFrame] = None, epg_lambda: Optional[Union[float, int]] = 0.01, epg_mu: Optional[Union[float, int]] = 0.1, epg_trimmingradius: Optional = np.inf, epg_initnodes: Optional[int] = 3, epg_verbose: bool = False, device: Literal["cpu", "gpu"] = "cpu", plot: bool = False, basis: Optional[str] = "umap", seed: Optional[int] = None, copy: bool = False, ): """\ Generate a principal circle. Learn a circled representation on any space, composed of nodes, approximating the position of the cells on a given space such as gene expression, pca, diffusion maps, ... Uses ElpiGraph algorithm. Parameters ---------- adata Annotated data matrix. Nodes Number of nodes composing the principial tree, use a range of 10 to 100 for ElPiGraph approach and 100 to 2000 for PPT approach. use_rep Choose the space to be learned by the principal tree. ndims_rep Number of dimensions to use for the inference. init Initialise the point positions. epg_lambda Parameter for ElPiGraph, coefficient of ‘stretching’ elasticity [Albergante20]_. epg_mu Parameter for ElPiGraph, coefficient of ‘bending’ elasticity [Albergante20]_. epg_trimmingradius Parameter for ElPiGraph, trimming radius for MSE-based data approximation term [Albergante20]_. epg_initnodes numerical 2D matrix, the k-by-m matrix with k m-dimensional positions of the nodes in the initial step epg_verbose show verbose output of epg algorithm device Run method on either `cpu` or on `gpu` plot Plot the resulting tree. basis Basis onto which the resulting tree should be projected. seed A numpy random seed. copy Return a copy instead of writing to adata. Returns ------- adata : anndata.AnnData if `copy=True` it returns or else add fields to `adata`: `.uns['epg']` dictionnary containing information from elastic principal curve `.obsm['X_R']` soft assignment of cells to principal points `.uns['graph']['B']` adjacency matrix of the principal points `.uns['graph']['F']` coordinates of principal points in representation space """ logg.info( "inferring a principal circle", reset=True, end=" " if settings.verbosity > 2 else "\n", ) adata = adata.copy() if copy else adata if Nodes is None: if adata.shape[0] * 2 > 100: Nodes = 100 else: Nodes = int(adata.shape[0] / 2) logg.hint( "parameters used \n" " " + str(Nodes) + " principal points, mu = " + str(epg_mu) + ", lambda = " + str(epg_lambda) ) circle_epg( adata, Nodes, use_rep, ndims_rep, init, epg_lambda, epg_mu, epg_trimmingradius, epg_initnodes, device, seed, epg_verbose, ) if plot: plot_graph(adata, basis) return adata if copy else None def tree_epg( X, Nodes: int = None, init: Optional[DataFrame] = None, lam: Optional[Union[float, int]] = 0.01, mu: Optional[Union[float, int]] = 0.1, trimmingradius: Optional = np.inf, initnodes: int = None, device: str = "cpu", seed: Optional[int] = None, verbose: bool = True, ): try: import elpigraph except Exception as e: warnings.warn( 'ElPiGraph package is not installed \ \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it' ) logg.hint( "parameters used \n" " " + str(Nodes) + " principal points, mu = " + str(mu) + ", lambda = " + str(lam) ) if seed is not None: np.random.seed(seed) if device == "gpu": import cupy as cp from cuml.metrics import pairwise_distances from .utils import cor_mat_gpu Tree = elpigraph.computeElasticPrincipalTree( X.values.astype(np.float64), NumNodes=Nodes, Do_PCA=False, InitNodes=initnodes, Lambda=lam, Mu=mu, TrimmingRadius=trimmingradius, GPU=True, verbose=verbose, ) R = pairwise_distances( cp.asarray(X.values), cp.asarray(Tree[0]["NodePositions"]) ) R = cp.asnumpy(R) # Hard assigment R = sparse.csr_matrix( (np.repeat(1, R.shape[0]), (range(R.shape[0]), R.argmin(axis=1))), R.shape ).A else: from .utils import cor_mat_cpu from sklearn.metrics import pairwise_distances Tree = elpigraph.computeElasticPrincipalTree( X.values.astype(np.float64), NumNodes=Nodes, Do_PCA=False, InitNodes=initnodes, Lambda=lam, Mu=mu, TrimmingRadius=trimmingradius, verbose=verbose, ) R = pairwise_distances(X.values, Tree[0]["NodePositions"]) # Hard assigment R = sparse.csr_matrix( (np.repeat(1, R.shape[0]), (range(R.shape[0]), R.argmin(axis=1))), R.shape ).A g = igraph.Graph(directed=False) g.add_vertices(np.unique(Tree[0]["Edges"][0].flatten().astype(int))) g.add_edges( pd.DataFrame(Tree[0]["Edges"][0]).astype(int).apply(tuple, axis=1).values ) # mat = np.asarray(g.get_adjacency().data) # mat = mat + mat.T - np.diag(np.diag(mat)) # B=((mat>0).astype(int)) B = np.asarray(g.get_adjacency().data) emptynodes = np.argwhere(R.max(axis=0) == 0).ravel() sel = ~np.isin(np.arange(R.shape[1]), emptynodes) B = B[sel, :][:, sel] R = R[:, sel] F = Tree[0]["NodePositions"].T[:, sel] g = igraph.Graph.Adjacency((B > 0).tolist(), mode="undirected") tips = np.argwhere(np.array(g.degree()) == 1).flatten() def reconnect(): tips = np.argwhere(np.array(g.degree()) == 1).flatten() distmat = np.triu(pairwise_distances(F[:, tips].T)) distmat = pd.DataFrame(distmat, columns=tips, index=tips) distmat[distmat == 0] = np.inf row, col = np.unravel_index(np.argmin(distmat.values), distmat.shape) i, j = distmat.index[row], distmat.columns[col] B[i, j] = 1 B[j, i] = 1 return B if len(emptynodes) > 0: logg.info(" removed %d non assigned nodes" % (len(emptynodes))) recon = len(np.unique(np.array(g.clusters().membership))) > 1 while recon: B = reconnect() g = igraph.Graph.Adjacency((B > 0).tolist(), mode="undirected") tips = np.argwhere(np.array(g.degree()) == 1).flatten() recon = len(np.unique(np.array(g.clusters().membership))) > 1 forks = np.argwhere(np.array(g.degree()) > 2).flatten() graph = { "B": B, "R": R, "F": Tree[0]["NodePositions"].T, "tips": tips, "forks": forks, "cells_fitted": X.index.tolist(), "metrics": "euclidean", } Tree[0]["Edges"] = list(Tree[0]["Edges"])[0] return graph, Tree[0] def curve_epg( adata: AnnData, Nodes: int = None, use_rep: str = None, ndims_rep: Optional[int] = None, init: Optional[DataFrame] = None, lam: Optional[Union[float, int]] = 0.01, mu: Optional[Union[float, int]] = 0.1, trimmingradius: Optional = np.inf, initnodes: int = None, device: str = "cpu", seed: Optional[int] = None, verbose: bool = True, ): try: import elpigraph except Exception as e: warnings.warn( 'ElPiGraph package is not installed \ \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it' ) X, use_rep = get_data(adata, use_rep, ndims_rep) if seed is not None: np.random.seed(seed) if device == "gpu": import cupy as cp from .utils import cor_mat_gpu from cuml.metrics import pairwise_distances Curve = elpigraph.computeElasticPrincipalCurve( X.values.astype(np.float64), NumNodes=Nodes, Do_PCA=False, InitNodes=initnodes, Lambda=lam, Mu=mu, TrimmingRadius=trimmingradius, GPU=True, verbose=verbose, ) R = pairwise_distances( cp.asarray(X.values), cp.asarray(Curve[0]["NodePositions"]) ) R = cp.asnumpy(R) # Hard assigment R = sparse.csr_matrix( (np.repeat(1, R.shape[0]), (range(R.shape[0]), R.argmin(axis=1))), R.shape ).A else: from .utils import cor_mat_cpu from sklearn.metrics import pairwise_distances Curve = elpigraph.computeElasticPrincipalCurve( X.values.astype(np.float64), NumNodes=Nodes, Do_PCA=False, InitNodes=initnodes, Lambda=lam, Mu=mu, TrimmingRadius=trimmingradius, verbose=verbose, ) R = pairwise_distances(X.values, Curve[0]["NodePositions"]) # Hard assigment R = sparse.csr_matrix( (np.repeat(1, R.shape[0]), (range(R.shape[0]), R.argmin(axis=1))), R.shape ).A g = igraph.Graph(directed=False) g.add_vertices(np.unique(Curve[0]["Edges"][0].flatten().astype(int))) g.add_edges( pd.DataFrame(Curve[0]["Edges"][0]).astype(int).apply(tuple, axis=1).values ) # mat = np.asarray(g.get_adjacency().data) # mat = mat + mat.T - np.diag(np.diag(mat)) # B=((mat>0).astype(int)) B = np.asarray(g.get_adjacency().data) emptynodes = np.argwhere(R.max(axis=0) == 0).ravel() sel = ~np.isin(np.arange(R.shape[1]), emptynodes) B = B[sel, :][:, sel] R = R[:, sel] F = Curve[0]["NodePositions"].T[:, sel] g = igraph.Graph.Adjacency((B > 0).tolist(), mode="undirected") tips = np.argwhere(np.array(g.degree()) == 1).flatten() def reconnect(): tips = np.argwhere(np.array(g.degree()) == 1).flatten() distmat = np.triu(pairwise_distances(F[:, tips].T)) distmat = pd.DataFrame(distmat, columns=tips, index=tips) distmat[distmat == 0] = np.inf row, col = np.unravel_index(np.argmin(distmat.values), distmat.shape) i, j = distmat.index[row], distmat.columns[col] B[i, j] = 1 B[j, i] = 1 return B if len(emptynodes) > 0: logg.info(" removed %d non assigned nodes" % (len(emptynodes))) recon = len(np.unique(np.array(g.clusters().membership))) > 1 while recon: B = reconnect() g = igraph.Graph.Adjacency((B > 0).tolist(), mode="undirected") tips = np.argwhere(np.array(g.degree()) == 1).flatten() recon = len(np.unique(np.array(g.clusters().membership))) > 1 forks = np.argwhere(np.array(g.degree()) > 2).flatten() graph = { "B": B, "F": Curve[0]["NodePositions"].T, "tips": tips, "forks": forks, "metrics": "euclidean", "use_rep": use_rep, "ndims_rep": ndims_rep, } Curve[0]["Edges"] = list(Curve[0]["Edges"])[0] adata.uns["graph"] = graph adata.uns["epg"] = Curve[0] adata.obsm["X_R"] = R logg.info(" finished", time=True, end=" " if settings.verbosity > 2 else "\n") logg.hint( "added \n" " .uns['epg'] dictionnary containing inferred elastic curve generated from elpigraph.\n" " .obsm['X_R'] hard assignment of cells to principal points.\n" " .uns['graph']['B'] adjacency matrix of the principal points.\n" " .uns['graph']['F'], coordinates of principal points in representation space." ) return adata def circle_epg( adata: AnnData, Nodes: int = None, use_rep: str = None, ndims_rep: Optional[int] = None, init: Optional[DataFrame] = None, lam: Optional[Union[float, int]] = 0.01, mu: Optional[Union[float, int]] = 0.1, trimmingradius: Optional = np.inf, initnodes: int = None, device: str = "cpu", seed: Optional[int] = None, verbose: bool = True, ): try: import elpigraph except Exception as e: warnings.warn( 'ElPiGraph package is not installed \ \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it' ) X, use_rep = get_data(adata, use_rep, ndims_rep) if seed is not None: np.random.seed(seed) if device == "gpu": import cupy as cp from .utils import cor_mat_gpu from cuml.metrics import pairwise_distances Curve = elpigraph.computeElasticPrincipalCircle( X.values.astype(np.float64), NumNodes=Nodes, Do_PCA=False, InitNodes=initnodes, Lambda=lam, Mu=mu, TrimmingRadius=trimmingradius, GPU=True, verbose=verbose, ) R = pairwise_distances( cp.asarray(X.values), cp.asarray(Curve[0]["NodePositions"]) ) R = cp.asnumpy(R) # Hard assigment R = sparse.csr_matrix( (np.repeat(1, R.shape[0]), (range(R.shape[0]), R.argmin(axis=1))), R.shape ).A else: from .utils import cor_mat_cpu from sklearn.metrics import pairwise_distances Curve = elpigraph.computeElasticPrincipalCircle( X.values.astype(np.float64), NumNodes=Nodes, Do_PCA=False, InitNodes=initnodes, Lambda=lam, Mu=mu, TrimmingRadius=trimmingradius, verbose=verbose, ) R = pairwise_distances(X.values, Curve[0]["NodePositions"]) # Hard assigment R = sparse.csr_matrix( (np.repeat(1, R.shape[0]), (range(R.shape[0]), R.argmin(axis=1))), R.shape ).A g = igraph.Graph(directed=False) g.add_vertices(np.unique(Curve[0]["Edges"][0].flatten().astype(int))) g.add_edges( pd.DataFrame(Curve[0]["Edges"][0]).astype(int).apply(tuple, axis=1).values ) # mat = np.asarray(g.get_adjacency().data) # mat = mat + mat.T - np.diag(np.diag(mat)) # B=((mat>0).astype(int)) B = np.asarray(g.get_adjacency().data) emptynodes = np.argwhere(R.max(axis=0) == 0).ravel() sel = ~np.isin(np.arange(R.shape[1]), emptynodes) B = B[sel, :][:, sel] R = R[:, sel] F = Curve[0]["NodePositions"].T[:, sel] g = igraph.Graph.Adjacency((B > 0).tolist(), mode="undirected") tips = np.argwhere(np.array(g.degree()) == 1).flatten() def reconnect(): tips = np.argwhere(np.array(g.degree()) == 1).flatten() distmat = np.triu(pairwise_distances(F[:, tips].T)) distmat = pd.DataFrame(distmat, columns=tips, index=tips) distmat[distmat == 0] = np.inf row, col = np.unravel_index(np.argmin(distmat.values), distmat.shape) i, j = distmat.index[row], distmat.columns[col] B[i, j] = 1 B[j, i] = 1 return B if len(emptynodes) > 0: logg.info(" removed %d non assigned nodes" % (len(emptynodes))) recon = len(tips) > 0 while recon: B = reconnect() g = igraph.Graph.Adjacency((B > 0).tolist(), mode="undirected") tips = np.argwhere(np.array(g.degree()) == 1).flatten() recon = len(tips) > 0 forks = np.argwhere(np.array(g.degree()) > 2).flatten() graph = { "B": B, "F": F, "tips": tips, "forks": forks, "metrics": "euclidean", "use_rep": use_rep, "ndims_rep": ndims_rep, } Curve[0]["Edges"] = list(Curve[0]["Edges"])[0] adata.uns["graph"] = graph adata.uns["epg"] = Curve[0] adata.obsm["X_R"] = R logg.info(" finished", time=True, end=" " if settings.verbosity > 2 else "\n") logg.hint( "added \n" " .uns['epg'] dictionnary containing inferred elastic circle generated from elpigraph.\n" " .obsm['X_R'] hard assignment of cells to principal points.\n" " .uns['graph']['B'] adjacency matrix of the principal points.\n" " .uns['graph']['F'], coordinates of principal points in representation space." ) return adata def get_data(adata, use_rep, ndims_rep): if use_rep not in adata.obsm.keys() and f"X_{use_rep}" in adata.obsm.keys(): use_rep = f"X_{use_rep}" if ( (use_rep not in adata.layers.keys()) & (use_rep not in adata.obsm.keys()) & (use_rep != "X") ): use_rep = "X" if adata.n_vars < 50 or n_pcs == 0 else "X_pca" n_pcs = None if use_rep == "X" else n_pcs if use_rep == "X": ndims_rep = None if sparse.issparse(adata.X): X = DataFrame(adata.X.A, index=adata.obs_names) else: X = DataFrame(adata.X, index=adata.obs_names) elif use_rep in adata.layers.keys(): if sparse.issparse(adata.layers[use_rep]): X = DataFrame(adata.layers[use_rep].A, index=adata.obs_names) else: X = DataFrame(adata.layers[use_rep], index=adata.obs_names) elif use_rep in adata.obsm.keys(): X = DataFrame(adata.obsm[use_rep], index=adata.obs_names) if ndims_rep is not None: X = X.iloc[:, :ndims_rep] return X, use_rep
[ "cupy.asnumpy", "numpy.repeat", "simpleppt.ppt", "sklearn.metrics.pairwise_distances", "scipy.sparse.issparse", "numpy.random.seed", "numpy.argmin", "pandas.DataFrame", "warnings.warn", "cupy.asarray", "numpy.arange", "igraph.Graph" ]
[((15835, 15863), 'igraph.Graph', 'igraph.Graph', ([], {'directed': '(False)'}), '(directed=False)\n', (15847, 15863), False, 'import igraph\n'), ((19928, 19956), 'igraph.Graph', 'igraph.Graph', ([], {'directed': '(False)'}), '(directed=False)\n', (19940, 19956), False, 'import igraph\n'), ((24583, 24611), 'igraph.Graph', 'igraph.Graph', ([], {'directed': '(False)'}), '(directed=False)\n', (24595, 24611), False, 'import igraph\n'), ((8585, 8809), 'simpleppt.ppt', 'simpleppt.ppt', (['X', 'W'], {'Nodes': 'Nodes', 'init': 'init', 'sigma': 'ppt_sigma', 'lam': 'ppt_lambda', 'metric': 'ppt_metric', 'nsteps': 'ppt_nsteps', 'err_cut': 'ppt_err_cut', 'device': 'device', 'gpu_tbp': 'ppt_gpu_tpb', 'seed': 'seed', 'progress': '(settings.verbosity > 1)'}), '(X, W, Nodes=Nodes, init=init, sigma=ppt_sigma, lam=ppt_lambda,\n metric=ppt_metric, nsteps=ppt_nsteps, err_cut=ppt_err_cut, device=\n device, gpu_tbp=ppt_gpu_tpb, seed=seed, progress=settings.verbosity > 1)\n', (8598, 8809), False, 'import simpleppt\n'), ((14401, 14421), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (14415, 14421), True, 'import numpy as np\n'), ((15021, 15034), 'cupy.asnumpy', 'cp.asnumpy', (['R'], {}), '(R)\n', (15031, 15034), True, 'import cupy as cp\n'), ((15616, 15670), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['X.values', "Tree[0]['NodePositions']"], {}), "(X.values, Tree[0]['NodePositions'])\n", (15634, 15670), False, 'from sklearn.metrics import pairwise_distances\n'), ((16703, 16750), 'pandas.DataFrame', 'pd.DataFrame', (['distmat'], {'columns': 'tips', 'index': 'tips'}), '(distmat, columns=tips, index=tips)\n', (16715, 16750), True, 'import pandas as pd\n'), ((18488, 18508), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (18502, 18508), True, 'import numpy as np\n'), ((19111, 19124), 'cupy.asnumpy', 'cp.asnumpy', (['R'], {}), '(R)\n', (19121, 19124), True, 'import cupy as cp\n'), ((19708, 19763), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['X.values', "Curve[0]['NodePositions']"], {}), "(X.values, Curve[0]['NodePositions'])\n", (19726, 19763), False, 'from sklearn.metrics import pairwise_distances\n'), ((20799, 20846), 'pandas.DataFrame', 'pd.DataFrame', (['distmat'], {'columns': 'tips', 'index': 'tips'}), '(distmat, columns=tips, index=tips)\n', (20811, 20846), True, 'import pandas as pd\n'), ((23141, 23161), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (23155, 23161), True, 'import numpy as np\n'), ((23765, 23778), 'cupy.asnumpy', 'cp.asnumpy', (['R'], {}), '(R)\n', (23775, 23778), True, 'import cupy as cp\n'), ((24363, 24418), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['X.values', "Curve[0]['NodePositions']"], {}), "(X.values, Curve[0]['NodePositions'])\n", (24381, 24418), False, 'from sklearn.metrics import pairwise_distances\n'), ((25454, 25501), 'pandas.DataFrame', 'pd.DataFrame', (['distmat'], {'columns': 'tips', 'index': 'tips'}), '(distmat, columns=tips, index=tips)\n', (25466, 25501), True, 'import pandas as pd\n'), ((27425, 27449), 'scipy.sparse.issparse', 'sparse.issparse', (['adata.X'], {}), '(adata.X)\n', (27440, 27449), False, 'from scipy import sparse\n'), ((14004, 14171), 'warnings.warn', 'warnings.warn', (['"""ElPiGraph package is not installed \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it"""'], {}), '(\n """ElPiGraph package is not installed \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it"""\n )\n', (14017, 14171), False, 'import warnings\n'), ((14939, 14959), 'cupy.asarray', 'cp.asarray', (['X.values'], {}), '(X.values)\n', (14949, 14959), True, 'import cupy as cp\n'), ((14961, 14997), 'cupy.asarray', 'cp.asarray', (["Tree[0]['NodePositions']"], {}), "(Tree[0]['NodePositions'])\n", (14971, 14997), True, 'import cupy as cp\n'), ((16289, 16310), 'numpy.arange', 'np.arange', (['R.shape[1]'], {}), '(R.shape[1])\n', (16298, 16310), True, 'import numpy as np\n'), ((16651, 16683), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['F[:, tips].T'], {}), '(F[:, tips].T)\n', (16669, 16683), False, 'from sklearn.metrics import pairwise_distances\n'), ((16826, 16851), 'numpy.argmin', 'np.argmin', (['distmat.values'], {}), '(distmat.values)\n', (16835, 16851), True, 'import numpy as np\n'), ((18221, 18388), 'warnings.warn', 'warnings.warn', (['"""ElPiGraph package is not installed \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it"""'], {}), '(\n """ElPiGraph package is not installed \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it"""\n )\n', (18234, 18388), False, 'import warnings\n'), ((19028, 19048), 'cupy.asarray', 'cp.asarray', (['X.values'], {}), '(X.values)\n', (19038, 19048), True, 'import cupy as cp\n'), ((19050, 19087), 'cupy.asarray', 'cp.asarray', (["Curve[0]['NodePositions']"], {}), "(Curve[0]['NodePositions'])\n", (19060, 19087), True, 'import cupy as cp\n'), ((20384, 20405), 'numpy.arange', 'np.arange', (['R.shape[1]'], {}), '(R.shape[1])\n', (20393, 20405), True, 'import numpy as np\n'), ((20747, 20779), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['F[:, tips].T'], {}), '(F[:, tips].T)\n', (20765, 20779), False, 'from sklearn.metrics import pairwise_distances\n'), ((20922, 20947), 'numpy.argmin', 'np.argmin', (['distmat.values'], {}), '(distmat.values)\n', (20931, 20947), True, 'import numpy as np\n'), ((22874, 23041), 'warnings.warn', 'warnings.warn', (['"""ElPiGraph package is not installed \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it"""'], {}), '(\n """ElPiGraph package is not installed \nPlease use "pip install git+https://github.com/j-bac/elpigraph-python.git" to install it"""\n )\n', (22887, 23041), False, 'import warnings\n'), ((23682, 23702), 'cupy.asarray', 'cp.asarray', (['X.values'], {}), '(X.values)\n', (23692, 23702), True, 'import cupy as cp\n'), ((23704, 23741), 'cupy.asarray', 'cp.asarray', (["Curve[0]['NodePositions']"], {}), "(Curve[0]['NodePositions'])\n", (23714, 23741), True, 'import cupy as cp\n'), ((25039, 25060), 'numpy.arange', 'np.arange', (['R.shape[1]'], {}), '(R.shape[1])\n', (25048, 25060), True, 'import numpy as np\n'), ((25402, 25434), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['F[:, tips].T'], {}), '(F[:, tips].T)\n', (25420, 25434), False, 'from sklearn.metrics import pairwise_distances\n'), ((25577, 25602), 'numpy.argmin', 'np.argmin', (['distmat.values'], {}), '(distmat.values)\n', (25586, 25602), True, 'import numpy as np\n'), ((27467, 27510), 'pandas.DataFrame', 'DataFrame', (['adata.X.A'], {'index': 'adata.obs_names'}), '(adata.X.A, index=adata.obs_names)\n', (27476, 27510), False, 'from pandas import DataFrame\n'), ((27541, 27582), 'pandas.DataFrame', 'DataFrame', (['adata.X'], {'index': 'adata.obs_names'}), '(adata.X, index=adata.obs_names)\n', (27550, 27582), False, 'from pandas import DataFrame\n'), ((27635, 27673), 'scipy.sparse.issparse', 'sparse.issparse', (['adata.layers[use_rep]'], {}), '(adata.layers[use_rep])\n', (27650, 27673), False, 'from scipy import sparse\n'), ((27691, 27748), 'pandas.DataFrame', 'DataFrame', (['adata.layers[use_rep].A'], {'index': 'adata.obs_names'}), '(adata.layers[use_rep].A, index=adata.obs_names)\n', (27700, 27748), False, 'from pandas import DataFrame\n'), ((27779, 27834), 'pandas.DataFrame', 'DataFrame', (['adata.layers[use_rep]'], {'index': 'adata.obs_names'}), '(adata.layers[use_rep], index=adata.obs_names)\n', (27788, 27834), False, 'from pandas import DataFrame\n'), ((27886, 27939), 'pandas.DataFrame', 'DataFrame', (['adata.obsm[use_rep]'], {'index': 'adata.obs_names'}), '(adata.obsm[use_rep], index=adata.obs_names)\n', (27895, 27939), False, 'from pandas import DataFrame\n'), ((15104, 15128), 'numpy.repeat', 'np.repeat', (['(1)', 'R.shape[0]'], {}), '(1, R.shape[0])\n', (15113, 15128), True, 'import numpy as np\n'), ((15740, 15764), 'numpy.repeat', 'np.repeat', (['(1)', 'R.shape[0]'], {}), '(1, R.shape[0])\n', (15749, 15764), True, 'import numpy as np\n'), ((19194, 19218), 'numpy.repeat', 'np.repeat', (['(1)', 'R.shape[0]'], {}), '(1, R.shape[0])\n', (19203, 19218), True, 'import numpy as np\n'), ((19833, 19857), 'numpy.repeat', 'np.repeat', (['(1)', 'R.shape[0]'], {}), '(1, R.shape[0])\n', (19842, 19857), True, 'import numpy as np\n'), ((23848, 23872), 'numpy.repeat', 'np.repeat', (['(1)', 'R.shape[0]'], {}), '(1, R.shape[0])\n', (23857, 23872), True, 'import numpy as np\n'), ((24488, 24512), 'numpy.repeat', 'np.repeat', (['(1)', 'R.shape[0]'], {}), '(1, R.shape[0])\n', (24497, 24512), True, 'import numpy as np\n'), ((15962, 15995), 'pandas.DataFrame', 'pd.DataFrame', (["Tree[0]['Edges'][0]"], {}), "(Tree[0]['Edges'][0])\n", (15974, 15995), True, 'import pandas as pd\n'), ((20056, 20090), 'pandas.DataFrame', 'pd.DataFrame', (["Curve[0]['Edges'][0]"], {}), "(Curve[0]['Edges'][0])\n", (20068, 20090), True, 'import pandas as pd\n'), ((24711, 24745), 'pandas.DataFrame', 'pd.DataFrame', (["Curve[0]['Edges'][0]"], {}), "(Curve[0]['Edges'][0])\n", (24723, 24745), True, 'import pandas as pd\n')]
from load_oh import * from sklearn.neural_network import MLPRegressor from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import make_scorer from sklearn.model_selection import cross_val_score from sklearn.model_selection import RandomizedSearchCV import numpy as np import sys if __name__ == '__main__': if len(sys.argv) < 3: print('Usage: python _ data_dir ws') exit() data_dir = sys.argv[1] ws = int(sys.argv[2]) train_prot_windows, train_asas, test_prot_windows, test_asas = load_oh(data_dir, ws) print('Dataset loaded') print('Doing Random Grid Search with 5-fold cross validation') mlp = MLPRegressor(verbose=True, early_stopping=True) param_distributions = {'learning_rate_init':10.0**np.arange(-5,0), 'n_iter_no_change':list(range(2,20,2)), 'alpha':10.0**np.arange(-3,3), 'beta_1':1 - 10.0**np.arange(-3, 0), 'beta_2':1 - 10.0**np.arange(-6, -3)} rscv = RandomizedSearchCV(mlp, param_distributions, n_iter=25, scoring=make_scorer(mean_absolute_error), cv=5, verbose=100, return_train_score=True) rscv.fit(train_prot_windows, train_asas) #mlp = MLPRegressor(hidden_layer_sizes=(100,), verbose=True, early_stopping=True, learning_rate_init=0.01, alpha=1, n_iter_no_change=20) #print('Doing 5-fold cross validation') #cv_result = cross_val_score(mlp, train_prot_windows, train_asas, cv=5, scoring=make_scorer(mean_absolute_error), verbose=100, n_jobs=1) #print(cv_result) #print(cv_result.mean()) #print('Calling fit') #mlp.verbose = False #mlp.fit(train_prot_windows, train_asas) print(mean_absolute_error(test_asas, rscv.predict(test_prot_windows))) with open('rscv-output', 'w') as f: f.write(str(rscv.cv_results_)) f.write('\n') f.write(str(rscv.best_params_)) f.write('\n') f.write(str(rscv.best_score_)) f.write('\n') f.write(str(rscv.refit_time_))
[ "sklearn.neural_network.MLPRegressor", "sklearn.metrics.make_scorer", "numpy.arange" ]
[((707, 754), 'sklearn.neural_network.MLPRegressor', 'MLPRegressor', ([], {'verbose': '(True)', 'early_stopping': '(True)'}), '(verbose=True, early_stopping=True)\n', (719, 754), False, 'from sklearn.neural_network import MLPRegressor\n'), ((809, 825), 'numpy.arange', 'np.arange', (['(-5)', '(0)'], {}), '(-5, 0)\n', (818, 825), True, 'import numpy as np\n'), ((938, 954), 'numpy.arange', 'np.arange', (['(-3)', '(3)'], {}), '(-3, 3)\n', (947, 954), True, 'import numpy as np\n'), ((1161, 1193), 'sklearn.metrics.make_scorer', 'make_scorer', (['mean_absolute_error'], {}), '(mean_absolute_error)\n', (1172, 1193), False, 'from sklearn.metrics import make_scorer\n'), ((1002, 1018), 'numpy.arange', 'np.arange', (['(-3)', '(0)'], {}), '(-3, 0)\n', (1011, 1018), True, 'import numpy as np\n'), ((1067, 1084), 'numpy.arange', 'np.arange', (['(-6)', '(-3)'], {}), '(-6, -3)\n', (1076, 1084), True, 'import numpy as np\n')]
import numpy as np from numpy import linalg as LA from scipy.sparse.linalg import eigsh from scipy.linalg import expm import sys from tqdm import tqdm, trange sys.path.insert(0, '../') from startOpt.q_gamma import paramQ_star def runOpt_md(A, C, gamma, s, max_iter=100): n = A.shape[0] degs = A.sum(axis=0).T # Learning Rate eta = 5 p = 2 * LA.norm(C, ord='fro') / gamma Y = p / degs.sum() * np.eye(n) X = np.zeros((n ,n, max_iter)) grad = np.zeros(n) v0 = np.ones(n) for i in range(max_iter): Q = paramQ_star(Adj=A, degs=degs, gamma=gamma, Y=Y, r=s) _, u = eigsh(np.real(Q + C), k=1, which='LA', v0=v0, tol=0.000001) v0 = u X[:,:,i] = u * u.T QX = paramQ_star(A, degs, gamma, r=s, X=X[:,:,i]) # Y = expm(eta * grad / degs.max()) grad = QX Y = Y * expm( - eta * grad / degs.max() ) Y = Y / np.trace(np.diag(degs) * Y) * p M = X.mean(2) return M def runOpt_imd(A, C, gamma, s, max_iter=50, num_particles=10): n = A.shape[0] degs = A.sum(axis=0).T # Learning Rate eta = 5 p = 2 * LA.norm(C, ord='fro') / gamma D = degs.max() # A_ij = 1/Np interaction_mat = np.ones((num_particles, num_particles)) / num_particles particles = np.empty((n,n,num_particles), dtype=np.float) for j in range(num_particles): P = p / degs.sum() * (np.eye(n) + np.random.rand(n,n) * 0.1) P = (P + P.T) / 2 particles[:, : ,j] = P / np.trace(P) * p X = np.zeros((n ,n, max_iter, num_particles)) for i in range(max_iter): grad = np.zeros(n) v0 = np.ones(n) for part in range(num_particles): Y = particles[:,:,part].copy() Q = paramQ_star(Adj=A, degs=degs, gamma=gamma, Y=Y, r=s) _, u = eigsh(np.real(Q + C), k=1, which='LA', v0=v0, tol=0.000001) v0 = u X[:, :, i, part] = u.reshape(-1,1) * u.reshape(1,-1) #/ num_particles QX = paramQ_star(A, degs, gamma, r=s, X=X[:,:,i, part].squeeze()) grad = QX # particle_mean = np.average(particles, axis=2, weights=interaction_mat[part,:]) # # particle_mean += particles[:,:,part] * (1 - interaction_mat[part,part]) # particle_mean = particle_mean.reshape(n,n) # Y = particle_mean * expm( - eta * grad / D) # # Y_i' = Prod{i=1}^N Particles_{ij}^A_{ij} Y = np.prod(np.power(particles, interaction_mat[part]), axis=2) # Y_i = Y_i ' exp(-eta * grad_Y) Y = Y * expm( - eta * grad) # Normalise trace to p Y = Y / np.trace(np.diag(degs) * Y) * p particles[:, : ,part] = Y.copy() M = X.mean((2,3)) return M
[ "numpy.trace", "numpy.eye", "sys.path.insert", "numpy.ones", "numpy.random.rand", "numpy.power", "numpy.diag", "numpy.real", "numpy.zeros", "scipy.linalg.expm", "numpy.empty", "numpy.linalg.norm", "startOpt.q_gamma.paramQ_star" ]
[((166, 191), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../"""'], {}), "(0, '../')\n", (181, 191), False, 'import sys\n'), ((461, 487), 'numpy.zeros', 'np.zeros', (['(n, n, max_iter)'], {}), '((n, n, max_iter))\n', (469, 487), True, 'import numpy as np\n'), ((502, 513), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (510, 513), True, 'import numpy as np\n'), ((526, 536), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (533, 536), True, 'import numpy as np\n'), ((1352, 1399), 'numpy.empty', 'np.empty', (['(n, n, num_particles)'], {'dtype': 'np.float'}), '((n, n, num_particles), dtype=np.float)\n', (1360, 1399), True, 'import numpy as np\n'), ((1595, 1636), 'numpy.zeros', 'np.zeros', (['(n, n, max_iter, num_particles)'], {}), '((n, n, max_iter, num_particles))\n', (1603, 1636), True, 'import numpy as np\n'), ((442, 451), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (448, 451), True, 'import numpy as np\n'), ((585, 637), 'startOpt.q_gamma.paramQ_star', 'paramQ_star', ([], {'Adj': 'A', 'degs': 'degs', 'gamma': 'gamma', 'Y': 'Y', 'r': 's'}), '(Adj=A, degs=degs, gamma=gamma, Y=Y, r=s)\n', (596, 637), False, 'from startOpt.q_gamma import paramQ_star\n'), ((772, 818), 'startOpt.q_gamma.paramQ_star', 'paramQ_star', (['A', 'degs', 'gamma'], {'r': 's', 'X': 'X[:, :, i]'}), '(A, degs, gamma, r=s, X=X[:, :, i])\n', (783, 818), False, 'from startOpt.q_gamma import paramQ_star\n'), ((1279, 1318), 'numpy.ones', 'np.ones', (['(num_particles, num_particles)'], {}), '((num_particles, num_particles))\n', (1286, 1318), True, 'import numpy as np\n'), ((1688, 1699), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1696, 1699), True, 'import numpy as np\n'), ((1714, 1724), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (1721, 1724), True, 'import numpy as np\n'), ((384, 405), 'numpy.linalg.norm', 'LA.norm', (['C'], {'ord': '"""fro"""'}), "(C, ord='fro')\n", (391, 405), True, 'from numpy import linalg as LA\n'), ((660, 674), 'numpy.real', 'np.real', (['(Q + C)'], {}), '(Q + C)\n', (667, 674), True, 'import numpy as np\n'), ((1185, 1206), 'numpy.linalg.norm', 'LA.norm', (['C'], {'ord': '"""fro"""'}), "(C, ord='fro')\n", (1192, 1206), True, 'from numpy import linalg as LA\n'), ((1833, 1885), 'startOpt.q_gamma.paramQ_star', 'paramQ_star', ([], {'Adj': 'A', 'degs': 'degs', 'gamma': 'gamma', 'Y': 'Y', 'r': 's'}), '(Adj=A, degs=degs, gamma=gamma, Y=Y, r=s)\n', (1844, 1885), False, 'from startOpt.q_gamma import paramQ_star\n'), ((1468, 1477), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (1474, 1477), True, 'import numpy as np\n'), ((1568, 1579), 'numpy.trace', 'np.trace', (['P'], {}), '(P)\n', (1576, 1579), True, 'import numpy as np\n'), ((1912, 1926), 'numpy.real', 'np.real', (['(Q + C)'], {}), '(Q + C)\n', (1919, 1926), True, 'import numpy as np\n'), ((2573, 2615), 'numpy.power', 'np.power', (['particles', 'interaction_mat[part]'], {}), '(particles, interaction_mat[part])\n', (2581, 2615), True, 'import numpy as np\n'), ((2696, 2713), 'scipy.linalg.expm', 'expm', (['(-eta * grad)'], {}), '(-eta * grad)\n', (2700, 2713), False, 'from scipy.linalg import expm\n'), ((1480, 1500), 'numpy.random.rand', 'np.random.rand', (['n', 'n'], {}), '(n, n)\n', (1494, 1500), True, 'import numpy as np\n'), ((962, 975), 'numpy.diag', 'np.diag', (['degs'], {}), '(degs)\n', (969, 975), True, 'import numpy as np\n'), ((2782, 2795), 'numpy.diag', 'np.diag', (['degs'], {}), '(degs)\n', (2789, 2795), True, 'import numpy as np\n')]
from ctypes import (c_void_p, c_int, byref, POINTER, c_double, c_size_t) from . import MINTLIB from . import error_handler, warning_handler import numpy FILE = 'vectorinterp.py' DOUBLE_ARRAY_PTR = numpy.ctypeslib.ndpointer(dtype=numpy.float64) class VectorInterp(object): """ A class to compute the vector representation of a 1-form in 2D """ def __init__(self): """ Constructor. """ self.ptr = c_void_p() self.obj = byref(self.ptr) self.numTargetPoints = 0 self.numGridEdges = 0 self.numGridCells = 0 MINTLIB.mnt_vectorinterp_new.argtypes = [POINTER(c_void_p)] ier = MINTLIB.mnt_vectorinterp_new(self.obj) if ier: error_handler(FILE, '__init__', ier) def __del__(self): """ Destructor. """ MINTLIB.mnt_vectorinterp_del.argtypes = [POINTER(c_void_p)] ier = MINTLIB.mnt_vectorinterp_del(self.obj) if ier: error_handler(FILE, '__del__', ier) def setGrid(self, grid): """ Set the grid. :param grid: instance of Grid """ self.numGridEdges = grid.getNumberOfEdges() self.numGridCells = grid.getNumberOfCells() MINTLIB.mnt_vectorinterp_setGrid.argtypes = [POINTER(c_void_p), c_void_p] ier = MINTLIB.mnt_vectorinterp_setGrid(self.obj, grid.ptr) if ier: error_handler(FILE, 'setGrid', ier) def buildLocator(self, numCellsPerBucket=10, periodX=360.): """ Build the cell locator. :param numCellsPerBucket: approximate number of cells per bucket :param periodX: periodicity in x (set to 0 if non-periodic) :note: call this after setGrid """ MINTLIB.mnt_vectorinterp_buildLocator.argtypes = [POINTER(c_void_p), c_int, c_double] ier = MINTLIB.mnt_vectorinterp_buildLocator(self.obj, numCellsPerBucket, periodX) if ier: error_handler(FILE, 'buildLocator', ier) def findPoints(self, targetPoints, tol2=1.e-12): """ Find the cells containing the target points. :param targetPoints: array of size numPoints times 3 :param tol2: tolerance in the square of the distance :returns the number of points outside the domain """ if len(targetPoints.shape) != 2: msg = 'ERROR: targetPoints should have dims (numTargetPoints, 3)'\ f', got {targetPoints.shape}' raise RuntimeError(msg) if targetPoints.shape[-1] != 3: msg = "ERROR: targetPoints' last dimension should be 3,"\ f" got {targetPoints.shape[-1]}" raise RuntimeError(msg) MINTLIB.mnt_vectorinterp_findPoints.argtypes = [POINTER(c_void_p), c_size_t, DOUBLE_ARRAY_PTR, c_double] self.numTargetPoints = targetPoints.shape[0] numBad = MINTLIB.mnt_vectorinterp_findPoints(self.obj, self.numTargetPoints, targetPoints, tol2) return numBad def getEdgeVectors(self, data, placement): """ Get the edge vectors at given target points. :param data: edge data array of size number of unique edges :param placement: 0 if data are cell by cell (size num cells * 4), assume unique edge Id data otherwise (size num edges) :returns vector array of size numTargetPoints times 3 :note: call this after invoking findPoints. """ # check data size n = numpy.prod(data.shape) if placement == 0 and n != self.numGridCells * 4: msg = f"data has wrong size (= {n}), num cells*4 = {self.numGridCells*4}" ier = 10 error_handler(FILE, 'getEdgeVectors', ier, detailedmsg=msg) return elif placement != 0 and n != self.numGridEdges: msg = f"data has wrong size (= {n}), num edges = {self.numGridEdges}" ier = 11 error_handler(FILE, 'getEdgeVectors', ier, detailedmsg=msg) return MINTLIB.mnt_vectorinterp_getEdgeVectors.argtypes = [ POINTER(c_void_p), DOUBLE_ARRAY_PTR, DOUBLE_ARRAY_PTR, c_int] res = numpy.zeros((self.numTargetPoints, 3), numpy.float64) ier = MINTLIB.mnt_vectorinterp_getEdgeVectors(self.obj, data, res, placement) if ier: msg = "Some target lines fall outside the grid." warning_handler(FILE, 'getEdgeVectors', ier, detailedmsg=msg) return res def getFaceVectors(self, data, placement): """ Get the lateral face vectors at given target points. :param data: edge data array of size number of unique edges :param placement: 0 if data are cell by cell (size num cells * 4), assume unique edge Id data otherwise (size num edges) :returns vector array of size numTargetPoints times 3 :note: call this after invoking findPoints. """ # check data size n = numpy.prod(data.shape) if placement == 0 and n != self.numGridCells * 4: msg = f"data has wrong size (= {n}), num cells*4 = {self.numGridCells*4}" ier = 10 error_handler(FILE, 'getEdgeVectors', ier, detailedmsg=msg) return elif placement != 0 and n != self.numGridEdges: msg = f"data has wrong size (= {n}), num edges = {self.numGridEdges}" ier = 11 error_handler(FILE, 'getEdgeVectors', ier, detailedmsg=msg) return MINTLIB.mnt_vectorinterp_getFaceVectors.argtypes = [ POINTER(c_void_p), DOUBLE_ARRAY_PTR, DOUBLE_ARRAY_PTR, c_int] res = numpy.zeros((self.numTargetPoints, 3), numpy.float64) ier = MINTLIB.mnt_vectorinterp_getFaceVectors(self.obj, data, res, placement) if ier: msg = "Some target lines fall outside the grid." warning_handler(FILE, 'getFaceVectors', ier, detailedmsg=msg) return res
[ "numpy.prod", "ctypes.byref", "ctypes.POINTER", "numpy.zeros", "numpy.ctypeslib.ndpointer", "ctypes.c_void_p" ]
[((219, 265), 'numpy.ctypeslib.ndpointer', 'numpy.ctypeslib.ndpointer', ([], {'dtype': 'numpy.float64'}), '(dtype=numpy.float64)\n', (244, 265), False, 'import numpy\n'), ((469, 479), 'ctypes.c_void_p', 'c_void_p', ([], {}), '()\n', (477, 479), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n'), ((499, 514), 'ctypes.byref', 'byref', (['self.ptr'], {}), '(self.ptr)\n', (504, 514), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n'), ((3927, 3949), 'numpy.prod', 'numpy.prod', (['data.shape'], {}), '(data.shape)\n', (3937, 3949), False, 'import numpy\n'), ((4818, 4871), 'numpy.zeros', 'numpy.zeros', (['(self.numTargetPoints, 3)', 'numpy.float64'], {}), '((self.numTargetPoints, 3), numpy.float64)\n', (4829, 4871), False, 'import numpy\n'), ((5748, 5770), 'numpy.prod', 'numpy.prod', (['data.shape'], {}), '(data.shape)\n', (5758, 5770), False, 'import numpy\n'), ((6639, 6692), 'numpy.zeros', 'numpy.zeros', (['(self.numTargetPoints, 3)', 'numpy.float64'], {}), '((self.numTargetPoints, 3), numpy.float64)\n', (6650, 6692), False, 'import numpy\n'), ((658, 675), 'ctypes.POINTER', 'POINTER', (['c_void_p'], {}), '(c_void_p)\n', (665, 675), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n'), ((912, 929), 'ctypes.POINTER', 'POINTER', (['c_void_p'], {}), '(c_void_p)\n', (919, 929), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n'), ((1320, 1337), 'ctypes.POINTER', 'POINTER', (['c_void_p'], {}), '(c_void_p)\n', (1327, 1337), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n'), ((1840, 1857), 'ctypes.POINTER', 'POINTER', (['c_void_p'], {}), '(c_void_p)\n', (1847, 1857), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n'), ((2906, 2923), 'ctypes.POINTER', 'POINTER', (['c_void_p'], {}), '(c_void_p)\n', (2913, 2923), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n'), ((4574, 4591), 'ctypes.POINTER', 'POINTER', (['c_void_p'], {}), '(c_void_p)\n', (4581, 4591), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n'), ((6395, 6412), 'ctypes.POINTER', 'POINTER', (['c_void_p'], {}), '(c_void_p)\n', (6402, 6412), False, 'from ctypes import c_void_p, c_int, byref, POINTER, c_double, c_size_t\n')]
# -*- coding: utf-8 -*- """ @author : <NAME> """ import numpy as np def conv_forward(x, w, b, conv_param): """ a naive implementation of the forward pass for a convolutional layer """ stride = conv_param['stride'] pad = conv_param['pad'] N, C, H, W = x.shape F, C, HH, WW = w.shape H_out = 1 + (H + 2 * pad - HH) / stride W_out = 1 + (H + 2 * pad - WW) / stride H_out = int(H_out) W_out = int(W_out) out = np.zeros((N, F, H_out, W_out)) for n in range(N): conv_in = np.pad(x[n], ((0, 0), (pad, pad), (pad, pad)), mode='constant') for f in range(F): conv_w = w[f] conv_b = b[f] for i in range(H_out): for j in range(W_out): conv_i = i * stride conv_j = j * stride conv_area = conv_in[:, conv_i : conv_i + HH, conv_j : conv_j + WW] out[n, f, i, j] = np.sum(conv_area * conv_w) + conv_b cache = (x, w, b, conv_param) return out, cache def conv_backward(dout, cache): """ a naive implementation of the backward pass for a convolutional layer """ x, w, b, conv_param = cache stride = conv_param['stride'] pad = conv_param['pad'] N, C, H, W = x.shape F, C, HH, WW = w.shape H_out = 1 + (H + 2 * pad - HH) / stride W_out = 1 + (H + 2 * pad - WW) / stride H_out = int(H_out) W_out = int(W_out) dx = np.zeros(x.shape) dw = np.zeros(w.shape) db = np.zeros(b.shape) for n in range(N): conv_in = np.pad(x[n], ((0, 0), (pad, pad), (pad, pad)), mode='constant') dconv_in = np.zeros(conv_in.shape) for f in range(F): conv_w = w[f] conv_b = b[f] df = dout[n, f] for i in range(H_out): for j in range(W_out): conv_i = i * stride conv_j = j * stride conv_area = conv_in[:, conv_i : conv_i + HH, conv_j : conv_j + WW] dconv = df[i, j] db[f] += dconv dw[f] += dconv * conv_area dconv_in[:, conv_i: conv_i + HH, conv_j: conv_j + WW] += dconv * conv_w dx[n] += dconv_in[:, pad:-pad, pad:-pad] return dx, dw, db def relu_forward(x): out = x * (x > 0) cache = x return out, cache def relu_backward(dout, cache): x = cache dx = dout * (x > 0) return dx def batchnorm_forward(x, gamma, beta, bn_param): mode = bn_param['mode'] eps = bn_param.get('eps', 1e-5) momentum = bn_param.get('momentum', 0.9) D = x[0].shape if mode == 'train': running_mean = np.zeros(D, dtype=x.dtype) running_var = np.zeros(D, dtype=x.dtype) sample_mean = np.mean(x, axis=0) sample_var = np.var(x, axis=0) sample_std = np.sqrt(sample_var + eps) x_norm = (x - sample_mean) / sample_std out = x_norm * gamma + beta running_mean = momentum * running_mean + (1.0 - momentum) * sample_mean running_var = momentum * running_var + (1.0 - momentum) * sample_var cache = (x, sample_mean, sample_var, sample_std, x_norm, beta, gamma, eps) elif mode == 'test': running_mean = bn_param['running_mean'] running_std = bn_param['running_std'] x_norm = (x - running_mean) / running_std out = x_norm * gamma + beta cache = (running_mean, running_std) else: raise ValueError('Invalid forward batchnorm mode %s' % mode) # bn_param['running_mean'] = running_mean # bn_param['running_var'] = running_var return out, cache def batchnorm_backward(dout, cache): (x, sample_mean, sample_var, sample_std, x_norm, beta, gamma, eps) = cache dgamma = np.sum(dout * x_norm, axis=0) dbeta = np.sum(dout, axis=0) N, D, HH, WW = x.shape dx_norm = dout * gamma dsample_var = np.sum(-1 / 2 * dx_norm * (x - sample_mean) / (sample_var + eps) ** (3 / 2), axis = 0) dsample_mean = np.sum(-1 / sample_std * dx_norm, axis=0) + 1 / N * dsample_var * np.sum(-2 * (x - sample_mean), axis=0) dx = 1 / sample_std * dx_norm + dsample_var * 2 / N * (x - sample_mean) + 1 / N * dsample_mean return dx, dgamma, dbeta def dropout_forward(x, dp_param): p, mode = dp_param['p'], dp_param['mode'] mask = None out = None if mode == 'train': mask = 1.0 * (np.random.rand(x.shape) > p) def conv_relu_forward(x, w, b, conv_param): var, conv_cache = conv_forward(x, w, b, conv_param) out, relu_cache = rule_forward(var) cache = (conv_cache, relu_cache) return out, cache def conv_relu_backward(dout, cache): conv_cache, relu_cache = cache dvar = relu_backward(dout, relu_cache) dx, dw, db = conv_backward(dvar, conv_cache) return dx, dw, db def conv_bn_relu_forward(x, w, b, gamma, beta, conv_param, bn_param): var1, conv_cache = conv_forward(x, w, b, conv_param) var2, bn_cache = batchnorm_forward(var1, gamma, beta, bn_param) out, relu_cache = relu_forward(var2) cache = (conv_cache, bn_cache, relu_cache) if bn_param['mode'] == 'train': x, mean, var, std, x_norm, beta, gamma, eps = bn_cache return out, cache, mean, std else: mean, std = bn_cache return out, cache, mean, std def conv_bn_relu_backward(dout, cache): conv_cache, bn_cache, relu_cache = cache dvar2 = relu_backward(dout, relu_cache) dvar1, dgamma, dbeta = batchnorm_backward(dvar2, bn_cache) dx, dw, db = conv_backward(dvar1, conv_cache) return dx, dw, db, dgamma, dbeta
[ "numpy.mean", "numpy.sqrt", "numpy.random.rand", "numpy.sum", "numpy.zeros", "numpy.pad", "numpy.var" ]
[((457, 487), 'numpy.zeros', 'np.zeros', (['(N, F, H_out, W_out)'], {}), '((N, F, H_out, W_out))\n', (465, 487), True, 'import numpy as np\n'), ((1457, 1474), 'numpy.zeros', 'np.zeros', (['x.shape'], {}), '(x.shape)\n', (1465, 1474), True, 'import numpy as np\n'), ((1484, 1501), 'numpy.zeros', 'np.zeros', (['w.shape'], {}), '(w.shape)\n', (1492, 1501), True, 'import numpy as np\n'), ((1511, 1528), 'numpy.zeros', 'np.zeros', (['b.shape'], {}), '(b.shape)\n', (1519, 1528), True, 'import numpy as np\n'), ((3798, 3827), 'numpy.sum', 'np.sum', (['(dout * x_norm)'], {'axis': '(0)'}), '(dout * x_norm, axis=0)\n', (3804, 3827), True, 'import numpy as np\n'), ((3840, 3860), 'numpy.sum', 'np.sum', (['dout'], {'axis': '(0)'}), '(dout, axis=0)\n', (3846, 3860), True, 'import numpy as np\n'), ((3933, 4021), 'numpy.sum', 'np.sum', (['(-1 / 2 * dx_norm * (x - sample_mean) / (sample_var + eps) ** (3 / 2))'], {'axis': '(0)'}), '(-1 / 2 * dx_norm * (x - sample_mean) / (sample_var + eps) ** (3 / 2),\n axis=0)\n', (3939, 4021), True, 'import numpy as np\n'), ((529, 592), 'numpy.pad', 'np.pad', (['x[n]', '((0, 0), (pad, pad), (pad, pad))'], {'mode': '"""constant"""'}), "(x[n], ((0, 0), (pad, pad), (pad, pad)), mode='constant')\n", (535, 592), True, 'import numpy as np\n'), ((1570, 1633), 'numpy.pad', 'np.pad', (['x[n]', '((0, 0), (pad, pad), (pad, pad))'], {'mode': '"""constant"""'}), "(x[n], ((0, 0), (pad, pad), (pad, pad)), mode='constant')\n", (1576, 1633), True, 'import numpy as np\n'), ((1653, 1676), 'numpy.zeros', 'np.zeros', (['conv_in.shape'], {}), '(conv_in.shape)\n', (1661, 1676), True, 'import numpy as np\n'), ((2695, 2721), 'numpy.zeros', 'np.zeros', (['D'], {'dtype': 'x.dtype'}), '(D, dtype=x.dtype)\n', (2703, 2721), True, 'import numpy as np\n'), ((2744, 2770), 'numpy.zeros', 'np.zeros', (['D'], {'dtype': 'x.dtype'}), '(D, dtype=x.dtype)\n', (2752, 2770), True, 'import numpy as np\n'), ((2794, 2812), 'numpy.mean', 'np.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (2801, 2812), True, 'import numpy as np\n'), ((2834, 2851), 'numpy.var', 'np.var', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (2840, 2851), True, 'import numpy as np\n'), ((2873, 2898), 'numpy.sqrt', 'np.sqrt', (['(sample_var + eps)'], {}), '(sample_var + eps)\n', (2880, 2898), True, 'import numpy as np\n'), ((4039, 4080), 'numpy.sum', 'np.sum', (['(-1 / sample_std * dx_norm)'], {'axis': '(0)'}), '(-1 / sample_std * dx_norm, axis=0)\n', (4045, 4080), True, 'import numpy as np\n'), ((4105, 4143), 'numpy.sum', 'np.sum', (['(-2 * (x - sample_mean))'], {'axis': '(0)'}), '(-2 * (x - sample_mean), axis=0)\n', (4111, 4143), True, 'import numpy as np\n'), ((4430, 4453), 'numpy.random.rand', 'np.random.rand', (['x.shape'], {}), '(x.shape)\n', (4444, 4453), True, 'import numpy as np\n'), ((951, 977), 'numpy.sum', 'np.sum', (['(conv_area * conv_w)'], {}), '(conv_area * conv_w)\n', (957, 977), True, 'import numpy as np\n')]
import os import cv2 import platform import numpy as np import random as r import matplotlib.pyplot as plt import utils as u ##################################################################################################### # Function to get ORB Features from an image. def get_orb_features(orb, image): """ orb: ORB Object image: (np.ndarray) image data """ image = cv2.cvtColor(src=image, code=cv2.COLOR_RGB2GRAY) kp, des = orb.detectAndCompute(image, None) return kp, des # Fucntion to return topK keypoints. TopK keypoints are decided by their response def get_topK(kp, K=5): """ kp: List of ORB Keypoints K: Top K keypoints to use (Default: 5) """ responses = [] for k in kp: responses.append(k.response) if len(responses) > K: responses_idx = np.argpartition(responses, -K)[-K:].astype("int64") topK_kp = [] for idx in responses_idx: topK_kp.append(kp[idx]) return topK_kp else: return None # Image Analysis tool showing various keypoint attributes for a random keypoint def show_kp_info(kp): kp_sample = r.randint(0, len(kp)-1) u.breaker() print("Total Number of Keypoints : {}".format(len(kp))) u.breaker() print("Keypoint {} Information".format(kp_sample)) u.breaker() print("Angle : {:.5f}".format(kp[kp_sample].angle)) print("Octave : {:.5f}".format(kp[kp_sample].octave)) print("Point : {}".format(kp[kp_sample].pt)) print("Response : {:.5f}".format(kp[kp_sample].response)) print("Size : {:.5f}".format(kp[kp_sample].size)) # Image Analysis tool showing various keypoint attributes the entire list of keypoints def show_info(kp): angles = [] octaves = [] points = [] responses = [] sizes = [] for k in kp: angles.append(k.angle) octaves.append(k.octave) points.append(k.pt) responses.append(k.response) sizes.append(k.size) x_Axis = np.arange(1, len(kp)+1) plt.figure() plt.subplot(1, 4, 1) plt.plot(x_Axis, angles, "r") plt.grid() plt.title("Angles") plt.subplot(1, 4, 2) plt.plot(x_Axis, octaves, "r") plt.grid() plt.title("Octaves") plt.subplot(1, 4, 3) plt.plot(x_Axis, responses, "r") plt.grid() plt.title("Responses") plt.subplot(1, 4, 4) plt.plot(x_Axis, sizes, "r") plt.grid() plt.title("Sizes") plt.show() # Display the Keypoint image def show_kp_image(image, kp): """ image: (np.ndarray) Image data kp: (list) List of ORB Keypoints """ kp_image = cv2.drawKeypoints(image, kp, None, (0, 255, 0), cv2.DRAW_MATCHES_FLAGS_DEFAULT) plt.figure() plt.imshow(kp_image) plt.axis("off") plt.show() ##################################################################################################### # Function to handle image analysis def image_analysis(name, nfeatures, K): # Read Image file image = cv2.cvtColor(src=cv2.imread(os.path.join(u.IMAGE_PATH, name)), code=cv2.COLOR_BGR2RGB) # Create ORB object orb = cv2.ORB_create(nfeatures=nfeatures) # Obtain image keypoints kp, _ = get_orb_features(orb, image) # Show Random Keypoint Information show_kp_info(kp) # Show all keypoint information show_info(kp) # Get topK Keypoints topK_kp = get_topK(kp, K) # Show image with all the keypoints show_kp_image(image, kp) # Show image with topK keypoints show_kp_image(image, topK_kp) ##################################################################################################### def realtime_analysis(nfeatures, K=None): # Create ORB object orb = cv2.ORB_create(nfeatures=nfeatures) # Setting up capture object if platform.system() != "Windows": cap = cv2.VideoCapture(u.ID) else: cap = cv2.VideoCapture(u.ID, cv2.CAP_DSHOW) cap.set(cv2.CAP_PROP_FRAME_WIDTH, u.CAM_WIDTH) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, u.CAM_HEIGHT) cap.set(cv2.CAP_PROP_FPS, u.FPS) # Creat CLAHE object clahe = cv2.createCLAHE(clipLimit=5, tileGridSize=(2, 2)) while cap.isOpened(): _, frame = cap.read() # Preprocess frame with CLAHE (clipLimit:2, tileGridSize: (2, 2)) for i in range(frame.shape[-1]): frame[:, :, i] = clahe.apply(frame[:, :, i]) # frame = cv2.GaussianBlur(src=frame, ksize=(15, 15), sigmaX=0) # Obtain frame keypoints kp, _ = get_orb_features(orb, frame) # Get topK Keypoints if K is specified if K is None: frame = cv2.drawKeypoints(frame, kp, None, (0, 255, 0), cv2.DRAW_MATCHES_FLAGS_DEFAULT) else: topK_kp = get_topK(kp, K=K) if topK_kp is not None: frame = cv2.drawKeypoints(frame, topK_kp, None, (0, 255, 0), cv2.DRAW_MATCHES_FLAGS_DEFAULT) # Press 'q' to Quit cv2.imshow("Feed", frame) if cv2.waitKey(1) == ord("q"): break # Release capture cbject and destory all windows cap.release() cv2.destroyAllWindows() #####################################################################################################
[ "matplotlib.pyplot.grid", "cv2.imshow", "cv2.destroyAllWindows", "utils.breaker", "matplotlib.pyplot.imshow", "matplotlib.pyplot.plot", "platform.system", "cv2.ORB_create", "matplotlib.pyplot.axis", "cv2.waitKey", "cv2.cvtColor", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "cv2.dr...
[((401, 449), 'cv2.cvtColor', 'cv2.cvtColor', ([], {'src': 'image', 'code': 'cv2.COLOR_RGB2GRAY'}), '(src=image, code=cv2.COLOR_RGB2GRAY)\n', (413, 449), False, 'import cv2\n'), ((1195, 1206), 'utils.breaker', 'u.breaker', ([], {}), '()\n', (1204, 1206), True, 'import utils as u\n'), ((1271, 1282), 'utils.breaker', 'u.breaker', ([], {}), '()\n', (1280, 1282), True, 'import utils as u\n'), ((1342, 1353), 'utils.breaker', 'u.breaker', ([], {}), '()\n', (1351, 1353), True, 'import utils as u\n'), ((2061, 2073), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2071, 2073), True, 'import matplotlib.pyplot as plt\n'), ((2078, 2098), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(1)'], {}), '(1, 4, 1)\n', (2089, 2098), True, 'import matplotlib.pyplot as plt\n'), ((2103, 2132), 'matplotlib.pyplot.plot', 'plt.plot', (['x_Axis', 'angles', '"""r"""'], {}), "(x_Axis, angles, 'r')\n", (2111, 2132), True, 'import matplotlib.pyplot as plt\n'), ((2137, 2147), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2145, 2147), True, 'import matplotlib.pyplot as plt\n'), ((2152, 2171), 'matplotlib.pyplot.title', 'plt.title', (['"""Angles"""'], {}), "('Angles')\n", (2161, 2171), True, 'import matplotlib.pyplot as plt\n'), ((2176, 2196), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(2)'], {}), '(1, 4, 2)\n', (2187, 2196), True, 'import matplotlib.pyplot as plt\n'), ((2201, 2231), 'matplotlib.pyplot.plot', 'plt.plot', (['x_Axis', 'octaves', '"""r"""'], {}), "(x_Axis, octaves, 'r')\n", (2209, 2231), True, 'import matplotlib.pyplot as plt\n'), ((2236, 2246), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2244, 2246), True, 'import matplotlib.pyplot as plt\n'), ((2251, 2271), 'matplotlib.pyplot.title', 'plt.title', (['"""Octaves"""'], {}), "('Octaves')\n", (2260, 2271), True, 'import matplotlib.pyplot as plt\n'), ((2276, 2296), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(3)'], {}), '(1, 4, 3)\n', (2287, 2296), True, 'import matplotlib.pyplot as plt\n'), ((2301, 2333), 'matplotlib.pyplot.plot', 'plt.plot', (['x_Axis', 'responses', '"""r"""'], {}), "(x_Axis, responses, 'r')\n", (2309, 2333), True, 'import matplotlib.pyplot as plt\n'), ((2338, 2348), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2346, 2348), True, 'import matplotlib.pyplot as plt\n'), ((2353, 2375), 'matplotlib.pyplot.title', 'plt.title', (['"""Responses"""'], {}), "('Responses')\n", (2362, 2375), True, 'import matplotlib.pyplot as plt\n'), ((2380, 2400), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(4)'], {}), '(1, 4, 4)\n', (2391, 2400), True, 'import matplotlib.pyplot as plt\n'), ((2405, 2433), 'matplotlib.pyplot.plot', 'plt.plot', (['x_Axis', 'sizes', '"""r"""'], {}), "(x_Axis, sizes, 'r')\n", (2413, 2433), True, 'import matplotlib.pyplot as plt\n'), ((2438, 2448), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2446, 2448), True, 'import matplotlib.pyplot as plt\n'), ((2453, 2471), 'matplotlib.pyplot.title', 'plt.title', (['"""Sizes"""'], {}), "('Sizes')\n", (2462, 2471), True, 'import matplotlib.pyplot as plt\n'), ((2476, 2486), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2484, 2486), True, 'import matplotlib.pyplot as plt\n'), ((2659, 2738), 'cv2.drawKeypoints', 'cv2.drawKeypoints', (['image', 'kp', 'None', '(0, 255, 0)', 'cv2.DRAW_MATCHES_FLAGS_DEFAULT'], {}), '(image, kp, None, (0, 255, 0), cv2.DRAW_MATCHES_FLAGS_DEFAULT)\n', (2676, 2738), False, 'import cv2\n'), ((2743, 2755), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2753, 2755), True, 'import matplotlib.pyplot as plt\n'), ((2760, 2780), 'matplotlib.pyplot.imshow', 'plt.imshow', (['kp_image'], {}), '(kp_image)\n', (2770, 2780), True, 'import matplotlib.pyplot as plt\n'), ((2785, 2800), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2793, 2800), True, 'import matplotlib.pyplot as plt\n'), ((2805, 2815), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2813, 2815), True, 'import matplotlib.pyplot as plt\n'), ((3161, 3196), 'cv2.ORB_create', 'cv2.ORB_create', ([], {'nfeatures': 'nfeatures'}), '(nfeatures=nfeatures)\n', (3175, 3196), False, 'import cv2\n'), ((3766, 3801), 'cv2.ORB_create', 'cv2.ORB_create', ([], {'nfeatures': 'nfeatures'}), '(nfeatures=nfeatures)\n', (3780, 3801), False, 'import cv2\n'), ((4156, 4205), 'cv2.createCLAHE', 'cv2.createCLAHE', ([], {'clipLimit': '(5)', 'tileGridSize': '(2, 2)'}), '(clipLimit=5, tileGridSize=(2, 2))\n', (4171, 4205), False, 'import cv2\n'), ((5156, 5179), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5177, 5179), False, 'import cv2\n'), ((3846, 3863), 'platform.system', 'platform.system', ([], {}), '()\n', (3861, 3863), False, 'import platform\n'), ((3892, 3914), 'cv2.VideoCapture', 'cv2.VideoCapture', (['u.ID'], {}), '(u.ID)\n', (3908, 3914), False, 'import cv2\n'), ((3939, 3976), 'cv2.VideoCapture', 'cv2.VideoCapture', (['u.ID', 'cv2.CAP_DSHOW'], {}), '(u.ID, cv2.CAP_DSHOW)\n', (3955, 3976), False, 'import cv2\n'), ((4993, 5018), 'cv2.imshow', 'cv2.imshow', (['"""Feed"""', 'frame'], {}), "('Feed', frame)\n", (5003, 5018), False, 'import cv2\n'), ((4677, 4756), 'cv2.drawKeypoints', 'cv2.drawKeypoints', (['frame', 'kp', 'None', '(0, 255, 0)', 'cv2.DRAW_MATCHES_FLAGS_DEFAULT'], {}), '(frame, kp, None, (0, 255, 0), cv2.DRAW_MATCHES_FLAGS_DEFAULT)\n', (4694, 4756), False, 'import cv2\n'), ((5030, 5044), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5041, 5044), False, 'import cv2\n'), ((3063, 3095), 'os.path.join', 'os.path.join', (['u.IMAGE_PATH', 'name'], {}), '(u.IMAGE_PATH, name)\n', (3075, 3095), False, 'import os\n'), ((4871, 4960), 'cv2.drawKeypoints', 'cv2.drawKeypoints', (['frame', 'topK_kp', 'None', '(0, 255, 0)', 'cv2.DRAW_MATCHES_FLAGS_DEFAULT'], {}), '(frame, topK_kp, None, (0, 255, 0), cv2.\n DRAW_MATCHES_FLAGS_DEFAULT)\n', (4888, 4960), False, 'import cv2\n'), ((850, 880), 'numpy.argpartition', 'np.argpartition', (['responses', '(-K)'], {}), '(responses, -K)\n', (865, 880), True, 'import numpy as np\n')]
#!/usr/bin/env python import glob import os import sys try: sys.path.append(glob.glob(os.path.abspath('%s/../../carla/dist/carla-*%d.%d-%s.egg' % ( os.path.realpath(__file__), sys.version_info.major, sys.version_info.minor, 'win-amd64' if os.name == 'nt' else 'linux-x86_64')))[0]) except IndexError: pass os.environ["PYRO_LOGFILE"] = "pyro.log" os.environ["PYRO_LOGLEVEL"] = "DEBUG" from collections import defaultdict from multiprocessing import Process from threading import RLock import Pyro4 import argparse import carla import math import numpy as np import random import time if sys.version_info.major == 2: from pathlib2 import Path else: from pathlib import Path ''' ========== CONSTANTS ========== ''' DATA_PATH = Path(os.path.realpath(__file__)).parent.parent.parent/'Data' PATH_MIN_POINTS = 20 PATH_INTERVAL = 1.0 SPAWN_DESTROY_MAX_RATE = 15.0 GAMMA_MAX_RATE = 40.0 CONTROL_MAX_RATE = 20.0 COLLISION_STATISTICS_MAX_RATE = 5.0 SPAWN_DESTROY_REPETITIONS = 3 # Ziegler-Nichols tuning params: K_p, T_u CAR_SPEED_PID_PROFILES = { 'vehicle.volkswagen.t2': [1.5, 25.0 / 25], 'vehicle.carlamotors.carlacola': [3.0, 25.0 / 25], 'vehicle.jeep.wrangler_rubicon': [1.5, 25.0 / 27], 'vehicle.nissan.patrol': [1.5, 25.0 / 24], # 'vehicle.tesla.cybertruck': [3.0, 25.0 / 28], 'vehicle.chevrolet.impala': [0.8, 20.0 / 17], 'vehicle.audi.tt': [0.8, 20.0 / 15], 'vehicle.mustang.mustang': [1.0, 20.0 / 15], 'vehicle.citroen.c3': [0.7, 20.0 / 14], 'vehicle.toyota.prius': [1.2, 20.0 / 15], 'vehicle.dodge_charger.police': [1.0, 20.0 /17], 'vehicle.mini.cooperst': [0.8, 20.0 / 14], 'vehicle.audi.a2': [0.8, 20.0 / 18], 'vehicle.nissan.micra': [0.8, 20.0 / 19], 'vehicle.seat.leon': [0.8, 20.0 / 16], 'vehicle.tesla.model3': [1.5, 20.0 / 16], 'vehicle.mercedes-benz.coupe': [0.8, 20.0 / 15], 'vehicle.lincoln.mkz2017': [1.3, 20.0 / 15], 'vehicle.bmw.grandtourer': [1.5, 20.0 / 16], 'default': [1.6, 25.0 / 34] } BIKE_SPEED_PID_PROFILES = { 'vehicle.diamondback.century': [1.5, 20.0 / 23.0], 'vehicle.gazelle.omafiets': [1.5, 20.0 / 23.0], 'vehicle.bh.crossbike': [1.5, 20.0 / 23.0], 'default': [0.75, 25.0 / 35.0] } CAR_STEER_PID_PROFILES = { 'vehicle.volkswagen.t2': [2.5, 10.0 / 13], 'vehicle.carlamotors.carlacola': [2.5, 10.0 / 15], 'vehicle.jeep.wrangler_rubicon': [2.8, 10.0 / 17], 'vehicle.nissan.patrol': [3.2, 10.0 / 14], # 'vehicle.tesla.cybertruck': [4.0, 10.0 / 16.0], 'vehicle.audi.etron': [3.0, 10.0 / 15], 'vehicle.chevrolet.impala': [2.5, 10.0 / 19], 'vehicle.audi.tt': [2.3, 10.0 / 20], 'vehicle.mustang.mustang': [2.8, 10.0/ 19], 'vehicle.citroen.c3': [2.0, 10.0 / 17], 'vehicle.toyota.prius': [2.1, 10.0 / 18], 'vehicle.dodge_charger.police': [2.3, 10.0 / 21], 'vehicle.mini.cooperst': [2.0, 10.0 / 16], 'vehicle.audi.a2': [2.0, 10.0 / 18], 'vehicle.nissan.micra': [3.3, 10.0 / 23], 'vehicle.seat.leon': [2.2, 10.0 / 20], 'vehicle.tesla.model3': [2.7, 10.0 / 19], 'vehicle.mercedes-benz.coupe': [2.7, 10.0 / 20], 'vehicle.lincoln.mkz2017': [2.7, 10.0 / 16], 'vehicle.bmw.grandtourer': [2.7, 10.0/ 17], 'default': [2.8, 10.0 / 15] } BIKE_STEER_PID_PROFILES = { 'vehicle.diamondback.century': [1.7, 10.0 / 8], 'vehicle.gazelle.omafiets': [1.7, 10.0 / 8], 'vehicle.harley-davidson.low_rider': [1.5, 10.0 / 9], 'vehicle.bh.crossbike': [2.5, 10.0 / 8.0], 'default': [2.0, 10.0 / 9] } # Convert (K_p, T_u) -> (K_p, K_i, K_d) for (k, v) in CAR_SPEED_PID_PROFILES.items(): scale = 1.0 CAR_SPEED_PID_PROFILES[k] = [0.8 * v[0] * scale, 0.0, v[0] * v[1] / 10.0 * scale] # PD # CAR_SPEED_PID_PROFILES[k] = [v[0] / 5.0, v[0] * 2.0 / 5.0 / v[1], v[0] / 15.0 * v[1]] # no overshoot for (k, v) in BIKE_SPEED_PID_PROFILES.items(): BIKE_SPEED_PID_PROFILES[k] = [v[0] / 2.0, 0.0, 0.0] # p for (k, v) in CAR_STEER_PID_PROFILES.items(): scale = 0.9 CAR_STEER_PID_PROFILES[k] = [v[0] / 2.0, 0.0, 0.0] for (k, v) in BIKE_STEER_PID_PROFILES.items(): scale = 0.9 BIKE_STEER_PID_PROFILES[k] = [0.8 * v[0] * scale, 0.0, v[0] * v[1] / 10.0 * scale ] # PD def get_car_speed_pid_profile(blueprint_id): result = CAR_SPEED_PID_PROFILES.get(blueprint_id) if result is not None: return result else: return CAR_SPEED_PID_PROFILES['default'] def get_bike_speed_pid_profile(blueprint_id): result = BIKE_SPEED_PID_PROFILES.get(blueprint_id) if result is not None: return result else: return BIKE_SPEED_PID_PROFILES['default'] def get_car_steer_pid_profile(blueprint_id): result = CAR_STEER_PID_PROFILES.get(blueprint_id) if result is not None: return result else: return CAR_STEER_PID_PROFILES['default'] def get_bike_steer_pid_profile(blueprint_id): result = BIKE_STEER_PID_PROFILES.get(blueprint_id) if result is not None: return result else: return BIKE_STEER_PID_PROFILES['default'] CAR_STEER_KP = 1.5 BIKE_STEER_KP = 1.0 Pyro4.config.SERIALIZERS_ACCEPTED.add('serpent') Pyro4.config.SERIALIZER = 'serpent' Pyro4.util.SerializerBase.register_class_to_dict( carla.Vector2D, lambda o: { '__class__': 'carla.Vector2D', 'x': o.x, 'y': o.y }) Pyro4.util.SerializerBase.register_dict_to_class( 'carla.Vector2D', lambda c, o: carla.Vector2D(o['x'], o['y'])) Pyro4.util.SerializerBase.register_class_to_dict( carla.SumoNetworkRoutePoint, lambda o: { '__class__': 'carla.SumoNetworkRoutePoint', 'edge': o.edge, 'lane': o.lane, 'segment': o.segment, 'offset': o.offset }) def dict_to_sumo_network_route_point(c, o): r = carla.SumoNetworkRoutePoint() r.edge = str(o['edge']) # In python2, this is a unicode, so use str() to convert. r.lane = o['lane'] r.segment = o['segment'] r.offset = o['offset'] return r Pyro4.util.SerializerBase.register_dict_to_class( 'carla.SumoNetworkRoutePoint', dict_to_sumo_network_route_point) Pyro4.util.SerializerBase.register_class_to_dict( carla.SidewalkRoutePoint, lambda o: { '__class__': 'carla.SidewalkRoutePoint', 'polygon_id': o.polygon_id, 'segment_id': o.segment_id, 'offset': o.offset }) def dict_to_sidewalk_route_point(c, o): r = carla.SidewalkRoutePoint() r.polygon_id = o['polygon_id'] r.segment_id = o['segment_id'] r.offset = o['offset'] return r Pyro4.util.SerializerBase.register_dict_to_class( 'carla.SidewalkRoutePoint', dict_to_sidewalk_route_point) ''' ========== MESSAGE PASSING SERVICE ========== ''' @Pyro4.expose @Pyro4.behavior(instance_mode="single") class CrowdService(): def __init__(self): self._simulation_bounds_min = None self._simulation_bounds_max = None self._simulation_bounds_lock = RLock() self._forbidden_bounds_min = None self._forbidden_bounds_max = None self._forbidden_bounds_lock = RLock() self._spawn_car = False self._new_cars = [] self._new_cars_lock = RLock() self._spawn_bike = False self._new_bikes = [] self._new_bikes_lock = RLock() self._spawn_pedestrian = False self._new_pedestrians = [] self._new_pedestrians_lock = RLock() self._control_velocities = [] self._control_velocities_lock = RLock() self._local_intentions = [] self._local_intentions_lock = RLock() self._destroy_list = [] self._destroy_list_lock = RLock() @property def simulation_bounds(self): self._simulation_bounds_lock.acquire() simulation_bounds_min = None if self._simulation_bounds_min is None else \ carla.Vector2D(self._simulation_bounds_min.x, self._simulation_bounds_min.y) simulation_bounds_max = None if self._simulation_bounds_max is None else \ carla.Vector2D(self._simulation_bounds_max.x, self._simulation_bounds_max.y) self._simulation_bounds_lock.release() return (simulation_bounds_min, simulation_bounds_max) @simulation_bounds.setter def simulation_bounds(self, bounds): self._simulation_bounds_lock.acquire() self._simulation_bounds_min = bounds[0] self._simulation_bounds_max = bounds[1] self._simulation_bounds_lock.release() @property def forbidden_bounds(self): self._forbidden_bounds_lock.acquire() forbidden_bounds_min = None if self._forbidden_bounds_min is None else \ carla.Vector2D(self._forbidden_bounds_min.x, self._forbidden_bounds_min.y) forbidden_bounds_max = None if self._forbidden_bounds_max is None else \ carla.Vector2D(self._forbidden_bounds_max.x, self._forbidden_bounds_max.y) self._forbidden_bounds_lock.release() return (forbidden_bounds_min, forbidden_bounds_max) @forbidden_bounds.setter def forbidden_bounds(self, bounds): self._forbidden_bounds_lock.acquire() self._forbidden_bounds_min = bounds[0] self._forbidden_bounds_max = bounds[1] self._forbidden_bounds_lock.release() @property def spawn_car(self): return self._spawn_car @spawn_car.setter def spawn_car(self, value): self._spawn_car = value @property def new_cars(self): return self._new_cars @new_cars.setter def new_cars(self, cars): self._new_cars = cars def append_new_cars(self, info): self._new_cars.append(info) def acquire_new_cars(self): self._new_cars_lock.acquire() def release_new_cars(self): try: self._new_cars_lock.release() except Exception as e: print(e) sys.stdout.flush() @property def spawn_bike(self): return self._spawn_bike @spawn_bike.setter def spawn_bike(self, value): self._spawn_bike = value @property def new_bikes(self): return self._new_bikes @new_bikes.setter def new_bikes(self, bikes): self._new_bikes = bikes def append_new_bikes(self, info): self._new_bikes.append(info) def acquire_new_bikes(self): self._new_bikes_lock.acquire() def release_new_bikes(self): try: self._new_bikes_lock.release() except Exception as e: print(e) sys.stdout.flush() @property def spawn_pedestrian(self): return self._spawn_pedestrian @spawn_pedestrian.setter def spawn_pedestrian(self, value): self._spawn_pedestrian = value @property def new_pedestrians(self): return self._new_pedestrians @new_pedestrians.setter def new_pedestrians(self, pedestrians): self._new_pedestrians = pedestrians def append_new_pedestrians(self, info): self._new_pedestrians.append(info) def acquire_new_pedestrians(self): self._new_pedestrians_lock.acquire() def release_new_pedestrians(self): try: self._new_pedestrians_lock.release() except Exception as e: print(e) sys.stdout.flush() @property def control_velocities(self): return self._control_velocities @control_velocities.setter def control_velocities(self, velocities): self._control_velocities = velocities def acquire_control_velocities(self): self._control_velocities_lock.acquire() def release_control_velocities(self): try: self._control_velocities_lock.release() except Exception as e: print(e) sys.stdout.flush() @property def local_intentions(self): return self._local_intentions @local_intentions.setter def local_intentions(self, velocities): self._local_intentions = velocities def acquire_local_intentions(self): self._local_intentions_lock.acquire() def release_local_intentions(self): try: self._local_intentions_lock.release() except Exception as e: print(e) sys.stdout.flush() @property def destroy_list(self): return self._destroy_list @destroy_list.setter def destroy_list(self, items): self._destroy_list = items def append_destroy_list(self, item): self._destroy_list.append(item) def extend_destroy_list(self, items): self._destroy_list.extend(items) def acquire_destroy_list(self): self._destroy_list_lock.acquire() def release_destroy_list(self): try: self._destroy_list_lock.release() except Exception as e: print(e) sys.stdout.flush() ''' ========== UTILITY FUNCTIONS AND CLASSES ========== ''' def get_signed_angle_diff(vector1, vector2): theta = math.atan2(vector1.y, vector1.x) - math.atan2(vector2.y, vector2.x) theta = np.rad2deg(theta) if theta > 180: theta -= 360 elif theta < -180: theta += 360 return theta def get_steer_angle_range(actor): actor_physics_control = actor.get_physics_control() return (actor_physics_control.wheels[0].max_steer_angle + actor_physics_control.wheels[1].max_steer_angle) / 2 def get_position(actor): pos3d = actor.get_location() return carla.Vector2D(pos3d.x, pos3d.y) def get_forward_direction(actor): forward = actor.get_transform().get_forward_vector() return carla.Vector2D(forward.x, forward.y) def get_bounding_box(actor): return actor.bounding_box def get_position_3d(actor): return actor.get_location() def get_aabb(actor): bbox = actor.bounding_box loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor) forward_vec = get_forward_direction(actor).make_unit_vector() sideward_vec = forward_vec.rotate(np.deg2rad(90)) corners = [loc - bbox.extent.x * forward_vec + bbox.extent.y * sideward_vec, loc + bbox.extent.x * forward_vec + bbox.extent.y * sideward_vec, loc + bbox.extent.x * forward_vec - bbox.extent.y * sideward_vec, loc - bbox.extent.x * forward_vec - bbox.extent.y * sideward_vec] return carla.AABB2D( carla.Vector2D( min(v.x for v in corners), min(v.y for v in corners)), carla.Vector2D( max(v.x for v in corners), max(v.y for v in corners))) def get_velocity(actor): v = actor.get_velocity() return carla.Vector2D(v.x, v.y) def get_bounding_box_corners(actor): bbox = actor.bounding_box loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor) forward_vec = get_forward_direction(actor).make_unit_vector() sideward_vec = forward_vec.rotate(np.deg2rad(90)) half_y_len = bbox.extent.y half_x_len = bbox.extent.x corners = [loc - half_x_len * forward_vec + half_y_len * sideward_vec, loc + half_x_len * forward_vec + half_y_len * sideward_vec, loc + half_x_len * forward_vec - half_y_len * sideward_vec, loc - half_x_len * forward_vec - half_y_len * sideward_vec] return corners def get_vehicle_bounding_box_corners(actor): bbox = actor.bounding_box loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor) forward_vec = get_forward_direction(actor).make_unit_vector() sideward_vec = forward_vec.rotate(np.deg2rad(90)) half_y_len = bbox.extent.y + 0.3 half_x_len_forward = bbox.extent.x + 1.0 half_x_len_backward = bbox.extent.x + 0.1 corners = [loc - half_x_len_backward * forward_vec + half_y_len * sideward_vec, loc + half_x_len_forward * forward_vec + half_y_len * sideward_vec, loc + half_x_len_forward * forward_vec - half_y_len * sideward_vec, loc - half_x_len_backward * forward_vec - half_y_len * sideward_vec] return corners def get_pedestrian_bounding_box_corners(actor): bbox = actor.bounding_box loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor) forward_vec = get_forward_direction(actor).make_unit_vector() sideward_vec = forward_vec.rotate(np.deg2rad(90)) # Hardcoded values for pedestrians. half_y_len = 0.25 half_x_len = 0.25 corners = [loc - half_x_len * forward_vec + half_y_len * sideward_vec, loc + half_x_len * forward_vec + half_y_len * sideward_vec, loc + half_x_len * forward_vec - half_y_len * sideward_vec, loc - half_x_len * forward_vec - half_y_len * sideward_vec] return corners def get_lane_constraints(sidewalk, position, forward_vec): left_line_end = position + (1.5 + 2.0 + 0.8) * ((forward_vec.rotate(np.deg2rad(-90))).make_unit_vector()) right_line_end = position + (1.5 + 2.0 + 0.8) * ((forward_vec.rotate(np.deg2rad(90))).make_unit_vector()) left_lane_constrained_by_sidewalk = sidewalk.intersects(carla.Segment2D(position, left_line_end)) right_lane_constrained_by_sidewalk = sidewalk.intersects(carla.Segment2D(position, right_line_end)) return left_lane_constrained_by_sidewalk, right_lane_constrained_by_sidewalk def is_car(actor): return isinstance(actor, carla.Vehicle) and int(actor.attributes['number_of_wheels']) > 2 def is_bike(actor): return isinstance(actor, carla.Vehicle) and int(actor.attributes['number_of_wheels']) == 2 def is_pedestrian(actor): return isinstance(actor, carla.Walker) class SumoNetworkAgentPath: def __init__(self, route_points, min_points, interval): self.route_points = route_points self.min_points = min_points self.interval = interval @staticmethod def rand_path(sumo_network, min_points, interval, segment_map, rng=random): spawn_point = None route_paths = None while not spawn_point or len(route_paths) < 1: spawn_point = segment_map.rand_point() spawn_point = sumo_network.get_nearest_route_point(spawn_point) route_paths = sumo_network.get_next_route_paths(spawn_point, min_points - 1, interval) return SumoNetworkAgentPath(rng.choice(route_paths), min_points, interval) def resize(self, sumo_network, rng=random): while len(self.route_points) < self.min_points: next_points = sumo_network.get_next_route_points(self.route_points[-1], self.interval) if len(next_points) == 0: return False self.route_points.append(rng.choice(next_points)) return True def get_min_offset(self, sumo_network, position): min_offset = None for i in range(int(len(self.route_points) / 2)): route_point = self.route_points[i] offset = position - sumo_network.get_route_point_position(route_point) offset = offset.length() if min_offset == None or offset < min_offset: min_offset = offset return min_offset def cut(self, sumo_network, position): cut_index = 0 min_offset = None min_offset_index = None for i in range(int(len(self.route_points) / 2)): route_point = self.route_points[i] offset = position - sumo_network.get_route_point_position(route_point) offset = offset.length() if min_offset == None or offset < min_offset: min_offset = offset min_offset_index = i if offset <= 1.0: cut_index = i + 1 # Invalid path because too far away. if min_offset > 1.0: self.route_points = self.route_points[min_offset_index:] else: self.route_points = self.route_points[cut_index:] def get_position(self, sumo_network, index=0): return sumo_network.get_route_point_position(self.route_points[index]) def get_yaw(self, sumo_network, index=0): pos = sumo_network.get_route_point_position(self.route_points[index]) next_pos = sumo_network.get_route_point_position(self.route_points[index + 1]) return np.rad2deg(math.atan2(next_pos.y - pos.y, next_pos.x - pos.x)) class SidewalkAgentPath: def __init__(self, route_points, route_orientations, min_points, interval): self.min_points = min_points self.interval = interval self.route_points = route_points self.route_orientations = route_orientations @staticmethod def rand_path(sidewalk, min_points, interval, cross_probability, segment_map, rng=None): if rng is None: rng = random spawn_point = sidewalk.get_nearest_route_point(segment_map.rand_point()) path = SidewalkAgentPath([spawn_point], [rng.choice([True, False])], min_points, interval) path.resize(sidewalk, cross_probability) return path def resize(self, sidewalk, cross_probability, rng=None): if rng is None: rng = random while len(self.route_points) < self.min_points: if rng.random() <= cross_probability: adjacent_route_point = sidewalk.get_adjacent_route_point(self.route_points[-1], 50.0) if adjacent_route_point is not None: self.route_points.append(adjacent_route_point) self.route_orientations.append(rng.randint(0, 1) == 1) continue if self.route_orientations[-1]: self.route_points.append( sidewalk.get_next_route_point(self.route_points[-1], self.interval)) self.route_orientations.append(True) else: self.route_points.append( sidewalk.get_previous_route_point(self.route_points[-1], self.interval)) self.route_orientations.append(False) return True def cut(self, sidewalk, position): cut_index = 0 min_offset = None min_offset_index = None for i in range(int(len(self.route_points) / 2)): route_point = self.route_points[i] offset = position - sidewalk.get_route_point_position(route_point) offset = offset.length() if min_offset is None or offset < min_offset: min_offset = offset min_offset_index = i if offset <= 1.0: cut_index = i + 1 # Invalid path because too far away. if min_offset > 1.0: self.route_points = self.route_points[min_offset_index:] self.route_orientations = self.route_orientations[min_offset_index:] else: self.route_points = self.route_points[cut_index:] self.route_orientations = self.route_orientations[cut_index:] def get_position(self, sidewalk, index=0): return sidewalk.get_route_point_position(self.route_points[index]) def get_yaw(self, sidewalk, index=0): pos = sidewalk.get_route_point_position(self.route_points[index]) next_pos = sidewalk.get_route_point_position(self.route_points[index + 1]) return np.rad2deg(math.atan2(next_pos.y - pos.y, next_pos.x - pos.x)) class Agent(object): def __init__(self, actor, type_tag, path, preferred_speed, steer_angle_range=0.0, rand=0): self.actor = actor self.type_tag = type_tag self.path = path self.preferred_speed = preferred_speed self.stuck_time = None self.control_velocity = carla.Vector2D(0, 0) self.steer_angle_range = steer_angle_range self.behavior_type = self.rand_agent_behavior_type(rand) def rand_agent_behavior_type(self, prob): prob_gamma_agent = 1.0 prob_simplified_gamma_agent = 0.0 prob_ttc_agent = 0.0 if prob <= prob_gamma_agent: return carla.AgentBehaviorType.Gamma elif prob <= prob_gamma_agent + prob_simplified_gamma_agent: return carla.AgentBehaviorType.SimplifiedGamma else: return -1 class Context(object): def __init__(self, args): self.args = args self.rng = random.Random(args.seed) with (DATA_PATH/'{}.sim_bounds'.format(args.dataset)).open('r') as f: self.bounds_min = carla.Vector2D(*[float(v) for v in f.readline().split(',')]) self.bounds_max = carla.Vector2D(*[float(v) for v in f.readline().split(',')]) self.bounds_occupancy = carla.OccupancyMap(self.bounds_min, self.bounds_max) self.forbidden_bounds_min = None self.forbidden_bounds_max = None self.forbidden_bounds_occupancy = None self.sumo_network = carla.SumoNetwork.load(str(DATA_PATH/'{}.net.xml'.format(args.dataset))) self.sumo_network_segments = self.sumo_network.create_segment_map() self.sumo_network_spawn_segments = self.sumo_network_segments.intersection(carla.OccupancyMap(self.bounds_min, self.bounds_max)) self.sumo_network_spawn_segments.seed_rand(self.rng.getrandbits(32)) self.sumo_network_occupancy = carla.OccupancyMap.load(str(DATA_PATH/'{}.network.wkt'.format(args.dataset))) self.sidewalk = self.sumo_network_occupancy.create_sidewalk(1.5) self.sidewalk_segments = self.sidewalk.create_segment_map() self.sidewalk_spawn_segments = self.sidewalk_segments.intersection(carla.OccupancyMap(self.bounds_min, self.bounds_max)) self.sidewalk_spawn_segments.seed_rand(self.rng.getrandbits(32)) self.sidewalk_occupancy = carla.OccupancyMap.load(str(DATA_PATH/'{}.sidewalk.wkt'.format(args.dataset))) self.client = carla.Client(args.host, args.port) self.client.set_timeout(10.0) self.world = self.client.get_world() self.crowd_service = Pyro4.Proxy('PYRO:crowdservice.warehouse@localhost:{}'.format(args.pyroport)) self.pedestrian_blueprints = self.world.get_blueprint_library().filter('walker.pedestrian.*') self.vehicle_blueprints = self.world.get_blueprint_library().filter('vehicle.*') self.car_blueprints = [x for x in self.vehicle_blueprints if int(x.get_attribute('number_of_wheels')) == 4] self.car_blueprints = [x for x in self.car_blueprints if x.id not in ['vehicle.bmw.isetta', 'vehicle.tesla.cybertruck']] # This dude moves too slow. self.bike_blueprints = [x for x in self.vehicle_blueprints if int(x.get_attribute('number_of_wheels')) == 2] class Statistics(object): def __init__(self, log_file): self.start_time = None self.total_num_cars = 0 self.total_num_bikes = 0 self.total_num_pedestrians = 0 self.stuck_num_cars = 0 self.stuck_num_bikes = 0 self.stuck_num_pedestrians = 0 self.avg_speed_cars = 0 self.avg_speed_bikes = 0 self.avg_speed_pedestrians = 0 self.log_file = log_file def write(self): self.log_file.write('{} {} {} {} {} {} {} {} {} {}\n'.format( time.time() - self.start_time, self.total_num_cars, self.total_num_bikes, self.total_num_pedestrians, self.stuck_num_cars, self.stuck_num_bikes, self.stuck_num_pedestrians, self.avg_speed_cars, self.avg_speed_bikes, self.avg_speed_pedestrians)) self.log_file.flush() os.fsync(self.log_file) ''' ========== MAIN LOGIC FUNCTIONS ========== ''' def do_spawn(c): c.crowd_service.acquire_new_cars() spawn_car = c.crowd_service.spawn_car c.crowd_service.release_new_cars() c.crowd_service.acquire_new_bikes() spawn_bike = c.crowd_service.spawn_bike c.crowd_service.release_new_bikes() c.crowd_service.acquire_new_pedestrians() spawn_pedestrian = c.crowd_service.spawn_pedestrian c.crowd_service.release_new_pedestrians() if not spawn_car and not spawn_bike and not spawn_pedestrian: return # Find car spawn point. if spawn_car: aabb_occupancy = carla.OccupancyMap() if c.forbidden_bounds_occupancy is None else c.forbidden_bounds_occupancy for actor in c.world.get_actors(): if isinstance(actor, carla.Vehicle) or isinstance(actor, carla.Walker): aabb = get_aabb(actor) aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap( carla.Vector2D(aabb.bounds_min.x - c.args.clearance_car, aabb.bounds_min.y - c.args.clearance_car), carla.Vector2D(aabb.bounds_max.x + c.args.clearance_car, aabb.bounds_max.y + c.args.clearance_car))) for _ in range(SPAWN_DESTROY_REPETITIONS): spawn_segments = c.sumo_network_spawn_segments.difference(aabb_occupancy) if spawn_segments.is_empty: continue spawn_segments.seed_rand(c.rng.getrandbits(32)) path = SumoNetworkAgentPath.rand_path(c.sumo_network, PATH_MIN_POINTS, PATH_INTERVAL, spawn_segments, rng=c.rng) position = path.get_position(c.sumo_network, 0) trans = carla.Transform() trans.location.x = position.x trans.location.y = position.y trans.location.z = 0.2 trans.rotation.yaw = path.get_yaw(c.sumo_network, 0) actor = c.world.try_spawn_actor(c.rng.choice(c.car_blueprints), trans) if actor: actor.set_collision_enabled(c.args.collision) c.world.wait_for_tick(1.0) # For actor to update pos and bounds, and for collision to apply. c.crowd_service.acquire_new_cars() c.crowd_service.append_new_cars(( actor.id, [p for p in path.route_points], # Convert to python list. get_steer_angle_range(actor))) c.crowd_service.release_new_cars() aabb = get_aabb(actor) aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap( carla.Vector2D(aabb.bounds_min.x - c.args.clearance_car, aabb.bounds_min.y - c.args.clearance_car), carla.Vector2D(aabb.bounds_max.x + c.args.clearance_car, aabb.bounds_max.y + c.args.clearance_car))) # Find bike spawn point. if spawn_bike: aabb_occupancy = carla.OccupancyMap() if c.forbidden_bounds_occupancy is None else c.forbidden_bounds_occupancy for actor in c.world.get_actors(): if isinstance(actor, carla.Vehicle) or isinstance(actor, carla.Walker): aabb = get_aabb(actor) aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap( carla.Vector2D(aabb.bounds_min.x - c.args.clearance_bike, aabb.bounds_min.y - c.args.clearance_bike), carla.Vector2D(aabb.bounds_max.x + c.args.clearance_bike, aabb.bounds_max.y + c.args.clearance_bike))) for _ in range(SPAWN_DESTROY_REPETITIONS): spawn_segments = c.sumo_network_spawn_segments.difference(aabb_occupancy) if spawn_segments.is_empty: continue spawn_segments.seed_rand(c.rng.getrandbits(32)) path = SumoNetworkAgentPath.rand_path(c.sumo_network, PATH_MIN_POINTS, PATH_INTERVAL, spawn_segments, rng=c.rng) position = path.get_position(c.sumo_network, 0) trans = carla.Transform() trans.location.x = position.x trans.location.y = position.y trans.location.z = 0.2 trans.rotation.yaw = path.get_yaw(c.sumo_network, 0) actor = c.world.try_spawn_actor(c.rng.choice(c.bike_blueprints), trans) if actor: actor.set_collision_enabled(c.args.collision) c.world.wait_for_tick(1.0) # For actor to update pos and bounds, and for collision to apply. c.crowd_service.acquire_new_bikes() c.crowd_service.append_new_bikes(( actor.id, [p for p in path.route_points], # Convert to python list. get_steer_angle_range(actor))) c.crowd_service.release_new_bikes() aabb = get_aabb(actor) aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap( carla.Vector2D(aabb.bounds_min.x - c.args.clearance_bike, aabb.bounds_min.y - c.args.clearance_bike), carla.Vector2D(aabb.bounds_max.x + c.args.clearance_bike, aabb.bounds_max.y + c.args.clearance_bike))) if spawn_pedestrian: aabb_occupancy = carla.OccupancyMap() if c.forbidden_bounds_occupancy is None else c.forbidden_bounds_occupancy for actor in c.world.get_actors(): if isinstance(actor, carla.Vehicle) or isinstance(actor, carla.Walker): aabb = get_aabb(actor) aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap( carla.Vector2D(aabb.bounds_min.x - c.args.clearance_pedestrian, aabb.bounds_min.y - c.args.clearance_pedestrian), carla.Vector2D(aabb.bounds_max.x + c.args.clearance_pedestrian, aabb.bounds_max.y + c.args.clearance_pedestrian))) for _ in range(SPAWN_DESTROY_REPETITIONS): spawn_segments = c.sidewalk_spawn_segments.difference(aabb_occupancy) if spawn_segments.is_empty: continue spawn_segments.seed_rand(c.rng.getrandbits(32)) path = SidewalkAgentPath.rand_path(c.sidewalk, PATH_MIN_POINTS, PATH_INTERVAL, c.args.cross_probability, c.sidewalk_spawn_segments, c.rng) position = path.get_position(c.sidewalk, 0) trans = carla.Transform() trans.location.x = position.x trans.location.y = position.y trans.location.z = 0.5 trans.rotation.yaw = path.get_yaw(c.sidewalk, 0) actor = c.world.try_spawn_actor(c.rng.choice(c.pedestrian_blueprints), trans) if actor: actor.set_collision_enabled(c.args.collision) c.world.wait_for_tick(1.0) # For actor to update pos and bounds, and for collision to apply. c.crowd_service.acquire_new_pedestrians() c.crowd_service.append_new_pedestrians(( actor.id, [p for p in path.route_points], # Convert to python list. path.route_orientations)) c.crowd_service.release_new_pedestrians() aabb = get_aabb(actor) aabb_occupancy = aabb_occupancy.union(carla.OccupancyMap( carla.Vector2D(aabb.bounds_min.x - c.args.clearance_pedestrian, aabb.bounds_min.y - c.args.clearance_pedestrian), carla.Vector2D(aabb.bounds_max.x + c.args.clearance_pedestrian, aabb.bounds_max.y + c.args.clearance_pedestrian))) def do_destroy(c): c.crowd_service.acquire_destroy_list() destroy_list = c.crowd_service.destroy_list c.crowd_service.destroy_list = [] c.crowd_service.release_destroy_list() commands = [carla.command.DestroyActor(x) for x in destroy_list] c.client.apply_batch_sync(commands) c.world.wait_for_tick(1.0) def pull_new_agents(c, car_agents, bike_agents, pedestrian_agents, statistics): new_car_agents = [] new_bike_agents = [] new_pedestrian_agents = [] c.crowd_service.acquire_new_cars() for (actor_id, route_points, steer_angle_range) in c.crowd_service.new_cars: path = SumoNetworkAgentPath(route_points, PATH_MIN_POINTS, PATH_INTERVAL) new_car_agents.append(Agent( c.world.get_actor(actor_id), 'Car', path, c.args.speed_car + c.rng.uniform(-0.5, 0.5), steer_angle_range, rand=c.rng.uniform(0.0, 1.0))) c.crowd_service.new_cars = [] c.crowd_service.spawn_car = len(car_agents) < c.args.num_car c.crowd_service.release_new_cars() c.crowd_service.acquire_new_bikes() for (actor_id, route_points, steer_angle_range) in c.crowd_service.new_bikes: path = SumoNetworkAgentPath(route_points, PATH_MIN_POINTS, PATH_INTERVAL) new_bike_agents.append(Agent( c.world.get_actor(actor_id), 'Bicycle', path, c.args.speed_bike + c.rng.uniform(-0.5, 0.5), steer_angle_range, rand=c.rng.uniform(0.0, 1.0))) c.crowd_service.new_bikes = [] c.crowd_service.spawn_bike = len(bike_agents) < c.args.num_bike c.crowd_service.release_new_bikes() c.crowd_service.acquire_new_pedestrians() for (actor_id, route_points, route_orientations) in c.crowd_service.new_pedestrians: path = SidewalkAgentPath(route_points, route_orientations, PATH_MIN_POINTS, PATH_INTERVAL) path.resize(c.sidewalk, c.args.cross_probability) new_pedestrian_agents.append(Agent( c.world.get_actor(actor_id), 'People', path, c.args.speed_pedestrian + c.rng.uniform(-0.5, 0.5), rand=c.rng.uniform(0.0, 1.0))) c.crowd_service.new_pedestrians = [] c.crowd_service.spawn_pedestrian = len(pedestrian_agents) < c.args.num_pedestrian c.crowd_service.release_new_pedestrians() statistics.total_num_cars += len(new_car_agents) statistics.total_num_bikes += len(new_bike_agents) statistics.total_num_pedestrians += len(new_pedestrian_agents) return (car_agents + new_car_agents, bike_agents + new_bike_agents, pedestrian_agents + new_pedestrian_agents, statistics) def do_death(c, car_agents, bike_agents, pedestrian_agents, destroy_list, statistics): update_time = time.time() next_car_agents = [] next_bike_agents = [] next_pedestrian_agents = [] new_destroy_list = [] for (agents, next_agents) in zip([car_agents, bike_agents, pedestrian_agents], [next_car_agents, next_bike_agents, next_pedestrian_agents]): for agent in agents: delete = False if not delete and not c.bounds_occupancy.contains(get_position(agent.actor)): delete = True if not delete and get_position_3d(agent.actor).z < -10: delete = True if not delete and \ ((agent.type_tag in ['Car', 'Bicycle']) and not c.sumo_network_occupancy.contains(get_position(agent.actor))): delete = True if not delete and \ len(agent.path.route_points) < agent.path.min_points: delete = True if get_velocity(agent.actor).length() < c.args.stuck_speed: if agent.stuck_time is not None: if update_time - agent.stuck_time >= c.args.stuck_duration: if agents == car_agents: statistics.stuck_num_cars += 1 elif agents == bike_agents: statistics.stuck_num_bikes += 1 elif agents == pedestrian_agents: statistics.stuck_num_pedestrians += 1 delete = True else: agent.stuck_time = update_time else: agent.stuck_time = None if delete: new_destroy_list.append(agent.actor.id) else: next_agents.append(agent) return (next_car_agents, next_bike_agents, next_pedestrian_agents, destroy_list + new_destroy_list, statistics) def do_speed_statistics(c, car_agents, bike_agents, pedestrian_agents, statistics): avg_speed_cars = 0.0 avg_speed_bikes = 0.0 avg_speed_pedestrians = 0.0 for agent in car_agents: avg_speed_cars += get_velocity(agent.actor).length() for agent in bike_agents: avg_speed_bikes += get_velocity(agent.actor).length() for agent in pedestrian_agents: avg_speed_pedestrians += get_velocity(agent.actor).length() if len(car_agents) > 0: avg_speed_cars /= len(car_agents) if len(bike_agents) > 0: avg_speed_bikes /= len(bike_agents) if len(pedestrian_agents) > 0: avg_speed_pedestrians /= len(pedestrian_agents) statistics.avg_speed_cars = avg_speed_cars statistics.avg_speed_bikes = avg_speed_bikes statistics.avg_speed_pedestrians = avg_speed_pedestrians return statistics def do_collision_statistics(c, timestamp, log_file): actors = c.world.get_actors() actors = [a for a in actors if is_car(a) or is_bike(a) or is_pedestrian(a)] bounding_boxes = [carla.OccupancyMap(get_bounding_box_corners(actor)) for actor in actors] collisions = [0 for _ in range(len(actors))] for i in range(len(actors) - 1): if collisions[i] == 1: continue for j in range(i + 1, len(actors)): if bounding_boxes[i].intersects(bounding_boxes[j]): collisions[i] = 1 collisions[j] = 1 log_file.write('{} {}\n'.format(timestamp, 0.0 if len(collisions) == 0 else float(sum(collisions)) / len(collisions))) log_file.flush() os.fsync(log_file) def do_gamma(c, car_agents, bike_agents, pedestrian_agents, destroy_list): agents = car_agents + bike_agents + pedestrian_agents agents_lookup = {} for agent in agents: agents_lookup[agent.actor.id] = agent next_agents = [] next_agent_gamma_ids = [] new_destroy_list = [] if len(agents) > 0: gamma = carla.RVOSimulator() gamma_id = 0 # For external agents not tracked. for actor in c.world.get_actors(): if actor.id not in agents_lookup: if isinstance(actor, carla.Vehicle): if is_bike(actor): type_tag = 'Bicycle' else: type_tag = 'Car' bounding_box_corners = get_vehicle_bounding_box_corners(actor) elif isinstance(actor, carla.Walker): type_tag = 'People' bounding_box_corners = get_pedestrian_bounding_box_corners(actor) else: continue agent_params = carla.AgentParams.get_default(type_tag) if type_tag == 'Bicycle': agent_params.max_speed = c.args.speed_bike elif type_tag == 'Car': agent_params.max_speed = c.args.speed_car elif type_tag == 'People': agent_params.max_speed = c.args.speed_pedestrian gamma.add_agent(agent_params, gamma_id) gamma.set_agent_position(gamma_id, get_position(actor)) gamma.set_agent_velocity(gamma_id, get_velocity(actor)) gamma.set_agent_heading(gamma_id, get_forward_direction(actor)) gamma.set_agent_bounding_box_corners(gamma_id, bounding_box_corners) gamma.set_agent_pref_velocity(gamma_id, get_velocity(actor)) gamma_id += 1 # For tracked agents. for agent in agents: actor = agent.actor # Declare variables. is_valid = True pref_vel = None path_forward = None bounding_box_corners = None lane_constraints = None # Update path, check validity, process variables. if agent.type_tag == 'Car' or agent.type_tag == 'Bicycle': position = get_position(actor) # Lane change if possible. if c.rng.uniform(0.0, 1.0) <= c.args.lane_change_probability: new_path_candidates = c.sumo_network.get_next_route_paths( c.sumo_network.get_nearest_route_point(position), agent.path.min_points - 1, agent.path.interval) if len(new_path_candidates) > 0: new_path = SumoNetworkAgentPath(c.rng.choice(new_path_candidates)[0:agent.path.min_points], agent.path.min_points, agent.path.interval) agent.path = new_path # Cut, resize, check. if not agent.path.resize(c.sumo_network): is_valid = False else: agent.path.cut(c.sumo_network, position) if not agent.path.resize(c.sumo_network): is_valid = False # Calculate variables. if is_valid: target_position = agent.path.get_position(c.sumo_network, 5) ## to check velocity = (target_position - position).make_unit_vector() pref_vel = agent.preferred_speed * velocity path_forward = (agent.path.get_position(c.sumo_network, 1) - agent.path.get_position(c.sumo_network, 0)).make_unit_vector() bounding_box_corners = get_vehicle_bounding_box_corners(actor) lane_constraints = get_lane_constraints(c.sidewalk, position, path_forward) elif agent.type_tag == 'People': position = get_position(actor) # Cut, resize, check. if not agent.path.resize(c.sidewalk, c.args.cross_probability): is_valid = False else: agent.path.cut(c.sidewalk, position) if not agent.path.resize(c.sidewalk, c.args.cross_probability): is_valid = False # Calculate pref_vel. if is_valid: target_position = agent.path.get_position(c.sidewalk, 0) velocity = (target_position - position).make_unit_vector() pref_vel = agent.preferred_speed * velocity path_forward = carla.Vector2D(0, 0) # Irrelevant for pedestrian. bounding_box_corners = get_pedestrian_bounding_box_corners(actor) # Add info to GAMMA. if pref_vel: gamma.add_agent(carla.AgentParams.get_default(agent.type_tag), gamma_id) gamma.set_agent_position(gamma_id, get_position(actor)) gamma.set_agent_velocity(gamma_id, get_velocity(actor)) gamma.set_agent_heading(gamma_id, get_forward_direction(actor)) gamma.set_agent_bounding_box_corners(gamma_id, bounding_box_corners) gamma.set_agent_pref_velocity(gamma_id, pref_vel) gamma.set_agent_path_forward(gamma_id, path_forward) if lane_constraints is not None: # Flip LR -> RL since GAMMA uses right-handed instead. gamma.set_agent_lane_constraints(gamma_id, lane_constraints[1], lane_constraints[0]) if agent.behavior_type is not -1: gamma.set_agent_behavior_type(gamma_id, agent.behavior_type) next_agents.append(agent) next_agent_gamma_ids.append(gamma_id) gamma_id += 1 else: new_destroy_list.append(agent.actor.id) if agent.behavior_type is -1: agent.control_velocity = get_ttc_vel(agent, agents, pref_vel) start = time.time() gamma.do_step() for (agent, gamma_id) in zip(next_agents, next_agent_gamma_ids): if agent.behavior_type is not -1 or agent.control_velocity is None: agent.control_velocity = gamma.get_agent_velocity(gamma_id) next_car_agents = [a for a in next_agents if a.type_tag == 'Car'] next_bike_agents = [a for a in next_agents if a.type_tag == 'Bicycle'] next_pedestrian_agents = [a for a in next_agents if a.type_tag == 'People'] next_destroy_list = destroy_list + new_destroy_list c.crowd_service.acquire_control_velocities() c.crowd_service.control_velocities = [ (agent.actor.id, agent.type_tag, agent.control_velocity, agent.preferred_speed, agent.steer_angle_range) for agent in next_agents] c.crowd_service.release_control_velocities() local_intentions = [] for agent in next_agents: if agent.type_tag == 'People': local_intentions.append((agent.actor.id, agent.type_tag, agent.path.route_points[0], agent.path.route_orientations[0])) else: local_intentions.append((agent.actor.id, agent.type_tag, agent.path.route_points[0])) c.crowd_service.acquire_local_intentions() c.crowd_service.local_intentions = local_intentions c.crowd_service.release_local_intentions() return (next_car_agents, next_bike_agents, next_pedestrian_agents, next_destroy_list) def get_ttc_vel(agent, agents, pref_vel): try: if agent: vel_to_exe = pref_vel if not vel_to_exe: # path is not ready. return None speed_to_exe = agent.preferred_speed for other_agent in agents: if other_agent and agent.actor.id != other_agent.actor.id: s_f = get_velocity(other_agent.actor).length() d_f = (get_position(other_agent.actor) - get_position(agent.actor)).length() d_safe = 5.0 a_max = 3.0 s = max(0, s_f * s_f + 2 * a_max * (d_f - d_safe))**0.5 speed_to_exe = min(speed_to_exe, s) cur_vel = get_velocity(agent.actor) angle_diff = get_signed_angle_diff(vel_to_exe, cur_vel) if angle_diff > 30 or angle_diff < -30: vel_to_exe = 0.5 * (vel_to_exe + cur_vel) vel_to_exe = vel_to_exe.make_unit_vector() * speed_to_exe return vel_to_exe except Exception as e: print(e) return None def do_control(c, speed_pid_integrals, speed_pid_last_errors, steer_pid_integrals, steer_pid_last_errors, pid_last_update_time): start = time.time() c.crowd_service.acquire_control_velocities() control_velocities = c.crowd_service.control_velocities c.crowd_service.release_control_velocities() commands = [] cur_time = time.time() if pid_last_update_time is None: dt = 0.0 else: dt = cur_time - pid_last_update_time for (actor_id, type_tag, control_velocity, preferred_speed, steer_angle_range) in control_velocities: actor = c.world.get_actor(actor_id) if actor is None: if actor_id in speed_pid_integrals: del speed_pid_integrals[actor_id] if actor_id in speed_pid_last_errors: del speed_pid_last_errors[actor_id] if actor_id in steer_pid_integrals: del steer_pid_integrals[actor_id] if actor_id in steer_pid_last_errors: del steer_pid_last_errors[actor_id] continue cur_vel = get_velocity(actor) angle_diff = get_signed_angle_diff(control_velocity, cur_vel) if angle_diff > 30 or angle_diff < -30: target_speed = 0.5 * (control_velocity + cur_vel) if type_tag == 'Car' or type_tag == 'Bicycle': speed = get_velocity(actor).length() target_speed = control_velocity.length() control = actor.get_control() (speed_kp, speed_ki, speed_kd) = get_car_speed_pid_profile(actor.type_id) if type_tag == 'Car' else get_bike_speed_pid_profile(actor.type_id) (steer_kp, steer_ki, steer_kd) = get_car_steer_pid_profile(actor.type_id) if type_tag == 'Car' else get_bike_steer_pid_profile(actor.type_id) # Clip to stabilize PID against sudden changes in GAMMA. if type_tag == 'Car': target_speed = np.clip(target_speed, speed - 2.0, min(speed + 1.0, c.args.speed_car)) if type_tag == 'Bicycle': target_speed = np.clip(target_speed, speed - 1.5, min(speed + 1.0, c.args.speed_bike)) heading = math.atan2(cur_vel.y, cur_vel.x) heading_error = np.deg2rad(get_signed_angle_diff(control_velocity, cur_vel)) target_heading = heading + heading_error # Calculate error. speed_error = target_speed - speed heading_error = target_heading - heading # heading_error = np.clip(heading_error, -1.5, 1.5) # Add to integral. Clip to stablize integral term. speed_pid_integrals[actor_id] += np.clip(speed_error, -0.3 / speed_kp, 0.3 / speed_kp) * dt steer_pid_integrals[actor_id] += np.clip(heading_error, -0.3 / steer_kp, 0.3 / steer_kp) * dt # Clip integral to prevent integral windup. steer_pid_integrals[actor_id] = np.clip(steer_pid_integrals[actor_id], -0.02, 0.02) # Calculate output. speed_control = speed_kp * speed_error + speed_ki * speed_pid_integrals[actor_id] steer_control = steer_kp * heading_error + steer_ki * steer_pid_integrals[actor_id] if pid_last_update_time is not None and actor_id in speed_pid_last_errors: speed_control += speed_kd * (speed_error - speed_pid_last_errors[actor_id]) / dt if pid_last_update_time is not None and actor_id in steer_pid_last_errors: steer_control += steer_kd * (heading_error - steer_pid_last_errors[actor_id]) / dt # Update history. speed_pid_last_errors[actor_id] = speed_error steer_pid_last_errors[actor_id] = heading_error # Set control. if speed_control >= 0: control.throttle = speed_control control.brake = 0.0 control.hand_brake = False else: control.throttle = 0.0 control.brake = -speed_control control.hand_brake = False control.steer = np.clip( steer_control, -1.0, 1.0) control.manual_gear_shift = True # DO NOT REMOVE: Reduces transmission lag. control.gear = 1 # DO NOT REMOVE: Reduces transmission lag. # Append to commands. commands.append(carla.command.ApplyVehicleControl(actor_id, control)) elif type_tag == 'People': velocity = np.clip(control_velocity.length(), 0.0, preferred_speed) * control_velocity.make_unit_vector() control = carla.WalkerControl(carla.Vector3D(velocity.x, velocity.y), 1.0, False) commands.append(carla.command.ApplyWalkerControl(actor_id, control)) c.client.apply_batch(commands) return cur_time # New pid_last_update_time. def spawn_destroy_loop(args): try: # Wait for crowd service. time.sleep(3) c = Context(args) # Upload bounds. c.crowd_service.simulation_bounds = (c.bounds_min, c.bounds_max) last_bounds_update = None print('Spawn-destroy loop running.') while True: start = time.time() # Download bounds if last_bounds_update is None or start - last_bounds_update > 1.0: new_bounds = c.crowd_service.simulation_bounds if (new_bounds[0] is not None and new_bounds[0] != c.bounds_min) or \ (new_bounds[1] is not None and new_bounds[1] != c.bounds_max): c.bounds_min = new_bounds[0] c.bounds_max = new_bounds[1] c.bounds_occupancy = carla.OccupancyMap(c.bounds_min, c.bounds_max) c.sumo_network_spawn_segments = c.sumo_network_segments.intersection(carla.OccupancyMap(c.bounds_min, c.bounds_max)) c.sumo_network_spawn_segments.seed_rand(c.rng.getrandbits(32)) c.sidewalk_spawn_segments = c.sidewalk_segments.intersection(carla.OccupancyMap(c.bounds_min, c.bounds_max)) c.sidewalk_spawn_segments.seed_rand(c.rng.getrandbits(32)) last_bounds_update = time.time() do_spawn(c) do_destroy(c) time.sleep(max(0, 1 / SPAWN_DESTROY_MAX_RATE - (time.time() - start))) # print('({}) Spawn-destroy rate: {} Hz'.format(os.getpid(), 1 / max(time.time() - start, 0.001))) except Pyro4.errors.ConnectionClosedError: pass def control_loop(args): try: # Wait for crowd service. time.sleep(3) c = Context(args) print('Control loop running.') speed_pid_integrals = defaultdict(float) speed_pid_last_errors = defaultdict(float) pid_last_update_time = None steer_pid_integrals = defaultdict(float) steer_pid_last_errors = defaultdict(float) while True: start = time.time() pid_last_update_time = do_control(c, speed_pid_integrals, speed_pid_last_errors, steer_pid_integrals, steer_pid_last_errors, pid_last_update_time) time.sleep(max(0, 1 / CONTROL_MAX_RATE - (time.time() - start))) # 20 Hz # print('({}) Control rate: {} Hz'.format(os.getpid(), 1 / max(time.time() - start, 0.001))) except Pyro4.errors.ConnectionClosedError: pass def gamma_loop(args): try: # Wait for crowd service. time.sleep(3) c = Context(args) print('GAMMA loop running.') car_agents = [] bike_agents = [] pedestrian_agents = [] statistics_file = open('statistics.log', 'w') statistics = Statistics(statistics_file) statistics.start_time = time.time() last_bounds_update = None rate_statistics_start = None rate_statistics_count = 0 rate_statistics_done = False while True: destroy_list = [] start = time.time() # Download bounds. # Required for death process. if last_bounds_update is None or start - last_bounds_update > 1.0: new_bounds = c.crowd_service.simulation_bounds if (new_bounds[0] is not None and new_bounds[0] != c.bounds_min) or \ (new_bounds[1] is not None and new_bounds[1] != c.bounds_max): c.bounds_min = new_bounds[0] c.bounds_max = new_bounds[1] c.bounds_occupancy = carla.OccupancyMap(c.bounds_min, c.bounds_max) new_forbidden_bounds = c.crowd_service.forbidden_bounds if (new_forbidden_bounds[0] is not None and new_forbidden_bounds[0] != c.forbidden_bounds_min) or \ (new_forbidden_bounds[1] is not None and new_forbidden_bounds[1] != c.forbidden_bounds_max): c.forbidden_bounds_min = new_forbidden_bounds[0] c.forbidden_bounds_max = new_forbidden_bounds[1] c.forbidden_bounds_occupancy = carla.OccupancyMap(c.forbidden_bounds_min, c.forbidden_bounds_max) last_bounds_update = time.time() # TODO: Maybe an functional-immutable interface wasn't the best idea... # Do this first if not new agents from pull_new_agents will affect avg. speed. (statistics) = \ do_speed_statistics(c, car_agents, bike_agents, pedestrian_agents, statistics) (car_agents, bike_agents, pedestrian_agents, statistics) = \ pull_new_agents(c, car_agents, bike_agents, pedestrian_agents, statistics) (car_agents, bike_agents, pedestrian_agents, destroy_list) = \ do_gamma(c, car_agents, bike_agents, pedestrian_agents, destroy_list) (car_agents, bike_agents, pedestrian_agents, destroy_list, statistics) = \ do_death(c, car_agents, bike_agents, pedestrian_agents, destroy_list, statistics) #statistics.write() c.crowd_service.acquire_destroy_list() c.crowd_service.extend_destroy_list(destroy_list) c.crowd_service.release_destroy_list() time.sleep(max(0, 1 / GAMMA_MAX_RATE - (time.time() - start))) # 40 Hz # print('({}) GAMMA rate: {} Hz'.format(os.getpid(), 1 / max(time.time() - start, 0.001))) ''' if not rate_statistics_done: print(len(car_agents), len(bike_agents), len(pedestrian_agents), time.time() - statistics.start_time) if rate_statistics_start is None: if time.time() - statistics.start_time > 180: rate_statistics_start = time.time() else: rate_statistics_count += 1 if time.time() - rate_statistics_start > 300: print('Rate statistics = {:2f} Hz'.format(float(rate_statistics_count) / (time.time() - rate_statistics_start))) rate_statistics_done = True ''' except Pyro4.errors.ConnectionClosedError: pass def collision_statistics_loop(args): try: # Wait for crowd service. time.sleep(3) c = Context(args) print('Collision statistics loop running.') statistics_file = open('statistics_collision.log', 'w') sim_start_time = time.time() while True: start = time.time() do_collision_statistics(c, time.time() - sim_start_time, statistics_file) time.sleep(max(0, 1 / COLLISION_STATISTICS_MAX_RATE - (time.time() - start))) # 40 Hz # print('({}) Collision statistics rate: {} Hz'.format(os.getpid(), 1 / max(time.time() - start, 0.001))) except Pyro4.errors.ConnectionClosedError: pass def main(args): spawn_destroy_process = Process(target=spawn_destroy_loop, args=(args,)) spawn_destroy_process.daemon = True spawn_destroy_process.start() control_process = Process(target=control_loop, args=(args,)) control_process.daemon = True control_process.start() gamma_process = Process(target=gamma_loop, args=(args,)) gamma_process.daemon = True gamma_process.start() ''' collision_statistics_process = Process(target=collision_statistics_loop, args=(args,)) collision_statistics_process.daemon = True collision_statistics_process.start() ''' Pyro4.Daemon.serveSimple( { CrowdService: "crowdservice.warehouse" }, port=args.pyroport, ns=False) if __name__ == '__main__': argparser = argparse.ArgumentParser( description=__doc__) argparser.add_argument( '--host', default='127.0.0.1', help='IP of the host server (default: 127.0.0.1)') argparser.add_argument( '-p', '--port', default=2000, type=int, help='TCP port to listen to (default: 2000)') argparser.add_argument( '-pyp', '--pyroport', default=8100, type=int, help='TCP port for pyro4 to listen to (default: 8100)') argparser.add_argument( '-d', '--dataset', default='meskel_square', help='Name of dataset (default: meskel_square)') argparser.add_argument( '-s', '--seed', default='-1', help='Value of random seed (default: -1)', type=int) argparser.add_argument( '--collision', help='Enables collision for controlled agents', action='store_true') argparser.add_argument( '--num-car', default='20', help='Number of cars to spawn (default: 20)', type=int) argparser.add_argument( '--num-bike', default='20', help='Number of bikes to spawn (default: 20)', type=int) argparser.add_argument( '--num-pedestrian', default='20', help='Number of pedestrians to spawn (default: 20)', type=int) argparser.add_argument( '--speed-car', default='4.0', help='Mean preferred_speed of cars', type=float) argparser.add_argument( '--speed-bike', default='2.0', help='Mean preferred_speed of bikes', type=float) argparser.add_argument( '--speed-pedestrian', default='1.0', help='Mean preferred_speed of pedestrains', type=float) argparser.add_argument( '--clearance-car', default='10.0', help='Minimum clearance (m) when spawning a car (default: 10.0)', type=float) argparser.add_argument( '--clearance-bike', default='10.0', help='Minimum clearance (m) when spawning a bike (default: 10.0)', type=float) argparser.add_argument( '--clearance-pedestrian', default='1.0', help='Minimum clearance (m) when spawning a pedestrian (default: 1.0)', type=float) argparser.add_argument( '--lane-change-probability', default='0.0', help='Probability of lane change for cars and bikes (default: 0.0)', type=float) argparser.add_argument( '--cross-probability', default='0.1', help='Probability of crossing road for pedestrians (default: 0.1)', type=float) argparser.add_argument( '--stuck-speed', default='0.2', help='Maximum speed (m/s) for an agent to be considered stuck (default: 0.2)', type=float) argparser.add_argument( '--stuck-duration', default='5.0', help='Minimum duration (s) for an agent to be considered stuck (default: 5)', type=float) args = argparser.parse_args() main(args)
[ "numpy.clip", "multiprocessing.Process", "carla.Vector2D", "time.sleep", "carla.SidewalkRoutePoint", "os.fsync", "carla.command.ApplyWalkerControl", "carla.OccupancyMap", "carla.command.ApplyVehicleControl", "carla.RVOSimulator", "argparse.ArgumentParser", "random.Random", "Pyro4.config.SERI...
[((5120, 5168), 'Pyro4.config.SERIALIZERS_ACCEPTED.add', 'Pyro4.config.SERIALIZERS_ACCEPTED.add', (['"""serpent"""'], {}), "('serpent')\n", (5157, 5168), False, 'import Pyro4\n'), ((5205, 5336), 'Pyro4.util.SerializerBase.register_class_to_dict', 'Pyro4.util.SerializerBase.register_class_to_dict', (['carla.Vector2D', "(lambda o: {'__class__': 'carla.Vector2D', 'x': o.x, 'y': o.y})"], {}), "(carla.Vector2D, lambda o:\n {'__class__': 'carla.Vector2D', 'x': o.x, 'y': o.y})\n", (5253, 5336), False, 'import Pyro4\n'), ((5527, 5747), 'Pyro4.util.SerializerBase.register_class_to_dict', 'Pyro4.util.SerializerBase.register_class_to_dict', (['carla.SumoNetworkRoutePoint', "(lambda o: {'__class__': 'carla.SumoNetworkRoutePoint', 'edge': o.edge,\n 'lane': o.lane, 'segment': o.segment, 'offset': o.offset})"], {}), "(carla.\n SumoNetworkRoutePoint, lambda o: {'__class__':\n 'carla.SumoNetworkRoutePoint', 'edge': o.edge, 'lane': o.lane,\n 'segment': o.segment, 'offset': o.offset})\n", (5575, 5747), False, 'import Pyro4\n'), ((6115, 6232), 'Pyro4.util.SerializerBase.register_dict_to_class', 'Pyro4.util.SerializerBase.register_dict_to_class', (['"""carla.SumoNetworkRoutePoint"""', 'dict_to_sumo_network_route_point'], {}), "('carla.SumoNetworkRoutePoint',\n dict_to_sumo_network_route_point)\n", (6163, 6232), False, 'import Pyro4\n'), ((6245, 6458), 'Pyro4.util.SerializerBase.register_class_to_dict', 'Pyro4.util.SerializerBase.register_class_to_dict', (['carla.SidewalkRoutePoint', "(lambda o: {'__class__': 'carla.SidewalkRoutePoint', 'polygon_id': o.\n polygon_id, 'segment_id': o.segment_id, 'offset': o.offset})"], {}), "(carla.SidewalkRoutePoint, \n lambda o: {'__class__': 'carla.SidewalkRoutePoint', 'polygon_id': o.\n polygon_id, 'segment_id': o.segment_id, 'offset': o.offset})\n", (6293, 6458), False, 'import Pyro4\n'), ((6741, 6851), 'Pyro4.util.SerializerBase.register_dict_to_class', 'Pyro4.util.SerializerBase.register_dict_to_class', (['"""carla.SidewalkRoutePoint"""', 'dict_to_sidewalk_route_point'], {}), "('carla.SidewalkRoutePoint',\n dict_to_sidewalk_route_point)\n", (6789, 6851), False, 'import Pyro4\n'), ((6932, 6970), 'Pyro4.behavior', 'Pyro4.behavior', ([], {'instance_mode': '"""single"""'}), "(instance_mode='single')\n", (6946, 6970), False, 'import Pyro4\n'), ((5892, 5921), 'carla.SumoNetworkRoutePoint', 'carla.SumoNetworkRoutePoint', ([], {}), '()\n', (5919, 5921), False, 'import carla\n'), ((6594, 6620), 'carla.SidewalkRoutePoint', 'carla.SidewalkRoutePoint', ([], {}), '()\n', (6618, 6620), False, 'import carla\n'), ((13305, 13322), 'numpy.rad2deg', 'np.rad2deg', (['theta'], {}), '(theta)\n', (13315, 13322), True, 'import numpy as np\n'), ((13701, 13733), 'carla.Vector2D', 'carla.Vector2D', (['pos3d.x', 'pos3d.y'], {}), '(pos3d.x, pos3d.y)\n', (13715, 13733), False, 'import carla\n'), ((13837, 13873), 'carla.Vector2D', 'carla.Vector2D', (['forward.x', 'forward.y'], {}), '(forward.x, forward.y)\n', (13851, 13873), False, 'import carla\n'), ((14869, 14893), 'carla.Vector2D', 'carla.Vector2D', (['v.x', 'v.y'], {}), '(v.x, v.y)\n', (14883, 14893), False, 'import carla\n'), ((37920, 37931), 'time.time', 'time.time', ([], {}), '()\n', (37929, 37931), False, 'import time\n'), ((41386, 41404), 'os.fsync', 'os.fsync', (['log_file'], {}), '(log_file)\n', (41394, 41404), False, 'import os\n'), ((50427, 50438), 'time.time', 'time.time', ([], {}), '()\n', (50436, 50438), False, 'import time\n'), ((50632, 50643), 'time.time', 'time.time', ([], {}), '()\n', (50641, 50643), False, 'import time\n'), ((62240, 62288), 'multiprocessing.Process', 'Process', ([], {'target': 'spawn_destroy_loop', 'args': '(args,)'}), '(target=spawn_destroy_loop, args=(args,))\n', (62247, 62288), False, 'from multiprocessing import Process\n'), ((62386, 62428), 'multiprocessing.Process', 'Process', ([], {'target': 'control_loop', 'args': '(args,)'}), '(target=control_loop, args=(args,))\n', (62393, 62428), False, 'from multiprocessing import Process\n'), ((62516, 62556), 'multiprocessing.Process', 'Process', ([], {'target': 'gamma_loop', 'args': '(args,)'}), '(target=gamma_loop, args=(args,))\n', (62523, 62556), False, 'from multiprocessing import Process\n'), ((62820, 62921), 'Pyro4.Daemon.serveSimple', 'Pyro4.Daemon.serveSimple', (["{CrowdService: 'crowdservice.warehouse'}"], {'port': 'args.pyroport', 'ns': '(False)'}), "({CrowdService: 'crowdservice.warehouse'}, port=\n args.pyroport, ns=False)\n", (62844, 62921), False, 'import Pyro4\n'), ((63028, 63072), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (63051, 63072), False, 'import argparse\n'), ((5495, 5525), 'carla.Vector2D', 'carla.Vector2D', (["o['x']", "o['y']"], {}), "(o['x'], o['y'])\n", (5509, 5525), False, 'import carla\n'), ((7142, 7149), 'threading.RLock', 'RLock', ([], {}), '()\n', (7147, 7149), False, 'from threading import RLock\n'), ((7273, 7280), 'threading.RLock', 'RLock', ([], {}), '()\n', (7278, 7280), False, 'from threading import RLock\n'), ((7372, 7379), 'threading.RLock', 'RLock', ([], {}), '()\n', (7377, 7379), False, 'from threading import RLock\n'), ((7474, 7481), 'threading.RLock', 'RLock', ([], {}), '()\n', (7479, 7481), False, 'from threading import RLock\n'), ((7594, 7601), 'threading.RLock', 'RLock', ([], {}), '()\n', (7599, 7601), False, 'from threading import RLock\n'), ((7681, 7688), 'threading.RLock', 'RLock', ([], {}), '()\n', (7686, 7688), False, 'from threading import RLock\n'), ((7764, 7771), 'threading.RLock', 'RLock', ([], {}), '()\n', (7769, 7771), False, 'from threading import RLock\n'), ((7839, 7846), 'threading.RLock', 'RLock', ([], {}), '()\n', (7844, 7846), False, 'from threading import RLock\n'), ((13225, 13257), 'math.atan2', 'math.atan2', (['vector1.y', 'vector1.x'], {}), '(vector1.y, vector1.x)\n', (13235, 13257), False, 'import math\n'), ((13260, 13292), 'math.atan2', 'math.atan2', (['vector2.y', 'vector2.x'], {}), '(vector2.y, vector2.x)\n', (13270, 13292), False, 'import math\n'), ((14057, 14105), 'carla.Vector2D', 'carla.Vector2D', (['bbox.location.x', 'bbox.location.y'], {}), '(bbox.location.x, bbox.location.y)\n', (14071, 14105), False, 'import carla\n'), ((14232, 14246), 'numpy.deg2rad', 'np.deg2rad', (['(90)'], {}), '(90)\n', (14242, 14246), True, 'import numpy as np\n'), ((14976, 15024), 'carla.Vector2D', 'carla.Vector2D', (['bbox.location.x', 'bbox.location.y'], {}), '(bbox.location.x, bbox.location.y)\n', (14990, 15024), False, 'import carla\n'), ((15151, 15165), 'numpy.deg2rad', 'np.deg2rad', (['(90)'], {}), '(90)\n', (15161, 15165), True, 'import numpy as np\n'), ((15634, 15682), 'carla.Vector2D', 'carla.Vector2D', (['bbox.location.x', 'bbox.location.y'], {}), '(bbox.location.x, bbox.location.y)\n', (15648, 15682), False, 'import carla\n'), ((15809, 15823), 'numpy.deg2rad', 'np.deg2rad', (['(90)'], {}), '(90)\n', (15819, 15823), True, 'import numpy as np\n'), ((16395, 16443), 'carla.Vector2D', 'carla.Vector2D', (['bbox.location.x', 'bbox.location.y'], {}), '(bbox.location.x, bbox.location.y)\n', (16409, 16443), False, 'import carla\n'), ((16570, 16584), 'numpy.deg2rad', 'np.deg2rad', (['(90)'], {}), '(90)\n', (16580, 16584), True, 'import numpy as np\n'), ((17333, 17373), 'carla.Segment2D', 'carla.Segment2D', (['position', 'left_line_end'], {}), '(position, left_line_end)\n', (17348, 17373), False, 'import carla\n'), ((17436, 17477), 'carla.Segment2D', 'carla.Segment2D', (['position', 'right_line_end'], {}), '(position, right_line_end)\n', (17451, 17477), False, 'import carla\n'), ((23868, 23888), 'carla.Vector2D', 'carla.Vector2D', (['(0)', '(0)'], {}), '(0, 0)\n', (23882, 23888), False, 'import carla\n'), ((24504, 24528), 'random.Random', 'random.Random', (['args.seed'], {}), '(args.seed)\n', (24517, 24528), False, 'import random\n'), ((26005, 26039), 'carla.Client', 'carla.Client', (['args.host', 'args.port'], {}), '(args.host, args.port)\n', (26017, 26039), False, 'import carla\n'), ((27756, 27779), 'os.fsync', 'os.fsync', (['self.log_file'], {}), '(self.log_file)\n', (27764, 27779), False, 'import os\n'), ((35452, 35481), 'carla.command.DestroyActor', 'carla.command.DestroyActor', (['x'], {}), '(x)\n', (35478, 35481), False, 'import carla\n'), ((41752, 41772), 'carla.RVOSimulator', 'carla.RVOSimulator', ([], {}), '()\n', (41770, 41772), False, 'import carla\n'), ((47746, 47757), 'time.time', 'time.time', ([], {}), '()\n', (47755, 47757), False, 'import time\n'), ((55193, 55206), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (55203, 55206), False, 'import time\n'), ((56873, 56886), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (56883, 56886), False, 'import time\n'), ((56999, 57017), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (57010, 57017), False, 'from collections import defaultdict\n'), ((57050, 57068), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (57061, 57068), False, 'from collections import defaultdict\n'), ((57137, 57155), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (57148, 57155), False, 'from collections import defaultdict\n'), ((57188, 57206), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (57199, 57206), False, 'from collections import defaultdict\n'), ((57765, 57778), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (57775, 57778), False, 'import time\n'), ((58066, 58077), 'time.time', 'time.time', ([], {}), '()\n', (58075, 58077), False, 'import time\n'), ((61577, 61590), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (61587, 61590), False, 'import time\n'), ((61767, 61778), 'time.time', 'time.time', ([], {}), '()\n', (61776, 61778), False, 'import time\n'), ((8041, 8117), 'carla.Vector2D', 'carla.Vector2D', (['self._simulation_bounds_min.x', 'self._simulation_bounds_min.y'], {}), '(self._simulation_bounds_min.x, self._simulation_bounds_min.y)\n', (8055, 8117), False, 'import carla\n'), ((8217, 8293), 'carla.Vector2D', 'carla.Vector2D', (['self._simulation_bounds_max.x', 'self._simulation_bounds_max.y'], {}), '(self._simulation_bounds_max.x, self._simulation_bounds_max.y)\n', (8231, 8293), False, 'import carla\n'), ((8860, 8934), 'carla.Vector2D', 'carla.Vector2D', (['self._forbidden_bounds_min.x', 'self._forbidden_bounds_min.y'], {}), '(self._forbidden_bounds_min.x, self._forbidden_bounds_min.y)\n', (8874, 8934), False, 'import carla\n'), ((9032, 9106), 'carla.Vector2D', 'carla.Vector2D', (['self._forbidden_bounds_max.x', 'self._forbidden_bounds_max.y'], {}), '(self._forbidden_bounds_max.x, self._forbidden_bounds_max.y)\n', (9046, 9106), False, 'import carla\n'), ((20490, 20540), 'math.atan2', 'math.atan2', (['(next_pos.y - pos.y)', '(next_pos.x - pos.x)'], {}), '(next_pos.y - pos.y, next_pos.x - pos.x)\n', (20500, 20540), False, 'import math\n'), ((23504, 23554), 'math.atan2', 'math.atan2', (['(next_pos.y - pos.y)', '(next_pos.x - pos.x)'], {}), '(next_pos.y - pos.y, next_pos.x - pos.x)\n', (23514, 23554), False, 'import math\n'), ((24826, 24878), 'carla.OccupancyMap', 'carla.OccupancyMap', (['self.bounds_min', 'self.bounds_max'], {}), '(self.bounds_min, self.bounds_max)\n', (24844, 24878), False, 'import carla\n'), ((25278, 25330), 'carla.OccupancyMap', 'carla.OccupancyMap', (['self.bounds_min', 'self.bounds_max'], {}), '(self.bounds_min, self.bounds_max)\n', (25296, 25330), False, 'import carla\n'), ((25742, 25794), 'carla.OccupancyMap', 'carla.OccupancyMap', (['self.bounds_min', 'self.bounds_max'], {}), '(self.bounds_min, self.bounds_max)\n', (25760, 25794), False, 'import carla\n'), ((28411, 28431), 'carla.OccupancyMap', 'carla.OccupancyMap', ([], {}), '()\n', (28429, 28431), False, 'import carla\n'), ((29457, 29474), 'carla.Transform', 'carla.Transform', ([], {}), '()\n', (29472, 29474), False, 'import carla\n'), ((30679, 30699), 'carla.OccupancyMap', 'carla.OccupancyMap', ([], {}), '()\n', (30697, 30699), False, 'import carla\n'), ((31737, 31754), 'carla.Transform', 'carla.Transform', ([], {}), '()\n', (31752, 31754), False, 'import carla\n'), ((32944, 32964), 'carla.OccupancyMap', 'carla.OccupancyMap', ([], {}), '()\n', (32962, 32964), False, 'import carla\n'), ((34044, 34061), 'carla.Transform', 'carla.Transform', ([], {}), '()\n', (34059, 34061), False, 'import carla\n'), ((52463, 52495), 'math.atan2', 'math.atan2', (['cur_vel.y', 'cur_vel.x'], {}), '(cur_vel.y, cur_vel.x)\n', (52473, 52495), False, 'import math\n'), ((53211, 53262), 'numpy.clip', 'np.clip', (['steer_pid_integrals[actor_id]', '(-0.02)', '(0.02)'], {}), '(steer_pid_integrals[actor_id], -0.02, 0.02)\n', (53218, 53262), True, 'import numpy as np\n'), ((54372, 54405), 'numpy.clip', 'np.clip', (['steer_control', '(-1.0)', '(1.0)'], {}), '(steer_control, -1.0, 1.0)\n', (54379, 54405), True, 'import numpy as np\n'), ((55470, 55481), 'time.time', 'time.time', ([], {}), '()\n', (55479, 55481), False, 'import time\n'), ((57248, 57259), 'time.time', 'time.time', ([], {}), '()\n', (57257, 57259), False, 'import time\n'), ((58293, 58304), 'time.time', 'time.time', ([], {}), '()\n', (58302, 58304), False, 'import time\n'), ((61820, 61831), 'time.time', 'time.time', ([], {}), '()\n', (61829, 61831), False, 'import time\n'), ((10081, 10099), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (10097, 10099), False, 'import sys\n'), ((10736, 10754), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (10752, 10754), False, 'import sys\n'), ((11504, 11522), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (11520, 11522), False, 'import sys\n'), ((12000, 12018), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (12016, 12018), False, 'import sys\n'), ((12477, 12495), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (12493, 12495), False, 'import sys\n'), ((13086, 13104), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (13102, 13104), False, 'import sys\n'), ((42487, 42526), 'carla.AgentParams.get_default', 'carla.AgentParams.get_default', (['type_tag'], {}), '(type_tag)\n', (42516, 42526), False, 'import carla\n'), ((52943, 52996), 'numpy.clip', 'np.clip', (['speed_error', '(-0.3 / speed_kp)', '(0.3 / speed_kp)'], {}), '(speed_error, -0.3 / speed_kp, 0.3 / speed_kp)\n', (52950, 52996), True, 'import numpy as np\n'), ((53048, 53103), 'numpy.clip', 'np.clip', (['heading_error', '(-0.3 / steer_kp)', '(0.3 / steer_kp)'], {}), '(heading_error, -0.3 / steer_kp, 0.3 / steer_kp)\n', (53055, 53103), True, 'import numpy as np\n'), ((54642, 54694), 'carla.command.ApplyVehicleControl', 'carla.command.ApplyVehicleControl', (['actor_id', 'control'], {}), '(actor_id, control)\n', (54675, 54694), False, 'import carla\n'), ((56479, 56490), 'time.time', 'time.time', ([], {}), '()\n', (56488, 56490), False, 'import time\n'), ((59509, 59520), 'time.time', 'time.time', ([], {}), '()\n', (59518, 59520), False, 'import time\n'), ((784, 810), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (800, 810), False, 'import os\n'), ((27361, 27372), 'time.time', 'time.time', ([], {}), '()\n', (27370, 27372), False, 'import time\n'), ((46545, 46590), 'carla.AgentParams.get_default', 'carla.AgentParams.get_default', (['agent.type_tag'], {}), '(agent.type_tag)\n', (46574, 46590), False, 'import carla\n'), ((54892, 54930), 'carla.Vector3D', 'carla.Vector3D', (['velocity.x', 'velocity.y'], {}), '(velocity.x, velocity.y)\n', (54906, 54930), False, 'import carla\n'), ((54972, 55023), 'carla.command.ApplyWalkerControl', 'carla.command.ApplyWalkerControl', (['actor_id', 'control'], {}), '(actor_id, control)\n', (55004, 55023), False, 'import carla\n'), ((55967, 56013), 'carla.OccupancyMap', 'carla.OccupancyMap', (['c.bounds_min', 'c.bounds_max'], {}), '(c.bounds_min, c.bounds_max)\n', (55985, 56013), False, 'import carla\n'), ((58846, 58892), 'carla.OccupancyMap', 'carla.OccupancyMap', (['c.bounds_min', 'c.bounds_max'], {}), '(c.bounds_min, c.bounds_max)\n', (58864, 58892), False, 'import carla\n'), ((59404, 59470), 'carla.OccupancyMap', 'carla.OccupancyMap', (['c.forbidden_bounds_min', 'c.forbidden_bounds_max'], {}), '(c.forbidden_bounds_min, c.forbidden_bounds_max)\n', (59422, 59470), False, 'import carla\n'), ((61871, 61882), 'time.time', 'time.time', ([], {}), '()\n', (61880, 61882), False, 'import time\n'), ((17125, 17140), 'numpy.deg2rad', 'np.deg2rad', (['(-90)'], {}), '(-90)\n', (17135, 17140), True, 'import numpy as np\n'), ((17236, 17250), 'numpy.deg2rad', 'np.deg2rad', (['(90)'], {}), '(90)\n', (17246, 17250), True, 'import numpy as np\n'), ((28766, 28868), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_min.x - c.args.clearance_car)', '(aabb.bounds_min.y - c.args.clearance_car)'], {}), '(aabb.bounds_min.x - c.args.clearance_car, aabb.bounds_min.y -\n c.args.clearance_car)\n', (28780, 28868), False, 'import carla\n'), ((28887, 28989), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_max.x + c.args.clearance_car)', '(aabb.bounds_max.y + c.args.clearance_car)'], {}), '(aabb.bounds_max.x + c.args.clearance_car, aabb.bounds_max.y +\n c.args.clearance_car)\n', (28901, 28989), False, 'import carla\n'), ((30382, 30484), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_min.x - c.args.clearance_car)', '(aabb.bounds_min.y - c.args.clearance_car)'], {}), '(aabb.bounds_min.x - c.args.clearance_car, aabb.bounds_min.y -\n c.args.clearance_car)\n', (30396, 30484), False, 'import carla\n'), ((30503, 30605), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_max.x + c.args.clearance_car)', '(aabb.bounds_max.y + c.args.clearance_car)'], {}), '(aabb.bounds_max.x + c.args.clearance_car, aabb.bounds_max.y +\n c.args.clearance_car)\n', (30517, 30605), False, 'import carla\n'), ((31034, 31138), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_min.x - c.args.clearance_bike)', '(aabb.bounds_min.y - c.args.clearance_bike)'], {}), '(aabb.bounds_min.x - c.args.clearance_bike, aabb.bounds_min.y -\n c.args.clearance_bike)\n', (31048, 31138), False, 'import carla\n'), ((31157, 31261), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_max.x + c.args.clearance_bike)', '(aabb.bounds_max.y + c.args.clearance_bike)'], {}), '(aabb.bounds_max.x + c.args.clearance_bike, aabb.bounds_max.y +\n c.args.clearance_bike)\n', (31171, 31261), False, 'import carla\n'), ((32666, 32770), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_min.x - c.args.clearance_bike)', '(aabb.bounds_min.y - c.args.clearance_bike)'], {}), '(aabb.bounds_min.x - c.args.clearance_bike, aabb.bounds_min.y -\n c.args.clearance_bike)\n', (32680, 32770), False, 'import carla\n'), ((32789, 32893), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_max.x + c.args.clearance_bike)', '(aabb.bounds_max.y + c.args.clearance_bike)'], {}), '(aabb.bounds_max.x + c.args.clearance_bike, aabb.bounds_max.y +\n c.args.clearance_bike)\n', (32803, 32893), False, 'import carla\n'), ((33299, 33416), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_min.x - c.args.clearance_pedestrian)', '(aabb.bounds_min.y - c.args.clearance_pedestrian)'], {}), '(aabb.bounds_min.x - c.args.clearance_pedestrian, aabb.\n bounds_min.y - c.args.clearance_pedestrian)\n', (33313, 33416), False, 'import carla\n'), ((33434, 33551), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_max.x + c.args.clearance_pedestrian)', '(aabb.bounds_max.y + c.args.clearance_pedestrian)'], {}), '(aabb.bounds_max.x + c.args.clearance_pedestrian, aabb.\n bounds_max.y + c.args.clearance_pedestrian)\n', (33448, 33551), False, 'import carla\n'), ((34987, 35104), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_min.x - c.args.clearance_pedestrian)', '(aabb.bounds_min.y - c.args.clearance_pedestrian)'], {}), '(aabb.bounds_min.x - c.args.clearance_pedestrian, aabb.\n bounds_min.y - c.args.clearance_pedestrian)\n', (35001, 35104), False, 'import carla\n'), ((35122, 35239), 'carla.Vector2D', 'carla.Vector2D', (['(aabb.bounds_max.x + c.args.clearance_pedestrian)', '(aabb.bounds_max.y + c.args.clearance_pedestrian)'], {}), '(aabb.bounds_max.x + c.args.clearance_pedestrian, aabb.\n bounds_max.y + c.args.clearance_pedestrian)\n', (35136, 35239), False, 'import carla\n'), ((46306, 46326), 'carla.Vector2D', 'carla.Vector2D', (['(0)', '(0)'], {}), '(0, 0)\n', (46320, 46326), False, 'import carla\n'), ((56103, 56149), 'carla.OccupancyMap', 'carla.OccupancyMap', (['c.bounds_min', 'c.bounds_max'], {}), '(c.bounds_min, c.bounds_max)\n', (56121, 56149), False, 'import carla\n'), ((56315, 56361), 'carla.OccupancyMap', 'carla.OccupancyMap', (['c.bounds_min', 'c.bounds_max'], {}), '(c.bounds_min, c.bounds_max)\n', (56333, 56361), False, 'import carla\n'), ((162, 188), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (178, 188), False, 'import os\n'), ((56602, 56613), 'time.time', 'time.time', ([], {}), '()\n', (56611, 56613), False, 'import time\n'), ((57494, 57505), 'time.time', 'time.time', ([], {}), '()\n', (57503, 57505), False, 'import time\n'), ((60601, 60612), 'time.time', 'time.time', ([], {}), '()\n', (60610, 60612), False, 'import time\n'), ((61985, 61996), 'time.time', 'time.time', ([], {}), '()\n', (61994, 61996), False, 'import time\n')]
from openface.openface_model import create_model from openface.preprocess_face_data import load_metadata from openface.align import AlignDlib import numpy as np import cv2 import config import os from datetime import datetime # using pre-trained model print('load_model') nn4_small2_pretrained = create_model() nn4_small2_pretrained.load_weights('models/nn4.small2.v1.h5') # nn4_small2_pretrained.summary() start = datetime.now() # load customDataset print(config.faceImagesPath) metadata = load_metadata('faceImages', num=2) print(metadata) def load_image(path): img = cv2.imread(path, 1) # OpenCV loads images with color channels # in BGR order. So we need to reverse them return img[..., ::-1] # Initialize the OpenFace face alignment utility aligment = AlignDlib('models/landmarks.dat') # Align image on face def align_image(img): return aligment.align(96, img, aligment.getLargestFaceBoundingBox(img), landmarkIndices=AlignDlib.OUTER_EYES_AND_NOSE) # Embedding vectors good_image_index = [] unfit_image_index = [] embedded = np.zeros((metadata.shape[0], 128)) print('preprocess image') for i, m in enumerate(metadata): img = load_image(m.image_path()) img = align_image(img) try: # scale RGB values to interval [0,1] img = (img / 255.).astype(np.float32) except TypeError: unfit_image_index.append(i) print("The image is not Clear to extract the Embeddings") else: # obtain embedding vector for image embedded[i] = nn4_small2_pretrained.predict(np.expand_dims(img, axis=0))[0] good_image_index.append(i) stop = datetime.now() print(stop - start) metadata = metadata[good_image_index] print(metadata) embedded = embedded[good_image_index] print(embedded) print('face embedded create complete') print('save metadata and embedded') if not os.path.exists(config.faceData): os.makedirs(config.faceData, exist_ok='True') # save metadata np.save(config.faceData+'/metadata.npy', metadata) # save embedded np.save(config.faceData+'/embedded.npy', embedded)
[ "os.path.exists", "os.makedirs", "openface.align.AlignDlib", "datetime.datetime.now", "numpy.zeros", "openface.preprocess_face_data.load_metadata", "numpy.expand_dims", "openface.openface_model.create_model", "cv2.imread", "numpy.save" ]
[((297, 311), 'openface.openface_model.create_model', 'create_model', ([], {}), '()\n', (309, 311), False, 'from openface.openface_model import create_model\n'), ((417, 431), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (429, 431), False, 'from datetime import datetime\n'), ((493, 527), 'openface.preprocess_face_data.load_metadata', 'load_metadata', (['"""faceImages"""'], {'num': '(2)'}), "('faceImages', num=2)\n", (506, 527), False, 'from openface.preprocess_face_data import load_metadata\n'), ((777, 810), 'openface.align.AlignDlib', 'AlignDlib', (['"""models/landmarks.dat"""'], {}), "('models/landmarks.dat')\n", (786, 810), False, 'from openface.align import AlignDlib\n'), ((1082, 1116), 'numpy.zeros', 'np.zeros', (['(metadata.shape[0], 128)'], {}), '((metadata.shape[0], 128))\n', (1090, 1116), True, 'import numpy as np\n'), ((1644, 1658), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1656, 1658), False, 'from datetime import datetime\n'), ((1968, 2020), 'numpy.save', 'np.save', (["(config.faceData + '/metadata.npy')", 'metadata'], {}), "(config.faceData + '/metadata.npy', metadata)\n", (1975, 2020), True, 'import numpy as np\n'), ((2035, 2087), 'numpy.save', 'np.save', (["(config.faceData + '/embedded.npy')", 'embedded'], {}), "(config.faceData + '/embedded.npy', embedded)\n", (2042, 2087), True, 'import numpy as np\n'), ((577, 596), 'cv2.imread', 'cv2.imread', (['path', '(1)'], {}), '(path, 1)\n', (587, 596), False, 'import cv2\n'), ((1869, 1900), 'os.path.exists', 'os.path.exists', (['config.faceData'], {}), '(config.faceData)\n', (1883, 1900), False, 'import os\n'), ((1906, 1951), 'os.makedirs', 'os.makedirs', (['config.faceData'], {'exist_ok': '"""True"""'}), "(config.faceData, exist_ok='True')\n", (1917, 1951), False, 'import os\n'), ((1570, 1597), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (1584, 1597), True, 'import numpy as np\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. import unittest import numpy as np import paddle from op_test import OpTest paddle.enable_static() ################## TEST OP: BitwiseAnd ################## class TestBitwiseAnd(OpTest): def setUp(self): self.op_type = "bitwise_and" self.init_dtype() self.init_shape() self.init_bound() x = np.random.randint( self.low, self.high, self.x_shape, dtype=self.dtype) y = np.random.randint( self.low, self.high, self.y_shape, dtype=self.dtype) out = np.bitwise_and(x, y) self.inputs = {'X': x, 'Y': y} self.outputs = {'Out': out} def test_check_output(self): self.check_output() def test_check_grad(self): pass def init_dtype(self): self.dtype = np.int32 def init_shape(self): self.x_shape = [2, 3, 4, 5] self.y_shape = [2, 3, 4, 5] def init_bound(self): self.low = -100 self.high = 100 class TestBitwiseAndUInt8(TestBitwiseAnd): def init_dtype(self): self.dtype = np.uint8 def init_bound(self): self.low = 0 self.high = 100 class TestBitwiseAndInt8(TestBitwiseAnd): def init_dtype(self): self.dtype = np.int8 def init_shape(self): self.x_shape = [4, 5] self.y_shape = [2, 3, 4, 5] class TestBitwiseAndInt16(TestBitwiseAnd): def init_dtype(self): self.dtype = np.int16 def init_shape(self): self.x_shape = [2, 3, 4, 5] self.y_shape = [4, 1] class TestBitwiseAndInt64(TestBitwiseAnd): def init_dtype(self): self.dtype = np.int64 def init_shape(self): self.x_shape = [1, 4, 1] self.y_shape = [2, 3, 4, 5] class TestBitwiseAndBool(TestBitwiseAnd): def setUp(self): self.op_type = "bitwise_and" self.init_shape() x = np.random.choice([True, False], self.x_shape) y = np.random.choice([True, False], self.y_shape) out = np.bitwise_and(x, y) self.inputs = {'X': x, 'Y': y} self.outputs = {'Out': out} ################## TEST OP: BitwiseOr ################## class TestBitwiseOr(OpTest): def setUp(self): self.op_type = "bitwise_or" self.init_dtype() self.init_shape() self.init_bound() x = np.random.randint( self.low, self.high, self.x_shape, dtype=self.dtype) y = np.random.randint( self.low, self.high, self.y_shape, dtype=self.dtype) out = np.bitwise_or(x, y) self.inputs = {'X': x, 'Y': y} self.outputs = {'Out': out} def test_check_output(self): self.check_output() def test_check_grad(self): pass def init_dtype(self): self.dtype = np.int32 def init_shape(self): self.x_shape = [2, 3, 4, 5] self.y_shape = [2, 3, 4, 5] def init_bound(self): self.low = -100 self.high = 100 class TestBitwiseOrUInt8(TestBitwiseOr): def init_dtype(self): self.dtype = np.uint8 def init_bound(self): self.low = 0 self.high = 100 class TestBitwiseOrInt8(TestBitwiseOr): def init_dtype(self): self.dtype = np.int8 def init_shape(self): self.x_shape = [4, 5] self.y_shape = [2, 3, 4, 5] class TestBitwiseOrInt16(TestBitwiseOr): def init_dtype(self): self.dtype = np.int16 def init_shape(self): self.x_shape = [2, 3, 4, 5] self.y_shape = [4, 1] class TestBitwiseOrInt64(TestBitwiseOr): def init_dtype(self): self.dtype = np.int64 def init_shape(self): self.x_shape = [1, 4, 1] self.y_shape = [2, 3, 4, 5] class TestBitwiseOrBool(TestBitwiseOr): def setUp(self): self.op_type = "bitwise_or" self.init_shape() x = np.random.choice([True, False], self.x_shape) y = np.random.choice([True, False], self.y_shape) out = np.bitwise_or(x, y) self.inputs = {'X': x, 'Y': y} self.outputs = {'Out': out} ################## TEST OP: BitwiseXor ################## class TestBitwiseXor(OpTest): def setUp(self): self.op_type = "bitwise_xor" self.init_dtype() self.init_shape() self.init_bound() x = np.random.randint( self.low, self.high, self.x_shape, dtype=self.dtype) y = np.random.randint( self.low, self.high, self.y_shape, dtype=self.dtype) out = np.bitwise_xor(x, y) self.inputs = {'X': x, 'Y': y} self.outputs = {'Out': out} def test_check_output(self): self.check_output() def test_check_grad(self): pass def init_dtype(self): self.dtype = np.int32 def init_shape(self): self.x_shape = [2, 3, 4, 5] self.y_shape = [2, 3, 4, 5] def init_bound(self): self.low = -100 self.high = 100 class TestBitwiseXorUInt8(TestBitwiseXor): def init_dtype(self): self.dtype = np.uint8 def init_bound(self): self.low = 0 self.high = 100 class TestBitwiseXorInt8(TestBitwiseXor): def init_dtype(self): self.dtype = np.int8 def init_shape(self): self.x_shape = [4, 5] self.y_shape = [2, 3, 4, 5] class TestBitwiseXorInt16(TestBitwiseXor): def init_dtype(self): self.dtype = np.int16 def init_shape(self): self.x_shape = [2, 3, 4, 5] self.y_shape = [4, 1] class TestBitwiseXorInt64(TestBitwiseXor): def init_dtype(self): self.dtype = np.int64 def init_shape(self): self.x_shape = [1, 4, 1] self.y_shape = [2, 3, 4, 5] class TestBitwiseXorBool(TestBitwiseXor): def setUp(self): self.op_type = "bitwise_xor" self.init_shape() x = np.random.choice([True, False], self.x_shape) y = np.random.choice([True, False], self.y_shape) out = np.bitwise_xor(x, y) self.inputs = {'X': x, 'Y': y} self.outputs = {'Out': out} ################## TEST OP: BitwiseNot ################## class TestBitwiseNot(OpTest): def setUp(self): self.op_type = "bitwise_not" self.init_dtype() self.init_shape() self.init_bound() x = np.random.randint( self.low, self.high, self.x_shape, dtype=self.dtype) out = np.bitwise_not(x) self.inputs = {'X': x} self.outputs = {'Out': out} def test_check_output(self): self.check_output() def test_check_grad(self): pass def init_dtype(self): self.dtype = np.int32 def init_shape(self): self.x_shape = [2, 3, 4, 5] def init_bound(self): self.low = -100 self.high = 100 class TestBitwiseNotUInt8(TestBitwiseNot): def init_dtype(self): self.dtype = np.uint8 def init_bound(self): self.low = 0 self.high = 100 class TestBitwiseNotInt8(TestBitwiseNot): def init_dtype(self): self.dtype = np.int8 def init_shape(self): self.x_shape = [4, 5] class TestBitwiseNotInt16(TestBitwiseNot): def init_dtype(self): self.dtype = np.int16 def init_shape(self): self.x_shape = [2, 3, 4, 5] self.y_shape = [4, 1] class TestBitwiseNotInt64(TestBitwiseNot): def init_dtype(self): self.dtype = np.int64 def init_shape(self): self.x_shape = [1, 4, 1] class TestBitwiseNotBool(TestBitwiseNot): def setUp(self): self.op_type = "bitwise_not" self.init_shape() x = np.random.choice([True, False], self.x_shape) out = np.bitwise_not(x) self.inputs = {'X': x} self.outputs = {'Out': out} if __name__ == "__main__": unittest.main()
[ "numpy.bitwise_or", "numpy.random.choice", "numpy.bitwise_xor", "paddle.enable_static", "numpy.bitwise_and", "numpy.random.randint", "numpy.bitwise_not", "unittest.main" ]
[((690, 712), 'paddle.enable_static', 'paddle.enable_static', ([], {}), '()\n', (710, 712), False, 'import paddle\n'), ((8367, 8382), 'unittest.main', 'unittest.main', ([], {}), '()\n', (8380, 8382), False, 'import unittest\n'), ((952, 1022), 'numpy.random.randint', 'np.random.randint', (['self.low', 'self.high', 'self.x_shape'], {'dtype': 'self.dtype'}), '(self.low, self.high, self.x_shape, dtype=self.dtype)\n', (969, 1022), True, 'import numpy as np\n'), ((1048, 1118), 'numpy.random.randint', 'np.random.randint', (['self.low', 'self.high', 'self.y_shape'], {'dtype': 'self.dtype'}), '(self.low, self.high, self.y_shape, dtype=self.dtype)\n', (1065, 1118), True, 'import numpy as np\n'), ((1146, 1166), 'numpy.bitwise_and', 'np.bitwise_and', (['x', 'y'], {}), '(x, y)\n', (1160, 1166), True, 'import numpy as np\n'), ((2478, 2523), 'numpy.random.choice', 'np.random.choice', (['[True, False]', 'self.x_shape'], {}), '([True, False], self.x_shape)\n', (2494, 2523), True, 'import numpy as np\n'), ((2536, 2581), 'numpy.random.choice', 'np.random.choice', (['[True, False]', 'self.y_shape'], {}), '([True, False], self.y_shape)\n', (2552, 2581), True, 'import numpy as np\n'), ((2596, 2616), 'numpy.bitwise_and', 'np.bitwise_and', (['x', 'y'], {}), '(x, y)\n', (2610, 2616), True, 'import numpy as np\n'), ((2929, 2999), 'numpy.random.randint', 'np.random.randint', (['self.low', 'self.high', 'self.x_shape'], {'dtype': 'self.dtype'}), '(self.low, self.high, self.x_shape, dtype=self.dtype)\n', (2946, 2999), True, 'import numpy as np\n'), ((3025, 3095), 'numpy.random.randint', 'np.random.randint', (['self.low', 'self.high', 'self.y_shape'], {'dtype': 'self.dtype'}), '(self.low, self.high, self.y_shape, dtype=self.dtype)\n', (3042, 3095), True, 'import numpy as np\n'), ((3123, 3142), 'numpy.bitwise_or', 'np.bitwise_or', (['x', 'y'], {}), '(x, y)\n', (3136, 3142), True, 'import numpy as np\n'), ((4443, 4488), 'numpy.random.choice', 'np.random.choice', (['[True, False]', 'self.x_shape'], {}), '([True, False], self.x_shape)\n', (4459, 4488), True, 'import numpy as np\n'), ((4501, 4546), 'numpy.random.choice', 'np.random.choice', (['[True, False]', 'self.y_shape'], {}), '([True, False], self.y_shape)\n', (4517, 4546), True, 'import numpy as np\n'), ((4561, 4580), 'numpy.bitwise_or', 'np.bitwise_or', (['x', 'y'], {}), '(x, y)\n', (4574, 4580), True, 'import numpy as np\n'), ((4896, 4966), 'numpy.random.randint', 'np.random.randint', (['self.low', 'self.high', 'self.x_shape'], {'dtype': 'self.dtype'}), '(self.low, self.high, self.x_shape, dtype=self.dtype)\n', (4913, 4966), True, 'import numpy as np\n'), ((4992, 5062), 'numpy.random.randint', 'np.random.randint', (['self.low', 'self.high', 'self.y_shape'], {'dtype': 'self.dtype'}), '(self.low, self.high, self.y_shape, dtype=self.dtype)\n', (5009, 5062), True, 'import numpy as np\n'), ((5090, 5110), 'numpy.bitwise_xor', 'np.bitwise_xor', (['x', 'y'], {}), '(x, y)\n', (5104, 5110), True, 'import numpy as np\n'), ((6422, 6467), 'numpy.random.choice', 'np.random.choice', (['[True, False]', 'self.x_shape'], {}), '([True, False], self.x_shape)\n', (6438, 6467), True, 'import numpy as np\n'), ((6480, 6525), 'numpy.random.choice', 'np.random.choice', (['[True, False]', 'self.y_shape'], {}), '([True, False], self.y_shape)\n', (6496, 6525), True, 'import numpy as np\n'), ((6540, 6560), 'numpy.bitwise_xor', 'np.bitwise_xor', (['x', 'y'], {}), '(x, y)\n', (6554, 6560), True, 'import numpy as np\n'), ((6877, 6947), 'numpy.random.randint', 'np.random.randint', (['self.low', 'self.high', 'self.x_shape'], {'dtype': 'self.dtype'}), '(self.low, self.high, self.x_shape, dtype=self.dtype)\n', (6894, 6947), True, 'import numpy as np\n'), ((6975, 6992), 'numpy.bitwise_not', 'np.bitwise_not', (['x'], {}), '(x)\n', (6989, 6992), True, 'import numpy as np\n'), ((8188, 8233), 'numpy.random.choice', 'np.random.choice', (['[True, False]', 'self.x_shape'], {}), '([True, False], self.x_shape)\n', (8204, 8233), True, 'import numpy as np\n'), ((8248, 8265), 'numpy.bitwise_not', 'np.bitwise_not', (['x'], {}), '(x)\n', (8262, 8265), True, 'import numpy as np\n')]
# Copyright (c) 2020, <NAME> # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> import copy import math import numpy as np class Grid(np.ndarray): """Object to store SWHS values on a grid This class subclasses numpy's ndarray object, so that it should act like a numpy array in many respects, even with functions like np.zeros_like. NOTE: The functions `np.copy(grid)` and `np.array(grid, copy=True)` return `ndarray` objects; they lose information about the SWSH attributes, and have different ufuncs. If you wish to keep this information, use `grid.copy()`. Also note that pickling works as expected, as do copy.copy and copy.deepcopy. The number of dimensions is arbitrary as long as it is 2 or more, but the grid must be stored in the last 2 axes. Specifically, the grid must have shape (n_theta, n_phi). (See the function `spherical_functions.theta_phi` for an example of the actual grid locations expected.) For example, a SWSH function of time may be stored as a 3-d array where the first axis represents different times, and the second and third axes represent the function values at each instant of time. This class also does two important things that are unlike numpy arrays: 1) It tracks the spin weight of the function represented by this data. 2) It overrides most of numpy's "universal functions" (ufuncs) to work appropriately for spin-weighted functions. Specifically, these ufuncs are interpreted as acting on the spin-weighted function itself, rather than just the grid values. The returned values are -- where possible -- Grid objects. Most importantly, we have these overriden methods: a) Multiplying two Grid objects will result in a new Grid object that represents the pointwise product of the functions themselves (and will correctly have spin weight given by the sum of the spin weights of the first two functions). Division is only permitted when the divisor has spin weight zero. b) Addition (and subtraction) is permitted for functions of the same spin weight, but it does not make sense to add (or subtract) functions with different spin weights, so any attempt to do so raises a ValueError. Note that a constant is implicitly a function of spin weight zero, and is treated as such. Numerous other ufuncs -- such as log, exp, trigonometric ufuncs, bit-twiddling ufuncs, and so on -- are disabled because they don't result in objects of specific spin weights. It is possible to treat the underlying data of a Grid object `grid` as an ordinary numpy array by taking `grid.view(np.ndarray)`. However, it is hoped that this class already performs all reasonable operations. If you find a missing feature that requires you to resort to this, please feel free to open an issue in this project's github page to discuss it. Also, be aware that ndarrays also have various built-in methods that cannot be overridden very easily, such as max, copysign, etc. If you try to use -- even indirectly -- those functions that don't have any clear interpretation for spin-weighted functions, things will likely break. Constructor parameters ====================== input_array: array_like This may be a numpy ndarray, or any subclass. It must be able to be viewed as complex. If it has a `_metadata` attribute, that field will be copied to the new array; if the following parameters are not passed to the constructor, they will be searched for in the metadata. spin_weight: int [optional if present in `input_array._metadata`] The spin weight of the function that this Modes object describes. This must be specified somehow, whether via a `_metadata` attribute of the input array, or as a keyword argument, or as the second positional argument (where the latter will override the former values). """ # https://numpy.org/doc/1.18/user/basics.subclassing.html def __new__(cls, input_array, *args, **kwargs): if len(args) > 1: raise ValueError("Only one positional argument is recognized") elif len(args) == 1: kwargs['spin_weight'] = args[0] metadata = copy.copy(getattr(input_array, '_metadata', {})) metadata.update(**kwargs) input_array = np.asanyarray(input_array) if np.ndim(input_array) < 2: raise ValueError(f"Input array must have at least two dimensions; it has shape {input_array.shape}") n_theta, n_phi = input_array.shape[-2:] spin_weight = metadata.get('spin_weight', None) if spin_weight is None: raise ValueError("Spin weight must be specified") if n_theta < 2*abs(spin_weight)+1 or n_phi < 2*abs(spin_weight)+1: raise ValueError(f"Input array must have at least {2*abs(s)+1} points in each direction to have any " f"nontrivial content for a field of spin weight {spin_weight}.") obj = input_array.view(cls) obj._metadata = metadata return obj # https://numpy.org/doc/1.18/user/basics.subclassing.html def __array_finalize__(self, obj): if obj is None: return self._metadata = copy.copy(getattr(obj, '_metadata', {})) if not 'spin_weight' in self._metadata: self._metadata['spin_weight'] = None # For pickling def __reduce__(self): state = super(Modes, self).__reduce__() new_attributes = state[2] + (self._metadata,) return (state[0], state[1], new_attributes) # For unpickling def __setstate__(self, state): self._metadata = copy.deepcopy(state[-1]) super(Modes, self).__setstate__(state[:-1]) @property def ndarray(self): """View this array as a numpy ndarray""" return self.view(np.ndarray) @property def s(self): """Spin weight of this Modes object""" return self._metadata['spin_weight'] spin_weight = s @property def n_theta(self): """Number of elements along the theta axis""" return self.shape[-2] @property def n_phi(self): """Number of elements along the phi axis""" return self.shape[-1] from .algebra import ( conjugate, bar, real, imag, absolute, add, subtract, multiply, divide ) conj = conjugate from .utilities import ( modes, _check_broadcasting ) from .ufuncs import __array_ufunc__
[ "copy.deepcopy", "numpy.ndim", "numpy.asanyarray" ]
[((4468, 4494), 'numpy.asanyarray', 'np.asanyarray', (['input_array'], {}), '(input_array)\n', (4481, 4494), True, 'import numpy as np\n'), ((5792, 5816), 'copy.deepcopy', 'copy.deepcopy', (['state[-1]'], {}), '(state[-1])\n', (5805, 5816), False, 'import copy\n'), ((4506, 4526), 'numpy.ndim', 'np.ndim', (['input_array'], {}), '(input_array)\n', (4513, 4526), True, 'import numpy as np\n')]
from plugins.image_viewer.tools.image_viewer_tool import ImageViewerTool from core import settings import keras import tensorflow as tf from keras.backend import flatten, sum, sigmoid import numpy as np import cv2 from tensorflow.python.tools import freeze_graph SMOOTH = 1. # or just 0.9 and 0.1 def binary_loss(y_true, y_pred): y = y_true pred = y_pred loss_map = tf.nn.sigmoid_cross_entropy_with_logits(logits=pred, labels=y) ones = tf.count_nonzero(y) / tf.reduce_prod(tf.shape(y, out_type=tf.int64)) ones = tf.cast(ones, tf.float32) weight_map = (1 - ones) * y + (tf.ones_like(y) - y) * ones loss_map = tf.multiply(weight_map, loss_map) return tf.reduce_mean(loss_map) def dice_coef_with_sigmoid(y_true, y_pred): y_true_f = flatten(y_true) y_pred_f = sigmoid(flatten(y_pred)) intersection = sum(y_true_f * y_pred_f) return (2. * intersection + SMOOTH) / (sum(y_true_f) + sum(y_pred_f) + SMOOTH) def dice_coef_loss(y_true, y_pred): return 1 - dice_coef_with_sigmoid(y_true, y_pred) def bce_dice_loss(y_true, y_pred): return binary_loss(y_true, y_pred) + (dice_coef_loss(y_true, y_pred)) class AnnPredictionTool(ImageViewerTool): def __init__(self, viewer, parent=None): super().__init__(viewer, parent) try: # self.model = keras.models.load_model('D:/Projects/MandibularNerve/Models/2018.11.16.Model_Los014_64size.h5', # custom_objects={'bce_dice_loss': bce_dice_loss, # 'dice_coef_with_sigmoid': dice_coef_with_sigmoid # } # ) # DO it only ONE time self.model = keras.models.load_model('D:/Projects/Temp/ImReg/Dicoms/ConvertedMriConvert/BrainData/BrainModels/BrainModel_Loss017_NoOptimizer.h5', #D:/Projects/BsAnn/Models/2018.11.26.Model_Loss025.h5', #2018.11.14.Model_594EditedSlices3_loss027.h5', custom_objects={'bce_dice_loss': bce_dice_loss, 'dice_coef_with_sigmoid': dice_coef_with_sigmoid } ) # DO it only ONE time except Exception as exception: print('model exception: ', type(exception).__name__) print(exception) return ''' print('model name:', self.model.output.op.name) saver = tf.train.Saver() save_res = saver.save(keras.backend.get_session(), 'tmp/keras_model.ckpt') print('save_res', save_res) input_saver_def_path = "" input_binary = True output_node_names = self.model.output.op.name # [out.op.name for out in self.model.outputs] #"'conv2d_19/BiasAdd' #"output_node" restore_op_name = "save/restore_all" filename_tensor_name = "save/Const:0" clear_devices = False checkpoint_path = save_res #'tmp/keras_model.ckpt' input_meta_graph = checkpoint_path + ".meta" output_graph = 'tmp/out/keras_frozen.pb' # see example: https://github.com/tensorflow/tensorflow/blob/v1.12.0/tensorflow/python/tools/freeze_graph_test.py res = freeze_graph.freeze_graph( "", input_saver_def_path, input_binary, checkpoint_path, output_node_names, restore_op_name, filename_tensor_name, output_graph, clear_devices, "", "", "", input_meta_graph) # res = freeze_graph.freeze_graph(input_meta_graph='tmp/keras_model.ckpt.meta', # input_checkpoint='tpm/keras_model.ckpt', # output_graph='tmp/out/keras_frozen.pb', # output_node_names='conv2d_19/BiasAdd', # input_binary=True) print('res:', res) ''' def recreate_tool_mask(self): super().recreate_tool_mask() if not self.viewer.has_image(): return # self.predict_64() self.predict_lesions() def predict_64(self): print('Predict') image = self.viewer.image().data[:, :, 0] x_center = image.shape[0] // 2 y_center = image.shape[1] // 2 image = image[x_center - 32: x_center + 32, y_center - 32: y_center + 32] images = np.zeros((1, 64, 64, 1), dtype=np.float32) images[0, :, :, 0] = image / image.max() try: preds = self.model.predict(images) except Exception as exception: print('predict exception: ', type(exception).__name__) print(exception) return pred = preds[0, :, :, 0] # pred[pred < 0] = 0 # pred[pred > 1] = 1 # cv2.imwrite('pred.png', pred * 255) # print_image_info(pred) src_image_width = self.viewer.image().data.shape[0] src_image_height = self.viewer.image().data.shape[1] pred_empty = np.zeros((src_image_width, src_image_height), dtype=np.float32) pred_empty[x_center - 32: x_center + 32:, y_center - 32: y_center + 32:] = pred pred = pred_empty print('s1', self.viewer.image().data.shape) print('s2', pred.shape) self.tool_mask.data = np.zeros(self.viewer.image().data.shape, np.uint8) self.tool_mask.data[np.where((pred > 0.5))] = settings.TOOL_FOREGROUND self.viewer.update_scaled_combined_image() def predict_128(self): print('Predict') image = self.viewer.image().data[:, :, 0] row_pad = max(image.shape[1] - image.shape[0], 0) col_pad = max(image.shape[0] - image.shape[1], 0) image = np.pad(image, ((0, row_pad), (0, col_pad)), 'constant') image = cv2.resize(image, (128, 128), cv2.INTER_LANCZOS4) images = np.zeros((1, 128, 128, 1), dtype=np.float32) images[0, :, :, 0] = image / image.max() try: preds = self.model.predict(images) except Exception as exception: print('predict exception: ', type(exception).__name__) print(exception) return pred = preds[0, :, :, 0] # pred[pred < 0] = 0 # pred[pred > 1] = 1 # cv2.imwrite('pred.png', pred * 255) # print_image_info(pred) src_image_width = self.viewer.image().data.shape[0] src_image_height = self.viewer.image().data.shape[1] src_image_max_size = max(src_image_width, src_image_height) pred = cv2.resize(pred, (src_image_max_size, src_image_max_size), cv2.INTER_LANCZOS4) pred = pred[0: src_image_width, 0: src_image_height] print('s1', self.viewer.image().data.shape) print('s2', pred.shape) self.tool_mask.data = np.zeros(self.viewer.image().data.shape, np.uint8) self.tool_mask.data[np.where((pred > 0.5))] = settings.TOOL_FOREGROUND self.viewer.update_scaled_combined_image() def predict_lesions(self): print('Predict Lesions') image = self.viewer.image().data[:, :, 0] row_pad = max(image.shape[1] - image.shape[0], 0) col_pad = max(image.shape[0] - image.shape[1], 0) image = np.pad(image, ((0, row_pad), (0, col_pad)), 'constant') image = cv2.resize(image, (512, 512), cv2.INTER_LANCZOS4) images = np.zeros((1, 512, 512, 1), dtype=np.float32) images[0, :, :, 0] = image / image.max() try: preds = self.model.predict(images) except Exception as exception: print('predict exception: ', type(exception).__name__) print(exception) return pred = preds[0, :, :, 0] # pred[pred < 0] = 0 # pred[pred > 1] = 1 # cv2.imwrite('pred.png', pred * 255) # print_image_info(pred) src_image_width = self.viewer.image().data.shape[0] src_image_height = self.viewer.image().data.shape[1] src_image_max_size = max(src_image_width, src_image_height) pred = cv2.resize(pred, (src_image_max_size, src_image_max_size), cv2.INTER_LANCZOS4) pred = pred[0: src_image_width, 0: src_image_height] print('s1', self.viewer.image().data.shape) print('s2', pred.shape) self.tool_mask.data = np.zeros(self.viewer.image().data.shape, np.uint8) self.tool_mask.data[np.where((pred > 0.5))] = settings.TOOL_FOREGROUND self.viewer.update_scaled_combined_image()
[ "tensorflow.shape", "keras.backend.sum", "cv2.resize", "keras.models.load_model", "numpy.where", "tensorflow.count_nonzero", "tensorflow.multiply", "keras.backend.flatten", "numpy.zeros", "tensorflow.ones_like", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "tensorflow.reduce_mean", "nu...
[((384, 446), 'tensorflow.nn.sigmoid_cross_entropy_with_logits', 'tf.nn.sigmoid_cross_entropy_with_logits', ([], {'logits': 'pred', 'labels': 'y'}), '(logits=pred, labels=y)\n', (423, 446), True, 'import tensorflow as tf\n'), ((539, 564), 'tensorflow.cast', 'tf.cast', (['ones', 'tf.float32'], {}), '(ones, tf.float32)\n', (546, 564), True, 'import tensorflow as tf\n'), ((645, 678), 'tensorflow.multiply', 'tf.multiply', (['weight_map', 'loss_map'], {}), '(weight_map, loss_map)\n', (656, 678), True, 'import tensorflow as tf\n'), ((691, 715), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss_map'], {}), '(loss_map)\n', (705, 715), True, 'import tensorflow as tf\n'), ((777, 792), 'keras.backend.flatten', 'flatten', (['y_true'], {}), '(y_true)\n', (784, 792), False, 'from keras.backend import flatten, sum, sigmoid\n'), ((852, 876), 'keras.backend.sum', 'sum', (['(y_true_f * y_pred_f)'], {}), '(y_true_f * y_pred_f)\n', (855, 876), False, 'from keras.backend import flatten, sum, sigmoid\n'), ((459, 478), 'tensorflow.count_nonzero', 'tf.count_nonzero', (['y'], {}), '(y)\n', (475, 478), True, 'import tensorflow as tf\n'), ((816, 831), 'keras.backend.flatten', 'flatten', (['y_pred'], {}), '(y_pred)\n', (823, 831), False, 'from keras.backend import flatten, sum, sigmoid\n'), ((4545, 4587), 'numpy.zeros', 'np.zeros', (['(1, 64, 64, 1)'], {'dtype': 'np.float32'}), '((1, 64, 64, 1), dtype=np.float32)\n', (4553, 4587), True, 'import numpy as np\n'), ((5166, 5229), 'numpy.zeros', 'np.zeros', (['(src_image_width, src_image_height)'], {'dtype': 'np.float32'}), '((src_image_width, src_image_height), dtype=np.float32)\n', (5174, 5229), True, 'import numpy as np\n'), ((5878, 5933), 'numpy.pad', 'np.pad', (['image', '((0, row_pad), (0, col_pad))', '"""constant"""'], {}), "(image, ((0, row_pad), (0, col_pad)), 'constant')\n", (5884, 5933), True, 'import numpy as np\n'), ((5950, 5999), 'cv2.resize', 'cv2.resize', (['image', '(128, 128)', 'cv2.INTER_LANCZOS4'], {}), '(image, (128, 128), cv2.INTER_LANCZOS4)\n', (5960, 5999), False, 'import cv2\n'), ((6018, 6062), 'numpy.zeros', 'np.zeros', (['(1, 128, 128, 1)'], {'dtype': 'np.float32'}), '((1, 128, 128, 1), dtype=np.float32)\n', (6026, 6062), True, 'import numpy as np\n'), ((6703, 6781), 'cv2.resize', 'cv2.resize', (['pred', '(src_image_max_size, src_image_max_size)', 'cv2.INTER_LANCZOS4'], {}), '(pred, (src_image_max_size, src_image_max_size), cv2.INTER_LANCZOS4)\n', (6713, 6781), False, 'import cv2\n'), ((7389, 7444), 'numpy.pad', 'np.pad', (['image', '((0, row_pad), (0, col_pad))', '"""constant"""'], {}), "(image, ((0, row_pad), (0, col_pad)), 'constant')\n", (7395, 7444), True, 'import numpy as np\n'), ((7461, 7510), 'cv2.resize', 'cv2.resize', (['image', '(512, 512)', 'cv2.INTER_LANCZOS4'], {}), '(image, (512, 512), cv2.INTER_LANCZOS4)\n', (7471, 7510), False, 'import cv2\n'), ((7529, 7573), 'numpy.zeros', 'np.zeros', (['(1, 512, 512, 1)'], {'dtype': 'np.float32'}), '((1, 512, 512, 1), dtype=np.float32)\n', (7537, 7573), True, 'import numpy as np\n'), ((8214, 8292), 'cv2.resize', 'cv2.resize', (['pred', '(src_image_max_size, src_image_max_size)', 'cv2.INTER_LANCZOS4'], {}), '(pred, (src_image_max_size, src_image_max_size), cv2.INTER_LANCZOS4)\n', (8224, 8292), False, 'import cv2\n'), ((496, 526), 'tensorflow.shape', 'tf.shape', (['y'], {'out_type': 'tf.int64'}), '(y, out_type=tf.int64)\n', (504, 526), True, 'import tensorflow as tf\n'), ((1810, 2055), 'keras.models.load_model', 'keras.models.load_model', (['"""D:/Projects/Temp/ImReg/Dicoms/ConvertedMriConvert/BrainData/BrainModels/BrainModel_Loss017_NoOptimizer.h5"""'], {'custom_objects': "{'bce_dice_loss': bce_dice_loss, 'dice_coef_with_sigmoid':\n dice_coef_with_sigmoid}"}), "(\n 'D:/Projects/Temp/ImReg/Dicoms/ConvertedMriConvert/BrainData/BrainModels/BrainModel_Loss017_NoOptimizer.h5'\n , custom_objects={'bce_dice_loss': bce_dice_loss,\n 'dice_coef_with_sigmoid': dice_coef_with_sigmoid})\n", (1833, 2055), False, 'import keras\n'), ((5539, 5559), 'numpy.where', 'np.where', (['(pred > 0.5)'], {}), '(pred > 0.5)\n', (5547, 5559), True, 'import numpy as np\n'), ((7038, 7058), 'numpy.where', 'np.where', (['(pred > 0.5)'], {}), '(pred > 0.5)\n', (7046, 7058), True, 'import numpy as np\n'), ((8549, 8569), 'numpy.where', 'np.where', (['(pred > 0.5)'], {}), '(pred > 0.5)\n', (8557, 8569), True, 'import numpy as np\n'), ((601, 616), 'tensorflow.ones_like', 'tf.ones_like', (['y'], {}), '(y)\n', (613, 616), True, 'import tensorflow as tf\n'), ((920, 933), 'keras.backend.sum', 'sum', (['y_true_f'], {}), '(y_true_f)\n', (923, 933), False, 'from keras.backend import flatten, sum, sigmoid\n'), ((936, 949), 'keras.backend.sum', 'sum', (['y_pred_f'], {}), '(y_pred_f)\n', (939, 949), False, 'from keras.backend import flatten, sum, sigmoid\n')]
#!/usr/bin/python ############################################################################### # # ############################################################################### # # MODULES # #import Numeric,sys,os import numpy,sys,os #import Nio # for reading netCDF files import Ngl from diag_functions import * # import Scientific.IO.NetCDF # #---------- Get Arguments ------------------------------------------ if len(sys.argv) < 2: print("usage "+sys.argv[0]+": <file1> <file2> ... <fileN> <title>") sys.exit(1) else: title = sys.argv[len(sys.argv)-1] files={} for i in range(1,len(sys.argv)-1): files[i-1]=sys.argv[i] figname = title.replace(" ","_")+"_tracks" #---------- Setup Plotting ------------------------------------------ # # Open a workstation and specify a different color map. # wkres = Ngl.Resources() cmap = numpy.array([[1.,1.,1.],[0.,0.,0.], \ [0.2,0.8,1.],[0.4,1.,.8], \ [1.,1.,0.4],[1.,.7,0.2], \ [1.,0.5,0.],[1.,0.2,0.], \ [0.7,0.,0.]],'f') wkres.wkColorMap = cmap wks_type = "eps" wks = Ngl.open_wks(wks_type,figname,wkres) #---------- Get storm tracks ------------------------------------------ # set up plot resources = Ngl.Resources() resources.nglFrame = False resources.nglDraw = False resources.mpFillOn = True resources.mpLabelsOn = False resources.mpOutlineOn = True resources.mpLandFillColor = "grey" resources.mpOceanFillColor = "white" resources.mpGridAndLimbOn = False resources.vpXF = 0.05 resources.vpYF = 0.95 resources.vpWidthF = 0.95 resources.vpHeightF = 0.90 resources.tmXBTickStartF = -75 resources.tmXBTickEndF = -25 resources.tmYROn = True resources.tmXTOn = True resources.tmXBLabelFontHeightF = 0.022 resources.tmYLLabelFontHeightF = 0.022 resources.mpLimitMode = "LatLon" resources.mpMinLonF = -140 resources.mpMaxLonF = 20 resources.mpMinLatF = -5 resources.mpMaxLatF = 60 resources.mpProjection = "CylindricalEquidistant" # draw title txres = Ngl.Resources() txres.txFontHeightF = 0.025 txres.txFontColor = 1 txres.txFont = 22 Ngl.text_ndc(wks,title,0.52,0.98,txres) # draw legend yl=0.19 scale=0.75 shift=0.10 txres.txFontHeightF = 0.015 xleg = [0.07,0.19,0.31,0.43,0.56,0.69,0.82] xtxt = [0.12,0.24,0.36,0.49,0.61,0.74,0.87] for i in range(len(xleg)): xleg[i]=shift+scale*xleg[i] for i in range(len(xtxt)): xtxt[i]=shift+scale*xtxt[i] yleg = [yl,yl,yl,yl,yl,yl,yl] ytxt = [yl,yl,yl,yl,yl,yl,yl] labels = ["TD","TS","Cat1","Cat2","Cat3","Cat4","Cat5"] gxres = Ngl.Resources() gxres.gsMarkerIndex = 16 for i in range(0,7): gxres.gsMarkerColor = 2+i Ngl.polymarker_ndc(wks,0.05+xleg[i],-0.15+yleg[i],gxres) Ngl.text_ndc(wks,labels[i],0.05+xtxt[i],-0.15+ytxt[i],txres) # # Draw the trajectories. # pres = Ngl.Resources() # polyline resources pres.gsLineThicknessF = 2 # line thickness pres.gsLineColor = "grey" mres = Ngl.Resources() # marker resources mres.gsMarkerSizeF = .0015 # marker size mres.gsMarkerIndex = 16 # filled circle plots = [] for k in range(len(files)): #if k==0: resources.tiMainString = title mplot = Ngl.map(wks,resources) # Draw map. plots.append(mplot) # loop through trajectories for k in range(len(files)): [tracks]=read_trajectories(files[k]) for i in range(len(tracks)): nt = len(tracks[i][0]) for j in range(nt-1): x = tracks[i][0][j] y = tracks[i][1][j] w = tracks[i][2][j] p = tracks[i][3][j] x_pair = tracks[i][0][j:j+2] y_pair = tracks[i][1][j:j+2] if 10.0 <= w < 17.0: pres.gsLineColor = 2 if 17.0 <= w < 32.0: pres.gsLineColor = 3 if 32.0 <= w < 42.0: pres.gsLineColor = 4 if 42.0 <= w < 49.0: pres.gsLineColor = 5 if 49.0 <= w < 58.0: pres.gsLineColor = 6 if 58.0 <= w < 70.0: pres.gsLineColor = 7 if 70.0 <= w: pres.gsLineColor = 8 # draw polyline Ngl.add_polyline(wks,plots[k],x_pair,y_pair,pres) #Ngl.frame(wks) #del mplot panelres = Ngl.Resources() panelres.nglPanelYWhiteSpacePercent = 3 panelres.nglPanelXWhiteSpacePercent = 0 panelres.nglPanelTop = 0.95 panelres.nglPanelBottom = 0.08 panelres.nglPanelFigureStrings = ["A","B","C"] panelres.nglPanelFigureStringsJust = "BottomRight" panelres.nglPanelFigureStringsFontHeightF = 0.02 Ngl.panel(wks,plots,[len(files),1],panelres) Ngl.end()
[ "Ngl.Resources", "Ngl.end", "Ngl.open_wks", "Ngl.text_ndc", "Ngl.polymarker_ndc", "numpy.array", "sys.exit", "Ngl.map", "Ngl.add_polyline" ]
[((860, 875), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (873, 875), False, 'import Ngl\n'), ((883, 1064), 'numpy.array', 'numpy.array', (['[[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.2, 0.8, 1.0], [0.4, 1.0, 0.8], [1.0, \n 1.0, 0.4], [1.0, 0.7, 0.2], [1.0, 0.5, 0.0], [1.0, 0.2, 0.0], [0.7, 0.0,\n 0.0]]', '"""f"""'], {}), "([[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.2, 0.8, 1.0], [0.4, 1.0, \n 0.8], [1.0, 1.0, 0.4], [1.0, 0.7, 0.2], [1.0, 0.5, 0.0], [1.0, 0.2, 0.0\n ], [0.7, 0.0, 0.0]], 'f')\n", (894, 1064), False, 'import numpy, sys, os\n'), ((1092, 1130), 'Ngl.open_wks', 'Ngl.open_wks', (['wks_type', 'figname', 'wkres'], {}), '(wks_type, figname, wkres)\n', (1104, 1130), False, 'import Ngl\n'), ((1231, 1246), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (1244, 1246), False, 'import Ngl\n'), ((2010, 2025), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (2023, 2025), False, 'import Ngl\n'), ((2104, 2147), 'Ngl.text_ndc', 'Ngl.text_ndc', (['wks', 'title', '(0.52)', '(0.98)', 'txres'], {}), '(wks, title, 0.52, 0.98, txres)\n', (2116, 2147), False, 'import Ngl\n'), ((2550, 2565), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (2563, 2565), False, 'import Ngl\n'), ((2807, 2822), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (2820, 2822), False, 'import Ngl\n'), ((2942, 2957), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (2955, 2957), False, 'import Ngl\n'), ((4149, 4164), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (4162, 4164), False, 'import Ngl\n'), ((4498, 4507), 'Ngl.end', 'Ngl.end', ([], {}), '()\n', (4505, 4507), False, 'import Ngl\n'), ((529, 540), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (537, 540), False, 'import numpy, sys, os\n'), ((2647, 2710), 'Ngl.polymarker_ndc', 'Ngl.polymarker_ndc', (['wks', '(0.05 + xleg[i])', '(-0.15 + yleg[i])', 'gxres'], {}), '(wks, 0.05 + xleg[i], -0.15 + yleg[i], gxres)\n', (2665, 2710), False, 'import Ngl\n'), ((2708, 2776), 'Ngl.text_ndc', 'Ngl.text_ndc', (['wks', 'labels[i]', '(0.05 + xtxt[i])', '(-0.15 + ytxt[i])', 'txres'], {}), '(wks, labels[i], 0.05 + xtxt[i], -0.15 + ytxt[i], txres)\n', (2720, 2776), False, 'import Ngl\n'), ((3188, 3211), 'Ngl.map', 'Ngl.map', (['wks', 'resources'], {}), '(wks, resources)\n', (3195, 3211), False, 'import Ngl\n'), ((4052, 4105), 'Ngl.add_polyline', 'Ngl.add_polyline', (['wks', 'plots[k]', 'x_pair', 'y_pair', 'pres'], {}), '(wks, plots[k], x_pair, y_pair, pres)\n', (4068, 4105), False, 'import Ngl\n')]
from keras.datasets import mnist import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import decomposition np.random.seed(5) # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') # x_train /= 255 # x_test /= 255 print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # X = np.concatenate((x_train, x_test), axis=0) plt.cla() pca = decomposition.PCA(n_components=200) pca.fit(X) X = pca.transform(X) print (X.shape)
[ "sklearn.decomposition.PCA", "matplotlib.pyplot.cla", "numpy.random.seed", "keras.datasets.mnist.load_data" ]
[((162, 179), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (176, 179), True, 'import numpy as np\n'), ((279, 296), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (294, 296), False, 'from keras.datasets import mnist\n'), ((605, 614), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (612, 614), True, 'import matplotlib.pyplot as plt\n'), ((621, 656), 'sklearn.decomposition.PCA', 'decomposition.PCA', ([], {'n_components': '(200)'}), '(n_components=200)\n', (638, 656), False, 'from sklearn import decomposition\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests/Examples for dThetaXZ TODO ==== """ # Fix Python 2.x try: input = raw_input except NameError: pass import os, sys import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec from sloth.inst.dthetaxz import ( dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats, ) from sloth.inst.dthetaxz_plot import plotEffScatt, plotScanThetaFile #: TESTS def test009(): """effective scattering figure (updt: 2014-08-15)""" mxx1, mzz1 = getMeshMasked( mask="circular", r1p=500.0, cryst_x=50.0, cryst_z=50.0, csteps=500j ) wrc = 1.25e-4 cases = ["Jn", "Js", "SphJn", "TorJs"] casesLabs = ["1. Johann", "2. Johansson", "3. Spherical Jn", "4. Toroidal Js"] angles = [35, 55, 75] plotEffScatt( mxx1, mzz1, wrc=wrc, cases=cases, angles=angles, nlevels=30, plotMask=True, absWrc=False, casesLabels=casesLabs, xyFigSize=(8 * 150, 4.3 * 150), figName="test009", ) def test009b(): """effective scattering figure (updt: 2014-08-21)""" mxx1, mzz1 = getMeshMasked( mask="circular", r1p=500.0, cryst_x=50.0, cryst_z=50.0, csteps=500j ) wrc = 1.25e-4 cases = ["Jn", "Js", "SphJn", "TorJs", "JsFocus"] casesLabs = [ "1. Johann", "2. Johansson", "3. Spherical Jn", "4. Toroidal Js", "5. Gen. Js focus", ] angles = [35, 55, 75] plotEffScatt( mxx1, mzz1, wrc=wrc, cases=cases, casesLabels=casesLabs, angles=angles, nlevels=30, plotMask=True, absWrc=False, xyFigSize=(8.3 * 150, 3.7 * 150), figName="test009b", fontSize=9, colSpan=2, xyTicks=0.1, ) def test009c(retDats=False, showPlot=True): """effective scattering figure (updt: 2014-09-03)""" mxx1, mzz1 = getMeshMasked( mask="circular", r1p=500.0, cryst_x=50.0, cryst_z=50.0, csteps=500j ) wrc = 1.25e-4 cases = ["Jn", "Js", "SphJn", "TorJs", "JsFocus"] casesLabs = [ "1. Johann", "2. Johansson", "3. Spherical Jn", "4. Toroidal Js", "5. Gen. Js focus", ] angles = [15, 45, 75] if showPlot: plotEffScatt( mxx1, mzz1, wrc=wrc, cases=cases, casesLabels=casesLabs, angles=angles, nlevels=30, plotMask=True, absWrc=False, xyFigSize=(8.3 * 150, 3.7 * 150), figName="test009c", fontSize=9, colSpan=2, xyTicks=0.1, ) if retDats: return getDthetaDats(mxx1, mzz1, wrc=wrc, cases=cases, angles=angles) def test009d(): """effective scattering figure (updt: 2015-02-12) """ wrc = 1.25e-4 cases = ["SphJn", "Js", "TorJs"] casesLabs = ["1. Spherical", "2. Johansson", "3. Toroidal Js"] angles = [35, 55, 75] rd = 500.0 # bending radius msks = ["circular", "rectangular"] mxx1, mzz1 = getMeshMasked( mask=msks[0], r1p=rd, cryst_x=50.0, cryst_z=50.0, csteps=500j ) mxx2, mzz2 = getMeshMasked( mask=msks[1], r1p=rd, cryst_x=50.0, cryst_z=12.5, csteps=500j ) mzz3, mxx3 = getMeshMasked( mask=msks[1], r1p=rd, cryst_x=50.0, cryst_z=17.5, csteps=500j ) mxx4, mzz4 = getMeshMasked( mask=msks[1], r1p=rd, cryst_x=50.0, cryst_z=25.0, csteps=500j ) # all circular plotEffScatt( mxx1, mzz1, wrc=wrc, cases=cases, casesLabels=casesLabs, angles=angles, xlabel=r"x, sag. (R$_{1}^{\prime}$)", ylabel=r"z, mer. (R$_{1}^{\prime}$)", nlevels=30, xyFigHalfRange=0.1, plotMask=True, plotVert=True, absWrc=False, xyFigSize=(6.0 * 150, 4.0 * 150), xylab=(0.04, 0.96), figName="{0}mm.{1}".format(int(rd), msks[0]), fontSize=9, colSpan=2, xyTicks=0.1, ) # js rect lmxx = [mxx1, mxx2, mxx1] lmzz = [mzz1, mzz2, mzz1] plotEffScatt( lmxx, lmzz, wrc=wrc, cases=cases, casesLabels=casesLabs, angles=angles, xlabel=r"x, sag. (R$_{1}^{\prime}$)", ylabel=r"z, mer. (R$_{1}^{\prime}$)", nlevels=30, xyFigHalfRange=0.1, plotMask=True, plotVert=True, absWrc=False, xyFigSize=(6.0 * 150, 4.0 * 150), xylab=(0.04, 0.96), figName="{0}mm.{1}".format(int(rd), msks[1]), fontSize=9, colSpan=2, xyTicks=0.1, ) input("Press ENTER to close figures") def test010(): """multiple effective scattering figures (updt: 2014-06-29)""" for rd in [1000.0, 500.0]: for msk, cx, cz in zip(["circular", "rectangular"], [50.0, 40.0], [50.0, 12.5]): mxx1, mzz1 = getMeshMasked( mask=msk, r1p=rd, cryst_x=cx, cryst_z=cz, csteps=500j ) plotEffScatt( mxx1, mzz1, wrc=1e-4, cases=["Johansson", "Spherical Jn", "Spherical Js", "Toroidal Js"], angles=[35, 55, 75], nlevels=30, plotMask=True, absWrc=False, figName="{0}mm.{1}".format(int(rd), msk), xyFigHalfRange=0.1, xyFigSize=(8 * 150, 4.3 * 150), ) def plotDats011(_d): """buggy""" fig = plt.figure(num="plotDats011", figsize=(5, 5), dpi=150) gs = gridspec.GridSpec(1, 2) for ird, rd in enumerate(_d["rds"]): gsplt = plt.subplot(gs[ird]) for msk in _d["msks"]: if msk == "circular": _ls = "-" _mk = None # _mk = 'o' _ms = 2 mC = 1.0 else: _ls = "--" mC = 3.0 _mk = None _ms = 2 lab = "{0}mm.{1}".format(int(rd), msk) for cs, cl in zip(_d["cases"], _d["colors"]): gsplt.plot( _d[lab][cs]["thetaB"], np.array(_d[lab][cs]["sa"]) * mC, lw=2, color=cl, ls=_ls, marker=_mk, ms=_ms, label=r"{0} $\times$ {1} {2}".format(int(mC), msk[:4], cs), ) gsplt.set_ylim(0.0, 0.05) gsplt.set_xlabel(r"Bragg angle $\theta_B$ (deg)") gsplt.set_ylabel(r"Effective solid angle (sr)") gsplt.set_title(r"Rect vs Circ at {0} mm bending".format(int(rd))) gsplt.legend(loc="best") plt.tight_layout() plt.show() return fig def test011(retDats=True, plotDats=False): """angular study for analyser shapes: circular 50^2 vs rectangular 80x25""" _d = {} # container _d["rds"] = [1000.0, 500.0] # _d['cases'] = ['Johansson', 'Spherical Jn', 'Toroidal Js', 'Spherical Js', 'Js 45 deg focusing', 'Berreman'] # _d['cases'] = ['Johansson', 'Spherical Jn', 'Toroidal Js'] _d["colors"] = ["blue", "green", "red", "orange"] _d["angles"] = np.linspace(15, 85, 29) _d["msks"] = ["circular", "rectangular"] _d["cxs"] = [50.0, 40.0] _d["czs"] = [50.0, 12.5] _d["csteps"] = 500j _d["wrc"] = 1.25e-4 for rd in _d["rds"]: for msk, cx, cz in zip(_d["msks"], _d["cxs"], _d["czs"]): mxx, mzz = getMeshMasked( mask=msk, r1p=rd, cryst_x=cx, cryst_z=cz, csteps=_d["csteps"] ) lab = "{0}mm.{1}".format(int(rd), msk) print("{0}:".format(lab)) _d["label"] = lab _d[lab] = getDthetaDats( mxx, mzz, wrc=_d["wrc"], cases=_d["cases"], angles=_d["angles"] ) # if plotDats: fig011 = plotDats011(_d) if retDats: return _d def plotDats012(_d): """buggy""" fig = plt.figure(num="plotDats012", figsize=(5, 5), dpi=150) # gs = gridspec.GridSpec(1,2) gs = [] gs.append(fig.add_subplot(211)) gs.append(fig.add_subplot(212)) cs = _d["cases"] _ls = 2 # line size _mk = None # marker style _ms = 5 # marker size for ird, rd in enumerate(_d["rds"]): gsplt = plt.subplot(gs[ird]) for cz, cl in zip(_d["czs"], _d["colors"]): lab = "{0}mm/{1}".format(int(rd), cz) gsplt.plot( _d[lab][cs]["thetaB"], _d[lab][cs]["eres"], lw=2, color=cl, ls=_ls, marker=_mk, ms=_ms, label=r"{0}mm".format(cz * 2), ) # gsplt.set_ylim(0.,0.05) gsplt.set_xlabel(r"Bragg angle $\theta_B$ (deg)") gsplt.set_ylabel(r"Energy resolution $\frac{\Delta E}{E}$") gsplt.set_title(r"Js 80 mm height at {0} mm bending".format(int(rd))) gsplt.legend(loc="best") plt.tight_layout() plt.show() return fig def test012(retDats=True): """ js energy resolution vs rectangular crystal size width """ d = {} # container d["fname"] = "dth_test012.spec" d["rds"] = [1000.0, 500.0] d["cases"] = ["Js"] d["angles"] = np.linspace(35, 85, 21) d["msks"] = "rectangular" d["cxs"] = 40.0 d["czs"] = [2.5, 5.0, 7.5, 10.0, 12.5, 15.0] d["csteps"] = 500j d["wrc"] = 1.25e-4 for rd in d["rds"]: # rectangular Js for cz in d["czs"]: mxx, mzz = getMeshMasked( mask=d["msks"], r1p=rd, cryst_x=d["cxs"], cryst_z=cz, csteps=d["csteps"] ) lab = "{0}/{1}mm/{2}".format(d["cases"][0], int(rd), cz * 2) motpos = [ mapCase2Num(d["cases"][0]), rd, d["msks"], d["cxs"], cz, d["wrc"], d["csteps"], ] print("{0}:".format(lab)) d[lab] = getDthetaDats( mxx, mzz, wrc=d["wrc"], cases=d["cases"], angles=d["angles"] ) writeScanDats(d[lab], d["fname"], scanLabel=lab, motpos=motpos) # Spherical plate, Wittry and General point focus 80x50 mm^2 for comparison for case in ["SphJn", "TorJs", "JsFocus"]: cz = 25.0 mxx, mzz = getMeshMasked( mask=d["msks"], r1p=rd, cryst_x=d["cxs"], cryst_z=cz, csteps=d["csteps"] ) lab = "{0}/{1}mm/{2}".format(case, int(rd), cz * 2) motpos = [ mapCase2Num(case), rd, d["msks"], d["cxs"], cz, d["wrc"], d["csteps"], ] print("{0}:".format(lab)) d[lab] = getDthetaDats( mxx, mzz, wrc=d["wrc"], cases=[case], angles=d["angles"] ) writeScanDats(d[lab], d["fname"], scanLabel=lab, motpos=motpos) # if retDats: return d def test013(retDats=True): """energy resolution""" d = {} # container d["fname"] = "dth_test013.spec" d["rds"] = [1000.0, 500.0] d["cases"] = ["Js", "SphJn", "TorJs", "JsFocus"] d["angles"] = np.linspace(35, 85, 21) d["cxs"] = 50.0 d["csteps"] = 500j d["wrc"] = 2e-4 for rd in d["rds"]: for case in d["cases"]: if case == "Js": # for Js need to use an optimized mask in z d["msks"] = "rectangular" d["czs"] = 12.5 else: d["msks"] = "circular" d["czs"] = 50.0 mxx, mzz = getMeshMasked( mask=d["msks"], r1p=rd, cryst_x=d["cxs"], cryst_z=d["czs"], csteps=d["csteps"], ) lab = "{0}/{1}mm/{2}{3}".format( case, int(rd), d["msks"][:4], int(d["czs"] * 2) ) motpos = [ mapCase2Num(case), rd, d["msks"], d["cxs"], d["czs"], d["wrc"], d["csteps"], ] print("{0}:".format(lab)) d[lab] = getDthetaDats( mxx, mzz, wrc=d["wrc"], cases=[case], angles=d["angles"] ) writeScanDats(d[lab], d["fname"], scanLabel=lab, motpos=motpos) # if retDats: return d if __name__ == "__main__": # pass ### TESTS ### # uncomment at your convenience # utils # from genericutils import ipythonAutoreload, getPyMcaMain # ipythonAutoreload() # m = getPyMcaMain() # mxx1, mzz1 = test009(retDats=True) # test009() # d = test011(retDats=True, plotDats=False) # d = test012(retDats=True) # plotScanThetaFile('dth_test012.spec', str2rng('5, 7, 8, 13, 15, 16'), signal='eres', plotDeeShells=True, figName='fig1', showLegend=True) # plotScanThetaFile('dth_test012.spec', str2rng('5, 7, 8, 13, 15, 16'), signal='eres', plotDeeShells=True, figName='figEres', showLegend=True, xlims=(34,86), ylims=(9E-6, 1.1E-2), figSize=(3.5,6)) # plotScanThetaFile('dth_test012.spec', str2rng('5, 7, 8, 13, 15, 16'), signal='sa', plotDeeShells=False, figName='figSA', showLegend=False, xlims=(34,86), ylims=None, figSize=(4.5,6), ylog=False, yscale=1) # plotScanThetaFile('dth_test013.spec', str2rng('1:8'), signal='eres', plotDeeShells=True, figName='figEres', showLegend=True, xlims=(34,86), ylims=(9E-6, 1.1E-2), figSize=(4.5,6), ylog=True, yscale=1) # plotScanThetaFile('dth_test013.spec', str2rng('1:8'), signal='eres', plotDeeShells=True, figName='figEres', showLegend=True, xlims=(34,86), ylims=(9E-6, 1.1E-2), figSize=(3,4), ylog=True, yscale=1) # # mxx1, mzz1 = test009c(retDats=True, showPlot=False) test009d()
[ "sloth.inst.dthetaxz.mapCase2Num", "sloth.inst.dthetaxz.getDthetaDats", "matplotlib.pyplot.subplot", "numpy.array", "sloth.inst.dthetaxz.getMeshMasked", "matplotlib.pyplot.figure", "matplotlib.gridspec.GridSpec", "numpy.linspace", "matplotlib.pyplot.tight_layout", "sloth.inst.dthetaxz.writeScanDat...
[((576, 664), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': '"""circular"""', 'r1p': '(500.0)', 'cryst_x': '(50.0)', 'cryst_z': '(50.0)', 'csteps': '(500.0j)'}), "(mask='circular', r1p=500.0, cryst_x=50.0, cryst_z=50.0,\n csteps=500.0j)\n", (589, 664), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((847, 1031), 'sloth.inst.dthetaxz_plot.plotEffScatt', 'plotEffScatt', (['mxx1', 'mzz1'], {'wrc': 'wrc', 'cases': 'cases', 'angles': 'angles', 'nlevels': '(30)', 'plotMask': '(True)', 'absWrc': '(False)', 'casesLabels': 'casesLabs', 'xyFigSize': '(8 * 150, 4.3 * 150)', 'figName': '"""test009"""'}), "(mxx1, mzz1, wrc=wrc, cases=cases, angles=angles, nlevels=30,\n plotMask=True, absWrc=False, casesLabels=casesLabs, xyFigSize=(8 * 150,\n 4.3 * 150), figName='test009')\n", (859, 1031), False, 'from sloth.inst.dthetaxz_plot import plotEffScatt, plotScanThetaFile\n'), ((1211, 1299), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': '"""circular"""', 'r1p': '(500.0)', 'cryst_x': '(50.0)', 'cryst_z': '(50.0)', 'csteps': '(500.0j)'}), "(mask='circular', r1p=500.0, cryst_x=50.0, cryst_z=50.0,\n csteps=500.0j)\n", (1224, 1299), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((1560, 1783), 'sloth.inst.dthetaxz_plot.plotEffScatt', 'plotEffScatt', (['mxx1', 'mzz1'], {'wrc': 'wrc', 'cases': 'cases', 'casesLabels': 'casesLabs', 'angles': 'angles', 'nlevels': '(30)', 'plotMask': '(True)', 'absWrc': '(False)', 'xyFigSize': '(8.3 * 150, 3.7 * 150)', 'figName': '"""test009b"""', 'fontSize': '(9)', 'colSpan': '(2)', 'xyTicks': '(0.1)'}), "(mxx1, mzz1, wrc=wrc, cases=cases, casesLabels=casesLabs,\n angles=angles, nlevels=30, plotMask=True, absWrc=False, xyFigSize=(8.3 *\n 150, 3.7 * 150), figName='test009b', fontSize=9, colSpan=2, xyTicks=0.1)\n", (1572, 1783), False, 'from sloth.inst.dthetaxz_plot import plotEffScatt, plotScanThetaFile\n'), ((2015, 2103), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': '"""circular"""', 'r1p': '(500.0)', 'cryst_x': '(50.0)', 'cryst_z': '(50.0)', 'csteps': '(500.0j)'}), "(mask='circular', r1p=500.0, cryst_x=50.0, cryst_z=50.0,\n csteps=500.0j)\n", (2028, 2103), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((3187, 3265), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': 'msks[0]', 'r1p': 'rd', 'cryst_x': '(50.0)', 'cryst_z': '(50.0)', 'csteps': '(500.0j)'}), '(mask=msks[0], r1p=rd, cryst_x=50.0, cryst_z=50.0, csteps=500.0j)\n', (3200, 3265), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((3295, 3373), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': 'msks[1]', 'r1p': 'rd', 'cryst_x': '(50.0)', 'cryst_z': '(12.5)', 'csteps': '(500.0j)'}), '(mask=msks[1], r1p=rd, cryst_x=50.0, cryst_z=12.5, csteps=500.0j)\n', (3308, 3373), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((3403, 3481), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': 'msks[1]', 'r1p': 'rd', 'cryst_x': '(50.0)', 'cryst_z': '(17.5)', 'csteps': '(500.0j)'}), '(mask=msks[1], r1p=rd, cryst_x=50.0, cryst_z=17.5, csteps=500.0j)\n', (3416, 3481), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((3511, 3589), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': 'msks[1]', 'r1p': 'rd', 'cryst_x': '(50.0)', 'cryst_z': '(25.0)', 'csteps': '(500.0j)'}), '(mask=msks[1], r1p=rd, cryst_x=50.0, cryst_z=25.0, csteps=500.0j)\n', (3524, 3589), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((5651, 5705), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '"""plotDats011"""', 'figsize': '(5, 5)', 'dpi': '(150)'}), "(num='plotDats011', figsize=(5, 5), dpi=150)\n", (5661, 5705), True, 'import matplotlib.pyplot as plt\n'), ((5715, 5738), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(2)'], {}), '(1, 2)\n', (5732, 5738), False, 'from matplotlib import gridspec\n'), ((6869, 6887), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6885, 6887), True, 'import matplotlib.pyplot as plt\n'), ((6892, 6902), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6900, 6902), True, 'import matplotlib.pyplot as plt\n'), ((7353, 7376), 'numpy.linspace', 'np.linspace', (['(15)', '(85)', '(29)'], {}), '(15, 85, 29)\n', (7364, 7376), True, 'import numpy as np\n'), ((8138, 8192), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '"""plotDats012"""', 'figsize': '(5, 5)', 'dpi': '(150)'}), "(num='plotDats012', figsize=(5, 5), dpi=150)\n", (8148, 8192), True, 'import matplotlib.pyplot as plt\n'), ((9155, 9173), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9171, 9173), True, 'import matplotlib.pyplot as plt\n'), ((9178, 9188), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9186, 9188), True, 'import matplotlib.pyplot as plt\n'), ((9433, 9456), 'numpy.linspace', 'np.linspace', (['(35)', '(85)', '(21)'], {}), '(35, 85, 21)\n', (9444, 9456), True, 'import numpy as np\n'), ((11440, 11463), 'numpy.linspace', 'np.linspace', (['(35)', '(85)', '(21)'], {}), '(35, 85, 21)\n', (11451, 11463), True, 'import numpy as np\n'), ((2385, 2608), 'sloth.inst.dthetaxz_plot.plotEffScatt', 'plotEffScatt', (['mxx1', 'mzz1'], {'wrc': 'wrc', 'cases': 'cases', 'casesLabels': 'casesLabs', 'angles': 'angles', 'nlevels': '(30)', 'plotMask': '(True)', 'absWrc': '(False)', 'xyFigSize': '(8.3 * 150, 3.7 * 150)', 'figName': '"""test009c"""', 'fontSize': '(9)', 'colSpan': '(2)', 'xyTicks': '(0.1)'}), "(mxx1, mzz1, wrc=wrc, cases=cases, casesLabels=casesLabs,\n angles=angles, nlevels=30, plotMask=True, absWrc=False, xyFigSize=(8.3 *\n 150, 3.7 * 150), figName='test009c', fontSize=9, colSpan=2, xyTicks=0.1)\n", (2397, 2608), False, 'from sloth.inst.dthetaxz_plot import plotEffScatt, plotScanThetaFile\n'), ((2811, 2873), 'sloth.inst.dthetaxz.getDthetaDats', 'getDthetaDats', (['mxx1', 'mzz1'], {'wrc': 'wrc', 'cases': 'cases', 'angles': 'angles'}), '(mxx1, mzz1, wrc=wrc, cases=cases, angles=angles)\n', (2824, 2873), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((5796, 5816), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[ird]'], {}), '(gs[ird])\n', (5807, 5816), True, 'import matplotlib.pyplot as plt\n'), ((8472, 8492), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[ird]'], {}), '(gs[ird])\n', (8483, 8492), True, 'import matplotlib.pyplot as plt\n'), ((5041, 5111), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': 'msk', 'r1p': 'rd', 'cryst_x': 'cx', 'cryst_z': 'cz', 'csteps': '(500.0j)'}), '(mask=msk, r1p=rd, cryst_x=cx, cryst_z=cz, csteps=500.0j)\n', (5054, 5111), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((7642, 7718), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': 'msk', 'r1p': 'rd', 'cryst_x': 'cx', 'cryst_z': 'cz', 'csteps': "_d['csteps']"}), "(mask=msk, r1p=rd, cryst_x=cx, cryst_z=cz, csteps=_d['csteps'])\n", (7655, 7718), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((7890, 7968), 'sloth.inst.dthetaxz.getDthetaDats', 'getDthetaDats', (['mxx', 'mzz'], {'wrc': "_d['wrc']", 'cases': "_d['cases']", 'angles': "_d['angles']"}), "(mxx, mzz, wrc=_d['wrc'], cases=_d['cases'], angles=_d['angles'])\n", (7903, 7968), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((9702, 9794), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': "d['msks']", 'r1p': 'rd', 'cryst_x': "d['cxs']", 'cryst_z': 'cz', 'csteps': "d['csteps']"}), "(mask=d['msks'], r1p=rd, cryst_x=d['cxs'], cryst_z=cz, csteps=\n d['csteps'])\n", (9715, 9794), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((10181, 10256), 'sloth.inst.dthetaxz.getDthetaDats', 'getDthetaDats', (['mxx', 'mzz'], {'wrc': "d['wrc']", 'cases': "d['cases']", 'angles': "d['angles']"}), "(mxx, mzz, wrc=d['wrc'], cases=d['cases'], angles=d['angles'])\n", (10194, 10256), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((10299, 10362), 'sloth.inst.dthetaxz.writeScanDats', 'writeScanDats', (['d[lab]', "d['fname']"], {'scanLabel': 'lab', 'motpos': 'motpos'}), "(d[lab], d['fname'], scanLabel=lab, motpos=motpos)\n", (10312, 10362), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((10543, 10635), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': "d['msks']", 'r1p': 'rd', 'cryst_x': "d['cxs']", 'cryst_z': 'cz', 'csteps': "d['csteps']"}), "(mask=d['msks'], r1p=rd, cryst_x=d['cxs'], cryst_z=cz, csteps=\n d['csteps'])\n", (10556, 10635), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((11004, 11075), 'sloth.inst.dthetaxz.getDthetaDats', 'getDthetaDats', (['mxx', 'mzz'], {'wrc': "d['wrc']", 'cases': '[case]', 'angles': "d['angles']"}), "(mxx, mzz, wrc=d['wrc'], cases=[case], angles=d['angles'])\n", (11017, 11075), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((11118, 11181), 'sloth.inst.dthetaxz.writeScanDats', 'writeScanDats', (['d[lab]', "d['fname']"], {'scanLabel': 'lab', 'motpos': 'motpos'}), "(d[lab], d['fname'], scanLabel=lab, motpos=motpos)\n", (11131, 11181), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((11858, 11955), 'sloth.inst.dthetaxz.getMeshMasked', 'getMeshMasked', ([], {'mask': "d['msks']", 'r1p': 'rd', 'cryst_x': "d['cxs']", 'cryst_z': "d['czs']", 'csteps': "d['csteps']"}), "(mask=d['msks'], r1p=rd, cryst_x=d['cxs'], cryst_z=d['czs'],\n csteps=d['csteps'])\n", (11871, 11955), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((12455, 12526), 'sloth.inst.dthetaxz.getDthetaDats', 'getDthetaDats', (['mxx', 'mzz'], {'wrc': "d['wrc']", 'cases': '[case]', 'angles': "d['angles']"}), "(mxx, mzz, wrc=d['wrc'], cases=[case], angles=d['angles'])\n", (12468, 12526), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((12569, 12632), 'sloth.inst.dthetaxz.writeScanDats', 'writeScanDats', (['d[lab]', "d['fname']"], {'scanLabel': 'lab', 'motpos': 'motpos'}), "(d[lab], d['fname'], scanLabel=lab, motpos=motpos)\n", (12582, 12632), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((9932, 9958), 'sloth.inst.dthetaxz.mapCase2Num', 'mapCase2Num', (["d['cases'][0]"], {}), "(d['cases'][0])\n", (9943, 9958), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((10764, 10781), 'sloth.inst.dthetaxz.mapCase2Num', 'mapCase2Num', (['case'], {}), '(case)\n', (10775, 10781), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((12209, 12226), 'sloth.inst.dthetaxz.mapCase2Num', 'mapCase2Num', (['case'], {}), '(case)\n', (12220, 12226), False, 'from sloth.inst.dthetaxz import dThetaXZ, mapCase2Num, mapNum2Case, getMeshMasked, getDthetaDats, writeScanDats\n'), ((6333, 6360), 'numpy.array', 'np.array', (["_d[lab][cs]['sa']"], {}), "(_d[lab][cs]['sa'])\n", (6341, 6360), True, 'import numpy as np\n')]
import argparse import rospy import math import csv import sys import matplotlib.pyplot as plt import numpy as np kNumTrajectoriesParamName = "waypoint_consistency_num_trajectories" kTrajectorySpecificPrefix = "trajectory_" kWaypointToNodeIdParamNameSuffix = "waypoint_to_node_id_file" kTrajectoryOutputSuffix = "trajectory_output_file" kNumComparisonApproachesParamName = "num_comparison_approaches" kComparisonApproachLabelSuffix = "approach_label" kComparisonApproachSpecificPrefix="comparison_approach_" kMaxXAxisBoundsMultiplier = 1.2 def readTrajectoryFromFile(file_name): with open(file_name, newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') firstRow = True trajectory = [] for row in spamreader: if (firstRow): firstRow = False continue pos = [float(row[1]), float(row[2])] angle = float(row[3]) pose = [pos, angle] trajectory.append(pose) return trajectory def readNodeAndWaypointPairingsFromFile(file_name): with open(file_name, newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') firstRow = True waypointNodeIdPairs = [] for row in spamreader: if (firstRow): firstRow = False continue waypoint = int(row[0]) node = int(row[1]) entry = [waypoint, node] waypointNodeIdPairs.append(entry) return waypointNodeIdPairs def constructTrajectorySpecificParamName(param_prefix, trajectory_num, param_suffix): return param_prefix + kTrajectorySpecificPrefix + str(trajectory_num) + "/" + param_suffix def angleDiff(angle0, angle1): s = math.sin(angle0 - angle1) c = math.cos(angle0 - angle1) return math.atan2(s, c) def angleDist(angle0, angle1): return abs(angleDiff(angle0, angle1)) def computeNorm(point1, point2): xDiff = point1[0] - point2[0] yDiff = point1[1] - point2[1] return math.sqrt((xDiff ** 2) + (yDiff ** 2)) def computePosDiff(point1, point2): xDiff = point1[0] - point2[0] yDiff = point1[1] - point2[1] return [xDiff, yDiff] def findMeanRotation(waypoint_poses): mean_unit_vector = [0, 0] for pose in waypoint_poses: mean_unit_vector[0] = mean_unit_vector[0] + math.cos(pose[1]) mean_unit_vector[1] = mean_unit_vector[1] + math.sin(pose[1]) mean_unit_vector[0] = mean_unit_vector[0] / len(waypoint_poses) mean_unit_vector[1] = mean_unit_vector[1] / len(waypoint_poses) return math.atan2(mean_unit_vector[1], mean_unit_vector[0]) def parseArgs(): parser = argparse.ArgumentParser(description='Plot results.') # parser.add_argument('param_prefix', required=False, default="", help='Parameter/node prefix') parser.add_argument('--param_prefix', default="") args = parser.parse_args() return args def plotPosOffsetsForWaypoints(waypoints, posOffsetLists, maxDeviation): # plt.figure(1) fig, axs = plt.subplots(4, 8, sharex=True, sharey=True) for waypoint in waypoints: plt_x = (waypoint -1 ) % 4 plt_y = int((waypoint -1 ) / 4) x = [] y = [] for posOffset in posOffsetLists[waypoint]: x.append(posOffset[0]) y.append(posOffset[1]) axs[plt_x, plt_y].scatter(x, y) axs[plt_x, plt_y].set_xlim([-1.1 * maxDeviation, 1.1 * maxDeviation]) axs[plt_x, plt_y].set_ylim([-1.1 * maxDeviation, 1.1 * maxDeviation]) axs[plt_x, plt_y].set_title("Waypoint " + str(waypoint)) plt.show(block=False) def plotPosOffsetForWaypoint(waypoint, posOffsets, maxDeviation): plt.figure(3) x = [] y = [] for posOffset in posOffsets: x.append(posOffset[0]) y.append(posOffset[1]) plt.scatter(x, y) plt.xlim([-1.1 * maxDeviation, 1.1 * maxDeviation]) plt.ylim([-1.1 * maxDeviation, 1.1 * maxDeviation]) plt.title("Waypoint " + str(waypoint)) plt.show() def plotAngleOffsetsForWaypoints(waypoints, angleOffsetLists): # plt.figure(2) fig, axs = plt.subplots(4, 8, sharex=True, sharey=True) for waypoint in waypoints: plt_x = (waypoint -1 ) % 4 plt_y = int((waypoint -1 ) / 4) axs[plt_x, plt_y].hist(angleOffsetLists[waypoint]) # axs[plt_x, plt_y].set_xlim([-1.1 * maxDeviation, 1.1 * maxDeviation]) # axs[plt_x, plt_y].set_ylim([-1.1 * maxDeviation, 1.1 * maxDeviation]) axs[plt_x, plt_y].set_title("Waypoint " + str(waypoint)) # plt.show(block=False) plt.show() def plotAngleOffsetForWaypoint(waypoint, angleOffsets): plt.figure(4) x = [] y = [] plt.hist(angleOffsets) # plt.scatter(x, y) # plt.xlim([-1.1 * maxDeviation, 1.1 * maxDeviation]) # plt.ylim([-1.1 * maxDeviation, 1.1 * maxDeviation]) plt.title("Waypoint " + str(waypoint)) plt.show() def getCDFData(dataset, num_bins): # getting data of the histogram count, bins_count = np.histogram(dataset, bins=num_bins) # finding the PDF of the histogram using count values pdf = count / sum(count) # using numpy np.cumsum to calculate the CDF # We can also find using the PDF values by looping and adding cdf = np.cumsum(pdf) cdf = np.insert(cdf, 0, 0) max_val = np.amax(dataset) return (cdf, bins_count, max_val) def plotCDF(dataset_primary_approach, dataset_comparison_approaches, title, x_label, fig_num, bins=40): plt.figure(fig_num) comparison_approach_summary_max = 0 alternate_line_styles=['dotted', 'dashdot', 'dashed'] alternate_line_style_index = 0 # getting data of the histogram for comparison_label, comparison_dataset in dataset_comparison_approaches.items(): approach_cdf, bins_count, comparison_approach_max = getCDFData(comparison_dataset, bins) comparison_approach_summary_max = max(comparison_approach_max, comparison_approach_summary_max) plt.plot(bins_count, approach_cdf, linestyle=alternate_line_styles[alternate_line_style_index], label=comparison_label) alternate_line_style_index += 1 primary_approach_cdf, bins_count, primary_approach_max = getCDFData(dataset_primary_approach, bins) # linestyle or ls [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) | '-' | '--' | '-.' | ':' | 'None' | ' ' | ''] plt.plot(bins_count, primary_approach_cdf, linestyle='solid', label="POM-Localization") if (len(dataset_comparison_approaches) != 0): # if (primary_approach_max > comparison_approach_summary_max): x_lim = primary_approach_max # else: # x_lim = min(primary_approach_max * kMaxXAxisBoundsMultiplier, comparison_approach_summary_max) plt.xlim(0, x_lim) plt.legend() plt.ylim(0, 1) plt.title(title) plt.xlabel(x_label) plt.ylabel("Proportion of data") # plt.show() def getDeviationsFromCentroid(poses_by_waypoint): # For each waypoint, get centroid and find distance of each pose for the waypoint from the centroid deviations_from_centroid = [] for waypoint, poses_for_curr_waypoint in poses_by_waypoint.items(): if (len(poses_for_curr_waypoint) <= 1): continue transl_centroid = [0, 0] for pose_for_waypoint in poses_for_curr_waypoint: transl_centroid[0] = transl_centroid[0] + pose_for_waypoint[0][0] transl_centroid[1] = transl_centroid[1] + pose_for_waypoint[0][1] transl_centroid[0] = transl_centroid[0] / len(poses_for_curr_waypoint) transl_centroid[1] = transl_centroid[1] / len(poses_for_curr_waypoint) for pose_for_waypoint in poses_for_curr_waypoint: deviations_from_centroid.append(computeNorm(pose_for_waypoint[0], transl_centroid)) return deviations_from_centroid def plotWaypointDistanceConsistencyCDF(poses_by_waypoint_primary_approach, poses_by_waypoint_comparison_approaches): # For each waypoint, get centroid and find distance of each pose for the waypoint from the centroid deviations_from_centroid_primary_approach = getDeviationsFromCentroid(poses_by_waypoint_primary_approach) deviations_from_centroid_comparison_approaches = {} for comparison_approach_label, poses_by_waypoint in poses_by_waypoint_comparison_approaches.items(): deviations_from_centroid_comparison_approaches[comparison_approach_label] = getDeviationsFromCentroid(poses_by_waypoint) # Create CDF for centroid distance series plotCDF(deviations_from_centroid_primary_approach, deviations_from_centroid_comparison_approaches, "CDF of Position Deviation from Waypoint Estimate Centroid", "Meters from Respective Centroid", 1) def getAngleDeviations(poses_by_waypoint): angleDeviations = [] # For each waypoint, get mean orientation and deviation from mean orientation for each assocciated pose for waypoint, poses_for_curr_waypoint in poses_by_waypoint.items(): if (len(poses_for_curr_waypoint) <= 1): continue mean_rotation = findMeanRotation(poses_for_curr_waypoint) for pose_for_waypoint in poses_for_curr_waypoint: # print(pose_for_waypoint) angleDeviation = angleDist(pose_for_waypoint[1], mean_rotation) angleDeviations.append(angleDeviation) return angleDeviations def plotWaypointOrientationConsistencyCDF(poses_by_waypoint_primary_approach, poses_by_waypoint_comparison_approaches): angle_deviations_primary_approach = np.degrees(getAngleDeviations(poses_by_waypoint_primary_approach)) angle_deviations_comparison_approaches = {} for comparison_approach_label, poses_by_waypoint in poses_by_waypoint_comparison_approaches.items(): angle_deviations_comparison_approaches[comparison_approach_label] = np.degrees(getAngleDeviations(poses_by_waypoint)) plotCDF(angle_deviations_primary_approach, angle_deviations_comparison_approaches, "CDF of Orientation Estimate Deviation from Mean Waypoint Orientation", "Degrees from Mean Waypoint Orientation", 2) def getPosesForWaypoints(approach_namespace, num_traj): min_waypoint_id = sys.maxsize max_waypoint_id = 1 for i in range(num_traj): trajectory_file_param_name = constructTrajectorySpecificParamName(approach_namespace, i, kTrajectoryOutputSuffix) waypoint_to_node_id_file_param_name = constructTrajectorySpecificParamName(approach_namespace, i, kWaypointToNodeIdParamNameSuffix) trajectory_file_name = rospy.get_param(trajectory_file_param_name) waypoints_to_nodes_file_name = rospy.get_param(waypoint_to_node_id_file_param_name) trajectory_estimate = readTrajectoryFromFile(trajectory_file_name) primary_approach_trajectory_outputs_by_trajectory_num[i] = trajectory_estimate waypoints_and_node_ids_raw = readNodeAndWaypointPairingsFromFile(waypoints_to_nodes_file_name) waypoints_and_node_ids_for_traj = {} for waypoint_and_node_id in waypoints_and_node_ids_raw: waypoint = waypoint_and_node_id[0] node_id = waypoint_and_node_id[1] nodes_for_waypoint = [] if (waypoint in waypoints_and_node_ids_for_traj.keys()): nodes_for_waypoint = list(waypoints_and_node_ids_for_traj[waypoint]) nodes_for_waypoint.append(node_id) waypoints_and_node_ids_for_traj[waypoint] = set(nodes_for_waypoint) if (waypoint < min_waypoint_id): min_waypoint_id = waypoint if (waypoint > max_waypoint_id): max_waypoint_id = waypoint waypoints_to_node_id_by_trajectory_num[i] = waypoints_and_node_ids_for_traj poses_for_waypoints = {} for waypoint_id in range(min_waypoint_id, max_waypoint_id + 1): poses_for_waypoint = [] for i in range(num_traj): nodes_for_waypoint_for_traj = waypoints_to_node_id_by_trajectory_num[i][waypoint_id] if (len(nodes_for_waypoint_for_traj) == 0): continue trajectory = primary_approach_trajectory_outputs_by_trajectory_num[i] for node_id_for_waypoint in nodes_for_waypoint_for_traj: # print("Node id: " + str(node_id_for_waypoint)) # print("Trajectory node ") # print(trajectory[node_id_for_waypoint]) poses_for_waypoint.append(trajectory[node_id_for_waypoint]) if (len(poses_for_waypoint) != 0): poses_for_waypoints[waypoint_id] = poses_for_waypoint print("Min waypoint " + str(min_waypoint_id)) print("Max waypoint " + str(max_waypoint_id)) return poses_for_waypoints if __name__ == "__main__": cmdLineArgs = parseArgs() param_prefix = cmdLineArgs.param_prefix # param_prefix = "" node_prefix = param_prefix if (len(param_prefix) != 0): param_prefix = "/" + param_prefix + "/" node_prefix = node_prefix + "_" print("Param prefix: " + param_prefix) rospy.init_node(node_prefix + 'plot_waypoint_consistency_results') primary_approach_trajectory_outputs_by_trajectory_num = {} # // Outer key is the trajectory number # // Inner key is the waypoint number # // Inner value is the set of nodes that correspond to the waypoint # std::unordered_map<int, std::unordered_map<uint64_t, std::unordered_set<uint64_t>>> waypoints_to_node_id_by_trajectory_num; waypoints_to_node_id_by_trajectory_num = {} num_trajectories = rospy.get_param(param_prefix + kNumTrajectoriesParamName) # min_waypoint_id = sys.maxsize # max_waypoint_id = 1 if (num_trajectories <= 0): print("Trajectory count must be a positive number") exit() print("Num trajectories " + str(num_trajectories)) poses_for_waypoints_by_comparison_approach = {} print("Getting POM-Localization poses") poses_for_main_approach = getPosesForWaypoints(param_prefix, num_trajectories) num_comparison_approaches = rospy.get_param(param_prefix + kNumComparisonApproachesParamName) print("Num comparison approaches " + str(num_comparison_approaches)) for i in range(num_comparison_approaches): approach_specific_namespace = param_prefix + kComparisonApproachSpecificPrefix + str(i) + "/" approach_label = rospy.get_param(approach_specific_namespace + kComparisonApproachLabelSuffix) print("Getting " + approach_label + " poses") print("Getting poses for waypoints for label " + approach_label) poses_for_waypoints_by_comparison_approach[approach_label] = getPosesForWaypoints(approach_specific_namespace, num_trajectories) plotWaypointDistanceConsistencyCDF(poses_for_main_approach, poses_for_waypoints_by_comparison_approach) plotWaypointOrientationConsistencyCDF(poses_for_main_approach, poses_for_waypoints_by_comparison_approach) plt.show() # # for i in range(min_waypoint_id, max_waypoint_id +1): # print("Waypoint: " + str(i) + ", Transl Deviation: " + str(transl_deviation[i]) + ", angle deviation " + str(mean_rotation_deviations[i])) # print(position_offsets_for_waypoints[i]) # plotPosOffsetForWaypoint(i, position_offsets_for_waypoints[i], max_deviation) # plotAngleOffsetForWaypoint(i, angle_offsets_for_waypoints[i])
[ "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "rospy.init_node", "math.sqrt", "math.cos", "numpy.histogram", "argparse.ArgumentParser", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylim", "csv.reader", "rospy.get_param", "mat...
[((1796, 1821), 'math.sin', 'math.sin', (['(angle0 - angle1)'], {}), '(angle0 - angle1)\n', (1804, 1821), False, 'import math\n'), ((1830, 1855), 'math.cos', 'math.cos', (['(angle0 - angle1)'], {}), '(angle0 - angle1)\n', (1838, 1855), False, 'import math\n'), ((1867, 1883), 'math.atan2', 'math.atan2', (['s', 'c'], {}), '(s, c)\n', (1877, 1883), False, 'import math\n'), ((2071, 2105), 'math.sqrt', 'math.sqrt', (['(xDiff ** 2 + yDiff ** 2)'], {}), '(xDiff ** 2 + yDiff ** 2)\n', (2080, 2105), False, 'import math\n'), ((2631, 2683), 'math.atan2', 'math.atan2', (['mean_unit_vector[1]', 'mean_unit_vector[0]'], {}), '(mean_unit_vector[1], mean_unit_vector[0])\n', (2641, 2683), False, 'import math\n'), ((2715, 2767), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Plot results."""'}), "(description='Plot results.')\n", (2738, 2767), False, 'import argparse\n'), ((3079, 3123), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', '(8)'], {'sharex': '(True)', 'sharey': '(True)'}), '(4, 8, sharex=True, sharey=True)\n', (3091, 3123), True, 'import matplotlib.pyplot as plt\n'), ((3646, 3667), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (3654, 3667), True, 'import matplotlib.pyplot as plt\n'), ((3740, 3753), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (3750, 3753), True, 'import matplotlib.pyplot as plt\n'), ((3875, 3892), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {}), '(x, y)\n', (3886, 3892), True, 'import matplotlib.pyplot as plt\n'), ((3897, 3948), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-1.1 * maxDeviation, 1.1 * maxDeviation]'], {}), '([-1.1 * maxDeviation, 1.1 * maxDeviation])\n', (3905, 3948), True, 'import matplotlib.pyplot as plt\n'), ((3953, 4004), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-1.1 * maxDeviation, 1.1 * maxDeviation]'], {}), '([-1.1 * maxDeviation, 1.1 * maxDeviation])\n', (3961, 4004), True, 'import matplotlib.pyplot as plt\n'), ((4052, 4062), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4060, 4062), True, 'import matplotlib.pyplot as plt\n'), ((4163, 4207), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', '(8)'], {'sharex': '(True)', 'sharey': '(True)'}), '(4, 8, sharex=True, sharey=True)\n', (4175, 4207), True, 'import matplotlib.pyplot as plt\n'), ((4631, 4641), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4639, 4641), True, 'import matplotlib.pyplot as plt\n'), ((4704, 4717), 'matplotlib.pyplot.figure', 'plt.figure', (['(4)'], {}), '(4)\n', (4714, 4717), True, 'import matplotlib.pyplot as plt\n'), ((4745, 4767), 'matplotlib.pyplot.hist', 'plt.hist', (['angleOffsets'], {}), '(angleOffsets)\n', (4753, 4767), True, 'import matplotlib.pyplot as plt\n'), ((4955, 4965), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4963, 4965), True, 'import matplotlib.pyplot as plt\n'), ((5063, 5099), 'numpy.histogram', 'np.histogram', (['dataset'], {'bins': 'num_bins'}), '(dataset, bins=num_bins)\n', (5075, 5099), True, 'import numpy as np\n'), ((5316, 5330), 'numpy.cumsum', 'np.cumsum', (['pdf'], {}), '(pdf)\n', (5325, 5330), True, 'import numpy as np\n'), ((5341, 5361), 'numpy.insert', 'np.insert', (['cdf', '(0)', '(0)'], {}), '(cdf, 0, 0)\n', (5350, 5361), True, 'import numpy as np\n'), ((5377, 5393), 'numpy.amax', 'np.amax', (['dataset'], {}), '(dataset)\n', (5384, 5393), True, 'import numpy as np\n'), ((5542, 5561), 'matplotlib.pyplot.figure', 'plt.figure', (['fig_num'], {}), '(fig_num)\n', (5552, 5561), True, 'import matplotlib.pyplot as plt\n'), ((6436, 6528), 'matplotlib.pyplot.plot', 'plt.plot', (['bins_count', 'primary_approach_cdf'], {'linestyle': '"""solid"""', 'label': '"""POM-Localization"""'}), "(bins_count, primary_approach_cdf, linestyle='solid', label=\n 'POM-Localization')\n", (6444, 6528), True, 'import matplotlib.pyplot as plt\n'), ((6860, 6874), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (6868, 6874), True, 'import matplotlib.pyplot as plt\n'), ((6879, 6895), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (6888, 6895), True, 'import matplotlib.pyplot as plt\n'), ((6900, 6919), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {}), '(x_label)\n', (6910, 6919), True, 'import matplotlib.pyplot as plt\n'), ((6924, 6956), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Proportion of data"""'], {}), "('Proportion of data')\n", (6934, 6956), True, 'import matplotlib.pyplot as plt\n'), ((13058, 13124), 'rospy.init_node', 'rospy.init_node', (["(node_prefix + 'plot_waypoint_consistency_results')"], {}), "(node_prefix + 'plot_waypoint_consistency_results')\n", (13073, 13124), False, 'import rospy\n'), ((13550, 13607), 'rospy.get_param', 'rospy.get_param', (['(param_prefix + kNumTrajectoriesParamName)'], {}), '(param_prefix + kNumTrajectoriesParamName)\n', (13565, 13607), False, 'import rospy\n'), ((14048, 14113), 'rospy.get_param', 'rospy.get_param', (['(param_prefix + kNumComparisonApproachesParamName)'], {}), '(param_prefix + kNumComparisonApproachesParamName)\n', (14063, 14113), False, 'import rospy\n'), ((14927, 14937), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14935, 14937), True, 'import matplotlib.pyplot as plt\n'), ((652, 701), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""|"""'}), "(csvfile, delimiter=',', quotechar='|')\n", (662, 701), False, 'import csv\n'), ((1167, 1216), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""|"""'}), "(csvfile, delimiter=',', quotechar='|')\n", (1177, 1216), False, 'import csv\n'), ((6028, 6152), 'matplotlib.pyplot.plot', 'plt.plot', (['bins_count', 'approach_cdf'], {'linestyle': 'alternate_line_styles[alternate_line_style_index]', 'label': 'comparison_label'}), '(bins_count, approach_cdf, linestyle=alternate_line_styles[\n alternate_line_style_index], label=comparison_label)\n', (6036, 6152), True, 'import matplotlib.pyplot as plt\n'), ((6816, 6834), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', 'x_lim'], {}), '(0, x_lim)\n', (6824, 6834), True, 'import matplotlib.pyplot as plt\n'), ((6843, 6855), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (6853, 6855), True, 'import matplotlib.pyplot as plt\n'), ((10564, 10607), 'rospy.get_param', 'rospy.get_param', (['trajectory_file_param_name'], {}), '(trajectory_file_param_name)\n', (10579, 10607), False, 'import rospy\n'), ((10647, 10699), 'rospy.get_param', 'rospy.get_param', (['waypoint_to_node_id_file_param_name'], {}), '(waypoint_to_node_id_file_param_name)\n', (10662, 10699), False, 'import rospy\n'), ((14361, 14438), 'rospy.get_param', 'rospy.get_param', (['(approach_specific_namespace + kComparisonApproachLabelSuffix)'], {}), '(approach_specific_namespace + kComparisonApproachLabelSuffix)\n', (14376, 14438), False, 'import rospy\n'), ((2394, 2411), 'math.cos', 'math.cos', (['pose[1]'], {}), '(pose[1])\n', (2402, 2411), False, 'import math\n'), ((2464, 2481), 'math.sin', 'math.sin', (['pose[1]'], {}), '(pose[1])\n', (2472, 2481), False, 'import math\n')]
# ----------------------------------------------------------------------------- # # program: Dagger Simulation # # description: simulates the dagger algorithm using minecraft to teach the # actor to stay on course # # ----------------------------------------------------------------------------- # # imports # # ----------------------------------------------------------------------------- # to control Minecraft # from Player import Player # data modules # from PIL import Image import numpy as np # import imageio from matplotlib import pyplot as plt # modules for deep learning # from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.optimizers import Adam # ----------------------------------------------------------------------------- # # globals # # ----------------------------------------------------------------------------- # size of action vector # ACTION_DIM = 1 # image dimensions # IMG_DIM = (64, 64, 3) # number of dagger iterations # DAGGER_ITER = 5 # batch size and number of epochs # BATCH_SIZE = 32 NB_EPOCH = 100 # size to resize images # NEW_IMAGE_SIZE = (64, 64) # mission xml file and delay time between actions # MISSION_FILE = "../config/mission.xml" DELAY_TIME = 0.1 # ----------------------------------------------------------------------------- # # functions # # ----------------------------------------------------------------------------- # function: img_reshape # # arguments: # input_img: image from simulation to convert to standard image array format # # return: three dimensional array of image # # converts image from simulation to format recognizable my PIL # def img_reshape(input_img): # reshape the image # _img = np.transpose(input_img, (1, 2, 0)) _img = np.flipud(_img) _img = np.reshape(_img, (1, *input_img.shape)) # exit gracefully # return _img # # end of function # function: img_prepare # # arguments: # img: image to be prepared to be written to gif # # return: three dimensional array of resized image # # resizes an image to prepare it to be written to a gif # def img_prepare(img): # reshape and resize the image # im = Image.fromarray(img) im = im.resize(NEW_IMAGE_SIZE, Image.ANTIALIAS) # exit gracefully # return np.array(im).reshape((1, *IMG_DIM)) # # end of function # ----------------------------------------------------------------------------- # # main # # ----------------------------------------------------------------------------- def main(): # --------------------------------- # # initial run # # --------------------------------- # object to interact with Minecraft # player = Player(MISSION_FILE, action_delay=DELAY_TIME) # start a mission and listen # player.start() actions, states = player.listen_and_react_loop(limit_to=["Q", "E", "X"], move_forward=True) # --------------------------------- # # create neural network # # --------------------------------- # credit for model design: # https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py # print("constructing neural net!!") model = Sequential() model.add(Convolution2D(32, 3, 3, border_mode='same', input_shape=IMG_DIM, kernel_initializer="normal")) model.add(Activation('relu')) model.add(Convolution2D(32, 3, 3, kernel_initializer="normal")) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Convolution2D(64, 3, 3, border_mode='same', kernel_initializer="normal")) model.add(Activation('relu')) model.add(Convolution2D(64, 3, 3, kernel_initializer="normal")) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512, kernel_initializer="normal")) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(ACTION_DIM, kernel_initializer="normal")) model.add(Activation('tanh')) model.compile(loss='mean_squared_error', optimizer=Adam(lr=1e-3), metrics=['mean_squared_error']) # prepare images # print("dagger:: preparing images!!") frames = np.zeros((0, *IMG_DIM)) for state in states: frame = np.array(state.video_frames[-1].pixels).reshape((360, 480, 3)) frames = np.concatenate((frames, img_prepare(frame)), axis=0) # prepare actions # acts = [] act_map = {None: 0, "turn -1": -1, "turn 1": 1} for act in actions: acts.append(act_map[act]) # train model # model.fit(frames, acts, batch_size=BATCH_SIZE, epochs=NB_EPOCH, shuffle=True) # --------------------------------- # # iteratively train model # # --------------------------------- # aggregate and retrain for multiple dagger iterations # for itr in range(DAGGER_ITER): continue # # end of for # # end of main # begin gracefully # if __name__ == "__main__": main() # # end of program
[ "keras.optimizers.Adam", "Player.Player", "PIL.Image.fromarray", "keras.layers.Convolution2D", "numpy.reshape", "keras.layers.Flatten", "keras.layers.MaxPooling2D", "numpy.flipud", "keras.models.Sequential", "numpy.array", "numpy.zeros", "keras.layers.Activation", "keras.layers.Dense", "nu...
[((1804, 1838), 'numpy.transpose', 'np.transpose', (['input_img', '(1, 2, 0)'], {}), '(input_img, (1, 2, 0))\n', (1816, 1838), True, 'import numpy as np\n'), ((1850, 1865), 'numpy.flipud', 'np.flipud', (['_img'], {}), '(_img)\n', (1859, 1865), True, 'import numpy as np\n'), ((1877, 1916), 'numpy.reshape', 'np.reshape', (['_img', '(1, *input_img.shape)'], {}), '(_img, (1, *input_img.shape))\n', (1887, 1916), True, 'import numpy as np\n'), ((2259, 2279), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (2274, 2279), False, 'from PIL import Image\n'), ((2785, 2830), 'Player.Player', 'Player', (['MISSION_FILE'], {'action_delay': 'DELAY_TIME'}), '(MISSION_FILE, action_delay=DELAY_TIME)\n', (2791, 2830), False, 'from Player import Player\n'), ((3323, 3335), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (3333, 3335), False, 'from keras.models import Sequential\n'), ((4501, 4524), 'numpy.zeros', 'np.zeros', (['(0, *IMG_DIM)'], {}), '((0, *IMG_DIM))\n', (4509, 4524), True, 'import numpy as np\n'), ((3351, 3448), 'keras.layers.Convolution2D', 'Convolution2D', (['(32)', '(3)', '(3)'], {'border_mode': '"""same"""', 'input_shape': 'IMG_DIM', 'kernel_initializer': '"""normal"""'}), "(32, 3, 3, border_mode='same', input_shape=IMG_DIM,\n kernel_initializer='normal')\n", (3364, 3448), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), ((3516, 3534), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3526, 3534), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((3550, 3602), 'keras.layers.Convolution2D', 'Convolution2D', (['(32)', '(3)', '(3)'], {'kernel_initializer': '"""normal"""'}), "(32, 3, 3, kernel_initializer='normal')\n", (3563, 3602), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), ((3618, 3636), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3628, 3636), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((3652, 3682), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (3664, 3682), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), ((3698, 3711), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {}), '(0.25)\n', (3705, 3711), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((3728, 3800), 'keras.layers.Convolution2D', 'Convolution2D', (['(64)', '(3)', '(3)'], {'border_mode': '"""same"""', 'kernel_initializer': '"""normal"""'}), "(64, 3, 3, border_mode='same', kernel_initializer='normal')\n", (3741, 3800), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), ((3844, 3862), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3854, 3862), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((3878, 3930), 'keras.layers.Convolution2D', 'Convolution2D', (['(64)', '(3)', '(3)'], {'kernel_initializer': '"""normal"""'}), "(64, 3, 3, kernel_initializer='normal')\n", (3891, 3930), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), ((3946, 3964), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3956, 3964), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((3980, 4010), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (3992, 4010), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), ((4026, 4039), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {}), '(0.25)\n', (4033, 4039), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((4056, 4065), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (4063, 4065), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((4081, 4120), 'keras.layers.Dense', 'Dense', (['(512)'], {'kernel_initializer': '"""normal"""'}), "(512, kernel_initializer='normal')\n", (4086, 4120), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((4136, 4154), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4146, 4154), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((4170, 4182), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (4177, 4182), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((4198, 4244), 'keras.layers.Dense', 'Dense', (['ACTION_DIM'], {'kernel_initializer': '"""normal"""'}), "(ACTION_DIM, kernel_initializer='normal')\n", (4203, 4244), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((4260, 4278), 'keras.layers.Activation', 'Activation', (['"""tanh"""'], {}), "('tanh')\n", (4270, 4278), False, 'from keras.layers import Dense, Dropout, Activation, Flatten\n'), ((2372, 2384), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (2380, 2384), True, 'import numpy as np\n'), ((4354, 4368), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (4358, 4368), False, 'from keras.optimizers import Adam\n'), ((4566, 4605), 'numpy.array', 'np.array', (['state.video_frames[-1].pixels'], {}), '(state.video_frames[-1].pixels)\n', (4574, 4605), True, 'import numpy as np\n')]
""" Exploratory data analysis of visualization study on CESM-LENS Reference : Kay et al. (2015, BAMS) Author : <NAME> Date : 19 November 2020 """ ### Import modules import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid import cmocean import palettable.cubehelix as cm import scipy.stats as sts import read_LENS as LL from datetime import date today = '2020-11-19' ### Directory and time directorydata = '/Users/zlabe/Data/LENS/monthly/' directorydata2 = '/Users/zlabe/Documents/Research/Visualizations/Data/' directoryfigure = '/Users/zlabe/Documents/Research/Visualizations/Figures/Loop_ColorDiverging/' ### Set defaults vari = 'T2M' years = np.arange(1920,2100+1,1) ensembles = np.arange(0,39+1,1) samples = 60 sliceperiod = 'DJF' slicebase = np.arange(1951,1980+1,1) sliceshape = 4 slicenan = 'nan' addclimo = True takeEnsMean = False read_data = True ### Read in data if read_data == True: lat,lon,var,ENSmean = LL.read_LENS(directorydata,vari,sliceperiod, slicebase,sliceshape,addclimo, slicenan,takeEnsMean) ### Slice period yearq = np.where((years >= 1991) & (years <= 2020))[0] vart = var[:,yearq,:,:] ### Calculate trends per grid box trends = np.empty((vart.shape[0],lat.shape[0],lon.shape[0])) x = np.arange(vart.shape[1]) for ens in range(vart.shape[0]): for i in range(lat.shape[0]): for j in range(lon.shape[0]): mask = np.isfinite(vart[ens,:,i,j]) y = vart[ens,:,i,j] if np.sum(mask) == y.shape[0]: xx = x yy = y else: xx = x[mask] yy = y[mask] if np.isfinite(np.nanmean(yy)): trends[ens,i,j],intercepts,r_value,p_value,std_err = sts.linregress(xx,yy) else: trends[ens,i,j] = np.nan print('Completed: Calculated trends for %s ensemble!' % (ens+1)) ### Calculate change in temperature change = trends * yearq.shape[0] ens1 = np.genfromtxt(directorydata2 + 'EnsembleSelection_DifferProj_ENS-1_%s.txt' % today) ens2 = np.genfromtxt(directorydata2 + 'EnsembleSelection_DifferProj_ENS-2_%s.txt' % today) ############################################################################### ############################################################################### ############################################################################### for i in range(samples): var1 = change[int(ens1[i])] var2 = change[int(ens2[i])] count = i+1 print('Completed: Saved figures for %s!' % count) ########################################################################### ########################################################################### ########################################################################### ### Plot variable data for trends plt.rc('text',usetex=True) plt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']}) ### Set limits for contours and colorbars limit = np.arange(-6,6.1,0.5) barlim = np.arange(-6,7,2) label = r'\textbf{Temperature [$^{\circ}$C] Change [1991-2020]}' ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### fig = plt.figure(figsize=(9,4)) cmap = cmocean.cm.balance ########################################################################### ########################################################################### ########################################################################### var = var1 ax1 = plt.subplot(1,2,1) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### ########################################################################### ########################################################################### var = var2 ax1 = plt.subplot(1,2,2) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### cbar_ax = fig.add_axes([0.32,0.08,0.4,0.03]) cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal', extend='both',extendfrac=0.07,drawedges=False) cbar.set_label(label,fontsize=7,color='k',labelpad=1.4) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str,barlim))) cbar.ax.tick_params(axis='x', size=.01,labelsize=5) cbar.outline.set_edgecolor('dimgrey') plt.tight_layout() plt.subplots_adjust(wspace=0.01,hspace=0,bottom=0.14) plt.savefig(directoryfigure + 'Color1_1991-2020_%s.png' % count,dpi=300) ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### fig = plt.figure(figsize=(9,4)) cmap = cmocean.cm.diff ########################################################################### ########################################################################### ########################################################################### var = var1 ax1 = plt.subplot(1,2,1) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### ########################################################################### ########################################################################### var = var2 ax1 = plt.subplot(1,2,2) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### cbar_ax = fig.add_axes([0.32,0.08,0.4,0.03]) cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal', extend='both',extendfrac=0.07,drawedges=False) cbar.set_label(label,fontsize=7,color='k',labelpad=1.4) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str,barlim))) cbar.ax.tick_params(axis='x', size=.01,labelsize=5) cbar.outline.set_edgecolor('dimgrey') plt.tight_layout() plt.subplots_adjust(wspace=0.01,hspace=0,bottom=0.14) plt.savefig(directoryfigure + 'Color2_1991-2020_%s.png' % count,dpi=300) ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### fig = plt.figure(figsize=(9,4)) cmap = cmocean.cm.curl ########################################################################### ########################################################################### ########################################################################### var = var1 ax1 = plt.subplot(1,2,1) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### ########################################################################### ########################################################################### var = var2 ax1 = plt.subplot(1,2,2) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### cbar_ax = fig.add_axes([0.32,0.08,0.4,0.03]) cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal', extend='both',extendfrac=0.07,drawedges=False) cbar.set_label(label,fontsize=7,color='k',labelpad=1.4) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str,barlim))) cbar.ax.tick_params(axis='x', size=.01,labelsize=5) cbar.outline.set_edgecolor('dimgrey') plt.tight_layout() plt.subplots_adjust(wspace=0.01,hspace=0,bottom=0.14) plt.savefig(directoryfigure + 'Color3_1991-2020_%s.png' % count,dpi=300) ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### fig = plt.figure(figsize=(9,4)) cmap = cmocean.cm.delta ########################################################################### ########################################################################### ########################################################################### var = var1 ax1 = plt.subplot(1,2,1) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### ########################################################################### ########################################################################### var = var2 ax1 = plt.subplot(1,2,2) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### cbar_ax = fig.add_axes([0.32,0.08,0.4,0.03]) cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal', extend='both',extendfrac=0.07,drawedges=False) cbar.set_label(label,fontsize=7,color='k',labelpad=1.4) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str,barlim))) cbar.ax.tick_params(axis='x', size=.01,labelsize=5) cbar.outline.set_edgecolor('dimgrey') plt.tight_layout() plt.subplots_adjust(wspace=0.01,hspace=0,bottom=0.14) plt.savefig(directoryfigure + 'Color4_1991-2020_%s.png' % count,dpi=300) ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### ########################################################################### fig = plt.figure(figsize=(9,4)) cmap = cmocean.cm.tarn ########################################################################### ########################################################################### ########################################################################### var = var1 ax1 = plt.subplot(1,2,1) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### ########################################################################### ########################################################################### var = var2 ax1 = plt.subplot(1,2,2) m = Basemap(projection='ortho',lon_0=0,lat_0=90,resolution='l', area_thresh=10000.) circle = m.drawmapboundary(fill_color='k') circle.set_clip_on(False) m.drawcoastlines(color='dimgrey',linewidth=0.35) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) circle = m.drawmapboundary(fill_color='white',color='dimgrey', linewidth=0.7) circle.set_clip_on(False) cs = m.contourf(x,y,var,limit,extend='both') cs.set_cmap(cmap) ########################################################################### cbar_ax = fig.add_axes([0.32,0.08,0.4,0.03]) cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal', extend='both',extendfrac=0.07,drawedges=False) cbar.set_label(label,fontsize=7,color='k',labelpad=1.4) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str,barlim))) cbar.ax.tick_params(axis='x', size=.01,labelsize=5) cbar.outline.set_edgecolor('dimgrey') plt.tight_layout() plt.subplots_adjust(wspace=0.01,hspace=0,bottom=0.14) plt.savefig(directoryfigure + 'Color5_1991-2020_%s.png' % count,dpi=300)
[ "scipy.stats.linregress", "numpy.nanmean", "numpy.isfinite", "numpy.genfromtxt", "numpy.arange", "numpy.where", "numpy.empty", "numpy.meshgrid", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.rc", "mpl_toolkits.basemap.addcyclic", "numpy.sum", "matplot...
[((715, 743), 'numpy.arange', 'np.arange', (['(1920)', '(2100 + 1)', '(1)'], {}), '(1920, 2100 + 1, 1)\n', (724, 743), True, 'import numpy as np\n'), ((752, 775), 'numpy.arange', 'np.arange', (['(0)', '(39 + 1)', '(1)'], {}), '(0, 39 + 1, 1)\n', (761, 775), True, 'import numpy as np\n'), ((817, 845), 'numpy.arange', 'np.arange', (['(1951)', '(1980 + 1)', '(1)'], {}), '(1951, 1980 + 1, 1)\n', (826, 845), True, 'import numpy as np\n'), ((2167, 2254), 'numpy.genfromtxt', 'np.genfromtxt', (["(directorydata2 + 'EnsembleSelection_DifferProj_ENS-1_%s.txt' % today)"], {}), "(directorydata2 + 'EnsembleSelection_DifferProj_ENS-1_%s.txt' %\n today)\n", (2180, 2254), True, 'import numpy as np\n'), ((2258, 2345), 'numpy.genfromtxt', 'np.genfromtxt', (["(directorydata2 + 'EnsembleSelection_DifferProj_ENS-2_%s.txt' % today)"], {}), "(directorydata2 + 'EnsembleSelection_DifferProj_ENS-2_%s.txt' %\n today)\n", (2271, 2345), True, 'import numpy as np\n'), ((993, 1099), 'read_LENS.read_LENS', 'LL.read_LENS', (['directorydata', 'vari', 'sliceperiod', 'slicebase', 'sliceshape', 'addclimo', 'slicenan', 'takeEnsMean'], {}), '(directorydata, vari, sliceperiod, slicebase, sliceshape,\n addclimo, slicenan, takeEnsMean)\n', (1005, 1099), True, 'import read_LENS as LL\n'), ((1308, 1361), 'numpy.empty', 'np.empty', (['(vart.shape[0], lat.shape[0], lon.shape[0])'], {}), '((vart.shape[0], lat.shape[0], lon.shape[0]))\n', (1316, 1361), True, 'import numpy as np\n'), ((1368, 1392), 'numpy.arange', 'np.arange', (['vart.shape[1]'], {}), '(vart.shape[1])\n', (1377, 1392), True, 'import numpy as np\n'), ((3033, 3060), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (3039, 3060), True, 'import matplotlib.pyplot as plt\n'), ((3064, 3137), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **{'family': 'sans-serif', 'sans-serif': ['Avant Garde']})\n", (3070, 3137), True, 'import matplotlib.pyplot as plt\n'), ((3198, 3221), 'numpy.arange', 'np.arange', (['(-6)', '(6.1)', '(0.5)'], {}), '(-6, 6.1, 0.5)\n', (3207, 3221), True, 'import numpy as np\n'), ((3233, 3252), 'numpy.arange', 'np.arange', (['(-6)', '(7)', '(2)'], {}), '(-6, 7, 2)\n', (3242, 3252), True, 'import numpy as np\n'), ((4055, 4081), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 4)'}), '(figsize=(9, 4))\n', (4065, 4081), True, 'import matplotlib.pyplot as plt\n'), ((4381, 4401), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (4392, 4401), True, 'import matplotlib.pyplot as plt\n'), ((4408, 4496), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (4415, 4496), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((4675, 4694), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (4684, 4694), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((4718, 4765), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (4727, 4765), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((4784, 4813), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (4795, 4813), True, 'import numpy as np\n'), ((5335, 5355), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (5346, 5355), True, 'import matplotlib.pyplot as plt\n'), ((5362, 5450), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (5369, 5450), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((5629, 5648), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (5638, 5648), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((5672, 5719), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (5681, 5719), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((5738, 5767), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (5749, 5767), True, 'import numpy as np\n'), ((6566, 6584), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6582, 6584), True, 'import matplotlib.pyplot as plt\n'), ((6589, 6644), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0)', 'bottom': '(0.14)'}), '(wspace=0.01, hspace=0, bottom=0.14)\n', (6608, 6644), True, 'import matplotlib.pyplot as plt\n'), ((6652, 6725), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(directoryfigure + 'Color1_1991-2020_%s.png' % count)"], {'dpi': '(300)'}), "(directoryfigure + 'Color1_1991-2020_%s.png' % count, dpi=300)\n", (6663, 6725), True, 'import matplotlib.pyplot as plt\n'), ((7460, 7486), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 4)'}), '(figsize=(9, 4))\n', (7470, 7486), True, 'import matplotlib.pyplot as plt\n'), ((7783, 7803), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (7794, 7803), True, 'import matplotlib.pyplot as plt\n'), ((7810, 7898), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (7817, 7898), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((8077, 8096), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (8086, 8096), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((8120, 8167), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (8129, 8167), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((8186, 8215), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (8197, 8215), True, 'import numpy as np\n'), ((8737, 8757), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (8748, 8757), True, 'import matplotlib.pyplot as plt\n'), ((8764, 8852), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (8771, 8852), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((9031, 9050), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (9040, 9050), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((9074, 9121), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (9083, 9121), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((9140, 9169), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (9151, 9169), True, 'import numpy as np\n'), ((9968, 9986), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9984, 9986), True, 'import matplotlib.pyplot as plt\n'), ((9991, 10046), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0)', 'bottom': '(0.14)'}), '(wspace=0.01, hspace=0, bottom=0.14)\n', (10010, 10046), True, 'import matplotlib.pyplot as plt\n'), ((10054, 10127), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(directoryfigure + 'Color2_1991-2020_%s.png' % count)"], {'dpi': '(300)'}), "(directoryfigure + 'Color2_1991-2020_%s.png' % count, dpi=300)\n", (10065, 10127), True, 'import matplotlib.pyplot as plt\n'), ((10862, 10888), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 4)'}), '(figsize=(9, 4))\n', (10872, 10888), True, 'import matplotlib.pyplot as plt\n'), ((11185, 11205), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (11196, 11205), True, 'import matplotlib.pyplot as plt\n'), ((11212, 11300), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (11219, 11300), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((11479, 11498), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (11488, 11498), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((11522, 11569), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (11531, 11569), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((11588, 11617), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (11599, 11617), True, 'import numpy as np\n'), ((12139, 12159), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (12150, 12159), True, 'import matplotlib.pyplot as plt\n'), ((12166, 12254), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (12173, 12254), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((12433, 12452), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (12442, 12452), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((12476, 12523), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (12485, 12523), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((12542, 12571), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (12553, 12571), True, 'import numpy as np\n'), ((13370, 13388), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (13386, 13388), True, 'import matplotlib.pyplot as plt\n'), ((13393, 13448), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0)', 'bottom': '(0.14)'}), '(wspace=0.01, hspace=0, bottom=0.14)\n', (13412, 13448), True, 'import matplotlib.pyplot as plt\n'), ((13456, 13529), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(directoryfigure + 'Color3_1991-2020_%s.png' % count)"], {'dpi': '(300)'}), "(directoryfigure + 'Color3_1991-2020_%s.png' % count, dpi=300)\n", (13467, 13529), True, 'import matplotlib.pyplot as plt\n'), ((14264, 14290), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 4)'}), '(figsize=(9, 4))\n', (14274, 14290), True, 'import matplotlib.pyplot as plt\n'), ((14588, 14608), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (14599, 14608), True, 'import matplotlib.pyplot as plt\n'), ((14615, 14703), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (14622, 14703), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((14882, 14901), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (14891, 14901), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((14925, 14972), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (14934, 14972), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((14991, 15020), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (15002, 15020), True, 'import numpy as np\n'), ((15542, 15562), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (15553, 15562), True, 'import matplotlib.pyplot as plt\n'), ((15569, 15657), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (15576, 15657), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((15836, 15855), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (15845, 15855), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((15879, 15926), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (15888, 15926), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((15945, 15974), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (15956, 15974), True, 'import numpy as np\n'), ((16773, 16791), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (16789, 16791), True, 'import matplotlib.pyplot as plt\n'), ((16796, 16851), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0)', 'bottom': '(0.14)'}), '(wspace=0.01, hspace=0, bottom=0.14)\n', (16815, 16851), True, 'import matplotlib.pyplot as plt\n'), ((16859, 16932), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(directoryfigure + 'Color4_1991-2020_%s.png' % count)"], {'dpi': '(300)'}), "(directoryfigure + 'Color4_1991-2020_%s.png' % count, dpi=300)\n", (16870, 16932), True, 'import matplotlib.pyplot as plt\n'), ((17667, 17693), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 4)'}), '(figsize=(9, 4))\n', (17677, 17693), True, 'import matplotlib.pyplot as plt\n'), ((17990, 18010), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (18001, 18010), True, 'import matplotlib.pyplot as plt\n'), ((18017, 18105), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (18024, 18105), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((18284, 18303), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (18293, 18303), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((18327, 18374), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (18336, 18374), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((18393, 18422), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (18404, 18422), True, 'import numpy as np\n'), ((18944, 18964), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (18955, 18964), True, 'import matplotlib.pyplot as plt\n'), ((18971, 19059), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': '(0)', 'lat_0': '(90)', 'resolution': '"""l"""', 'area_thresh': '(10000.0)'}), "(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=\n 10000.0)\n", (18978, 19059), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((19238, 19257), 'mpl_toolkits.basemap.addcyclic', 'addcyclic', (['var', 'lon'], {}), '(var, lon)\n', (19247, 19257), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((19281, 19328), 'mpl_toolkits.basemap.shiftgrid', 'shiftgrid', (['(180.0)', 'var', 'lons_cyclic'], {'start': '(False)'}), '(180.0, var, lons_cyclic, start=False)\n', (19290, 19328), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((19347, 19376), 'numpy.meshgrid', 'np.meshgrid', (['lons_cyclic', 'lat'], {}), '(lons_cyclic, lat)\n', (19358, 19376), True, 'import numpy as np\n'), ((20175, 20193), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (20191, 20193), True, 'import matplotlib.pyplot as plt\n'), ((20198, 20253), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0)', 'bottom': '(0.14)'}), '(wspace=0.01, hspace=0, bottom=0.14)\n', (20217, 20253), True, 'import matplotlib.pyplot as plt\n'), ((20261, 20334), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(directoryfigure + 'Color5_1991-2020_%s.png' % count)"], {'dpi': '(300)'}), "(directoryfigure + 'Color5_1991-2020_%s.png' % count, dpi=300)\n", (20272, 20334), True, 'import matplotlib.pyplot as plt\n'), ((1181, 1224), 'numpy.where', 'np.where', (['((years >= 1991) & (years <= 2020))'], {}), '((years >= 1991) & (years <= 2020))\n', (1189, 1224), True, 'import numpy as np\n'), ((1533, 1564), 'numpy.isfinite', 'np.isfinite', (['vart[ens, :, i, j]'], {}), '(vart[ens, :, i, j])\n', (1544, 1564), True, 'import numpy as np\n'), ((1618, 1630), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (1624, 1630), True, 'import numpy as np\n'), ((1825, 1839), 'numpy.nanmean', 'np.nanmean', (['yy'], {}), '(yy)\n', (1835, 1839), True, 'import numpy as np\n'), ((1915, 1937), 'scipy.stats.linregress', 'sts.linregress', (['xx', 'yy'], {}), '(xx, yy)\n', (1929, 1937), True, 'import scipy.stats as sts\n')]
# Copyright 2020 NVIDIA. 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 torch from torch import nn from nemo.collections.nlp.nm.trainables.common.transformer import transformer_modules def get_non_pad_mask(seq, pad_id): assert seq.dim() == 2 return seq.ne(pad_id).type(torch.float).unsqueeze(-1) def get_sinusoid_encoding_table(n_position, d_hid, padding_idx=None): """Sinusoid position encoding table.""" def cal_angle(position, hid_idx): return position / np.power(10000, 2 * (hid_idx // 2) / d_hid) def get_posi_angle_vec(position): return [cal_angle(position, hid_j) for hid_j in range(d_hid)] sinusoid_table = np.array([get_posi_angle_vec(pos_i) for pos_i in range(n_position)]) sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1 if padding_idx is not None: # zero vector for padding dimension sinusoid_table[padding_idx] = 0.0 return torch.tensor(sinusoid_table).float() def get_attn_key_pad_mask(seq_k, seq_q, pad_id): """For masking out the padding part of key sequence.""" # Expand to fit the shape of key query attention matrix. len_q = seq_q.size(1) padding_mask = seq_k.eq(pad_id) padding_mask = padding_mask.unsqueeze(1).expand(-1, len_q, -1) # b x lq x lk return padding_mask class FFTBlock(torch.nn.Module): """FFT Block""" def __init__(self, d_model, d_inner, n_head, d_k, d_v, fft_conv1d_kernel, fft_conv1d_padding, dropout=0.1): super(FFTBlock, self).__init__() self.slf_attn = transformer_modules.MultiHeadAttention(d_model, n_head, attn_layer_dropout=dropout) self.n_head = n_head self.pos_ffn = transformer_modules.PositionWiseFF( hidden_size=d_model, inner_size=d_inner, ffn_dropout=dropout, ) def forward(self, enc_input, non_pad_mask=None, slf_attn_mask=None): slf_attn_mask = slf_attn_mask.unsqueeze(1).repeat(1, self.n_head, 1, 1) enc_output = self.slf_attn(enc_input, enc_input, enc_input, attention_mask=slf_attn_mask) enc_output *= non_pad_mask enc_output = self.pos_ffn(enc_output) enc_output *= non_pad_mask return enc_output class FastSpeechTransformerEncoder(nn.Module): """Encoder.""" def __init__( self, len_max_seq, d_word_vec, n_layers, n_head, d_k, d_v, d_model, d_inner, fft_conv1d_kernel, fft_conv1d_padding, dropout, n_src_vocab, pad_id, ): super(FastSpeechTransformerEncoder, self).__init__() n_position = len_max_seq + 1 self.src_word_emb = nn.Embedding(n_src_vocab, d_word_vec, padding_idx=pad_id) self.pad_id = pad_id self.position_enc = nn.Embedding.from_pretrained( get_sinusoid_encoding_table(n_position, d_word_vec, padding_idx=0), freeze=True ) self.layer_stack = nn.ModuleList( [ FFTBlock( d_model, d_inner, n_head, d_k, d_v, fft_conv1d_kernel=fft_conv1d_kernel, fft_conv1d_padding=fft_conv1d_padding, dropout=dropout, ) for _ in range(n_layers) ] ) def forward(self, src_seq, src_pos): # -- Prepare masks slf_attn_mask = get_attn_key_pad_mask(seq_k=src_seq, seq_q=src_seq, pad_id=self.pad_id) non_pad_mask = get_non_pad_mask(src_seq, pad_id=self.pad_id) # -- Forward enc_output = self.src_word_emb(src_seq) + self.position_enc(src_pos) for i, enc_layer in enumerate(self.layer_stack): enc_output = enc_layer(enc_output, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask) return enc_output, non_pad_mask class FastSpeechTransformerDecoder(nn.Module): """Decoder.""" def __init__( self, len_max_seq, d_word_vec, n_layers, n_head, d_k, d_v, d_model, d_inner, fft_conv1d_kernel, fft_conv1d_padding, dropout, pad_id, ): super(FastSpeechTransformerDecoder, self).__init__() n_position = len_max_seq + 1 self.position_dec = nn.Embedding.from_pretrained( get_sinusoid_encoding_table(n_position, d_word_vec, padding_idx=0), freeze=True ) self.pad_id = pad_id self.layer_stack = nn.ModuleList( [ FFTBlock( d_model, d_inner, n_head, d_k, d_v, fft_conv1d_kernel=fft_conv1d_kernel, fft_conv1d_padding=fft_conv1d_padding, dropout=dropout, ) for _ in range(n_layers) ] ) def forward(self, dec_seq, dec_pos): # -- Prepare masks slf_attn_mask = get_attn_key_pad_mask(seq_k=dec_pos, seq_q=dec_pos, pad_id=self.pad_id) non_pad_mask = get_non_pad_mask(dec_pos, pad_id=self.pad_id) # -- Forward dec_output = dec_seq + self.position_dec(dec_pos) for dec_layer in self.layer_stack: dec_output = dec_layer(dec_output, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask) return dec_output, non_pad_mask
[ "nemo.collections.nlp.nm.trainables.common.transformer.transformer_modules.MultiHeadAttention", "numpy.power", "torch.tensor", "nemo.collections.nlp.nm.trainables.common.transformer.transformer_modules.PositionWiseFF", "numpy.cos", "numpy.sin", "torch.nn.Embedding" ]
[((1310, 1341), 'numpy.sin', 'np.sin', (['sinusoid_table[:, 0::2]'], {}), '(sinusoid_table[:, 0::2])\n', (1316, 1341), True, 'import numpy as np\n'), ((1382, 1413), 'numpy.cos', 'np.cos', (['sinusoid_table[:, 1::2]'], {}), '(sinusoid_table[:, 1::2])\n', (1388, 1413), True, 'import numpy as np\n'), ((2169, 2257), 'nemo.collections.nlp.nm.trainables.common.transformer.transformer_modules.MultiHeadAttention', 'transformer_modules.MultiHeadAttention', (['d_model', 'n_head'], {'attn_layer_dropout': 'dropout'}), '(d_model, n_head, attn_layer_dropout=\n dropout)\n', (2207, 2257), False, 'from nemo.collections.nlp.nm.trainables.common.transformer import transformer_modules\n'), ((2305, 2405), 'nemo.collections.nlp.nm.trainables.common.transformer.transformer_modules.PositionWiseFF', 'transformer_modules.PositionWiseFF', ([], {'hidden_size': 'd_model', 'inner_size': 'd_inner', 'ffn_dropout': 'dropout'}), '(hidden_size=d_model, inner_size=d_inner,\n ffn_dropout=dropout)\n', (2339, 2405), False, 'from nemo.collections.nlp.nm.trainables.common.transformer import transformer_modules\n'), ((3302, 3359), 'torch.nn.Embedding', 'nn.Embedding', (['n_src_vocab', 'd_word_vec'], {'padding_idx': 'pad_id'}), '(n_src_vocab, d_word_vec, padding_idx=pad_id)\n', (3314, 3359), False, 'from torch import nn\n'), ((1035, 1078), 'numpy.power', 'np.power', (['(10000)', '(2 * (hid_idx // 2) / d_hid)'], {}), '(10000, 2 * (hid_idx // 2) / d_hid)\n', (1043, 1078), True, 'import numpy as np\n'), ((1557, 1585), 'torch.tensor', 'torch.tensor', (['sinusoid_table'], {}), '(sinusoid_table)\n', (1569, 1585), False, 'import torch\n')]
# Copyright 2021 The Cirq Developers # # 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 # # https://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. """Quantum gates to prepare a given target state.""" from typing import Any, Dict, Tuple, TYPE_CHECKING import numpy as np from cirq import protocols from cirq.ops import raw_types from cirq._compat import proper_repr if TYPE_CHECKING: import cirq class StatePreparationChannel(raw_types.Gate): """A channel which prepares any state provided as the state vector on it's target qubits.""" def __init__(self, target_state: np.ndarray, name: str = "StatePreparation") -> None: """Initializes a State Preparation channel. Args: target_state: The state vector that this gate should prepare. name: the name of the gate Raises: ValueError: if the array is not 1D, or does not have 2**n elements for some integer n. """ if len(target_state.shape) != 1: raise ValueError('`target_state` must be a 1d numpy array.') n = int(np.round(np.log2(target_state.shape[0] or 1))) if 2 ** n != target_state.shape[0]: raise ValueError(f'Matrix width ({target_state.shape[0]}) is not a power of 2') self._state = target_state.astype(np.complex128) / np.linalg.norm(target_state) self._num_qubits = n self._name = name self._qid_shape = (2,) * n @staticmethod def _has_unitary_() -> bool: """Checks and returns if the gate has a unitary representation. It doesn't, since the resetting of the channels is a non-unitary operations, it involves measurement.""" return False def _json_dict_(self) -> Dict[str, Any]: """Converts the gate object into a serializable dictionary""" return { 'cirq_type': self.__class__.__name__, 'target_state': self._state.tolist(), } @classmethod def _from_json_dict_(cls, target_state, **kwargs): """Recreates the channel object from it's serialized form Args: target_state: the state to prepare using this channel kwargs: other keyword arguments, ignored """ return cls(target_state=np.array(target_state)) def _num_qubits_(self): return self._num_qubits def _qid_shape_(self) -> Tuple[int, ...]: return self._qid_shape def _circuit_diagram_info_( self, _args: 'cirq.CircuitDiagramInfoArgs' ) -> 'cirq.CircuitDiagramInfo': """Returns the information required to draw out the circuit diagram for this channel.""" symbols = ( [self._name] if self._num_qubits == 1 else [f'{self._name}[{i+1}]' for i in range(0, self._num_qubits)] ) return protocols.CircuitDiagramInfo(wire_symbols=symbols) @staticmethod def _has_kraus_(): return True def _kraus_(self): """Returns the Kraus operator for this gate The Kraus Operator is |Psi><i| for all |i>, where |Psi> is the target state. This allows is to take any input state to the target state. The operator satisfies the completeness relation Sum(E^ E) = I. """ operator = np.zeros(shape=(2 ** self._num_qubits,) * 3, dtype=np.complex128) for i in range(len(operator)): operator[i, :, i] = self._state return operator def __repr__(self) -> str: return f'cirq.StatePreparationChannel({proper_repr(self._state)})' def __eq__(self, other) -> bool: if not isinstance(other, StatePreparationChannel): return False return np.allclose(self.state, other.state) @property def state(self): return self._state
[ "cirq.protocols.CircuitDiagramInfo", "numpy.allclose", "numpy.array", "numpy.zeros", "numpy.linalg.norm", "numpy.log2", "cirq._compat.proper_repr" ]
[((3270, 3320), 'cirq.protocols.CircuitDiagramInfo', 'protocols.CircuitDiagramInfo', ([], {'wire_symbols': 'symbols'}), '(wire_symbols=symbols)\n', (3298, 3320), False, 'from cirq import protocols\n'), ((3715, 3780), 'numpy.zeros', 'np.zeros', ([], {'shape': '((2 ** self._num_qubits,) * 3)', 'dtype': 'np.complex128'}), '(shape=(2 ** self._num_qubits,) * 3, dtype=np.complex128)\n', (3723, 3780), True, 'import numpy as np\n'), ((4132, 4168), 'numpy.allclose', 'np.allclose', (['self.state', 'other.state'], {}), '(self.state, other.state)\n', (4143, 4168), True, 'import numpy as np\n'), ((1760, 1788), 'numpy.linalg.norm', 'np.linalg.norm', (['target_state'], {}), '(target_state)\n', (1774, 1788), True, 'import numpy as np\n'), ((1526, 1561), 'numpy.log2', 'np.log2', (['(target_state.shape[0] or 1)'], {}), '(target_state.shape[0] or 1)\n', (1533, 1561), True, 'import numpy as np\n'), ((2705, 2727), 'numpy.array', 'np.array', (['target_state'], {}), '(target_state)\n', (2713, 2727), True, 'import numpy as np\n'), ((3967, 3991), 'cirq._compat.proper_repr', 'proper_repr', (['self._state'], {}), '(self._state)\n', (3978, 3991), False, 'from cirq._compat import proper_repr\n')]
import cv2 import numpy as np import matplotlib.pyplot as plt cap = cv2.VideoCapture("s:\Titan_2020_05_07.mp4") ret, frame = cap.read() combo_image = frame height=180 left = 150 right = 700 top = 150 bottom_margin = 150 x_top_offset = 20 last_center = 320 center = 500 bottom = 330 top = bottom - height polygons = np.array([ [(left, bottom), (right, bottom), (center + x_top_offset, top), (center - x_top_offset, top)] ]) mask = np.zeros_like(frame) cv2.fillPoly(frame, polygons, (255, 255, 255)) cv2.imshow('Result', frame) cv2.waitKey(0)
[ "cv2.fillPoly", "cv2.imshow", "numpy.array", "cv2.waitKey", "cv2.VideoCapture", "numpy.zeros_like" ]
[((69, 113), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""s:\\\\Titan_2020_05_07.mp4"""'], {}), "('s:\\\\Titan_2020_05_07.mp4')\n", (85, 113), False, 'import cv2\n'), ((325, 435), 'numpy.array', 'np.array', (['[[(left, bottom), (right, bottom), (center + x_top_offset, top), (center -\n x_top_offset, top)]]'], {}), '([[(left, bottom), (right, bottom), (center + x_top_offset, top), (\n center - x_top_offset, top)]])\n', (333, 435), True, 'import numpy as np\n'), ((460, 480), 'numpy.zeros_like', 'np.zeros_like', (['frame'], {}), '(frame)\n', (473, 480), True, 'import numpy as np\n'), ((482, 528), 'cv2.fillPoly', 'cv2.fillPoly', (['frame', 'polygons', '(255, 255, 255)'], {}), '(frame, polygons, (255, 255, 255))\n', (494, 528), False, 'import cv2\n'), ((530, 557), 'cv2.imshow', 'cv2.imshow', (['"""Result"""', 'frame'], {}), "('Result', frame)\n", (540, 557), False, 'import cv2\n'), ((563, 577), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (574, 577), False, 'import cv2\n')]
import json from os.path import exists import numpy as np from sklearn.linear_model import Ridge from sklearn.metrics import make_scorer from sklearn.model_selection import GridSearchCV, KFold from scipy.stats import rankdata, zscore from scipy.spatial.distance import cdist from gifti_io import read_gifti, write_gifti from split_stories import check_keys, load_split_data, split_models from brainiak.utils.utils import array_correlation # Function for selecting and aggregating subjects def aggregate_subjects(datasets, models, story_list, subject_list, hemi='lh', aggregation='average'): # Allow for easy single subject input if type(story_list) == str: story_list = [story_list] # Loop through requested stories data_stack, model_stack = [], [] for story in story_list: # Broadcast model if concatenating subjects if aggregation == 'concatenate': model = np.tile(models[story], (len(subject_list), 1)) else: model = models[story] # Allow for easy single subject input if type(subject_list) == str: subject = subject_list data = datasets[story][subject][hemi] else: if len(subject_list) == 1: data = datasets[story][subject_list[0]][hemi] else: n_subjects = len(subject_list) assert n_subjects > 1 # Check subjects are in the data for subject in subject_list: assert subject in datasets[story].keys() # Compile test subjects data_list = [] for subject in subject_list: data_list.append(datasets[story][subject][hemi]) # Average time data across subjects if aggregation == 'average' and n_subjects > 1: data = np.mean(data_list, axis=0) elif aggregation == 'concatenate' and n_subjects > 1: data = np.vstack(data_list) data_stack.append(data) model_stack.append(model) # Stack for multiple stories data_stack = np.vstack(data_stack) model_stack = np.vstack(model_stack) if len(model_stack) != len(data_stack): raise ValueError("Model and data have mismatching shape! " f"model: {model_stack.shape}, data: {data_stack.shape}") return data_stack, model_stack # Function to compute correlation-based rank accuracy def rank_accuracy(predicted_model, test_model, mean=True): n_predictions = test_model.shape[0] # Get correlations between pairs correlations = 1 - cdist(predicted_model, test_model, 'correlation') # Get rank of matching prediction for each ranks = [] for index in np.arange(n_predictions): ranks.append(rankdata(correlations[index])[index]) # Normalize ranks by number of choices ranks = (np.array(ranks) - 1) / (n_predictions - 1) if mean: ranks = np.mean(ranks) return ranks # Function to run grid search over alphas across voxels def grid_search(train_model, train_data, alphas, scorer, n_splits=10): # Get number of voxels n_voxels = train_data.shape[1] # Set up ridge regression ridge = Ridge(fit_intercept=True, normalize=False, copy_X=True, tol=0.001) # Set up grid search grid = GridSearchCV(ridge, {'alpha': alphas}, iid=False, scoring=scorer, cv=KFold(n_splits=n_splits), refit=False, return_train_score=False) # Loop through voxels best_alphas, best_scores, all_scores = [], [], [] for voxel in np.arange(n_voxels): # Perform grid search over alphas for voxel grid.fit(train_model, train_data[:, voxel]); best_alphas.append(grid.best_params_['alpha']) best_scores.append(grid.best_score_) # Get all scores across folds split_scores = [] for split in np.arange(n_splits): split_score = grid.cv_results_[f'split{split}_test_score'] split_scores.append(split_score) all_scores.append(np.mean(split_scores, axis=0)) best_alphas = np.array(best_alphas) best_scores = np.array(best_scores) all_scores = np.column_stack(all_scores) assert (best_alphas.shape[0] == best_scores.shape[0] == all_scores.shape[1] == n_voxels) return best_alphas, best_scores, all_scores # Name guard for actually running encoding model analysis if __name__ == '__main__': # Load dictionary of input filenames and parameters with open('data/metadata.json') as f: metadata = json.load(f) # Create story and subject lists stories = ['black', 'forgot'] # Set ROIs, spaces, and hemispheres rois = ['EAC', 'AAC', 'TPOJ', 'PMC'] prefixes = [('no SRM', 'noSRM', 'noSRM'), ('no SRM (average)', 'noSRM', 'noSRM'), ('no SRM (within-subject)', 'noSRM', 'noSRM'), ('cPCA (k = 100)', 'parcel-mean_k-100_cPCA-train', 'parcel-mean_k-100_cPCA-test'), ('cPCA (k = 50)', 'parcel-mean_k-50_cPCA-train', 'parcel-mean_k-50_cPCA-test'), ('cPCA (k = 10)', 'parcel-mean_k-10_cPCA-train', 'parcel-mean_k-10_cPCA-test'), ('cSRM (k = 100)', 'parcel-mean_k-100_cSRM-train', 'parcel-mean_k-100_cSRM-test'), ('cSRM (k = 50)', 'parcel-mean_k-50_cSRM-train', 'parcel-mean_k-50_cSRM-test'), ('cSRM (k = 10)', 'parcel-mean_k-10_cSRM-train', 'parcel-mean_k-10_cSRM-test')] stories = ['black', 'forgot'] hemis = ['lh', 'rh'] # Set some parameters for encoding model delays = [2, 3, 4, 5] aggregation = 'average' story_train = 'all' alpha = 100 # Make custom correlation scorer correlation_scorer = make_scorer(array_correlation) # Populate results file if it already exists results_fn = f'data/encoding_{story_train}-story_avg_inv_results.npy' if exists(results_fn): results = np.load(results_fn, allow_pickle=True).item() else: results = {} # Loop through keys without replacing existing ones for story in stories: if story not in results: results[story] = {} if story_train == 'within': train_stories, test_stories = story, story elif story_train == 'across': test_stories = story train_stories = [st for st in stories if st is not test_story] elif story_train == 'all': test_stories = story train_stories = stories # By default just grab all subjects subject_list = check_keys(metadata[story]['data']) # Split models and load in data splits train_model_dict = split_models(metadata, stories=stories, subjects=None, half=1, delays=delays) test_model_dict = split_models(metadata, stories=stories, subjects=None, half=2, delays=delays) for roi in rois: if roi not in results[story]: results[story][roi] = {} for prefix in prefixes: if prefix[0] not in results[story][roi]: results[story][roi][prefix[0]] = {} # Load in split cSRM data for train and test train_dict = load_split_data(metadata, stories=stories, subjects=None, hemisphere=hemis, half=1, prefix=f'{roi}_' + prefix[1]) test_dict = load_split_data(metadata, stories=stories, subjects=None, hemisphere=hemis, half=2, prefix=f'{roi}_' + prefix[2]) for s in range(len(subject_list)): test_subjects = [subject_list[s]] test_subject = test_subjects[0] # Use leave-one-subject-out cross-validation (unless within-subject) if prefix[0] == 'no SRM (within-subject)': train_subjects = test_subjects else: train_subjects = [sub for sub in subject_list if sub is not test_subjects[0]] if test_subject not in results[story][roi][prefix[0]]: results[story][roi][prefix[0]][test_subject] = {} for hemi in hemis: if hemi not in results[story][roi][prefix[0]][test_subject]: results[story][roi][prefix[0]][test_subject][hemi] = {} # Aggregate data and model across subjects train_data, train_model = aggregate_subjects(train_dict, train_model_dict, train_stories, train_subjects, hemi=hemi, aggregation=aggregation) test_data, test_model = aggregate_subjects(test_dict, test_model_dict, test_stories, test_subjects, hemi=hemi, aggregation=aggregation) # Get the regional average as well if prefix[0] == 'no SRM (average)': train_data = np.expand_dims(np.mean(train_data, axis=1), 1) test_data = np.expand_dims(np.mean(test_data, axis=1), 1) # Declare ridge regression model ridge = Ridge(alpha=alpha, fit_intercept=True, normalize=False, copy_X=True, tol=0.001, solver='auto') # Fit training data ridge.fit(train_model, train_data) # Get coefficients of trained model coefficients = ridge.coef_ # Use trained model to predict response for test data predicted_data = ridge.predict(test_model) # Compute correlation between predicted and test response performance = array_correlation(predicted_data, test_data) results[story][roi][prefix[0]][test_subject][hemi]['encoding'] = performance print(f"Finished forwarding encoding analysis for " f"{story}, {roi}, {prefix[0]}, {test_subjects}, " f"performance = {np.mean(performance):.4f}") # Decoding via dot product between test samples and coefficients if prefix[0] != 'no SRM (average)': # Collapse coefficients across delays for decoding collapse_coef = np.mean(np.split(ridge.coef_, len(delays), axis=1), axis=0) collapse_test_model = np.mean(np.split(test_model, len(delays), axis=1), axis=0) predicted_model = Ridge(alpha=alpha, fit_intercept=False).fit(collapse_coef, test_data.T).coef_ raise accuracy = rank_accuracy(predicted_model, collapse_test_model) results[story][roi][prefix[0]][test_subject][hemi]['decoding'] = accuracy print(f"Finished decoding analysis for " f"{story}, {roi}, {prefix[0]}, {test_subjects}, " f"accuracy = {accuracy:.4f} ({rank})") accuracies.append(accuracy) np.save(results_fn, results)
[ "os.path.exists", "numpy.mean", "scipy.stats.rankdata", "scipy.spatial.distance.cdist", "sklearn.linear_model.Ridge", "numpy.column_stack", "sklearn.metrics.make_scorer", "brainiak.utils.utils.array_correlation", "numpy.array", "split_stories.split_models", "numpy.vstack", "split_stories.check...
[((2210, 2231), 'numpy.vstack', 'np.vstack', (['data_stack'], {}), '(data_stack)\n', (2219, 2231), True, 'import numpy as np\n'), ((2250, 2272), 'numpy.vstack', 'np.vstack', (['model_stack'], {}), '(model_stack)\n', (2259, 2272), True, 'import numpy as np\n'), ((2878, 2902), 'numpy.arange', 'np.arange', (['n_predictions'], {}), '(n_predictions)\n', (2887, 2902), True, 'import numpy as np\n'), ((3361, 3427), 'sklearn.linear_model.Ridge', 'Ridge', ([], {'fit_intercept': '(True)', 'normalize': '(False)', 'copy_X': '(True)', 'tol': '(0.001)'}), '(fit_intercept=True, normalize=False, copy_X=True, tol=0.001)\n', (3366, 3427), False, 'from sklearn.linear_model import Ridge\n'), ((3787, 3806), 'numpy.arange', 'np.arange', (['n_voxels'], {}), '(n_voxels)\n', (3796, 3806), True, 'import numpy as np\n'), ((4322, 4343), 'numpy.array', 'np.array', (['best_alphas'], {}), '(best_alphas)\n', (4330, 4343), True, 'import numpy as np\n'), ((4362, 4383), 'numpy.array', 'np.array', (['best_scores'], {}), '(best_scores)\n', (4370, 4383), True, 'import numpy as np\n'), ((4401, 4428), 'numpy.column_stack', 'np.column_stack', (['all_scores'], {}), '(all_scores)\n', (4416, 4428), True, 'import numpy as np\n'), ((5973, 6003), 'sklearn.metrics.make_scorer', 'make_scorer', (['array_correlation'], {}), '(array_correlation)\n', (5984, 6003), False, 'from sklearn.metrics import make_scorer\n'), ((6135, 6153), 'os.path.exists', 'exists', (['results_fn'], {}), '(results_fn)\n', (6141, 6153), False, 'from os.path import exists\n'), ((13275, 13303), 'numpy.save', 'np.save', (['results_fn', 'results'], {}), '(results_fn, results)\n', (13282, 13303), True, 'import numpy as np\n'), ((2719, 2768), 'scipy.spatial.distance.cdist', 'cdist', (['predicted_model', 'test_model', '"""correlation"""'], {}), "(predicted_model, test_model, 'correlation')\n", (2724, 2768), False, 'from scipy.spatial.distance import cdist\n'), ((3093, 3107), 'numpy.mean', 'np.mean', (['ranks'], {}), '(ranks)\n', (3100, 3107), True, 'import numpy as np\n'), ((4109, 4128), 'numpy.arange', 'np.arange', (['n_splits'], {}), '(n_splits)\n', (4118, 4128), True, 'import numpy as np\n'), ((4789, 4801), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4798, 4801), False, 'import json\n'), ((6808, 6843), 'split_stories.check_keys', 'check_keys', (["metadata[story]['data']"], {}), "(metadata[story]['data'])\n", (6818, 6843), False, 'from split_stories import check_keys, load_split_data, split_models\n'), ((6919, 6996), 'split_stories.split_models', 'split_models', (['metadata'], {'stories': 'stories', 'subjects': 'None', 'half': '(1)', 'delays': 'delays'}), '(metadata, stories=stories, subjects=None, half=1, delays=delays)\n', (6931, 6996), False, 'from split_stories import check_keys, load_split_data, split_models\n'), ((7103, 7180), 'split_stories.split_models', 'split_models', (['metadata'], {'stories': 'stories', 'subjects': 'None', 'half': '(2)', 'delays': 'delays'}), '(metadata, stories=stories, subjects=None, half=2, delays=delays)\n', (7115, 7180), False, 'from split_stories import check_keys, load_split_data, split_models\n'), ((3020, 3035), 'numpy.array', 'np.array', (['ranks'], {}), '(ranks)\n', (3028, 3035), True, 'import numpy as np\n'), ((3600, 3624), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'n_splits'}), '(n_splits=n_splits)\n', (3605, 3624), False, 'from sklearn.model_selection import GridSearchCV, KFold\n'), ((4272, 4301), 'numpy.mean', 'np.mean', (['split_scores'], {'axis': '(0)'}), '(split_scores, axis=0)\n', (4279, 4301), True, 'import numpy as np\n'), ((2925, 2954), 'scipy.stats.rankdata', 'rankdata', (['correlations[index]'], {}), '(correlations[index])\n', (2933, 2954), False, 'from scipy.stats import rankdata, zscore\n'), ((6173, 6211), 'numpy.load', 'np.load', (['results_fn'], {'allow_pickle': '(True)'}), '(results_fn, allow_pickle=True)\n', (6180, 6211), True, 'import numpy as np\n'), ((7609, 7726), 'split_stories.load_split_data', 'load_split_data', (['metadata'], {'stories': 'stories', 'subjects': 'None', 'hemisphere': 'hemis', 'half': '(1)', 'prefix': "(f'{roi}_' + prefix[1])"}), "(metadata, stories=stories, subjects=None, hemisphere=hemis,\n half=1, prefix=f'{roi}_' + prefix[1])\n", (7624, 7726), False, 'from split_stories import check_keys, load_split_data, split_models\n'), ((7841, 7958), 'split_stories.load_split_data', 'load_split_data', (['metadata'], {'stories': 'stories', 'subjects': 'None', 'hemisphere': 'hemis', 'half': '(2)', 'prefix': "(f'{roi}_' + prefix[2])"}), "(metadata, stories=stories, subjects=None, hemisphere=hemis,\n half=2, prefix=f'{roi}_' + prefix[2])\n", (7856, 7958), False, 'from split_stories import check_keys, load_split_data, split_models\n'), ((1918, 1944), 'numpy.mean', 'np.mean', (['data_list'], {'axis': '(0)'}), '(data_list, axis=0)\n', (1925, 1944), True, 'import numpy as np\n'), ((2043, 2063), 'numpy.vstack', 'np.vstack', (['data_list'], {}), '(data_list)\n', (2052, 2063), True, 'import numpy as np\n'), ((10641, 10740), 'sklearn.linear_model.Ridge', 'Ridge', ([], {'alpha': 'alpha', 'fit_intercept': '(True)', 'normalize': '(False)', 'copy_X': '(True)', 'tol': '(0.001)', 'solver': '"""auto"""'}), "(alpha=alpha, fit_intercept=True, normalize=False, copy_X=True, tol=\n 0.001, solver='auto')\n", (10646, 10740), False, 'from sklearn.linear_model import Ridge\n'), ((11293, 11337), 'brainiak.utils.utils.array_correlation', 'array_correlation', (['predicted_data', 'test_data'], {}), '(predicted_data, test_data)\n', (11310, 11337), False, 'from brainiak.utils.utils import array_correlation\n'), ((10253, 10280), 'numpy.mean', 'np.mean', (['train_data'], {'axis': '(1)'}), '(train_data, axis=1)\n', (10260, 10280), True, 'import numpy as np\n'), ((10412, 10438), 'numpy.mean', 'np.mean', (['test_data'], {'axis': '(1)'}), '(test_data, axis=1)\n', (10419, 10438), True, 'import numpy as np\n'), ((11748, 11768), 'numpy.mean', 'np.mean', (['performance'], {}), '(performance)\n', (11755, 11768), True, 'import numpy as np\n'), ((12483, 12522), 'sklearn.linear_model.Ridge', 'Ridge', ([], {'alpha': 'alpha', 'fit_intercept': '(False)'}), '(alpha=alpha, fit_intercept=False)\n', (12488, 12522), False, 'from sklearn.linear_model import Ridge\n')]
# -*- coding: utf-8 -*- """ Created on Wed Nov 17 01:04:26 2021 @author: <NAME> """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_iris iris = load_iris() data = iris.data[:,:2] iris2 = pd.read_csv("data/iris.data").to_numpy() data = iris2[:, :2] plt.scatter(data[:,0],data[:,1],c='black') plt.show() k = 3 max_iteration = 2 def Distance2Point(point1, point2): dis = sum((point1 - point2)**2)**0.5 return dis def KMean(data): centroids = {} for i in range(k): centroids[i] = data[i] classes = {} for iteration in range(max_iteration): classes = {} for classKey in range(k): classes[classKey] = [] for dataPoint in data: Distance = [] for centroid in centroids: dis = Distance2Point(dataPoint, centroids[centroid]) Distance.append(dis) minDis = min(Distance) minDisIndex = Distance.index(minDis) classes[minDisIndex].append(dataPoint) oldCentroid = dict(centroids) for classKey in classes: classData = classes[classKey] NewCentroid = np.mean(classData, axis = 0) centroids[classKey] = NewCentroid isFine = True for centroid in oldCentroid: oldCent = oldCentroid[centroid] curr = centroids[centroid] if np.sum((curr - oldCent)/oldCent * 100) > 0.001: isFine = False if isFine: break return centroids, classes data = iris2[:, :4] centroids, classes = KMean(data[:, :4]) fig = plt.figure(figsize = (15,15)) ax = fig.add_subplot(111, projection='3d')
[ "sklearn.datasets.load_iris", "numpy.mean", "pandas.read_csv", "numpy.sum", "matplotlib.pyplot.figure", "matplotlib.pyplot.scatter", "matplotlib.pyplot.show" ]
[((215, 226), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (224, 226), False, 'from sklearn.datasets import load_iris\n'), ((327, 373), 'matplotlib.pyplot.scatter', 'plt.scatter', (['data[:, 0]', 'data[:, 1]'], {'c': '"""black"""'}), "(data[:, 0], data[:, 1], c='black')\n", (338, 373), True, 'import matplotlib.pyplot as plt\n'), ((371, 381), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (379, 381), True, 'import matplotlib.pyplot as plt\n'), ((1759, 1787), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 15)'}), '(figsize=(15, 15))\n', (1769, 1787), True, 'import matplotlib.pyplot as plt\n'), ((262, 291), 'pandas.read_csv', 'pd.read_csv', (['"""data/iris.data"""'], {}), "('data/iris.data')\n", (273, 291), True, 'import pandas as pd\n'), ((1280, 1306), 'numpy.mean', 'np.mean', (['classData'], {'axis': '(0)'}), '(classData, axis=0)\n', (1287, 1306), True, 'import numpy as np\n'), ((1538, 1578), 'numpy.sum', 'np.sum', (['((curr - oldCent) / oldCent * 100)'], {}), '((curr - oldCent) / oldCent * 100)\n', (1544, 1578), True, 'import numpy as np\n')]
import matplotlib.colors as colors import matplotlib.pyplot as plt import numpy as np import statsmodels.api as sm from matplotlib.gridspec import GridSpec from palettable.colorbrewer.diverging import RdBu_5 as PlotColor from .plot_base import PlotBase # Plot differences between rasters and show histogram of the differences class AreaDifferences(PlotBase): TITLE = '{0} differences' HIST_TEXT = 'Median (abs): {:4.2f}\n' \ 'NMAD : {:4.2f}\n' \ '68.3% (abs): {:4.2f}\n' \ '95% (abs): {:4.2f}' HIST_BIN_WIDTH = 0.01 BOX_PLOT_TEXT = '{0:8}: {1:6.3f}' BOX_PLOT_WHISKERS = [5, 95] OUTPUT_FILE_NAME = 'elevation_differences.png' COLORMAP = PlotColor.mpl_colormap def add_hist_stats(self, ax): box_text = self.HIST_TEXT.format( self.data.mad.percentile(50, absolute=True), self.data.mad.normalized(), self.data.mad.standard_deviation(1, absolute=True), self.data.mad.standard_deviation(2, absolute=True), ) self.add_to_legend( ax, box_text, loc='upper left', handlelength=0, handletextpad=0, ) def add_box_plot_stats(self, ax, box_plot_data, data): text = [ self.BOX_PLOT_TEXT.format( 'Median', box_plot_data['medians'][0].get_ydata()[0] ), self.BOX_PLOT_TEXT.format('Mean', data.mean()), self.BOX_PLOT_TEXT.format('Nmad', self.data.mad.normalized()), self.BOX_PLOT_TEXT.format('Std', data.std()), ] self.add_to_legend( ax, '\n'.join(text), handlelength=0, handletextpad=0 ) # TODO - Zoom into each graph to only show values within the 95th # percentile def plot(self): self.print_status() figure = plt.figure( figsize=(17, 14), dpi=150, constrained_layout=False, ) grid_opts = dict(figure=figure, height_ratios=[3, 1]) difference = self.data.band_values if self.data_description == 'Elevation': grid_spec = GridSpec( nrows=2, ncols=3, width_ratios=[3, 2, 2], **grid_opts ) bins = np.arange( difference.min(), difference.max() + self.HIST_BIN_WIDTH, self.HIST_BIN_WIDTH ) bounds = dict( norm=colors.BoundaryNorm( boundaries=bins, ncolors=self.COLORMAP.N, ) ) else: grid_spec = GridSpec( nrows=2, ncols=2, width_ratios=[3, 2], **grid_opts ) bounds = dict() ax1 = figure.add_subplot(grid_spec[0, :]) diff_plot = ax1.imshow( difference, cmap=self.COLORMAP, alpha=0.8, extent=self.sfm.extent, **bounds ) ax1.set_title(self.TITLE.format(self.data_description)) self.insert_colorbar( ax1, diff_plot, self.SCALE_BAR_LABEL[self.data_description] ) difference = difference[np.isfinite(difference)].compressed() # Reset bins to entire range of values for Histogram bins = np.arange( np.nanmin(difference), np.nanmax(difference), self.HIST_BIN_WIDTH ) ax2 = figure.add_subplot(grid_spec[1, 0]) ax2.hist(difference, bins=bins) ax2.set_xlabel(self.SCALE_BAR_LABEL[self.data_description]) ax2.set_ylabel("Count $(10^5)$") ax2.ticklabel_format(style='sci', axis='y', scilimits=(4, 4)) ax2.yaxis.get_offset_text().set_visible(False) if self.data_description == 'Elevation': ax2.set_title('Relative Elevation Differences') ax3 = figure.add_subplot(grid_spec[1, 1]) box = ax3.boxplot( difference, sym='k+', whis=self.BOX_PLOT_WHISKERS, positions=[0.1] ) ax3.set_xlim([0, .35]) ax3.tick_params( axis='x', which='both', bottom=False, top=False, labelbottom=False ) ax3.set_ylabel(self.SCALE_BAR_LABEL[self.data_description]) self.add_box_plot_stats(ax3, box, difference) if self.data_description == 'Elevation': ax3.set_title('Relative Elevation Differences') if self.data_description == 'Elevation': ax4 = figure.add_subplot(grid_spec[1, 2]) probplot = sm.ProbPlot(difference) probplot.qqplot(ax=ax4, line='s') ax4.get_lines()[0].set(markersize=1) ax4.get_lines()[1].set(color='black', dashes=[4, 1]) ax4.set_title('Normal Q-Q Plot') plt.savefig(self.output_file) return figure
[ "matplotlib.pyplot.savefig", "statsmodels.api.ProbPlot", "matplotlib.pyplot.figure", "matplotlib.gridspec.GridSpec", "numpy.isfinite", "numpy.nanmax", "numpy.nanmin", "matplotlib.colors.BoundaryNorm" ]
[((1852, 1915), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(17, 14)', 'dpi': '(150)', 'constrained_layout': '(False)'}), '(figsize=(17, 14), dpi=150, constrained_layout=False)\n', (1862, 1915), True, 'import matplotlib.pyplot as plt\n'), ((4781, 4810), 'matplotlib.pyplot.savefig', 'plt.savefig', (['self.output_file'], {}), '(self.output_file)\n', (4792, 4810), True, 'import matplotlib.pyplot as plt\n'), ((2143, 2206), 'matplotlib.gridspec.GridSpec', 'GridSpec', ([], {'nrows': '(2)', 'ncols': '(3)', 'width_ratios': '[3, 2, 2]'}), '(nrows=2, ncols=3, width_ratios=[3, 2, 2], **grid_opts)\n', (2151, 2206), False, 'from matplotlib.gridspec import GridSpec\n'), ((2608, 2668), 'matplotlib.gridspec.GridSpec', 'GridSpec', ([], {'nrows': '(2)', 'ncols': '(2)', 'width_ratios': '[3, 2]'}), '(nrows=2, ncols=2, width_ratios=[3, 2], **grid_opts)\n', (2616, 2668), False, 'from matplotlib.gridspec import GridSpec\n'), ((3303, 3324), 'numpy.nanmin', 'np.nanmin', (['difference'], {}), '(difference)\n', (3312, 3324), True, 'import numpy as np\n'), ((3338, 3359), 'numpy.nanmax', 'np.nanmax', (['difference'], {}), '(difference)\n', (3347, 3359), True, 'import numpy as np\n'), ((4543, 4566), 'statsmodels.api.ProbPlot', 'sm.ProbPlot', (['difference'], {}), '(difference)\n', (4554, 4566), True, 'import statsmodels.api as sm\n'), ((2455, 2516), 'matplotlib.colors.BoundaryNorm', 'colors.BoundaryNorm', ([], {'boundaries': 'bins', 'ncolors': 'self.COLORMAP.N'}), '(boundaries=bins, ncolors=self.COLORMAP.N)\n', (2474, 2516), True, 'import matplotlib.colors as colors\n'), ((3165, 3188), 'numpy.isfinite', 'np.isfinite', (['difference'], {}), '(difference)\n', (3176, 3188), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np import run import os from sklearn.preprocessing import OneHotEncoder import sys import h5py import scipy sys.path.append("../src") from convolutional_VAE import ConVae from data_loader import * print("PID:", os.getpid()) os.environ["CUDA_VISIBLE_DEVICES"] = "0" use_vgg = False use_dd = True data = "simulated" if "vgg" in data: use_vgg = True if data == "simulated": x_train, x_test, y_test = load_simulated("128") if use_dd: dd_train, dd_test = load_simulated_hist("128") elif data == "cleanevent": X_sim = np.load("../data/simulated/images/pr_train_simulated.npy") y_sim = np.load("../data/simulated/targets/train_targets.npy") x_train, x_test, y_test = load_clean_event("128") where_junk = y_test == 2 n_junk_to_steal = 200 which_to_steal = np.random.randint(0, where_junk.shape[0], size=n_junk_to_steal) x_train = np.concatenate([x_train, X_sim], axis=0) X_sim = np.concatenate([X_sim, x_test[which_to_steal]], axis=0) y_sim = np.concatenate([y_sim, y_test[which_to_steal].argmax(1)], axis=0) oh = OneHotEncoder(sparse=False) y_sim = oh.fit_transform(y_sim.reshape(-1, 1)) elif data == "vgg_simulated": x_train, target_x_train, x_test, y_test = load_vgg_simulated("128") n_layers = 4 filter_architecture = [32] * 2 + [64] * 2 + [128] * 1 kernel_arcitecture = [5, 5, 3, 3] strides_architecture = [1, 2, 1, 2] pooling_architecture = [0, 0, 0, 0] epochs = 5000 latent_dim = 3 batch_size = 200 mode_config = { "simulated_mode": False, "restore_mode": False, "use_vgg": use_vgg, "use_dd": use_dd, "include_KL": False, "include_MMD": False, "include_KM": True, } clustering_config = { "n_clusters": 2, "alpha": 1, "delta": 0.01, "update_interval": 140, "pretrain_epochs": 2, "pretrain_simulated": False, "self_supervise": False, } cvae = ConVae( n_layers, filter_architecture, kernel_arcitecture, strides_architecture, pooling_architecture, latent_dim, x_train, beta=0.8, mode_config=mode_config, clustering_config=clustering_config, labelled_data=[x_test, y_test], ) if use_vgg: cvae.target_images = target_x_train if use_dd: cvae.dd_targets = dd_train cvae.lmbd = 10000 cvae.dd_dense = 2 graph_kwds = {"activation": "lrelu"} cvae.compile_model(graph_kwds=graph_kwds) opt = tf.train.AdamOptimizer opt_args = [1e-4] opt_kwds = {"beta1": 0.4} cvae.compute_gradients(opt, opt_args, opt_kwds) sess = tf.InteractiveSession() with open("run.py", "w") as fo: fo.write("run={}".format(run.run + 1)) lx, lz = cvae.train( sess, epochs, batch_size, "../drawing", "../models", earlystopping=True, run=run.run )
[ "tensorflow.InteractiveSession", "convolutional_VAE.ConVae", "sklearn.preprocessing.OneHotEncoder", "numpy.random.randint", "os.getpid", "numpy.concatenate", "numpy.load", "sys.path.append" ]
[((151, 176), 'sys.path.append', 'sys.path.append', (['"""../src"""'], {}), "('../src')\n", (166, 176), False, 'import sys\n'), ((1915, 2154), 'convolutional_VAE.ConVae', 'ConVae', (['n_layers', 'filter_architecture', 'kernel_arcitecture', 'strides_architecture', 'pooling_architecture', 'latent_dim', 'x_train'], {'beta': '(0.8)', 'mode_config': 'mode_config', 'clustering_config': 'clustering_config', 'labelled_data': '[x_test, y_test]'}), '(n_layers, filter_architecture, kernel_arcitecture,\n strides_architecture, pooling_architecture, latent_dim, x_train, beta=\n 0.8, mode_config=mode_config, clustering_config=clustering_config,\n labelled_data=[x_test, y_test])\n', (1921, 2154), False, 'from convolutional_VAE import ConVae\n'), ((2539, 2562), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (2560, 2562), True, 'import tensorflow as tf\n'), ((256, 267), 'os.getpid', 'os.getpid', ([], {}), '()\n', (265, 267), False, 'import os\n'), ((582, 640), 'numpy.load', 'np.load', (['"""../data/simulated/images/pr_train_simulated.npy"""'], {}), "('../data/simulated/images/pr_train_simulated.npy')\n", (589, 640), True, 'import numpy as np\n'), ((653, 707), 'numpy.load', 'np.load', (['"""../data/simulated/targets/train_targets.npy"""'], {}), "('../data/simulated/targets/train_targets.npy')\n", (660, 707), True, 'import numpy as np\n'), ((838, 901), 'numpy.random.randint', 'np.random.randint', (['(0)', 'where_junk.shape[0]'], {'size': 'n_junk_to_steal'}), '(0, where_junk.shape[0], size=n_junk_to_steal)\n', (855, 901), True, 'import numpy as np\n'), ((916, 956), 'numpy.concatenate', 'np.concatenate', (['[x_train, X_sim]'], {'axis': '(0)'}), '([x_train, X_sim], axis=0)\n', (930, 956), True, 'import numpy as np\n'), ((969, 1024), 'numpy.concatenate', 'np.concatenate', (['[X_sim, x_test[which_to_steal]]'], {'axis': '(0)'}), '([X_sim, x_test[which_to_steal]], axis=0)\n', (983, 1024), True, 'import numpy as np\n'), ((1112, 1139), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'sparse': '(False)'}), '(sparse=False)\n', (1125, 1139), False, 'from sklearn.preprocessing import OneHotEncoder\n')]
from music21 import * from collections import defaultdict import sys import numpy as np import pickle def get_midi(midi_file_path): midi = converter.parse(midi_file_path) return midi def preview_midi(midi): s2 = instrument.partitionByInstrument(midi) for idx, part in enumerate(s2): print(f"part_id: {idx}, part: {part}") def get_pitches(midi, part_id=None): """Returns a list of pitches from input midi data Args: midi (midi): midi type from get_midi() Returns: pitch: pitches """ try: # file has instrument parts s2 = instrument.partitionByInstrument(midi) print(len(s2)) if part_id is not None: notes = s2.parts[part_id].recurse() pitches = [c.pitches for c in notes] pitch_arr = np.array(pitches)[None] ps_arr = np.array([pitch.ps for pitch in pitches]) else: pitch_arr = [] ps_arr = [] for part in s2: notes = part.recurse() pitches = [c.pitches for c in notes] pss = [pitch.ps for pitch in pitches] pitch_arr.append(pitches) ps_arr.append(pss) pitch_arr = np.array(pitch_arr) ps_arr = np.array(ps_arr) except: # file has notes in a flat structure notes = midi.flat.notes pitch_arr = np.array([c.pitches for c in notes]) ps_arr = np.array([pitch.ps for pitch in pitches]) return pitch_arr, ps_arr def get_dynamics(midi): pass # Returns <filename> as a list of (pitch, relative offset, duration) tuples def read_file_as_pitch_offset_duration(filename, dechord=True): score = midi.translate.midiFilePathToStream(filename, quarterLengthDivisors=(32,)) events = score.flat processed = [] print("processing ", filename, "...") for i in range(len(events)): elt = events[i] if isinstance(elt, chord.Chord): offset = elt.offset duration = elt.quarterLength if dechord==True: processed.append((elt[0].pitch.ps, offset, duration)) else: for n in elt: processed.append((n.pitch.ps, offset, duration)) if isinstance(elt, note.Rest) or isinstance(elt, note.Note): pitch = 0 if isinstance(elt, note.Rest) else elt.pitch.midi offset = elt.offset duration = elt.quarterLength processed.append((pitch, offset, duration)) processed.sort(key = lambda x: (x[1], x[0])) prev_abs_offset = 0 for i in range(len(processed)): curr_abs_offset = processed[i][1] processed[i] = (processed[i][0], curr_abs_offset - prev_abs_offset, processed[i][2]) prev_abs_offset = curr_abs_offset return np.array(processed) def output_pitch_offset_duration_as_midi_file(arr, output_file): input_len = arr.shape[0] pitches, offsets, durations = arr[:,0], arr[:,1], arr[:,2] # pitches = pitches.astype(np.int32).tolist() total_offset = 0 midi_stream = stream.Stream() for idx in range(arr.shape[0]): if pitches[idx]!=0.: tmp_note = note.Note() tmp_note.pitch.ps = pitches[idx] tmp_note.duration.quarterLength = durations[idx] total_offset += offsets[idx] tmp_note.offset = total_offset # if tmp_note.pitch.ps!=44.: # midi_stream.insert(tmp_note) midi_stream.insert(tmp_note) else: total_offset += offsets[idx] midi_stream.write('midi', fp=output_file) if __name__ == "__main__": x = read_file_as_pitch_offset_duration(sys.argv[1], dechord=False) print(x.shape) output_pitch_offset_duration_as_midi_file(x, "test.mid")
[ "numpy.array" ]
[((2833, 2852), 'numpy.array', 'np.array', (['processed'], {}), '(processed)\n', (2841, 2852), True, 'import numpy as np\n'), ((863, 904), 'numpy.array', 'np.array', (['[pitch.ps for pitch in pitches]'], {}), '([pitch.ps for pitch in pitches])\n', (871, 904), True, 'import numpy as np\n'), ((1245, 1264), 'numpy.array', 'np.array', (['pitch_arr'], {}), '(pitch_arr)\n', (1253, 1264), True, 'import numpy as np\n'), ((1286, 1302), 'numpy.array', 'np.array', (['ps_arr'], {}), '(ps_arr)\n', (1294, 1302), True, 'import numpy as np\n'), ((1404, 1440), 'numpy.array', 'np.array', (['[c.pitches for c in notes]'], {}), '([c.pitches for c in notes])\n', (1412, 1440), True, 'import numpy as np\n'), ((1458, 1499), 'numpy.array', 'np.array', (['[pitch.ps for pitch in pitches]'], {}), '([pitch.ps for pitch in pitches])\n', (1466, 1499), True, 'import numpy as np\n'), ((818, 835), 'numpy.array', 'np.array', (['pitches'], {}), '(pitches)\n', (826, 835), True, 'import numpy as np\n')]
#!/usr/bin/python # -*- encoding: utf-8 -*- import math import torch from torch.optim.lr_scheduler import _LRScheduler, LambdaLR import numpy as np class WarmupExpLrScheduler(_LRScheduler): def __init__( self, optimizer, power, step_interval=1, warmup_iter=500, warmup_ratio=5e-4, warmup='exp', last_epoch=-1, ): self.power = power self.step_interval = step_interval self.warmup_iter = warmup_iter self.warmup_ratio = warmup_ratio self.warmup = warmup super(WarmupExpLrScheduler, self).__init__(optimizer, last_epoch) def get_lr(self): ratio = self.get_lr_ratio() lrs = [ratio * lr for lr in self.base_lrs] return lrs def get_lr_ratio(self): if self.last_epoch < self.warmup_iter: ratio = self.get_warmup_ratio() else: real_iter = self.last_epoch - self.warmup_iter ratio = self.power ** (real_iter // self.step_interval) return ratio def get_warmup_ratio(self): assert self.warmup in ('linear', 'exp') alpha = self.last_epoch / self.warmup_iter if self.warmup == 'linear': ratio = self.warmup_ratio + (1 - self.warmup_ratio) * alpha elif self.warmup == 'exp': ratio = self.warmup_ratio ** (1. - alpha) return ratio class WarmupPolyLrScheduler(_LRScheduler): def __init__( self, optimizer, power, max_iter, warmup_iter, warmup_ratio=5e-4, warmup='exp', last_epoch=-1, ): self.power = power self.max_iter = max_iter self.warmup_iter = warmup_iter self.warmup_ratio = warmup_ratio self.warmup = warmup super(WarmupPolyLrScheduler, self).__init__(optimizer, last_epoch) def get_lr(self): ratio = self.get_lr_ratio() lrs = [ratio * lr for lr in self.base_lrs] return lrs def get_lr_ratio(self): if self.last_epoch < self.warmup_iter: ratio = self.get_warmup_ratio() else: real_iter = self.last_epoch - self.warmup_iter real_max_iter = self.max_iter - self.warmup_iter alpha = real_iter / real_max_iter ratio = (1 - alpha) ** self.power return ratio def get_warmup_ratio(self): assert self.warmup in ('linear', 'exp') alpha = self.last_epoch / self.warmup_iter if self.warmup == 'linear': ratio = self.warmup_ratio + (1 - self.warmup_ratio) * alpha elif self.warmup == 'exp': ratio = self.warmup_ratio ** (1. - alpha) return ratio class WarmupCosineLrScheduler(_LRScheduler): ''' This is different from official definition, this is implemented according to the paper of fix-match ''' def __init__( self, optimizer, max_iter, warmup_iter, warmup_ratio=5e-4, warmup='exp', last_epoch=-1, ): self.max_iter = max_iter self.warmup_iter = warmup_iter self.warmup_ratio = warmup_ratio self.warmup = warmup super(WarmupCosineLrScheduler, self).__init__(optimizer, last_epoch) def get_lr(self): ratio = self.get_lr_ratio() lrs = [ratio * lr for lr in self.base_lrs] return lrs def get_lr_ratio(self): if self.last_epoch < self.warmup_iter: ratio = self.get_warmup_ratio() else: real_iter = self.last_epoch - self.warmup_iter real_max_iter = self.max_iter - self.warmup_iter ratio = np.cos((7 * np.pi * real_iter) / (16 * real_max_iter)) return ratio def get_warmup_ratio(self): assert self.warmup in ('linear', 'exp') alpha = self.last_epoch / self.warmup_iter if self.warmup == 'linear': ratio = self.warmup_ratio + (1 - self.warmup_ratio) * alpha elif self.warmup == 'exp': ratio = self.warmup_ratio ** (1. - alpha) return ratio # from Fixmatch-pytorch def get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=7./16., last_epoch=-1): def _lr_lambda(current_step): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) no_progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps)) # return max(0., math.cos(math.pi * num_cycles * no_progress)) return max(0., (math.cos(math.pi * num_cycles * no_progress) + 1) * 0.5) return LambdaLR(optimizer, _lr_lambda, last_epoch) if __name__ == "__main__": model = torch.nn.Conv2d(3, 16, 3, 1, 1) optim = torch.optim.SGD(model.parameters(), lr=1e-3) max_iter = 20000 # lr_scheduler = WarmupCosineLrScheduler(optim, max_iter, 0) lr_scheduler = get_cosine_schedule_with_warmup( optim, 0, max_iter) lrs = [] for _ in range(max_iter): lr = lr_scheduler.get_lr()[0] print(lr) lrs.append(lr) lr_scheduler.step() import matplotlib import matplotlib.pyplot as plt import numpy as np lrs = np.array(lrs) n_lrs = len(lrs) plt.plot(np.arange(n_lrs), lrs) plt.title('3') plt.grid() plt.show()
[ "matplotlib.pyplot.grid", "torch.optim.lr_scheduler.LambdaLR", "torch.nn.Conv2d", "math.cos", "numpy.array", "numpy.cos", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.show" ]
[((4923, 4966), 'torch.optim.lr_scheduler.LambdaLR', 'LambdaLR', (['optimizer', '_lr_lambda', 'last_epoch'], {}), '(optimizer, _lr_lambda, last_epoch)\n', (4931, 4966), False, 'from torch.optim.lr_scheduler import _LRScheduler, LambdaLR\n'), ((5007, 5038), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['(3)', '(16)', '(3)', '(1)', '(1)'], {}), '(3, 16, 3, 1, 1)\n', (5022, 5038), False, 'import torch\n'), ((5505, 5518), 'numpy.array', 'np.array', (['lrs'], {}), '(lrs)\n', (5513, 5518), True, 'import numpy as np\n'), ((5580, 5594), 'matplotlib.pyplot.title', 'plt.title', (['"""3"""'], {}), "('3')\n", (5589, 5594), True, 'import matplotlib.pyplot as plt\n'), ((5599, 5609), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (5607, 5609), True, 'import matplotlib.pyplot as plt\n'), ((5614, 5624), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5622, 5624), True, 'import matplotlib.pyplot as plt\n'), ((5553, 5569), 'numpy.arange', 'np.arange', (['n_lrs'], {}), '(n_lrs)\n', (5562, 5569), True, 'import numpy as np\n'), ((3775, 3827), 'numpy.cos', 'np.cos', (['(7 * np.pi * real_iter / (16 * real_max_iter))'], {}), '(7 * np.pi * real_iter / (16 * real_max_iter))\n', (3781, 3827), True, 'import numpy as np\n'), ((4854, 4898), 'math.cos', 'math.cos', (['(math.pi * num_cycles * no_progress)'], {}), '(math.pi * num_cycles * no_progress)\n', (4862, 4898), False, 'import math\n')]
import matplotlib.pyplot as plt import pandas as pd import numpy as np import re plt.rcParams['pdf.fonttype'] = 42 from utility import * DATASET_LIST = ['wikivot', 'referendum', 'slashdot', 'wikicon'] + ['p2pgnutella31', 'youtube', 'roadnetCA', 'fb-artist'] Density = {'p2pgnutella31':2.3630204838142714, 'youtube':2.632522975795011, 'roadnetCA':1.4077949080147323, 'fb-artist':16.21906364446204} # edge density, required by computation of modularity score PCA_LIST = ['Type1', 'Type2', 'Type3', 'Type4'] def plot_q_Task(fname, qs, MODE='adj', ERR=False): df = pd.read_csv('{}.csv'.format(fname)) fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(6,3), constrained_layout=True) x1, x2 = df[df["algo"]=='RSVD'], df[df["algo"]=='RSum'] if MODE=='adj': c, ctitle, otitle, plot_baseline = "R", "$R(\hat{u})$", "polarity", True else: c, ctitle, otitle, plot_baseline = "eigval", "$\hat{u}^TA\hat{u}$", "modularity", False for j,dname in enumerate(DATASET_LIST): tx1, tx2 = x1[x1["dataset"]==dname], x2[x2["dataset"]==dname] if len(tx1)==0: continue rs1, rs2, re1, re2, os1, os2 = [],[],[],[],[],[] for q in qs: rs1 += [tx1[tx1["q"]==q][c].mean()] rs2 += [tx2[tx2["q"]==q][c].mean()] re1 += [tx1[tx1["q"]==q][c].std()] re2 += [tx2[tx2["q"]==q][c].std()] o1, o2 = tx1[tx1["q"]==q]["obj"].mean(), tx2[tx2["q"]==q]["obj"].mean() if MODE=='mod': o1, o2 = o1/(4*Density[dname]), o2/(4*Density[dname]) os1 += [o1] os2 += [o2] if ERR: axs[0].errorbar(qs, rs1, yerr=re1, label=dname, ls='-', color='C{}'.format(j)) axs[0].errorbar(qs, rs2, yerr=re2, ls='-.', color='C{}'.format(j)) else: axs[0].plot(qs, rs1, label=dname, ls='-', color='C{}'.format(j)) axs[0].plot(qs, rs2, ls='-.', color='C{}'.format(j)) axs[1].plot(qs, os1, label=dname, ls='-', color='C{}'.format(j)) axs[1].plot(qs, os2, ls='-.', color='C{}'.format(j)) # baseline scipy if plot_baseline: tx0 = df[(df["algo"]=='eigsh')&(df["dataset"]==dname)] o0 = tx0["obj"].mean() axs[1].hlines(o0, 1, qs[-1], label='Lanczos', ls='dotted', color='C{}'.format(j), linewidth=1) axs[0].set_title(ctitle) axs[0].set_xlabel("$q$") axs[1].set_title(otitle) axs[1].set_xlabel("$q$") plt.savefig('{}.pdf'.format(fname), bbox_inches='tight') def plot_d_Task(fname, ds, MODE='adj', ERR=False): df = pd.read_csv('{}.csv'.format(fname)) fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(6,3), constrained_layout=True) x1, x2 = df[df["algo"]=='RSVD'], df[df["algo"]=='RSum'] if MODE=='adj': c, ctitle, otitle, plot_baseline = "R", "$R(\hat{u})$", "polarity", True else: c, ctitle, otitle, plot_baseline = "eigval", "$\hat{u}^TA\hat{u}$", "modularity", False for j,dname in enumerate(DATASET_LIST): tx1, tx2 = x1[x1["dataset"]==dname], x2[x2["dataset"]==dname] if len(tx1)==0: continue rs1, rs2, re1, re2, os1, os2 = [],[],[],[],[],[] for d in ds: rs1 += [tx1[tx1["d"]==d][c].mean()] rs2 += [tx2[tx2["d"]==d][c].mean()] re1 += [tx1[tx1["d"]==d][c].std()] re2 += [tx2[tx2["d"]==d][c].std()] o1, o2 = tx1[tx1["d"]==d]["obj"].mean(), tx2[tx2["d"]==d]["obj"].mean() if MODE=='mod': o1, o2 = o1/(4*Density[dname]), o2/(4*Density[dname]) os1 += [o1] os2 += [o2] if ERR: axs[0].errorbar(ds, rs1, yerr=re1, label=dname, ls='-', color='C{}'.format(j)) axs[0].errorbar(ds, rs2, yerr=re2, ls='-.', color='C{}'.format(j)) else: axs[0].plot(ds, rs1, label=dname, ls='-', color='C{}'.format(j)) axs[0].plot(ds, rs2, ls='-.', color='C{}'.format(j)) axs[1].plot(ds, os1, label=dname, ls='-', color='C{}'.format(j)) axs[1].plot(ds, os2, ls='-.', color='C{}'.format(j)) # baseline scipy if plot_baseline: tx0 = df[(df["algo"]=='eigsh')&(df["dataset"]==dname)] o0 = tx0["obj"].mean() axs[1].hlines(o0, 1, ds[-1], label='Lanczos', ls='dotted', color='C{}'.format(j), linewidth=1) axs[0].set_title(ctitle) axs[0].set_xlabel("$d$") axs[1].set_title(otitle) axs[1].set_xlabel("$d$") plt.savefig('{}.pdf'.format(fname), bbox_inches='tight') def plot_d_q_Task(fdname, fqname, oname, ds, qs, MODE='adj'): df1, df2 = pd.read_csv('{}.csv'.format(fdname)), pd.read_csv('{}.csv'.format(fqname)) fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(6,2.5), constrained_layout=True) x11, x12, x21, x22 = df1[df1["algo"]=='RSVD'], df1[df1["algo"]=='RSum'], df2[df2["algo"]=='RSVD'], df2[df2["algo"]=='RSum'] if MODE=='adj': c, otitle = "obj", "polarity" elif MODE=='mod': c, otitle = "obj", "modularity" else: c, otitle = "eigval", "$R(\hat{u})$" # plot d for j,dname in enumerate(DATASET_LIST): tx1, tx2 = x11[x11["dataset"]==dname], x12[x12["dataset"]==dname] if len(tx1)==0: continue rs1, rs2 = [],[] for d in ds: r1, r2 = tx1[tx1["d"]==d][c].mean(), tx2[tx2["d"]==d][c].mean() if MODE=='mod': r1, r2 = r1/(4*Density[dname]), r2/(4*Density[dname]) rs1 += [r1] rs2 += [r2] axs[0].plot(ds, rs1, label=dname, ls='-', color='C{}'.format(j)) axs[0].plot(ds, rs2, ls='-.', color='C{}'.format(j)) # plot q for j,dname in enumerate(DATASET_LIST): tx1, tx2 = x21[x21["dataset"]==dname], x22[x22["dataset"]==dname] if len(tx1)==0: continue rs1, rs2 = [],[] for q in qs: r1, r2 = tx1[tx1["q"]==q][c].mean(), tx2[tx2["q"]==q][c].mean() if MODE=='mod': r1, r2 = r1/(4*Density[dname]), r2/(4*Density[dname]) rs1 += [r1] rs2 += [r2] axs[1].plot(qs, rs1, label=dname, ls='-', color='C{}'.format(j)) axs[1].plot(qs, rs2, ls='-.', color='C{}'.format(j)) axs[0].set_ylabel(otitle) axs[0].set_xlabel("$d$") axs[1].set_ylabel(otitle) axs[1].set_xlabel("$q$") plt.savefig('{}.pdf'.format(oname), bbox_inches='tight') def plot_q_PCA(fname, qs, ERR=False): df = pd.read_csv('{}.csv'.format(fname)) fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(6,2.5), constrained_layout=True) x1, x2 = df[df["algo"]=='RSVD'], df[df["algo"]=='RSum'] for j,dname in enumerate(PCA_LIST): tx1, tx2 = x1[x1["dataset"]==dname], x2[x2["dataset"]==dname] if len(tx1)==0: continue tx0 = df[(df["algo"]=='eigsh')&(df["dataset"]==dname)] t0 = tx0["time"].mean() rs1, rs2, re1, re2, ts1, ts2 = [],[],[],[],[],[] for q in qs: rs1 += [tx1[tx1["q"]==q]["R"].mean()] rs2 += [tx2[tx2["q"]==q]["R"].mean()] re1 += [tx1[tx1["q"]==q]["R"].std()] re2 += [tx2[tx2["q"]==q]["R"].std()] ts1 += [t0/tx1[tx1["q"]==q]["time"].mean()] ts2 += [t0/tx2[tx2["q"]==q]["time"].mean()] if ERR: axs[0].errorbar(qs, rs1, yerr=re1, label=dname, ls='-', color='C{}'.format(j)) #axs[0].errorbar(qs, rs2, yerr=re2, ls='-.', color='C{}'.format(j)) else: axs[0].plot(qs, rs1, label=dname, ls='-', color='C{}'.format(j)) #axs[0].plot(qs, rs2, ls='-.', color='C{}'.format(j)) axs[1].plot(qs, ts1, ls='-', color='C{}'.format(j)) #axs[1].plot(qs, ts2, ls='-.', color='C{}'.format(j)) axs[0].set_ylabel("$R(\hat{u})$") axs[0].set_xlabel("$q$") axs[1].set_ylabel("Speedup ratio") axs[1].set_xlabel("$q$") axs[1].hlines(1, 1, qs[-1], ls='dotted', color='C9', linewidth=1) plt.savefig('{}.pdf'.format(fname), bbox_inches='tight') def plot_d_PCA(fname, ds, ERR=False): df = pd.read_csv('{}.csv'.format(fname)) fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(6,2.5), constrained_layout=True) x1, x2 = df[df["algo"]=='RSVD'], df[df["algo"]=='RSum'] for j,dname in enumerate(PCA_LIST): tx1, tx2 = x1[x1["dataset"]==dname], x2[x2["dataset"]==dname] if len(tx1)==0: continue tx0 = df[(df["algo"]=='eigsh')&(df["dataset"]==dname)] t0 = tx0["time"].mean() rs1, rs2, re1, re2, ts1, ts2 = [],[],[],[],[],[] for d in ds: rs1 += [tx1[tx1["d"]==d]["R"].mean()] rs2 += [tx2[tx2["d"]==d]["R"].mean()] re1 += [tx1[tx1["d"]==d]["R"].std()] re2 += [tx2[tx2["d"]==d]["R"].std()] ts1 += [t0/tx1[tx1["d"]==d]["time"].mean()] ts2 += [t0/tx2[tx2["d"]==d]["time"].mean()] if ERR: axs[0].errorbar(ds, rs1, yerr=re1, label=dname, ls='-', color='C{}'.format(j)) #axs[0].errorbar(ds, rs2, yerr=re2, ls='-.', color='C{}'.format(j)) else: axs[0].plot(ds, rs1, label=dname, ls='-', color='C{}'.format(j)) #axs[0].plot(ds, rs2, ls='-.', color='C{}'.format(j)) axs[1].plot(ds, ts1, ls='-', color='C{}'.format(j)) #axs[1].plot(ds, ts2, ls='-.', color='C{}'.format(j)) axs[0].set_ylabel("$R(\hat{u})$") axs[0].set_xlabel("$d$") axs[1].set_ylabel("Speedup ratio") axs[1].set_xlabel("$d$") axs[1].hlines(1, 1, ds[-1], ls='dotted', color='C9', linewidth=1) plt.savefig('{}.pdf'.format(fname), bbox_inches='tight') def plot_SyntheticEigvals(N): fig = plt.figure(figsize=(3,3)) for j,type in enumerate(PCA_LIST): Sigma = get_eigvals(type, N=N) plt.plot(np.sort(Sigma)[::-1], label=type, color='C{}'.format(j)) print("kappa={:.4f}".format(np.sum(np.array(Sigma)**3) / np.sum(np.abs(np.array(Sigma)**3)))) plt.xlabel('$i$') plt.yscale('symlog', linthreshy=0.01) plt.ylabel('$\lambda_i$') #plt.legend(loc='center left', bbox_to_anchor=(-0.75, -0.5), fancybox=True, shadow=True, ncol=4) plt.savefig('synthetic-eigvals_n{}.pdf'.format(N), bbox_inches='tight') plot_d_q_Task("SCG-d_q1-R", "SCG-q_d10-R", "SCG-real_dq", [1,5,10,25,50], [1,2,4,8,16], MODE='adj') plot_d_q_Task("MOD-d_q1-S", "MOD-q_d10-S", "MOD-real_dq", [1,5,10,25,50], [1,2,4,8,16], MODE='mod') plot_SyntheticEigvals(10000) plot_d_PCA("SYN_d_q1_n10000", [1,5,10,25]) plot_q_PCA("SYN_q_d10_n10000", [1,2,4,8])
[ "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.sort", "numpy.array", "matplotlib.pyplot.figure", "matplotlib.pyplot.yscale", "matplotlib.pyplot.subplots" ]
[((620, 691), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'figsize': '(6, 3)', 'constrained_layout': '(True)'}), '(nrows=1, ncols=2, figsize=(6, 3), constrained_layout=True)\n', (632, 691), True, 'import matplotlib.pyplot as plt\n'), ((2595, 2666), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'figsize': '(6, 3)', 'constrained_layout': '(True)'}), '(nrows=1, ncols=2, figsize=(6, 3), constrained_layout=True)\n', (2607, 2666), True, 'import matplotlib.pyplot as plt\n'), ((4626, 4699), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'figsize': '(6, 2.5)', 'constrained_layout': '(True)'}), '(nrows=1, ncols=2, figsize=(6, 2.5), constrained_layout=True)\n', (4638, 4699), True, 'import matplotlib.pyplot as plt\n'), ((6356, 6429), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'figsize': '(6, 2.5)', 'constrained_layout': '(True)'}), '(nrows=1, ncols=2, figsize=(6, 2.5), constrained_layout=True)\n', (6368, 6429), True, 'import matplotlib.pyplot as plt\n'), ((7945, 8018), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'figsize': '(6, 2.5)', 'constrained_layout': '(True)'}), '(nrows=1, ncols=2, figsize=(6, 2.5), constrained_layout=True)\n', (7957, 8018), True, 'import matplotlib.pyplot as plt\n'), ((9477, 9503), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(3, 3)'}), '(figsize=(3, 3))\n', (9487, 9503), True, 'import matplotlib.pyplot as plt\n'), ((9761, 9778), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$i$"""'], {}), "('$i$')\n", (9771, 9778), True, 'import matplotlib.pyplot as plt\n'), ((9783, 9820), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""symlog"""'], {'linthreshy': '(0.01)'}), "('symlog', linthreshy=0.01)\n", (9793, 9820), True, 'import matplotlib.pyplot as plt\n'), ((9825, 9851), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\lambda_i$"""'], {}), "('$\\\\lambda_i$')\n", (9835, 9851), True, 'import matplotlib.pyplot as plt\n'), ((9598, 9612), 'numpy.sort', 'np.sort', (['Sigma'], {}), '(Sigma)\n', (9605, 9612), True, 'import numpy as np\n'), ((9698, 9713), 'numpy.array', 'np.array', (['Sigma'], {}), '(Sigma)\n', (9706, 9713), True, 'import numpy as np\n'), ((9734, 9749), 'numpy.array', 'np.array', (['Sigma'], {}), '(Sigma)\n', (9742, 9749), True, 'import numpy as np\n')]
import numpy as np import torch def to_numpy(tensor): if torch.is_tensor(tensor): return tensor.cpu().numpy() elif type(tensor).__module__ != 'numpy': raise ValueError("Cannot convert {} to numpy array" .format(type(tensor))) return tensor def to_torch(ndarray): if type(ndarray).__module__ == 'numpy': return torch.from_numpy(ndarray) elif not torch.is_tensor(ndarray): raise ValueError("Cannot convert {} to torch tensor" .format(type(ndarray))) return ndarray def get_head_box_channel(x_min, y_min, x_max, y_max, width, height, resolution, coordconv=False): head_box = np.array([x_min/width, y_min/height, x_max/width, y_max/height])*resolution head_box = head_box.astype(int) head_box = np.clip(head_box, 0, resolution-1) if coordconv: unit = np.array(range(0,resolution), dtype=np.float32) head_channel = [] for i in unit: head_channel.append([unit+i]) head_channel = np.squeeze(np.array(head_channel)) / float(np.max(head_channel)) head_channel[head_box[1]:head_box[3],head_box[0]:head_box[2]] = 0 else: head_channel = np.zeros((resolution,resolution), dtype=np.float32) head_channel[head_box[1]:head_box[3],head_box[0]:head_box[2]] = 1 head_channel = torch.from_numpy(head_channel) return head_channel def draw_labelmap(img, pt, sigma, type='Gaussian'): # Draw a 2D gaussian # Adopted from https://github.com/anewell/pose-hg-train/blob/master/src/pypose/draw.py img = to_numpy(img) # Check that any part of the gaussian is in-bounds ul = [int(pt[0] - 3 * sigma), int(pt[1] - 3 * sigma)] br = [int(pt[0] + 3 * sigma + 1), int(pt[1] + 3 * sigma + 1)] if (ul[0] >= img.shape[1] or ul[1] >= img.shape[0] or br[0] < 0 or br[1] < 0): # If not, just return the image as is return to_torch(img) # Generate gaussian size = 6 * sigma + 1 x = np.arange(0, size, 1, float) y = x[:, np.newaxis] x0 = y0 = size // 2 # The gaussian is not normalized, we want the center value to equal 1 if type == 'Gaussian': g = np.exp(- ((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2)) elif type == 'Cauchy': g = sigma / (((x - x0) ** 2 + (y - y0) ** 2 + sigma ** 2) ** 1.5) # Usable gaussian range g_x = max(0, -ul[0]), min(br[0], img.shape[1]) - ul[0] g_y = max(0, -ul[1]), min(br[1], img.shape[0]) - ul[1] # Image range img_x = max(0, ul[0]), min(br[0], img.shape[1]) img_y = max(0, ul[1]), min(br[1], img.shape[0]) img[img_y[0]:img_y[1], img_x[0]:img_x[1]] += g[g_y[0]:g_y[1], g_x[0]:g_x[1]] if np.max(img)!=0: img = img/np.max(img) # normalize heatmap so it has max value of 1 return to_torch(img)
[ "numpy.clip", "torch.from_numpy", "numpy.max", "numpy.exp", "torch.is_tensor", "numpy.array", "numpy.zeros", "numpy.arange" ]
[((62, 85), 'torch.is_tensor', 'torch.is_tensor', (['tensor'], {}), '(tensor)\n', (77, 85), False, 'import torch\n'), ((813, 849), 'numpy.clip', 'np.clip', (['head_box', '(0)', '(resolution - 1)'], {}), '(head_box, 0, resolution - 1)\n', (820, 849), True, 'import numpy as np\n'), ((1360, 1390), 'torch.from_numpy', 'torch.from_numpy', (['head_channel'], {}), '(head_channel)\n', (1376, 1390), False, 'import torch\n'), ((2016, 2044), 'numpy.arange', 'np.arange', (['(0)', 'size', '(1)', 'float'], {}), '(0, size, 1, float)\n', (2025, 2044), True, 'import numpy as np\n'), ((378, 403), 'torch.from_numpy', 'torch.from_numpy', (['ndarray'], {}), '(ndarray)\n', (394, 403), False, 'import torch\n'), ((686, 758), 'numpy.array', 'np.array', (['[x_min / width, y_min / height, x_max / width, y_max / height]'], {}), '([x_min / width, y_min / height, x_max / width, y_max / height])\n', (694, 758), True, 'import numpy as np\n'), ((1215, 1267), 'numpy.zeros', 'np.zeros', (['(resolution, resolution)'], {'dtype': 'np.float32'}), '((resolution, resolution), dtype=np.float32)\n', (1223, 1267), True, 'import numpy as np\n'), ((2207, 2266), 'numpy.exp', 'np.exp', (['(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))'], {}), '(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))\n', (2213, 2266), True, 'import numpy as np\n'), ((2727, 2738), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (2733, 2738), True, 'import numpy as np\n'), ((417, 441), 'torch.is_tensor', 'torch.is_tensor', (['ndarray'], {}), '(ndarray)\n', (432, 441), False, 'import torch\n'), ((2761, 2772), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (2767, 2772), True, 'import numpy as np\n'), ((1054, 1076), 'numpy.array', 'np.array', (['head_channel'], {}), '(head_channel)\n', (1062, 1076), True, 'import numpy as np\n'), ((1086, 1106), 'numpy.max', 'np.max', (['head_channel'], {}), '(head_channel)\n', (1092, 1106), True, 'import numpy as np\n')]
#!/usr/bin/python import numpy import theano import theano.tensor as T from theano.tensor.nnet import conv import theano.sandbox.neighbours as TSN class HiddenLayer(object): def __init__(self, rng, n_in, n_out, W=None, b=None, activation=T.tanh, name=""): """ Typical hidden layer of a MLP: units are fully-connected and have sigmoidal activation function. Weight matrix W is of shape (n_in,n_out) and the bias vector b is of shape (n_out,). NOTE : The nonlinearity used here is tanh Hidden unit activation is given by: tanh(dot(input,W) + b) :type rng: numpy.random.RandomState :param rng: a random number generator used to initialize weights :type input: theano.tensor.dmatrix :param input: a symbolic tensor of shape (n_examples, n_in) :type n_in: int :param n_in: dimensionality of input :type n_out: int :param n_out: number of hidden units :type activation: theano.Op or function :param activation: Non linearity to be applied in the hidden layer """ self.activation = activation if name != "": prefix = name else: prefix = "mlp_" if W is None: W_values = numpy.asarray(rng.uniform( low=-numpy.sqrt(6. / (n_in + n_out)), high=numpy.sqrt(6. / (n_in + n_out)), size=(n_in, n_out)), dtype=theano.config.floatX) if activation == theano.tensor.nnet.sigmoid: W_values *= 4 W = theano.shared(value=W_values, name=prefix+'W', borrow=True) if b is None: b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) b = theano.shared(value=b_values, name=prefix+'b', borrow=True) self.W = W self.b = b # parameters of the model self.params = [self.W, self.b] def getOutput(self, input): lin_output = T.dot(input, self.W) + self.b output = (lin_output if self.activation is None else self.activation(lin_output)) return output ######################################################################################### class LogisticRegression(object): def __init__(self, n_in, n_out, W = None, b = None, rng = None, randomInit = False): """ Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dimension of the space in which the datapoints lie :type n_out: int :param n_out: number of output units, the dimension of the space in which the labels lie """ self.numClasses = n_out if W == None: if randomInit: name = 'softmax_random_W' fan_in = n_in fan_out = n_out W_bound = numpy.sqrt(6. / (fan_in + fan_out)) self.W = theano.shared(value=numpy.asarray( rng.uniform(low=-W_bound, high=W_bound, size=(n_in, n_out)), dtype=theano.config.floatX), name=name, borrow=True) else: # initialize with 0 the weights W as a matrix of shape (n_in, n_out) self.W = theano.shared(value=numpy.zeros((n_in, n_out), dtype=theano.config.floatX), name='softmax_W', borrow=True) else: self.W = W self.params = [self.W] if b == None: # initialize the baises b as a vector of n_out 0s self.b = theano.shared(value=numpy.zeros((n_out,), dtype=theano.config.floatX), name='softmax_b', borrow=True) else: self.b = b self.params.append(self.b) def getMask(self, batchsize, maxSamplesInBag, samplesInBags): # mask entries outside of bags mask = T.zeros((batchsize, maxSamplesInBag)) maskAcc, _ = theano.scan(fn = lambda b, m: T.set_subtensor(m[b,:samplesInBags[b,0]], 1), outputs_info=mask, sequences=T.arange(batchsize)) mask = maskAcc[-1] mask2 = mask.repeat(self.numClasses, axis = 1).reshape((batchsize, maxSamplesInBag, self.numClasses)) return mask2 def nll_mi(self, x, y, samplesInBags, batchsize): self.p_y_given_x = T.nnet.softmax(T.dot(x, self.W) + self.b) maxSamplesInBag = self.p_y_given_x.shape[0] / batchsize self.p_y_given_x = self.p_y_given_x.reshape((batchsize, maxSamplesInBag, self.p_y_given_x.shape[1])) mask = self.getMask(batchsize, maxSamplesInBag, samplesInBags) self.p_y_given_x_masked = self.p_y_given_x * T.cast(mask, theano.config.floatX) maxpredvec = T.max(self.p_y_given_x_masked, axis = 1) batch_cost_log = T.log(maxpredvec)[T.arange(y.shape[0]), y] numberOfValidExamples = T.sum(T.cast(mask[:,:,0], theano.config.floatX)) return -T.sum(batch_cost_log) / numberOfValidExamples def getCostMI(self, x, y, samplesInBags, batchsize, rankingParam=2, m_minus = 0.5, m_plus = 2.5): return self.nll_mi(x, y, samplesInBags, batchsize) def getScores(self, x, samplesInBags, batchsize): return self.getScores_softmax(x, samplesInBags, batchsize) def getOutput(self, x, samplesInBags, batchsize): return self.getOutput_softmax(x, samplesInBags, batchsize) def getScores_softmax(self, x, samplesInBags, batchsize): predictions = T.dot(x, self.W) + self.b maxSamplesInBag = predictions.shape[0] / batchsize predictions = predictions.reshape((batchsize, maxSamplesInBag, predictions.shape[1])) mask = self.getMask(batchsize, maxSamplesInBag, samplesInBags) predictions_masked = predictions * T.cast(mask, theano.config.floatX) maxpredvec = T.max(predictions_masked, axis = 1) return maxpredvec def getOutput_softmax(self, x, samplesInBags, batchsize): self.p_y_given_x = T.nnet.softmax(T.dot(x, self.W) + self.b) maxSamplesInBag = self.p_y_given_x.shape[0] / batchsize self.p_y_given_x = self.p_y_given_x.reshape((batchsize, maxSamplesInBag, self.p_y_given_x.shape[1])) mask = self.getMask(batchsize, maxSamplesInBag, samplesInBags) self.p_y_given_x_masked = self.p_y_given_x * T.cast(mask, theano.config.floatX) argmaxpredvec = T.argmax(self.p_y_given_x_masked, axis = 2) maxpredvec = T.max(self.p_y_given_x_masked, axis = 2) return [argmaxpredvec, maxpredvec] #################################################################################### class LeNetConvPoolLayer(object): """Pool Layer of a convolutional network """ def preparePooling(self, conv_out): neighborsForPooling = TSN.images2neibs(ten4=conv_out, neib_shape=(1,conv_out.shape[3]), mode='ignore_borders') self.neighbors = neighborsForPooling neighborsArgSorted = T.argsort(neighborsForPooling, axis=1) neighborsArgSorted = neighborsArgSorted return neighborsForPooling, neighborsArgSorted def kmaxPooling(self, conv_out, k): neighborsForPooling, neighborsArgSorted = self.preparePooling(conv_out) kNeighborsArg = neighborsArgSorted[:,-k:] self.neigborsSorted = kNeighborsArg kNeighborsArgSorted = T.sort(kNeighborsArg, axis=1) ii = T.repeat(T.arange(neighborsForPooling.shape[0]), k) jj = kNeighborsArgSorted.flatten() self.ii = ii self.jj = jj pooledkmaxTmp = neighborsForPooling[ii, jj] self.pooled = pooledkmaxTmp # reshape pooled_out new_shape = T.cast(T.join(0, conv_out.shape[:-2], T.as_tensor([conv_out.shape[2]]), T.as_tensor([k])), 'int64') pooledkmax = T.reshape(pooledkmaxTmp, new_shape, ndim=4) return pooledkmax def convStep(self, curInput, curFilter): return conv.conv2d(input=curInput, filters=curFilter, filter_shape=self.filter_shape, image_shape=None) def __init__(self, rng, filter_shape, image_shape = None, W = None, b = None, poolsize=(2, 2)): """ Allocate a LeNetConvPoolLayer with shared variable internal parameters. :type rng: numpy.random.RandomState :param rng: a random number generator used to initialize weights :type W: theano.matrix :param W: the weight matrix used for convolution :type b: theano vector :param b: the bias used for convolution :type input: theano.tensor.dtensor4 :param input: symbolic image tensor, of shape image_shape :type filter_shape: tuple or list of length 4 :param filter_shape: (number of filters, num input feature maps, filter height,filter width) :type image_shape: tuple or list of length 4 :param image_shape: (batch size, num input feature maps, image height, image width) :type poolsize: tuple or list of length 2 :param poolsize: the downsampling (pooling) factor (#rows,#cols) """ self.filter_shape = filter_shape self.poolsize = poolsize if W == None: fan_in = numpy.prod(self.filter_shape[1:]) fan_out = (self.filter_shape[0] * numpy.prod(self.filter_shape[2:]) / numpy.prod(self.poolsize)) W_bound = numpy.sqrt(6. / (fan_in + fan_out)) # the convolution weight matrix self.W = theano.shared(numpy.asarray( rng.uniform(low=-W_bound, high=W_bound, size=filter_shape), dtype=theano.config.floatX), name='conv_W', borrow=True) else: self.W = W if b == None: # the bias is a 1D tensor -- one bias per output feature map b_values = numpy.zeros((filter_shape[0],), dtype=theano.config.floatX) self.b = theano.shared(value=b_values, name='conv_b', borrow=True) else: self.b = b # store parameters of this layer self.params = [self.W, self.b] def getOutput(self, input): # convolve input feature maps with filters conv_out = self.convStep(input, self.W) #self.conv_out_tanh = T.tanh(conv_out + self.b.dimshuffle('x', 0, 'x', 'x')) k = self.poolsize[1] self.pooledkmax = self.kmaxPooling(conv_out, k) # add the bias term. Since the bias is a vector (1D array), we first # reshape it to a tensor of shape (1,n_filters,1,1). Each bias will # thus be broadcasted across mini-batches and feature map # width & height output = T.tanh(self.pooledkmax + self.b.dimshuffle('x', 0, 'x', 'x')) return output ################################################################################### class CRF: # Code from https://github.com/glample/tagger/blob/master/model.py # but extended to support mini-batches def log_sum_exp(self, x, axis=None): """ Sum probabilities in the log-space. """ xmax = x.max(axis=axis, keepdims=True) xmax_ = x.max(axis=axis) return xmax_ + T.log(T.exp(x - xmax).sum(axis=axis)) def recurrence(self, obs, previous): previous = previous.dimshuffle(0, 1, 'x') obs = obs.dimshuffle(0, 'x', 1) return self.log_sum_exp(previous + obs + self.transitions.dimshuffle('x', 0, 1), axis=1) def recurrence_viterbi(self, obs, previous): previous = previous.dimshuffle(0, 1, 'x') obs = obs.dimshuffle(0, 'x', 1) scores = previous + obs + self.transitions.dimshuffle('x', 0, 1) out = scores.max(axis=1) return out def recurrence_viterbi_returnBest(self, obs, previous): previous = previous.dimshuffle(0, 1, 'x') obs = obs.dimshuffle(0, 'x', 1) scores = previous + obs + self.transitions.dimshuffle('x', 0, 1) out = scores.max(axis=1) out2 = scores.argmax(axis=1) return out, out2 def forward(self, observations, viterbi=False, return_alpha=False, return_best_sequence=False): """ Takes as input: - observations, sequence of shape (batch_size, n_steps, n_classes) Probabilities must be given in the log space. Compute alpha, matrix of size (batch_size, n_steps, n_classes), such that alpha[:, i, j] represents one of these 2 values: - the probability that the real path at node i ends in j - the maximum probability of a path finishing in j at node i (Viterbi) Returns one of these 2 values: - alpha - the final probability, which can be: - the sum of the probabilities of all paths - the probability of the best path (Viterbi) """ assert not return_best_sequence or (viterbi and not return_alpha) def recurrence_bestSequence(b): sequence_b, _ = theano.scan( fn=lambda beta_i, previous: beta_i[previous], outputs_info=T.cast(T.argmax(alpha[0][b][-1]), 'int32'), sequences=T.cast(alpha[1][b,::-1], 'int32') ) return sequence_b initial = observations[:,0] if viterbi: if return_best_sequence: alpha, _ = theano.scan( fn=self.recurrence_viterbi_returnBest, outputs_info=(initial, None), sequences=[observations[:,1:].dimshuffle(1,0,2)] # shuffle to get a sequence over time, not over batches ) alpha[0] = alpha[0].dimshuffle(1,0,2) # shuffle back alpha[1] = alpha[1].dimshuffle(1,0,2) else: alpha, _ = theano.scan( fn=self.recurrence_viterbi, outputs_info=initial, sequences=[observations[:,1:].dimshuffle(1,0,2)] # shuffle to get a sequence over time, not over batches ) alpha = alpha.dimshuffle(1,0,2) # shuffle back else: alpha, _ = theano.scan( fn=self.recurrence, outputs_info=initial, sequences=[observations[:,1:].dimshuffle(1,0,2)] # shuffle to get a sequence over time, not over batches ) alpha = alpha.dimshuffle(1,0,2) # shuffle back if return_alpha: return alpha elif return_best_sequence: batchsizeVar = alpha[0].shape[0] sequence, _ = theano.scan( fn=recurrence_bestSequence, outputs_info = None, sequences=T.arange(batchsizeVar) ) sequence = T.concatenate([sequence[:,::-1], T.argmax(alpha[0][:,-1], axis = 1).reshape((batchsizeVar, 1))], axis = 1) return sequence, alpha[0] else: if viterbi: return alpha[:,-1,:].max(axis=1) else: return self.log_sum_exp(alpha[:,-1,:], axis=1) def __init__(self, numClasses, rng, batchsizeVar, sequenceLength = 3): self.numClasses = numClasses shape_transitions = (numClasses + 2, numClasses + 2) # +2 because of start id and end id drange = numpy.sqrt(6.0 / numpy.sum(shape_transitions)) self.transitions = theano.shared(value = numpy.asarray(rng.uniform(low = -drange, high = drange, size = shape_transitions), dtype = theano.config.floatX), name = 'transitions') self.small = -1000 # log for very small probability b_s = numpy.array([[self.small] * numClasses + [0, self.small]]).astype(theano.config.floatX) e_s = numpy.array([[self.small] * numClasses + [self.small, 0]]).astype(theano.config.floatX) self.b_s_theano = theano.shared(value = b_s).dimshuffle('x', 0, 1) self.e_s_theano = theano.shared(value = e_s).dimshuffle('x', 0, 1) self.b_s_theano = self.b_s_theano.repeat(batchsizeVar, axis = 0) self.e_s_theano = self.e_s_theano.repeat(batchsizeVar, axis = 0) self.s_len = sequenceLength self.debug1 = self.e_s_theano self.params = [self.transitions] def getObservations(self, scores): batchsizeVar = scores.shape[0] observations = T.concatenate([scores, self.small * T.cast(T.ones((batchsizeVar, self.s_len, 2)), theano.config.floatX)], axis = 2) observations = T.concatenate([self.b_s_theano, observations, self.e_s_theano], axis = 1) return observations def getPrediction(self, scores): observations = self.getObservations(scores) prediction = self.forward(observations, viterbi=True, return_best_sequence=True) return prediction def getCost(self, scores, y_conc): batchsizeVar = scores.shape[0] observations = self.getObservations(scores) # score from classes scores_flattened = scores.reshape((scores.shape[0] * scores.shape[1], scores.shape[2])) y_flattened = y_conc.flatten(1) real_path_score = scores_flattened[T.arange(batchsizeVar * self.s_len), y_flattened] real_path_score = real_path_score.reshape((batchsizeVar, self.s_len)).sum(axis = 1) # score from transitions b_id = theano.shared(value=numpy.array([self.numClasses], dtype=numpy.int32)) # id for begin e_id = theano.shared(value=numpy.array([self.numClasses + 1], dtype=numpy.int32)) # id for end b_id = b_id.dimshuffle('x', 0).repeat(batchsizeVar, axis = 0) e_id = e_id.dimshuffle('x', 0).repeat(batchsizeVar, axis = 0) padded_tags_ids = T.concatenate([b_id, y_conc, e_id], axis=1) real_path_score2, _ = theano.scan(fn = lambda m: self.transitions[padded_tags_ids[m,T.arange(self.s_len+1)], padded_tags_ids[m,T.arange(self.s_len + 1) + 1]].sum(), sequences = T.arange(batchsizeVar), outputs_info = None) real_path_score += real_path_score2 all_paths_scores = self.forward(observations) self.debug1 = real_path_score cost = - T.mean(real_path_score - all_paths_scores) return cost def getCostAddLogWeights(self, scores, y_conc): batchsizeVar = scores.shape[0] observations = self.getObservations(scores) # score from classes scores_flattened = scores.reshape((scores.shape[0] * scores.shape[1], scores.shape[2])) y_flattened = y_conc.flatten(1) real_path_score = scores_flattened[T.arange(batchsizeVar * self.s_len), y_flattened] real_path_score = real_path_score.reshape((batchsizeVar, self.s_len)).sum(axis = 1) # score from transitions b_id = theano.shared(value=numpy.array([self.numClasses], dtype=numpy.int32)) # id for begin e_id = theano.shared(value=numpy.array([self.numClasses + 1], dtype=numpy.int32)) # id for end b_id = b_id.dimshuffle('x', 0).repeat(batchsizeVar, axis = 0) e_id = e_id.dimshuffle('x', 0).repeat(batchsizeVar, axis = 0) padded_tags_ids = T.concatenate([b_id, y_conc, e_id], axis=1) real_path_score2, _ = theano.scan(fn = lambda m: self.transitions[padded_tags_ids[m,T.arange(self.s_len+1)], padded_tags_ids[m,T.arange(self.s_len + 1) + 1]].sum(), sequences = T.arange(batchsizeVar), outputs_info = None) real_path_score += real_path_score2 all_paths_scores = self.forward(observations) self.debug1 = real_path_score cost = - T.mean(real_path_score - all_paths_scores) return cost
[ "theano.tensor.exp", "numpy.prod", "numpy.sqrt", "theano.tensor.ones", "theano.tensor.mean", "theano.tensor.argmax", "numpy.array", "theano.tensor.dot", "theano.shared", "theano.tensor.arange", "theano.tensor.zeros", "theano.tensor.set_subtensor", "theano.tensor.concatenate", "theano.tenso...
[((4290, 4327), 'theano.tensor.zeros', 'T.zeros', (['(batchsize, maxSamplesInBag)'], {}), '((batchsize, maxSamplesInBag))\n', (4297, 4327), True, 'import theano.tensor as T\n'), ((5117, 5155), 'theano.tensor.max', 'T.max', (['self.p_y_given_x_masked'], {'axis': '(1)'}), '(self.p_y_given_x_masked, axis=1)\n', (5122, 5155), True, 'import theano.tensor as T\n'), ((6186, 6219), 'theano.tensor.max', 'T.max', (['predictions_masked'], {'axis': '(1)'}), '(predictions_masked, axis=1)\n', (6191, 6219), True, 'import theano.tensor as T\n'), ((6722, 6763), 'theano.tensor.argmax', 'T.argmax', (['self.p_y_given_x_masked'], {'axis': '(2)'}), '(self.p_y_given_x_masked, axis=2)\n', (6730, 6763), True, 'import theano.tensor as T\n'), ((6785, 6823), 'theano.tensor.max', 'T.max', (['self.p_y_given_x_masked'], {'axis': '(2)'}), '(self.p_y_given_x_masked, axis=2)\n', (6790, 6823), True, 'import theano.tensor as T\n'), ((7107, 7201), 'theano.sandbox.neighbours.images2neibs', 'TSN.images2neibs', ([], {'ten4': 'conv_out', 'neib_shape': '(1, conv_out.shape[3])', 'mode': '"""ignore_borders"""'}), "(ten4=conv_out, neib_shape=(1, conv_out.shape[3]), mode=\n 'ignore_borders')\n", (7123, 7201), True, 'import theano.sandbox.neighbours as TSN\n'), ((7266, 7304), 'theano.tensor.argsort', 'T.argsort', (['neighborsForPooling'], {'axis': '(1)'}), '(neighborsForPooling, axis=1)\n', (7275, 7304), True, 'import theano.tensor as T\n'), ((7641, 7670), 'theano.tensor.sort', 'T.sort', (['kNeighborsArg'], {'axis': '(1)'}), '(kNeighborsArg, axis=1)\n', (7647, 7670), True, 'import theano.tensor as T\n'), ((8138, 8181), 'theano.tensor.reshape', 'T.reshape', (['pooledkmaxTmp', 'new_shape'], {'ndim': '(4)'}), '(pooledkmaxTmp, new_shape, ndim=4)\n', (8147, 8181), True, 'import theano.tensor as T\n'), ((8265, 8366), 'theano.tensor.nnet.conv.conv2d', 'conv.conv2d', ([], {'input': 'curInput', 'filters': 'curFilter', 'filter_shape': 'self.filter_shape', 'image_shape': 'None'}), '(input=curInput, filters=curFilter, filter_shape=self.\n filter_shape, image_shape=None)\n', (8276, 8366), False, 'from theano.tensor.nnet import conv\n'), ((16501, 16572), 'theano.tensor.concatenate', 'T.concatenate', (['[self.b_s_theano, observations, self.e_s_theano]'], {'axis': '(1)'}), '([self.b_s_theano, observations, self.e_s_theano], axis=1)\n', (16514, 16572), True, 'import theano.tensor as T\n'), ((17669, 17712), 'theano.tensor.concatenate', 'T.concatenate', (['[b_id, y_conc, e_id]'], {'axis': '(1)'}), '([b_id, y_conc, e_id], axis=1)\n', (17682, 17712), True, 'import theano.tensor as T\n'), ((19024, 19067), 'theano.tensor.concatenate', 'T.concatenate', (['[b_id, y_conc, e_id]'], {'axis': '(1)'}), '([b_id, y_conc, e_id], axis=1)\n', (19037, 19067), True, 'import theano.tensor as T\n'), ((1638, 1699), 'theano.shared', 'theano.shared', ([], {'value': 'W_values', 'name': "(prefix + 'W')", 'borrow': '(True)'}), "(value=W_values, name=prefix + 'W', borrow=True)\n", (1651, 1699), False, 'import theano\n'), ((1744, 1793), 'numpy.zeros', 'numpy.zeros', (['(n_out,)'], {'dtype': 'theano.config.floatX'}), '((n_out,), dtype=theano.config.floatX)\n', (1755, 1793), False, 'import numpy\n'), ((1810, 1871), 'theano.shared', 'theano.shared', ([], {'value': 'b_values', 'name': "(prefix + 'b')", 'borrow': '(True)'}), "(value=b_values, name=prefix + 'b', borrow=True)\n", (1823, 1871), False, 'import theano\n'), ((2037, 2057), 'theano.tensor.dot', 'T.dot', (['input', 'self.W'], {}), '(input, self.W)\n', (2042, 2057), True, 'import theano.tensor as T\n'), ((5063, 5097), 'theano.tensor.cast', 'T.cast', (['mask', 'theano.config.floatX'], {}), '(mask, theano.config.floatX)\n', (5069, 5097), True, 'import theano.tensor as T\n'), ((5181, 5198), 'theano.tensor.log', 'T.log', (['maxpredvec'], {}), '(maxpredvec)\n', (5186, 5198), True, 'import theano.tensor as T\n'), ((5261, 5304), 'theano.tensor.cast', 'T.cast', (['mask[:, :, 0]', 'theano.config.floatX'], {}), '(mask[:, :, 0], theano.config.floatX)\n', (5267, 5304), True, 'import theano.tensor as T\n'), ((5847, 5863), 'theano.tensor.dot', 'T.dot', (['x', 'self.W'], {}), '(x, self.W)\n', (5852, 5863), True, 'import theano.tensor as T\n'), ((6132, 6166), 'theano.tensor.cast', 'T.cast', (['mask', 'theano.config.floatX'], {}), '(mask, theano.config.floatX)\n', (6138, 6166), True, 'import theano.tensor as T\n'), ((6665, 6699), 'theano.tensor.cast', 'T.cast', (['mask', 'theano.config.floatX'], {}), '(mask, theano.config.floatX)\n', (6671, 6699), True, 'import theano.tensor as T\n'), ((7691, 7729), 'theano.tensor.arange', 'T.arange', (['neighborsForPooling.shape[0]'], {}), '(neighborsForPooling.shape[0])\n', (7699, 7729), True, 'import theano.tensor as T\n'), ((9599, 9632), 'numpy.prod', 'numpy.prod', (['self.filter_shape[1:]'], {}), '(self.filter_shape[1:])\n', (9609, 9632), False, 'import numpy\n'), ((9775, 9811), 'numpy.sqrt', 'numpy.sqrt', (['(6.0 / (fan_in + fan_out))'], {}), '(6.0 / (fan_in + fan_out))\n', (9785, 9811), False, 'import numpy\n'), ((10225, 10284), 'numpy.zeros', 'numpy.zeros', (['(filter_shape[0],)'], {'dtype': 'theano.config.floatX'}), '((filter_shape[0],), dtype=theano.config.floatX)\n', (10236, 10284), False, 'import numpy\n'), ((10304, 10361), 'theano.shared', 'theano.shared', ([], {'value': 'b_values', 'name': '"""conv_b"""', 'borrow': '(True)'}), "(value=b_values, name='conv_b', borrow=True)\n", (10317, 10361), False, 'import theano\n'), ((18088, 18130), 'theano.tensor.mean', 'T.mean', (['(real_path_score - all_paths_scores)'], {}), '(real_path_score - all_paths_scores)\n', (18094, 18130), True, 'import theano.tensor as T\n'), ((19443, 19485), 'theano.tensor.mean', 'T.mean', (['(real_path_score - all_paths_scores)'], {}), '(real_path_score - all_paths_scores)\n', (19449, 19485), True, 'import theano.tensor as T\n'), ((3152, 3188), 'numpy.sqrt', 'numpy.sqrt', (['(6.0 / (fan_in + fan_out))'], {}), '(6.0 / (fan_in + fan_out))\n', (3162, 3188), False, 'import numpy\n'), ((4478, 4497), 'theano.tensor.arange', 'T.arange', (['batchsize'], {}), '(batchsize)\n', (4486, 4497), True, 'import theano.tensor as T\n'), ((4746, 4762), 'theano.tensor.dot', 'T.dot', (['x', 'self.W'], {}), '(x, self.W)\n', (4751, 4762), True, 'import theano.tensor as T\n'), ((5199, 5219), 'theano.tensor.arange', 'T.arange', (['y.shape[0]'], {}), '(y.shape[0])\n', (5207, 5219), True, 'import theano.tensor as T\n'), ((5318, 5339), 'theano.tensor.sum', 'T.sum', (['batch_cost_log'], {}), '(batch_cost_log)\n', (5323, 5339), True, 'import theano.tensor as T\n'), ((6349, 6365), 'theano.tensor.dot', 'T.dot', (['x', 'self.W'], {}), '(x, self.W)\n', (6354, 6365), True, 'import theano.tensor as T\n'), ((8007, 8039), 'theano.tensor.as_tensor', 'T.as_tensor', (['[conv_out.shape[2]]'], {}), '([conv_out.shape[2]])\n', (8018, 8039), True, 'import theano.tensor as T\n'), ((8066, 8082), 'theano.tensor.as_tensor', 'T.as_tensor', (['[k]'], {}), '([k])\n', (8077, 8082), True, 'import theano.tensor as T\n'), ((9727, 9752), 'numpy.prod', 'numpy.prod', (['self.poolsize'], {}), '(self.poolsize)\n', (9737, 9752), False, 'import numpy\n'), ((15393, 15421), 'numpy.sum', 'numpy.sum', (['shape_transitions'], {}), '(shape_transitions)\n', (15402, 15421), False, 'import numpy\n'), ((15677, 15735), 'numpy.array', 'numpy.array', (['[[self.small] * numClasses + [0, self.small]]'], {}), '([[self.small] * numClasses + [0, self.small]])\n', (15688, 15735), False, 'import numpy\n'), ((15777, 15835), 'numpy.array', 'numpy.array', (['[[self.small] * numClasses + [self.small, 0]]'], {}), '([[self.small] * numClasses + [self.small, 0]])\n', (15788, 15835), False, 'import numpy\n'), ((15889, 15913), 'theano.shared', 'theano.shared', ([], {'value': 'b_s'}), '(value=b_s)\n', (15902, 15913), False, 'import theano\n'), ((15962, 15986), 'theano.shared', 'theano.shared', ([], {'value': 'e_s'}), '(value=e_s)\n', (15975, 15986), False, 'import theano\n'), ((17129, 17164), 'theano.tensor.arange', 'T.arange', (['(batchsizeVar * self.s_len)'], {}), '(batchsizeVar * self.s_len)\n', (17137, 17164), True, 'import theano.tensor as T\n'), ((17335, 17384), 'numpy.array', 'numpy.array', (['[self.numClasses]'], {'dtype': 'numpy.int32'}), '([self.numClasses], dtype=numpy.int32)\n', (17346, 17384), False, 'import numpy\n'), ((17434, 17487), 'numpy.array', 'numpy.array', (['[self.numClasses + 1]'], {'dtype': 'numpy.int32'}), '([self.numClasses + 1], dtype=numpy.int32)\n', (17445, 17487), False, 'import numpy\n'), ((17897, 17919), 'theano.tensor.arange', 'T.arange', (['batchsizeVar'], {}), '(batchsizeVar)\n', (17905, 17919), True, 'import theano.tensor as T\n'), ((18491, 18526), 'theano.tensor.arange', 'T.arange', (['(batchsizeVar * self.s_len)'], {}), '(batchsizeVar * self.s_len)\n', (18499, 18526), True, 'import theano.tensor as T\n'), ((18696, 18745), 'numpy.array', 'numpy.array', (['[self.numClasses]'], {'dtype': 'numpy.int32'}), '([self.numClasses], dtype=numpy.int32)\n', (18707, 18745), False, 'import numpy\n'), ((18795, 18848), 'numpy.array', 'numpy.array', (['[self.numClasses + 1]'], {'dtype': 'numpy.int32'}), '([self.numClasses + 1], dtype=numpy.int32)\n', (18806, 18848), False, 'import numpy\n'), ((19252, 19274), 'theano.tensor.arange', 'T.arange', (['batchsizeVar'], {}), '(batchsizeVar)\n', (19260, 19274), True, 'import theano.tensor as T\n'), ((3949, 3998), 'numpy.zeros', 'numpy.zeros', (['(n_out,)'], {'dtype': 'theano.config.floatX'}), '((n_out,), dtype=theano.config.floatX)\n', (3960, 3998), False, 'import numpy\n'), ((4377, 4423), 'theano.tensor.set_subtensor', 'T.set_subtensor', (['m[b, :samplesInBags[b, 0]]', '(1)'], {}), '(m[b, :samplesInBags[b, 0]], 1)\n', (4392, 4423), True, 'import theano.tensor as T\n'), ((9677, 9710), 'numpy.prod', 'numpy.prod', (['self.filter_shape[2:]'], {}), '(self.filter_shape[2:])\n', (9687, 9710), False, 'import numpy\n'), ((13451, 13485), 'theano.tensor.cast', 'T.cast', (['alpha[1][b, ::-1]', '"""int32"""'], {}), "(alpha[1][b, ::-1], 'int32')\n", (13457, 13485), True, 'import theano.tensor as T\n'), ((1432, 1464), 'numpy.sqrt', 'numpy.sqrt', (['(6.0 / (n_in + n_out))'], {}), '(6.0 / (n_in + n_out))\n', (1442, 1464), False, 'import numpy\n'), ((3592, 3646), 'numpy.zeros', 'numpy.zeros', (['(n_in, n_out)'], {'dtype': 'theano.config.floatX'}), '((n_in, n_out), dtype=theano.config.floatX)\n', (3603, 3646), False, 'import numpy\n'), ((11547, 11562), 'theano.tensor.exp', 'T.exp', (['(x - xmax)'], {}), '(x - xmax)\n', (11552, 11562), True, 'import theano.tensor as T\n'), ((13392, 13417), 'theano.tensor.argmax', 'T.argmax', (['alpha[0][b][-1]'], {}), '(alpha[0][b][-1])\n', (13400, 13417), True, 'import theano.tensor as T\n'), ((14815, 14837), 'theano.tensor.arange', 'T.arange', (['batchsizeVar'], {}), '(batchsizeVar)\n', (14823, 14837), True, 'import theano.tensor as T\n'), ((16407, 16444), 'theano.tensor.ones', 'T.ones', (['(batchsizeVar, self.s_len, 2)'], {}), '((batchsizeVar, self.s_len, 2))\n', (16413, 16444), True, 'import theano.tensor as T\n'), ((1374, 1406), 'numpy.sqrt', 'numpy.sqrt', (['(6.0 / (n_in + n_out))'], {}), '(6.0 / (n_in + n_out))\n', (1384, 1406), False, 'import numpy\n'), ((14900, 14933), 'theano.tensor.argmax', 'T.argmax', (['alpha[0][:, -1]'], {'axis': '(1)'}), '(alpha[0][:, -1], axis=1)\n', (14908, 14933), True, 'import theano.tensor as T\n'), ((17804, 17828), 'theano.tensor.arange', 'T.arange', (['(self.s_len + 1)'], {}), '(self.s_len + 1)\n', (17812, 17828), True, 'import theano.tensor as T\n'), ((19159, 19183), 'theano.tensor.arange', 'T.arange', (['(self.s_len + 1)'], {}), '(self.s_len + 1)\n', (19167, 19183), True, 'import theano.tensor as T\n'), ((17847, 17871), 'theano.tensor.arange', 'T.arange', (['(self.s_len + 1)'], {}), '(self.s_len + 1)\n', (17855, 17871), True, 'import theano.tensor as T\n'), ((19202, 19226), 'theano.tensor.arange', 'T.arange', (['(self.s_len + 1)'], {}), '(self.s_len + 1)\n', (19210, 19226), True, 'import theano.tensor as T\n')]
""" Vanilla Policy Gradient agent. """ import numpy as np import torch import torch.optim as optim from torch.distributions import Categorical device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class Agent(): def __init__(self, model, seed=0, load_file=None, lr=1e-2, action_map=None): """ Params ====== model: model object seed (int): Random seed load_file (str): path of checkpoint file to load lr (float): learning rate action_map (dict): how to map action indexes from model output to gym environment """ torch.manual_seed(seed) torch.cuda.manual_seed(seed) self.model = model.to(device) if load_file: # self.model.load_state_dict(torch.load(load_file)) self.model.load_state_dict(torch.load(load_file, map_location='cpu')) # load from GPU to CPU print('Loaded: {}'.format(load_file)) self.action_map = action_map self.optimizer = optim.Adam(model.parameters(), lr=lr) def _discount(self, rewards, gamma, normal): """ Calulate discounted future (and optionally normalized) rewards. From https://github.com/wagonhelm/Deep-Policy-Gradient """ discounted_rewards = np.zeros_like(rewards) G = 0.0 for i in reversed(range(0, len(rewards))): G = G * gamma + rewards[i] discounted_rewards[i] = G # normalize rewards if normal: mean = np.mean(discounted_rewards) std = np.std(discounted_rewards) std = max(1e-8, std) # avoid divide by zero if rewards = 0.0 discounted_rewards = (discounted_rewards - mean) / (std) return discounted_rewards def act(self, state): """Given a state, determine the next action.""" if len(state.shape) == 1: # reshape 1-D states into 2-D (as expected by the model) state = np.expand_dims(state, axis=0) state = torch.from_numpy(state).float().to(device) probs = self.model.forward(state).cpu() m = Categorical(probs) action = m.sample() # use action_map if it exists if self.action_map: return self.action_map[action.item()], m.log_prob(action) else: return action.item(), m.log_prob(action) def learn(self, rewards, saved_log_probs, gamma): """Update model weights.""" # calculate discounted rewards for each step and normalize them discounted_rewards = self._discount(rewards, gamma, True) policy_loss = [] for i, log_prob in enumerate(saved_log_probs): policy_loss.append(-log_prob * discounted_rewards[i]) policy_loss = torch.cat(policy_loss).sum() self.optimizer.zero_grad() policy_loss.backward() self.optimizer.step()
[ "torch.manual_seed", "numpy.mean", "torch.distributions.Categorical", "torch.load", "torch.from_numpy", "torch.cuda.is_available", "numpy.expand_dims", "numpy.std", "torch.cuda.manual_seed", "numpy.zeros_like", "torch.cat" ]
[((179, 204), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (202, 204), False, 'import torch\n'), ((638, 661), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (655, 661), False, 'import torch\n'), ((670, 698), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (692, 698), False, 'import torch\n'), ((1320, 1342), 'numpy.zeros_like', 'np.zeros_like', (['rewards'], {}), '(rewards)\n', (1333, 1342), True, 'import numpy as np\n'), ((2149, 2167), 'torch.distributions.Categorical', 'Categorical', (['probs'], {}), '(probs)\n', (2160, 2167), False, 'from torch.distributions import Categorical\n'), ((1553, 1580), 'numpy.mean', 'np.mean', (['discounted_rewards'], {}), '(discounted_rewards)\n', (1560, 1580), True, 'import numpy as np\n'), ((1599, 1625), 'numpy.std', 'np.std', (['discounted_rewards'], {}), '(discounted_rewards)\n', (1605, 1625), True, 'import numpy as np\n'), ((2000, 2029), 'numpy.expand_dims', 'np.expand_dims', (['state'], {'axis': '(0)'}), '(state, axis=0)\n', (2014, 2029), True, 'import numpy as np\n'), ((863, 904), 'torch.load', 'torch.load', (['load_file'], {'map_location': '"""cpu"""'}), "(load_file, map_location='cpu')\n", (873, 904), False, 'import torch\n'), ((2799, 2821), 'torch.cat', 'torch.cat', (['policy_loss'], {}), '(policy_loss)\n', (2808, 2821), False, 'import torch\n'), ((2046, 2069), 'torch.from_numpy', 'torch.from_numpy', (['state'], {}), '(state)\n', (2062, 2069), False, 'import torch\n')]
"""[Summary] : file where is handled the creation of the data files.""" #============================================================================ # Created By : <NAME>, <NAME>, <NAME> # Last Update : 02/01/2022 # Version : 1.0 #============================================================================ import json import os from datetime import date from datetime import timedelta import pandas as pd import numpy as np from pycoingecko import CoinGeckoAPI from utils.converters import DateConverter from utils import tools from pytrends.request import TrendReq #-- CLASS --# class DataCryptoGenerator: """ Generator of json file according to the content of the data dict for grahs. It will give a json with the prices, markets_caps and datetime or date of a crypto. """ cg = CoinGeckoAPI() ending_date = date.today() starting_date = ending_date - timedelta(days = 7) def __init__(self): self.data = {} def add_crypto(self, crypto_id, currency): """Add a crypto in our data dict. Args: crypto_id (string): id of the crypto (ex: 'bitcoin') currency (string): type of currency (ex: 'eur') """ self.data[crypto_id] = DataCryptoGenerator.cg.get_coin_market_chart_range_by_id( id = crypto_id, vs_currency = currency, from_timestamp = DateConverter.date_to_unix(DataCryptoGenerator.starting_date.year, DataCryptoGenerator.starting_date.month, DataCryptoGenerator.starting_date.day), to_timestamp = DateConverter.date_to_unix(DataCryptoGenerator.ending_date.year, DataCryptoGenerator.ending_date.month, DataCryptoGenerator.ending_date.day) ) def remove_crypto(self, crypto_id): """Remove a crypto from our data dict. Args: crypto_id (string): id of the crypto """ self.data.pop(crypto_id) def generate_json(self, filename): """Generate the json file. Args: filename (string): name of the file """ with open(os.getcwd() + '/models/' + filename, 'w+', encoding="utf-8") as file : json.dump(self.data, file) class DataMapGenerator: """ Generator of json file according to the content of the data dict for map. It will give a json file given info about the trend of each crypto(given) in the world by country to see the popularity of each crypto in the world and maybe explain the supremacy of one of those crypto """ def __init__(self): self.keywords = [] def add_keyword(self, keyword): """Add keyword in our list Args: keyword (string): keyword like 'bitcoin' """ self.keywords.append(keyword) def generate_json(self, filename): """Generate the json file. Args: filename (string): name of the file """ trend = TrendReq() trend.build_payload(self.keywords) data = trend.interest_by_region() with open(os.getcwd() + '/models/' + filename, 'w+', encoding="utf-8") as file : json.dump(json.loads(data.to_json()), file) #-- FUNCTIONS --# def get_market_caps(filename, cryptoname): """Get rate of crypto given from json file. Args: filename (string): name of file cryptoname (string): crypto's id Returns: [DataFrame]: rates """ data = pd.read_json(os.getcwd() + '/models/' + filename) return pd.DataFrame({'date':[ DateConverter.unix_to_datetime(i[0]) for i in data[cryptoname].market_caps ], 'market_caps':np.array(data[cryptoname].market_caps)[:,1] }) def get_prices(filename, cryptoname, datetime): """Get crypto prices from json file. Args: filename (string): name of json file cryptoname (string): id of crypto datetime (bool): if u want date or datetime Returns: [DataFrame]: prices """ data = pd.read_json(os.getcwd() + '/models/' + filename) if not datetime: return pd.DataFrame({'name': cryptoname, 'date':[ DateConverter.unix_to_date(i[0]) for i in data[cryptoname].prices ], 'prices':np.array(data[cryptoname].prices)[:,1] }) return pd.DataFrame({'name': cryptoname, 'date':[ DateConverter.unix_to_datetime(i[0]) for i in data[cryptoname].prices ], 'prices':np.array(data[cryptoname].prices)[:,1] }) def get_dataframe(filename, cryptoname): """Get DataFrame from filename given and cryptoname given. Args: filename (string): file name cryptoname (string): crypto name Returns: [DataFrame]: data """ data = pd.read_json(os.getcwd() + '/models/' + filename) return pd.DataFrame({'country':[ i for i in data[cryptoname].keys()], 'popularity':[ i for i in data[cryptoname]]}) def generate_markers(filename, data): """Generate markers json file. Args: filename (string): file name data (DataFrame): data which has the countries name """ markers = {} for i,j in zip(data.country, data.popularity): markers[str(i)] = [j, tools.latitude_longitude(i)] with open(os.getcwd() + '/models/' + filename, 'w+', encoding="utf-8") as file : json.dump(markers, file) def get_markers(filename): """Get markers json file. Args: filename (string): name of file Returns: [DataFrame]: json file """ return pd.read_json(os.getcwd() + '/models/' + filename, lines=True)
[ "utils.converters.DateConverter.date_to_unix", "utils.tools.latitude_longitude", "pycoingecko.CoinGeckoAPI", "pytrends.request.TrendReq", "datetime.timedelta", "os.getcwd", "numpy.array", "datetime.date.today", "utils.converters.DateConverter.unix_to_date", "utils.converters.DateConverter.unix_to_...
[((824, 838), 'pycoingecko.CoinGeckoAPI', 'CoinGeckoAPI', ([], {}), '()\n', (836, 838), False, 'from pycoingecko import CoinGeckoAPI\n'), ((857, 869), 'datetime.date.today', 'date.today', ([], {}), '()\n', (867, 869), False, 'from datetime import date\n'), ((904, 921), 'datetime.timedelta', 'timedelta', ([], {'days': '(7)'}), '(days=7)\n', (913, 921), False, 'from datetime import timedelta\n'), ((3167, 3177), 'pytrends.request.TrendReq', 'TrendReq', ([], {}), '()\n', (3175, 3177), False, 'from pytrends.request import TrendReq\n'), ((5723, 5747), 'json.dump', 'json.dump', (['markers', 'file'], {}), '(markers, file)\n', (5732, 5747), False, 'import json\n'), ((2398, 2424), 'json.dump', 'json.dump', (['self.data', 'file'], {}), '(self.data, file)\n', (2407, 2424), False, 'import json\n'), ((5600, 5627), 'utils.tools.latitude_longitude', 'tools.latitude_longitude', (['i'], {}), '(i)\n', (5624, 5627), False, 'from utils import tools\n'), ((1396, 1551), 'utils.converters.DateConverter.date_to_unix', 'DateConverter.date_to_unix', (['DataCryptoGenerator.starting_date.year', 'DataCryptoGenerator.starting_date.month', 'DataCryptoGenerator.starting_date.day'], {}), '(DataCryptoGenerator.starting_date.year,\n DataCryptoGenerator.starting_date.month, DataCryptoGenerator.\n starting_date.day)\n', (1422, 1551), False, 'from utils.converters import DateConverter\n'), ((1687, 1831), 'utils.converters.DateConverter.date_to_unix', 'DateConverter.date_to_unix', (['DataCryptoGenerator.ending_date.year', 'DataCryptoGenerator.ending_date.month', 'DataCryptoGenerator.ending_date.day'], {}), '(DataCryptoGenerator.ending_date.year,\n DataCryptoGenerator.ending_date.month, DataCryptoGenerator.ending_date.day)\n', (1713, 1831), False, 'from utils.converters import DateConverter\n'), ((3686, 3697), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (3695, 3697), False, 'import os\n'), ((3757, 3793), 'utils.converters.DateConverter.unix_to_datetime', 'DateConverter.unix_to_datetime', (['i[0]'], {}), '(i[0])\n', (3787, 3793), False, 'from utils.converters import DateConverter\n'), ((3913, 3951), 'numpy.array', 'np.array', (['data[cryptoname].market_caps'], {}), '(data[cryptoname].market_caps)\n', (3921, 3951), True, 'import numpy as np\n'), ((4274, 4285), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4283, 4285), False, 'import os\n'), ((4681, 4717), 'utils.converters.DateConverter.unix_to_datetime', 'DateConverter.unix_to_datetime', (['i[0]'], {}), '(i[0])\n', (4711, 4717), False, 'from utils.converters import DateConverter\n'), ((4819, 4852), 'numpy.array', 'np.array', (['data[cryptoname].prices'], {}), '(data[cryptoname].prices)\n', (4827, 4852), True, 'import numpy as np\n'), ((5127, 5138), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (5136, 5138), False, 'import os\n'), ((5934, 5945), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (5943, 5945), False, 'import os\n'), ((4418, 4450), 'utils.converters.DateConverter.unix_to_date', 'DateConverter.unix_to_date', (['i[0]'], {}), '(i[0])\n', (4444, 4450), False, 'from utils.converters import DateConverter\n'), ((4560, 4593), 'numpy.array', 'np.array', (['data[cryptoname].prices'], {}), '(data[cryptoname].prices)\n', (4568, 4593), True, 'import numpy as np\n'), ((5644, 5655), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (5653, 5655), False, 'import os\n'), ((2315, 2326), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2324, 2326), False, 'import os\n'), ((3281, 3292), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (3290, 3292), False, 'import os\n')]
import json from matplotlib import pyplot as plt import numpy as np from tests.ModelTest import ModelTest import sys, os; sys.path.append(os.path.abspath(os.getcwd()+"/../Python/Export")); class NEURONTest(ModelTest): def subSampleVector(self, nrnVector, everyNth): result = np.array(nrnVector.to_python()) result = result[0:len(result) - 1:int(everyNth)].tolist() return result def subSampleTVI(self, stepsPerMs): t = self.subSampleVector(self.tVector, stepsPerMs) v = self.subSampleVector(self.vVector, stepsPerMs) i = self.subSampleVector(self.iVector, stepsPerMs) return t, v, i def setupRecorders(self, t, v, i): self.tVector = self.h.Vector() self.tVector.record(t) self.vVector = self.h.Vector() self.vVector.record(v) self.iVector = self.h.Vector() self.iVector.record(i) def saveResults(self, result): self.resultsFilePath = self.startPath + "/" + self.resultsFile try: os.mkdir(os.path.dirname(self.resultsFilePath)) except: pass with open(self.resultsFilePath, "w") as file: json.dump(result, file, indent=4) def compareTraces(self, target, resultKey, variable): traces1 = self.loadResults()[resultKey] traces2 = target.loadResults()[resultKey] assert len(traces1) == len(traces2) traceErrors = [] plt.figure(figsize=(20, 10)) for t in range(len(traces1)): i1 = np.array(traces1[t][variable]) i2 = np.array(traces2[t][variable]) rangeExpected = np.max(i1) - np.min(i1) error = np.abs((i2 - i1))/rangeExpected*100.0 # Point-by-point absolute error as percentage of expected value range error[np.isnan(error)] = 100.0 # Treat NaNs as 100% error errorMean = np.mean(error) plt.subplot(len(traces1), 2, 2 * t + 1) plt.plot(traces1[t]['time'], i1, label="NEURON " + traces1[t]["label"]) plt.plot(traces2[t]['time'], i2, label="NeuroML " + traces2[t]["label"]) if (t != len(traces1) - 1): plt.gca().axes.get_xaxis().set_visible(False) plt.legend() plt.subplot(len(traces1), 2, 2 * t + 2) plt.plot(traces1[t]['time'], error, label="|Error| (mean: " + str(errorMean) + "%)") if (t != len(traces1) - 1): plt.gca().axes.get_xaxis().set_visible(False) plt.legend() traceErrors.append(errorMean) self.comparisonMean = np.mean(traceErrors) plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05, hspace=0.05) plt.suptitle(self.label + " Conversion Error: " + str(self.comparisonMean) + "%") # plt.show() plt.savefig(self.comparisonPath()) return self.comparisonMean def loadNEURONandModFiles(self): from neuron import h, gui self.h = h
[ "numpy.mean", "matplotlib.pyplot.subplots_adjust", "numpy.abs", "matplotlib.pyplot.legend", "matplotlib.pyplot.gca", "matplotlib.pyplot.plot", "os.getcwd", "numpy.max", "numpy.array", "matplotlib.pyplot.figure", "os.path.dirname", "numpy.isnan", "numpy.min", "json.dump" ]
[((1502, 1530), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 10)'}), '(figsize=(20, 10))\n', (1512, 1530), True, 'from matplotlib import pyplot as plt\n'), ((2689, 2709), 'numpy.mean', 'np.mean', (['traceErrors'], {}), '(traceErrors)\n', (2696, 2709), True, 'import numpy as np\n'), ((2721, 2799), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.05)', 'right': '(0.95)', 'top': '(0.95)', 'bottom': '(0.05)', 'hspace': '(0.05)'}), '(left=0.05, right=0.95, top=0.95, bottom=0.05, hspace=0.05)\n', (2740, 2799), True, 'from matplotlib import pyplot as plt\n'), ((158, 169), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (167, 169), False, 'import sys, os\n'), ((1223, 1256), 'json.dump', 'json.dump', (['result', 'file'], {'indent': '(4)'}), '(result, file, indent=4)\n', (1232, 1256), False, 'import json\n'), ((1590, 1620), 'numpy.array', 'np.array', (['traces1[t][variable]'], {}), '(traces1[t][variable])\n', (1598, 1620), True, 'import numpy as np\n'), ((1639, 1669), 'numpy.array', 'np.array', (['traces2[t][variable]'], {}), '(traces2[t][variable])\n', (1647, 1669), True, 'import numpy as np\n'), ((1949, 1963), 'numpy.mean', 'np.mean', (['error'], {}), '(error)\n', (1956, 1963), True, 'import numpy as np\n'), ((2032, 2103), 'matplotlib.pyplot.plot', 'plt.plot', (["traces1[t]['time']", 'i1'], {'label': "('NEURON ' + traces1[t]['label'])"}), "(traces1[t]['time'], i1, label='NEURON ' + traces1[t]['label'])\n", (2040, 2103), True, 'from matplotlib import pyplot as plt\n'), ((2117, 2189), 'matplotlib.pyplot.plot', 'plt.plot', (["traces2[t]['time']", 'i2'], {'label': "('NeuroML ' + traces2[t]['label'])"}), "(traces2[t]['time'], i2, label='NeuroML ' + traces2[t]['label'])\n", (2125, 2189), True, 'from matplotlib import pyplot as plt\n'), ((2311, 2323), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2321, 2323), True, 'from matplotlib import pyplot as plt\n'), ((2598, 2610), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2608, 2610), True, 'from matplotlib import pyplot as plt\n'), ((1079, 1116), 'os.path.dirname', 'os.path.dirname', (['self.resultsFilePath'], {}), '(self.resultsFilePath)\n', (1094, 1116), False, 'import sys, os\n'), ((1699, 1709), 'numpy.max', 'np.max', (['i1'], {}), '(i1)\n', (1705, 1709), True, 'import numpy as np\n'), ((1712, 1722), 'numpy.min', 'np.min', (['i1'], {}), '(i1)\n', (1718, 1722), True, 'import numpy as np\n'), ((1872, 1887), 'numpy.isnan', 'np.isnan', (['error'], {}), '(error)\n', (1880, 1887), True, 'import numpy as np\n'), ((1744, 1759), 'numpy.abs', 'np.abs', (['(i2 - i1)'], {}), '(i2 - i1)\n', (1750, 1759), True, 'import numpy as np\n'), ((2250, 2259), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2257, 2259), True, 'from matplotlib import pyplot as plt\n'), ((2537, 2546), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2544, 2546), True, 'from matplotlib import pyplot as plt\n')]
#!/usr/bin/python # -*- coding: utf-8 -*- import core from random import shuffle import copy import numpy import logging # http://code.activestate.com/recipes/521906-k-fold-cross-validation-partition/ def gridSearch(training_data, trainer, original_data_model, k=3, search_space=[.00001, .0001, .001, .01, .1, 1], randomize=True): training_data = training_data[numpy.random.permutation(training_data.size)] logging.info('using cross validation to find optimum alpha...') scores = [] fields = sorted(original_data_model['fields'].keys()) for alpha in search_space: all_score = 0 all_N = 0 for (training, validation) in kFolds(training_data, k): data_model = trainer(training, original_data_model, alpha) weight = numpy.array([data_model['fields'][field]['weight'] for field in fields]) bias = data_model['bias'] labels = validation['label'] predictions = numpy.dot(validation['distances'], weight) + bias true_dupes = numpy.sum(labels == 1) if true_dupes == 0 : logging.warning("not real positives, change size of folds") continue true_predicted_dupes = numpy.sum(predictions[labels == 1] > 0) recall = true_predicted_dupes/float(true_dupes) if recall == 0 : score = 0 else: precision = true_predicted_dupes/float(numpy.sum(predictions > 0)) score = 2 * recall * precision / (recall + precision) all_score += score average_score = all_score/k logging.debug("Average Score: %f", average_score) scores.append(average_score) best_alpha = search_space[::-1][scores[::-1].index(max(scores))] logging.info('optimum alpha: %f' % best_alpha) return best_alpha def kFolds(training_data, k): train_dtype = training_data.dtype slices = [training_data[i::k] for i in xrange(k)] for i in xrange(k): validation = slices[i] training = [datum for s in slices if s is not validation for datum in s] validation = numpy.array(validation, train_dtype) training = numpy.array(training, train_dtype) yield (training, validation)
[ "logging.debug", "logging.warning", "numpy.sum", "numpy.array", "numpy.dot", "logging.info", "numpy.random.permutation" ]
[((496, 559), 'logging.info', 'logging.info', (['"""using cross validation to find optimum alpha..."""'], {}), "('using cross validation to find optimum alpha...')\n", (508, 559), False, 'import logging\n'), ((1917, 1963), 'logging.info', 'logging.info', (["('optimum alpha: %f' % best_alpha)"], {}), "('optimum alpha: %f' % best_alpha)\n", (1929, 1963), False, 'import logging\n'), ((445, 489), 'numpy.random.permutation', 'numpy.random.permutation', (['training_data.size'], {}), '(training_data.size)\n', (469, 489), False, 'import numpy\n'), ((1754, 1803), 'logging.debug', 'logging.debug', (['"""Average Score: %f"""', 'average_score'], {}), "('Average Score: %f', average_score)\n", (1767, 1803), False, 'import logging\n'), ((2267, 2303), 'numpy.array', 'numpy.array', (['validation', 'train_dtype'], {}), '(validation, train_dtype)\n', (2278, 2303), False, 'import numpy\n'), ((2323, 2357), 'numpy.array', 'numpy.array', (['training', 'train_dtype'], {}), '(training, train_dtype)\n', (2334, 2357), False, 'import numpy\n'), ((864, 936), 'numpy.array', 'numpy.array', (["[data_model['fields'][field]['weight'] for field in fields]"], {}), "([data_model['fields'][field]['weight'] for field in fields])\n", (875, 936), False, 'import numpy\n'), ((1153, 1175), 'numpy.sum', 'numpy.sum', (['(labels == 1)'], {}), '(labels == 1)\n', (1162, 1175), False, 'import numpy\n'), ((1347, 1386), 'numpy.sum', 'numpy.sum', (['(predictions[labels == 1] > 0)'], {}), '(predictions[labels == 1] > 0)\n', (1356, 1386), False, 'import numpy\n'), ((1077, 1119), 'numpy.dot', 'numpy.dot', (["validation['distances']", 'weight'], {}), "(validation['distances'], weight)\n", (1086, 1119), False, 'import numpy\n'), ((1226, 1285), 'logging.warning', 'logging.warning', (['"""not real positives, change size of folds"""'], {}), "('not real positives, change size of folds')\n", (1241, 1285), False, 'import logging\n'), ((1578, 1604), 'numpy.sum', 'numpy.sum', (['(predictions > 0)'], {}), '(predictions > 0)\n', (1587, 1604), False, 'import numpy\n')]
from pathlib import Path import numpy as np from torchvision.transforms import transforms from torch.utils.data import Dataset from utils.logger import get_logger, Logger from utils.utils import namedtuple, load_mnist, Phase class BaseDataset(Dataset): def __init__(self, dataset_path:str, test_size:float=0.2, phase:Phase=Phase.TRAIN, logger:Logger=None): super().__init__() self.dataset_path = Path(dataset_path) self.test_size = test_size self.phase = phase self.logger = logger if logger is not None else get_logger('Dataset') self.__initialize__() self.dev_data = self.__dev_data() def __initialize__(self): # self.train_data, self.test_data = self.__load_data__(self.dataset_path) self.train_data, self.test_data = None, None raise NotImplementedError() def __dev_data(self): return {idx: self.train_data[idx] for idx in range(1000)} def __load_data__(self, dataset_path:Path): '''return (train_data, test_data, label_data)''' # return train_data, test_data, label_data raise NotImplementedError() def __len__(self): if self.phase == Phase.TRAIN: return len(self.train_data) elif self.phase == Phase.DEV: return len(self.dev_data) elif self.phase == Phase.TEST: return len(self.test_data) raise RuntimeError(f'Unknown phase: {self.pahse}') def __getitem__(self, index): if self.phase == Phase.TRAIN: target_index = self.train_indices[index] data = self.train_data[target_index] raise NotImplementedError() elif self.phase == Phase.TEST: target_index = self.test_indices[index] data = self.test_data[target_index] raise NotImplementedError() raise RuntimeError(f'Unknown phase: {self.pahse}') # phase change functions def train(self): self.phase = Phase.TRAIN def test(self): self.phase = Phase.TEST MnistItem = namedtuple('MnistItem', ('image', 'label')) class MnistDataset(BaseDataset): def __init__(self, dataset_path:str, test_size:float=0.2, phase:Phase=Phase.TRAIN, logger:Logger=None): super().__init__(dataset_path, test_size, phase, logger) def __initialize__(self): self.train_data, self.test_data = self.__load_data__(self.dataset_path) self.transform = transforms.Compose([ transforms.ToTensor(), ]) def __load_data__(self, dataset_path:Path): train_images, train_labels = load_mnist(dataset_path, Phase.TRAIN) test_images, test_labels = load_mnist(dataset_path, Phase.TEST) # list -> dict train_data = {idx: MnistItem(data.reshape(28, 28), label) for idx, (data, label) in enumerate(zip(train_images, train_labels))} test_data = {idx: MnistItem(data.reshape(28, 28), label) for idx, (data, label) in enumerate(zip(test_images, test_labels))} return train_data, test_data def __getitem__(self, index): if self.phase == Phase.TRAIN or self.phase == Phase.VALID: data:MnistItem = self.train_data[index] label = data.label data = self.transform(np.array(data.image)) return data, label elif self.phase == Phase.DEV: data:MnistItem = self.dev_data[index] label = data.label data = self.transform(np.array(data.image)) return data, label elif self.phase == Phase.TEST: data:MnistItem = self.test_data[index] data = self.transform(np.array(data.image)) return data raise RuntimeError(f'Unknown phase: {self.pahse}')
[ "pathlib.Path", "numpy.array", "torchvision.transforms.transforms.ToTensor", "utils.utils.namedtuple", "utils.logger.get_logger", "utils.utils.load_mnist" ]
[((2057, 2100), 'utils.utils.namedtuple', 'namedtuple', (['"""MnistItem"""', "('image', 'label')"], {}), "('MnistItem', ('image', 'label'))\n", (2067, 2100), False, 'from utils.utils import namedtuple, load_mnist, Phase\n'), ((419, 437), 'pathlib.Path', 'Path', (['dataset_path'], {}), '(dataset_path)\n', (423, 437), False, 'from pathlib import Path\n'), ((2601, 2638), 'utils.utils.load_mnist', 'load_mnist', (['dataset_path', 'Phase.TRAIN'], {}), '(dataset_path, Phase.TRAIN)\n', (2611, 2638), False, 'from utils.utils import namedtuple, load_mnist, Phase\n'), ((2674, 2710), 'utils.utils.load_mnist', 'load_mnist', (['dataset_path', 'Phase.TEST'], {}), '(dataset_path, Phase.TEST)\n', (2684, 2710), False, 'from utils.utils import namedtuple, load_mnist, Phase\n'), ((556, 577), 'utils.logger.get_logger', 'get_logger', (['"""Dataset"""'], {}), "('Dataset')\n", (566, 577), False, 'from utils.logger import get_logger, Logger\n'), ((2481, 2502), 'torchvision.transforms.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2500, 2502), False, 'from torchvision.transforms import transforms\n'), ((3271, 3291), 'numpy.array', 'np.array', (['data.image'], {}), '(data.image)\n', (3279, 3291), True, 'import numpy as np\n'), ((3479, 3499), 'numpy.array', 'np.array', (['data.image'], {}), '(data.image)\n', (3487, 3499), True, 'import numpy as np\n'), ((3657, 3677), 'numpy.array', 'np.array', (['data.image'], {}), '(data.image)\n', (3665, 3677), True, 'import numpy as np\n')]
from .advection_step_3P import advection_step_3P from .spectral import vertwind from ..core.state import State #, variables import numpy as np def wrap_wv(history, grid, params, alpha_method, order_alpha, F_method, verbose=0, **kwargs): """Wrap the water vapor method to fit the architecture. :param history: Current history of state :type history: :class:`History` object :param grid: Spatial grid of the simulation :type grid: :class:`Grid` object :param params: Dictionary of usefull parameters :type params: dictionary :param alpha_method: see :class:`advection_step_3P` :type alpha_method: str :param order_alpha: see :class:`advection_step_3P` :type order_alpha: int :param F_method: see :class:`advection_step_3P` :type F_method: str :param verbose: verbose, defaults to 0 :type verbose: int, optional """ assert history.size > 2 pre_state = history.state_list[-3] cur_state = history.state_list[-2] new_state = history.state_list[-1] dt = cur_state.t - pre_state.t # constant step invar = np.array([pre_state.vrs['Delta_z'],pre_state.vrs['Delta_T_hist']]) a_us, a_vs, outvar = advection_step_3P(pre_state.vrs['alpha_us'], pre_state.vrs['alpha_vs'], invar, dt, cur_state.vrs['us'], cur_state.vrs['vs'], grid.dx, grid.dy, alpha_method, order_alpha, F_method, verbose) print(" us vs done") if verbose > 2 else None new_dz = outvar[0] new_dT_hist = outvar[1] #UPDATE OF W --------------------------------------------------- k_hour = int(3600/dt) if ((np.floor(cur_state.t/dt)-1)%k_hour==0 ): cur_w = vertwind(grid.Lx, grid.Ly, cur_state.vrs['theta_t'], pre_state.vrs['theta_t'], dt, params, z=params['z_star']) new_w = vertwind(grid.Lx, grid.Ly, new_state.vrs['theta_t'], cur_state.vrs['theta_t'], dt, params, z=params['z_star']) mean_w = (cur_w + new_w)/2. cur_state.vrs['Delta_z'] += k_hour * dt * mean_w new_dz += k_hour * dt * mean_w dT_disp = params['gamma_2'] * cur_state.vrs['Delta_z'] dT_cloud = params['Delta_Tc'] * ( cur_state.vrs['Delta_z'] > params['Delta_zc'] ) dT_bb = cur_state.vrs['Delta_T_hist'] + dT_disp + dT_cloud cur_state.vrs['alpha_us'] = a_us cur_state.vrs['alpha_vs'] = a_vs new_state.vrs['Delta_z'] = new_dz new_state.vrs['Delta_T_hist'] = new_dT_hist cur_state.vrs['Delta_T_bb'] = dT_bb
[ "numpy.array", "numpy.floor" ]
[((1098, 1165), 'numpy.array', 'np.array', (["[pre_state.vrs['Delta_z'], pre_state.vrs['Delta_T_hist']]"], {}), "([pre_state.vrs['Delta_z'], pre_state.vrs['Delta_T_hist']])\n", (1106, 1165), True, 'import numpy as np\n'), ((2074, 2100), 'numpy.floor', 'np.floor', (['(cur_state.t / dt)'], {}), '(cur_state.t / dt)\n', (2082, 2100), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import timedelta, datetime plt.style.use('seaborn') # # download the new datasheet form JH # url ="https://s3-us-west-1.amazonaws.com/starschema.covid/JHU_COVID-19.csv" # url ="https://covid.ourworldindata.org/data/ecdc/full_data.csv" # output_directory = "." printimage = 'on' # on ou off # read a csv to DataFrame with pandas data = pd.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/jhu/full_data.csv") # data = pd.read_csv('/home/claudio/Documents/profissao_DS/projetos/corona/JHU_COVID-19.csv') # data = pd.read_csv('/home/claudio/Documents/profissao_DS/projetos/corona/full_data.csv') data.index = pd.to_datetime(data.date) ## sel data form Brazil ctry = data[data["location"] == 'Brazil'] tested = ctry.copy() dateCase = [] # do fiting3 ydata = tested.last("60W").resample('1W').mean().total_cases.values # ydata = tested.last("3W").total_cases.values xdata = np.arange(len(ydata)) ndate = tested.last("1D").index[0] for i in range(5): dateCase.append((ndate + timedelta(days=i)).date()) dateCase = pd.to_datetime(dateCase) # ajuste exponencial com a func, dos dados xdata e ydata Brasil from scipy.optimize import curve_fit def func(x, a, b, c): return a * np.exp(b * x) + c poptbr, pcovbr = curve_fit(func, xdata, ydata) perrbr = np.sqrt(np.diag(pcovbr)) # Forecast 5 days # ultimo = (ndate-case1).days # prbrxdata = np.arange(ultimo-1,ultimo+4) ultimo = len(xdata) prbrxdata = np.arange(ultimo - 1, ultimo + 4) prbrdata = func(prbrxdata, *poptbr) serro = func(prbrxdata, *(poptbr + perrbr)) ierro = func(prbrxdata, *poptbr - perrbr) hojebr = func(len(xdata)+1, *poptbr) # Prediction table to Br new = [] for i in dateCase.to_pydatetime(): new.append(i.strftime(format="%Y-%m-%d")) tocsv = pd.DataFrame() tocsv["Date"] = np.array(new) tocsv["Prediction"] = prbrdata.astype('int') tocsv.to_csv('./prediction_br.csv',index=False) # Graphic Brazil fig = plt.figure(figsize=[10, 6]) ax2 = plt.subplot() ax2.plot(dateCase[-len(prbrdata):], prbrdata, "b*-", label="5-day Forecast") # ax2.plot(dateCase[-len(prbrdata):], ierro, 'k--', lw=.8) # ax2.plot(dateCase[-len(prbrdata):], serro, 'k--', lw=.8) ax2.plot(tested.index, tested["total_cases"], "k*--", label="Confirmed Brazil") ax2.set_title("COVID19 - Brazil data updated "+str(tested["date"][tested.index[-1]])) ax2.text(pd.to_datetime('2021-05-20'), 30, 'update on ' + str(datetime.now().date())) ax2.set_xlabel("Date") ax2.set_ylabel("Number of Infections") ax2.set_xlim(pd.to_datetime("2020-03-01").date(), datetime.now().date()+timedelta(days=5)) ax2.set_yscale('log') ax2.set_ylim(1,) ax2.legend(loc="center right") ax2.grid('both','both') plt.show() fig.savefig("./images/log_data_forecast_brazil.png", dpi=350) # Countreis of South America ############################SA############## ############################SA############## total_data = data.copy() sa = ['Argentina', 'Bolivia', 'Brazil', 'Chile', 'Colombia', 'Ecuador', 'Falkland Islands', 'French Guiana', 'Guyana', 'Paraguay', 'Peru', 'Suriname', 'Uruguay', 'Venezuela'] sa = sorted(sa) san = total_data[(total_data.location.isin(sa))] san = san.drop(['date'], axis=1) psum = san.groupby('date').total_cases.sum() ############################SA############## today = datetime.now().date() fig = plt.figure(figsize=[10, 6]) ax = plt.subplot() for ii in sa: p = total_data[(total_data["location"] == ii) & (total_data["total_cases"] > 26.)] if len(p) > 0: ax.plot(pd.to_datetime(p.date),p.total_cases, label=ii) lf = p.total_cases.index[p.total_cases.argmax()].date() # ax.text(lf+timedelta(days=2),p.total_cases.max(), ii) ax.plot(psum,'-*',label= 'sum South America') ax.text(pd.to_datetime('2020-06-01'), 30, 'update on ' + str(today)) ax.set_yscale('log') ax.set_title("Countries of South America") ax.set_ylabel("Number of Infections") ax.set_xlim(pd.to_datetime('2020-03-13').date(), lf+timedelta(days=15)) ax.set_xlabel('Date when over 20 cases confirmeds') ax.set_ylim(10,) plt.legend(loc='upper right', bbox_to_anchor=(1.0, 0.3), shadow=True, ncol=2, fontsize=8) if printimage == "off": fig.savefig("images/southAmerica_brazil.png", dpi=350) plt.close() else: plt.show() fig.savefig("images/southAmerica_brazil.png", dpi=350) ############################ Countries bordering of Brazil ############################ ############################ Countries bordering of Brazil ############################ ############################ Countries bordering of Brazil ############################ borderBR = ['Argentina', 'Bolivia', 'Brazil', 'Colombia', 'French Guiana', 'Guyana', 'Paraguay', 'Peru', 'Suriname'] borderBR = sorted(borderBR) ############################ fig = plt.figure(figsize=[10, 6]) ax = plt.subplot() for ii in borderBR: p = total_data[(total_data["location"] == ii) & (total_data["total_cases"] > 26.)] if len(p) > 0: ax.plot(pd.to_datetime(p.date),p.total_cases, label=ii) lf = p.total_cases.index[p.total_cases.argmax()].date() # ax.text(lf+timedelta(days=2),p.total_cases.max(), ii) ax.text(pd.to_datetime('2020-06-01'), 20, 'update on ' + str(today)) # ax.set_yscale('log') ax.set_title("Countries bordering of Brazil") ax.set_ylabel("Number of Infections") ax.set_xlim(pd.to_datetime('2020-03-13').date(), lf+timedelta(days=15)) ax.set_xlabel('Date when over 20 cases confirmeds') ax.set_ylim(10,) plt.legend(loc='upper right', bbox_to_anchor=(1.0, 0.3), shadow=True, ncol=2, fontsize=8) if printimage == "off": fig.savefig("images/border_brazil.png", dpi=350) plt.close() else: plt.show() fig.savefig("images/border_brazil.png", dpi=350) ################# world############################ world########### ################# world############################ world########### top = total_data[~total_data.location.isin(['World'])].sort_values('total_cases',ascending=False).location.unique()[:5] ################# world############################ world########### ################# world############################ world########### fig = plt.figure(figsize=[10, 6]) ax = plt.subplot() for ii in top: p = total_data[(total_data["location"] == ii) & (total_data["total_cases"] > 100.)] if len(p) > 0: ax.plot(p.total_cases, label=ii) lf = p.total_cases.index[p.total_cases.argmax()].date() # ax.text(lf+timedelta(days=2),p.total_cases.max(), ii) ax.text(pd.to_datetime('2020-06-01'), 200, 'update on ' + str(today)) ax.set_yscale('log') ax.set_title("Countries of World") ax.set_ylabel("Number of Infections") ax.set_xlim(pd.to_datetime('2020-03-13').date(), lf+timedelta(days=16)) ax.set_xlabel('Days after the day with over 100 cases confirmeds') plt.legend(loc='upper right', bbox_to_anchor=(1.0, 0.3), shadow=True, ncol=1, fontsize=8) if printimage == "off": fig.savefig("images/top_world.png", dpi=350) plt.close() else: plt.show() fig.savefig("images/top_world.png", dpi=350) # top 5 STATES OF BRAZIL######################## # top 5 STATES OF BRAZIL######################## # top 5 STATES OF BRAZIL######################## url = "https://raw.githubusercontent.com/wcota/covid19br/master/cases-brazil-states.csv" dados_brazil = pd.read_csv(url, header=0, index_col="date") ############ ############ dados_brazil.index = pd.to_datetime(dados_brazil.index) queryNA = dados_brazil.loc[:, ["state", "totalCases"]].where((dados_brazil["state"] != 'TOTAL') & (dados_brazil["totalCases"] > 26.)).dropna().sort_values(by="totalCases",ascending=False) TOP5 = queryNA.state.unique()[:5] print(TOP5) ########################### TOP 5 ############ ############ ############ fig = plt.figure(figsize=[10, 6]) ax = plt.subplot() # totalCases_per_100k_inhabitants for ii in TOP5: p = dados_brazil[(dados_brazil["state"] == ii) & (dados_brazil["totalCases"] > 26.)] if len(p) > 0: ax.plot(p.totalCases_per_100k_inhabitants, label=ii) lf = p.totalCases_per_100k_inhabitants.index[p.totalCases_per_100k_inhabitants.argmax()].date() # ax.text(lf+timedelta(days=2),p.totalCases_per_100k_inhabitants.max(), ii) ax.text(pd.to_datetime('2020-06-01'), 1, 'update on ' + str(today)) ax.set_yscale('log') ax.set_title("5 States of Brazil") ax.set_ylabel("Number of Infections / 100mil hab") ax.set_xlim(pd.to_datetime('2020-03-13').date(), lf+timedelta(days=15)) ax.set_xlabel('Date when over 20 cases confirmeds') plt.legend(loc='upper right', bbox_to_anchor=(1.0, 0.3), shadow=True, ncol=1) plt.grid("both") if printimage == "off": fig.savefig("images/n20cases_TOP5.png", dpi=350) plt.close() else: plt.show() fig.savefig("images/n20cases_TOP5.png", dpi=350) ########################### FATALITY RATE OF BRAZIL ############ ############ ############ morte = dados_brazil.groupby('state')['deaths_by_totalCases'].last().mul(100) nx = morte.index.values.astype('str') nx[-1] = "BR" import matplotlib.ticker as mtick # Graphic Brazil fig = plt.figure(figsize=[10, 6]) ax2 = plt.subplot() # Fatality rate ax2.bar(nx[:-1], morte.values[:-1],label="Fatality",color='black') ax2.bar(nx[-1], morte.values[-1],color='red',label="Fatality of Brazil") ax2.text('AC', 5.0, 'update on ' + str(datetime.now().date())) ax2.set_xlabel("States of Brazil") yticks = mtick.FormatStrFormatter('%.2f%%') ax2.yaxis.set_major_formatter(yticks) ax2.set_ylabel("Fatality") ax2.set_xlim('AC', 'BR') ax2.legend(loc="upper left") plt.grid("both","both") if printimage == "off": fig.savefig("images/fatality_rate.png", dpi=350) plt.close() else: plt.show() fig.savefig("images/fatality_rate.png", dpi=350)
[ "scipy.optimize.curve_fit", "matplotlib.pyplot.grid", "pandas.read_csv", "numpy.arange", "matplotlib.pyplot.legend", "matplotlib.pyplot.style.use", "numpy.diag", "matplotlib.pyplot.close", "numpy.array", "matplotlib.pyplot.figure", "datetime.datetime.now", "numpy.exp", "pandas.DataFrame", ...
[((113, 137), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (126, 137), True, 'import matplotlib.pyplot as plt\n'), ((423, 537), 'pandas.read_csv', 'pd.read_csv', (['"""https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/jhu/full_data.csv"""'], {}), "(\n 'https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/jhu/full_data.csv'\n )\n", (434, 537), True, 'import pandas as pd\n'), ((728, 753), 'pandas.to_datetime', 'pd.to_datetime', (['data.date'], {}), '(data.date)\n', (742, 753), True, 'import pandas as pd\n'), ((1135, 1159), 'pandas.to_datetime', 'pd.to_datetime', (['dateCase'], {}), '(dateCase)\n', (1149, 1159), True, 'import pandas as pd\n'), ((1335, 1364), 'scipy.optimize.curve_fit', 'curve_fit', (['func', 'xdata', 'ydata'], {}), '(func, xdata, ydata)\n', (1344, 1364), False, 'from scipy.optimize import curve_fit\n'), ((1522, 1555), 'numpy.arange', 'np.arange', (['(ultimo - 1)', '(ultimo + 4)'], {}), '(ultimo - 1, ultimo + 4)\n', (1531, 1555), True, 'import numpy as np\n'), ((1839, 1853), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1851, 1853), True, 'import pandas as pd\n'), ((1870, 1883), 'numpy.array', 'np.array', (['new'], {}), '(new)\n', (1878, 1883), True, 'import numpy as np\n'), ((2001, 2028), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[10, 6]'}), '(figsize=[10, 6])\n', (2011, 2028), True, 'import matplotlib.pyplot as plt\n'), ((2035, 2048), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {}), '()\n', (2046, 2048), True, 'import matplotlib.pyplot as plt\n'), ((2746, 2756), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2754, 2756), True, 'import matplotlib.pyplot as plt\n'), ((3371, 3398), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[10, 6]'}), '(figsize=[10, 6])\n', (3381, 3398), True, 'import matplotlib.pyplot as plt\n'), ((3404, 3417), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {}), '()\n', (3415, 3417), True, 'import matplotlib.pyplot as plt\n'), ((4089, 4183), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'bbox_to_anchor': '(1.0, 0.3)', 'shadow': '(True)', 'ncol': '(2)', 'fontsize': '(8)'}), "(loc='upper right', bbox_to_anchor=(1.0, 0.3), shadow=True, ncol=\n 2, fontsize=8)\n", (4099, 4183), True, 'import matplotlib.pyplot as plt\n'), ((4794, 4821), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[10, 6]'}), '(figsize=[10, 6])\n', (4804, 4821), True, 'import matplotlib.pyplot as plt\n'), ((4827, 4840), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {}), '()\n', (4838, 4840), True, 'import matplotlib.pyplot as plt\n'), ((5477, 5571), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'bbox_to_anchor': '(1.0, 0.3)', 'shadow': '(True)', 'ncol': '(2)', 'fontsize': '(8)'}), "(loc='upper right', bbox_to_anchor=(1.0, 0.3), shadow=True, ncol=\n 2, fontsize=8)\n", (5487, 5571), True, 'import matplotlib.pyplot as plt\n'), ((6130, 6157), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[10, 6]'}), '(figsize=[10, 6])\n', (6140, 6157), True, 'import matplotlib.pyplot as plt\n'), ((6163, 6176), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {}), '()\n', (6174, 6176), True, 'import matplotlib.pyplot as plt\n'), ((6772, 6866), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'bbox_to_anchor': '(1.0, 0.3)', 'shadow': '(True)', 'ncol': '(1)', 'fontsize': '(8)'}), "(loc='upper right', bbox_to_anchor=(1.0, 0.3), shadow=True, ncol=\n 1, fontsize=8)\n", (6782, 6866), True, 'import matplotlib.pyplot as plt\n'), ((7262, 7306), 'pandas.read_csv', 'pd.read_csv', (['url'], {'header': '(0)', 'index_col': '"""date"""'}), "(url, header=0, index_col='date')\n", (7273, 7306), True, 'import pandas as pd\n'), ((7354, 7388), 'pandas.to_datetime', 'pd.to_datetime', (['dados_brazil.index'], {}), '(dados_brazil.index)\n', (7368, 7388), True, 'import pandas as pd\n'), ((7702, 7729), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[10, 6]'}), '(figsize=[10, 6])\n', (7712, 7729), True, 'import matplotlib.pyplot as plt\n'), ((7735, 7748), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {}), '()\n', (7746, 7748), True, 'import matplotlib.pyplot as plt\n'), ((8455, 8532), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'bbox_to_anchor': '(1.0, 0.3)', 'shadow': '(True)', 'ncol': '(1)'}), "(loc='upper right', bbox_to_anchor=(1.0, 0.3), shadow=True, ncol=1)\n", (8465, 8532), True, 'import matplotlib.pyplot as plt\n'), ((8533, 8549), 'matplotlib.pyplot.grid', 'plt.grid', (['"""both"""'], {}), "('both')\n", (8541, 8549), True, 'import matplotlib.pyplot as plt\n'), ((8986, 9013), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[10, 6]'}), '(figsize=[10, 6])\n', (8996, 9013), True, 'import matplotlib.pyplot as plt\n'), ((9020, 9033), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {}), '()\n', (9031, 9033), True, 'import matplotlib.pyplot as plt\n'), ((9297, 9331), 'matplotlib.ticker.FormatStrFormatter', 'mtick.FormatStrFormatter', (['"""%.2f%%"""'], {}), "('%.2f%%')\n", (9321, 9331), True, 'import matplotlib.ticker as mtick\n'), ((9451, 9475), 'matplotlib.pyplot.grid', 'plt.grid', (['"""both"""', '"""both"""'], {}), "('both', 'both')\n", (9459, 9475), True, 'import matplotlib.pyplot as plt\n'), ((1382, 1397), 'numpy.diag', 'np.diag', (['pcovbr'], {}), '(pcovbr)\n', (1389, 1397), True, 'import numpy as np\n'), ((2422, 2450), 'pandas.to_datetime', 'pd.to_datetime', (['"""2021-05-20"""'], {}), "('2021-05-20')\n", (2436, 2450), True, 'import pandas as pd\n'), ((3785, 3813), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-06-01"""'], {}), "('2020-06-01')\n", (3799, 3813), True, 'import pandas as pd\n'), ((4260, 4271), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4269, 4271), True, 'import matplotlib.pyplot as plt\n'), ((4280, 4290), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4288, 4290), True, 'import matplotlib.pyplot as plt\n'), ((5168, 5196), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-06-01"""'], {}), "('2020-06-01')\n", (5182, 5196), True, 'import pandas as pd\n'), ((5643, 5654), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5652, 5654), True, 'import matplotlib.pyplot as plt\n'), ((5663, 5673), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5671, 5673), True, 'import matplotlib.pyplot as plt\n'), ((6477, 6505), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-06-01"""'], {}), "('2020-06-01')\n", (6491, 6505), True, 'import pandas as pd\n'), ((6933, 6944), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6942, 6944), True, 'import matplotlib.pyplot as plt\n'), ((6953, 6963), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6961, 6963), True, 'import matplotlib.pyplot as plt\n'), ((8164, 8192), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-06-01"""'], {}), "('2020-06-01')\n", (8178, 8192), True, 'import pandas as pd\n'), ((8625, 8636), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (8634, 8636), True, 'import matplotlib.pyplot as plt\n'), ((8645, 8655), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8653, 8655), True, 'import matplotlib.pyplot as plt\n'), ((9550, 9561), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9559, 9561), True, 'import matplotlib.pyplot as plt\n'), ((9570, 9580), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9578, 9580), True, 'import matplotlib.pyplot as plt\n'), ((2633, 2650), 'datetime.timedelta', 'timedelta', ([], {'days': '(5)'}), '(days=5)\n', (2642, 2650), False, 'from datetime import timedelta, datetime\n'), ((3343, 3357), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3355, 3357), False, 'from datetime import timedelta, datetime\n'), ((4000, 4018), 'datetime.timedelta', 'timedelta', ([], {'days': '(15)'}), '(days=15)\n', (4009, 4018), False, 'from datetime import timedelta, datetime\n'), ((5388, 5406), 'datetime.timedelta', 'timedelta', ([], {'days': '(15)'}), '(days=15)\n', (5397, 5406), False, 'from datetime import timedelta, datetime\n'), ((6685, 6703), 'datetime.timedelta', 'timedelta', ([], {'days': '(16)'}), '(days=16)\n', (6694, 6703), False, 'from datetime import timedelta, datetime\n'), ((8383, 8401), 'datetime.timedelta', 'timedelta', ([], {'days': '(15)'}), '(days=15)\n', (8392, 8401), False, 'from datetime import timedelta, datetime\n'), ((1300, 1313), 'numpy.exp', 'np.exp', (['(b * x)'], {}), '(b * x)\n', (1306, 1313), True, 'import numpy as np\n'), ((2574, 2602), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-03-01"""'], {}), "('2020-03-01')\n", (2588, 2602), True, 'import pandas as pd\n'), ((3555, 3577), 'pandas.to_datetime', 'pd.to_datetime', (['p.date'], {}), '(p.date)\n', (3569, 3577), True, 'import pandas as pd\n'), ((3960, 3988), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-03-13"""'], {}), "('2020-03-13')\n", (3974, 3988), True, 'import pandas as pd\n'), ((4984, 5006), 'pandas.to_datetime', 'pd.to_datetime', (['p.date'], {}), '(p.date)\n', (4998, 5006), True, 'import pandas as pd\n'), ((5348, 5376), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-03-13"""'], {}), "('2020-03-13')\n", (5362, 5376), True, 'import pandas as pd\n'), ((6645, 6673), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-03-13"""'], {}), "('2020-03-13')\n", (6659, 6673), True, 'import pandas as pd\n'), ((8343, 8371), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-03-13"""'], {}), "('2020-03-13')\n", (8357, 8371), True, 'import pandas as pd\n'), ((2611, 2625), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2623, 2625), False, 'from datetime import timedelta, datetime\n'), ((1097, 1114), 'datetime.timedelta', 'timedelta', ([], {'days': 'i'}), '(days=i)\n', (1106, 1114), False, 'from datetime import timedelta, datetime\n'), ((2475, 2489), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2487, 2489), False, 'from datetime import timedelta, datetime\n'), ((9229, 9243), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (9241, 9243), False, 'from datetime import timedelta, datetime\n')]
import cv2 import numpy as np from PIL import Image import os, glob import characters as cd # 画像が保存されているルートディレクトリのパス root_dir = "../learning_data" # キャラクター名一覧 characters = cd.characters_name_mask # 画像データ用配列 X = [] # ラベルデータ用配列 Y = [] # 画像データごとにadd_sample()を呼び出し、X,Yの配列を返す関数 def make_sample(files): global X, Y X = [] Y = [] for cat, fname in files: add_sample(cat, fname) return np.array(X), np.array(Y) # 渡された画像データを読み込んでXに格納し、また、 # 画像データに対応するcategoriesのidxをY格納する関数 def add_sample(cat, fname): img = Image.open(fname) img = img.resize((202, 23)) data = np.asarray(img) data_gray = cv2.cvtColor(data, cv2.COLOR_RGB2GRAY) ret, result = cv2.threshold(data_gray, 180, 255, cv2.THRESH_BINARY) invResult = cv2.bitwise_not(result) cv2.imwrite('../save_data/ ' + str(cat) + '.png', invResult) X.append(invResult) Y.append(cat) def main(): # 全データ格納用配列 allfiles = [] # カテゴリ配列の各値と、それに対応するidxを認識し、全データをallfilesにまとめる for idx, cat in enumerate(characters): image_dir = root_dir + "/" + cat files = glob.glob(image_dir + "/*.png") for f in files: allfiles.append((idx, f)) X_train, y_train = make_sample(allfiles) # データを保存する(データの名前を「UB_name.npy」としている) np.save("../model/2_1/UB_name_2_1.npy", X_train) if __name__ == "__main__": main()
[ "PIL.Image.open", "cv2.threshold", "numpy.asarray", "numpy.array", "glob.glob", "cv2.cvtColor", "cv2.bitwise_not", "numpy.save" ]
[((537, 554), 'PIL.Image.open', 'Image.open', (['fname'], {}), '(fname)\n', (547, 554), False, 'from PIL import Image\n'), ((598, 613), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (608, 613), True, 'import numpy as np\n'), ((630, 668), 'cv2.cvtColor', 'cv2.cvtColor', (['data', 'cv2.COLOR_RGB2GRAY'], {}), '(data, cv2.COLOR_RGB2GRAY)\n', (642, 668), False, 'import cv2\n'), ((687, 740), 'cv2.threshold', 'cv2.threshold', (['data_gray', '(180)', '(255)', 'cv2.THRESH_BINARY'], {}), '(data_gray, 180, 255, cv2.THRESH_BINARY)\n', (700, 740), False, 'import cv2\n'), ((757, 780), 'cv2.bitwise_not', 'cv2.bitwise_not', (['result'], {}), '(result)\n', (772, 780), False, 'import cv2\n'), ((1274, 1322), 'numpy.save', 'np.save', (['"""../model/2_1/UB_name_2_1.npy"""', 'X_train'], {}), "('../model/2_1/UB_name_2_1.npy', X_train)\n", (1281, 1322), True, 'import numpy as np\n'), ((410, 421), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (418, 421), True, 'import numpy as np\n'), ((423, 434), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (431, 434), True, 'import numpy as np\n'), ((1088, 1119), 'glob.glob', 'glob.glob', (["(image_dir + '/*.png')"], {}), "(image_dir + '/*.png')\n", (1097, 1119), False, 'import os, glob\n')]
# -*- coding: utf-8 -*- """ Created on Fri Sep 1 19:11:52 2017 @author: mariapanteli """ import pytest import numpy as np import scripts.map_and_average as map_and_average def test_remove_inds(): labels = np.array(['a', 'a', 'b', 'unknown']) features = np.array([[0, 1], [0,2], [0, 3], [0, 4]]) audiolabels = np.array(['a', 'b', 'c', 'd']) features, labels, audiolabels = map_and_average.remove_inds(features, labels, audiolabels) assert len(features) == 3 and len(labels) == 3 and len(audiolabels) == 3 def test_remove_inds(): labels = np.array(['a', 'a', 'b', 'unknown']) features = np.array([[0, 1], [0,2], [0, 3], [0, 4]]) audiolabels = np.array(['a', 'b', 'c', 'd']) features, labels, audiolabels = map_and_average.remove_inds(features, labels, audiolabels) features_true = np.array([[0, 1], [0,2], [0, 3]]) assert np.array_equal(features, features_true) def test_averageframes(): classlabels = np.array(['a', 'a', 'b', 'b', 'b']) features = np.array([[0, 1], [0,2], [0, 1], [1, 1], [2, 1]]) audiolabels = np.array(['a', 'a', 'b', 'b', 'b']) feat, audio, labels = map_and_average.averageframes(features, audiolabels, classlabels) feat_true = np.array([[0, 1.5], [1, 1]]) assert np.array_equal(feat, feat_true) def test_limit_to_n_seconds(): X = np.random.randn(10, 3) Y = np.random.randn(10) Yaudio = np.concatenate([np.repeat('a', 7), np.repeat('b', 3)]) Xn, Yn, Yaudion = map_and_average.limit_to_n_seconds([X, Y, Yaudio], n_sec=3.0, win_sec=0.5) Yaudion_true = np.concatenate([np.repeat('a', 5), np.repeat('b', 3)]) assert np.array_equal(Yaudion_true, Yaudion) and len(Xn)==len(Yn) and len(Yn)==len(Yaudion)
[ "scripts.map_and_average.averageframes", "numpy.repeat", "numpy.array", "scripts.map_and_average.remove_inds", "numpy.array_equal", "scripts.map_and_average.limit_to_n_seconds", "numpy.random.randn" ]
[((216, 252), 'numpy.array', 'np.array', (["['a', 'a', 'b', 'unknown']"], {}), "(['a', 'a', 'b', 'unknown'])\n", (224, 252), True, 'import numpy as np\n'), ((268, 310), 'numpy.array', 'np.array', (['[[0, 1], [0, 2], [0, 3], [0, 4]]'], {}), '([[0, 1], [0, 2], [0, 3], [0, 4]])\n', (276, 310), True, 'import numpy as np\n'), ((328, 358), 'numpy.array', 'np.array', (["['a', 'b', 'c', 'd']"], {}), "(['a', 'b', 'c', 'd'])\n", (336, 358), True, 'import numpy as np\n'), ((395, 453), 'scripts.map_and_average.remove_inds', 'map_and_average.remove_inds', (['features', 'labels', 'audiolabels'], {}), '(features, labels, audiolabels)\n', (422, 453), True, 'import scripts.map_and_average as map_and_average\n'), ((570, 606), 'numpy.array', 'np.array', (["['a', 'a', 'b', 'unknown']"], {}), "(['a', 'a', 'b', 'unknown'])\n", (578, 606), True, 'import numpy as np\n'), ((622, 664), 'numpy.array', 'np.array', (['[[0, 1], [0, 2], [0, 3], [0, 4]]'], {}), '([[0, 1], [0, 2], [0, 3], [0, 4]])\n', (630, 664), True, 'import numpy as np\n'), ((682, 712), 'numpy.array', 'np.array', (["['a', 'b', 'c', 'd']"], {}), "(['a', 'b', 'c', 'd'])\n", (690, 712), True, 'import numpy as np\n'), ((749, 807), 'scripts.map_and_average.remove_inds', 'map_and_average.remove_inds', (['features', 'labels', 'audiolabels'], {}), '(features, labels, audiolabels)\n', (776, 807), True, 'import scripts.map_and_average as map_and_average\n'), ((828, 862), 'numpy.array', 'np.array', (['[[0, 1], [0, 2], [0, 3]]'], {}), '([[0, 1], [0, 2], [0, 3]])\n', (836, 862), True, 'import numpy as np\n'), ((873, 912), 'numpy.array_equal', 'np.array_equal', (['features', 'features_true'], {}), '(features, features_true)\n', (887, 912), True, 'import numpy as np\n'), ((959, 994), 'numpy.array', 'np.array', (["['a', 'a', 'b', 'b', 'b']"], {}), "(['a', 'a', 'b', 'b', 'b'])\n", (967, 994), True, 'import numpy as np\n'), ((1010, 1060), 'numpy.array', 'np.array', (['[[0, 1], [0, 2], [0, 1], [1, 1], [2, 1]]'], {}), '([[0, 1], [0, 2], [0, 1], [1, 1], [2, 1]])\n', (1018, 1060), True, 'import numpy as np\n'), ((1078, 1113), 'numpy.array', 'np.array', (["['a', 'a', 'b', 'b', 'b']"], {}), "(['a', 'a', 'b', 'b', 'b'])\n", (1086, 1113), True, 'import numpy as np\n'), ((1140, 1205), 'scripts.map_and_average.averageframes', 'map_and_average.averageframes', (['features', 'audiolabels', 'classlabels'], {}), '(features, audiolabels, classlabels)\n', (1169, 1205), True, 'import scripts.map_and_average as map_and_average\n'), ((1222, 1250), 'numpy.array', 'np.array', (['[[0, 1.5], [1, 1]]'], {}), '([[0, 1.5], [1, 1]])\n', (1230, 1250), True, 'import numpy as np\n'), ((1262, 1293), 'numpy.array_equal', 'np.array_equal', (['feat', 'feat_true'], {}), '(feat, feat_true)\n', (1276, 1293), True, 'import numpy as np\n'), ((1335, 1357), 'numpy.random.randn', 'np.random.randn', (['(10)', '(3)'], {}), '(10, 3)\n', (1350, 1357), True, 'import numpy as np\n'), ((1366, 1385), 'numpy.random.randn', 'np.random.randn', (['(10)'], {}), '(10)\n', (1381, 1385), True, 'import numpy as np\n'), ((1476, 1550), 'scripts.map_and_average.limit_to_n_seconds', 'map_and_average.limit_to_n_seconds', (['[X, Y, Yaudio]'], {'n_sec': '(3.0)', 'win_sec': '(0.5)'}), '([X, Y, Yaudio], n_sec=3.0, win_sec=0.5)\n', (1510, 1550), True, 'import scripts.map_and_average as map_and_average\n'), ((1636, 1673), 'numpy.array_equal', 'np.array_equal', (['Yaudion_true', 'Yaudion'], {}), '(Yaudion_true, Yaudion)\n', (1650, 1673), True, 'import numpy as np\n'), ((1415, 1432), 'numpy.repeat', 'np.repeat', (['"""a"""', '(7)'], {}), "('a', 7)\n", (1424, 1432), True, 'import numpy as np\n'), ((1434, 1451), 'numpy.repeat', 'np.repeat', (['"""b"""', '(3)'], {}), "('b', 3)\n", (1443, 1451), True, 'import numpy as np\n'), ((1586, 1603), 'numpy.repeat', 'np.repeat', (['"""a"""', '(5)'], {}), "('a', 5)\n", (1595, 1603), True, 'import numpy as np\n'), ((1605, 1622), 'numpy.repeat', 'np.repeat', (['"""b"""', '(3)'], {}), "('b', 3)\n", (1614, 1622), True, 'import numpy as np\n')]
#!/usr/bin/env python import freenect import cv2 import frame_convert2 import numpy as np import pyautogui pyautogui.FAILSAFE = False import pyfakewebcam threshold1 = 600 # threshold2 = 300 current_depth = 0 range_x, range_y = 640, 480 resolution = pyautogui.getInfo()[-2] k_x, k_y = resolution[0] / range_x, resolution[1] / range_y print(k_x, k_y) mouseDown = False camera = pyfakewebcam.FakeWebcam('/dev/video1', 640, 480) def show_depth(): global mouseDown global threshold1 global threshold2 global current_depth depth, timestamp = freenect.sync_get_depth() # print(depth.mean()) depth = 255 * ~np.logical_and(depth >= current_depth - threshold1, depth <= current_depth + threshold1) depth = depth.astype(np.uint8) cv2.imshow('Depth', depth) frame = np.zeros((480, 640, 3), dtype=np.uint8) frame[:,:,0] = depth camera.schedule_frame(frame) cv2.namedWindow('Depth') # cv2.namedWindow('Video') print('Press ESC in window to stop') while 1: show_depth() if cv2.waitKey(10) == 27: break
[ "numpy.logical_and", "freenect.sync_get_depth", "cv2.imshow", "pyautogui.getInfo", "numpy.zeros", "pyfakewebcam.FakeWebcam", "cv2.waitKey", "cv2.namedWindow" ]
[((382, 430), 'pyfakewebcam.FakeWebcam', 'pyfakewebcam.FakeWebcam', (['"""/dev/video1"""', '(640)', '(480)'], {}), "('/dev/video1', 640, 480)\n", (405, 430), False, 'import pyfakewebcam\n'), ((943, 967), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Depth"""'], {}), "('Depth')\n", (958, 967), False, 'import cv2\n'), ((253, 272), 'pyautogui.getInfo', 'pyautogui.getInfo', ([], {}), '()\n', (270, 272), False, 'import pyautogui\n'), ((565, 590), 'freenect.sync_get_depth', 'freenect.sync_get_depth', ([], {}), '()\n', (588, 590), False, 'import freenect\n'), ((797, 823), 'cv2.imshow', 'cv2.imshow', (['"""Depth"""', 'depth'], {}), "('Depth', depth)\n", (807, 823), False, 'import cv2\n'), ((837, 876), 'numpy.zeros', 'np.zeros', (['(480, 640, 3)'], {'dtype': 'np.uint8'}), '((480, 640, 3), dtype=np.uint8)\n', (845, 876), True, 'import numpy as np\n'), ((1068, 1083), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (1079, 1083), False, 'import cv2\n'), ((636, 728), 'numpy.logical_and', 'np.logical_and', (['(depth >= current_depth - threshold1)', '(depth <= current_depth + threshold1)'], {}), '(depth >= current_depth - threshold1, depth <= current_depth +\n threshold1)\n', (650, 728), True, 'import numpy as np\n')]
import numpy as np from sklearn.base import clone from sklearn.utils import check_array, check_consistent_length from .budgetmanager import ( FixedUncertaintyBudgetManager, VariableUncertaintyBudgetManager, SplitBudgetManager, RandomVariableUncertaintyBudgetManager, ) from ..base import ( BudgetManager, SingleAnnotatorStreamQueryStrategy, SkactivemlClassifier, ) from ..utils import ( check_type, call_func, check_budget_manager, ) class UncertaintyZliobaite(SingleAnnotatorStreamQueryStrategy): """The UncertaintyZliobaite (Utility calculation in [1]) query strategy samples instances based on the classifiers uncertainty assessed based on the classifier's predictions. The instance is queried when the probability of the most likely class exceeds a threshold calculated based on the budget and the number of classes. It is used as the base class for uncertainty strategies provided by Zliobaite in [1]. Parameters ---------- budget : float, default=None The budget which models the budgeting constraint used in the stream-based active learning setting. budget_manager : BudgetManager, default=None The BudgetManager which models the budgeting constraint used in the stream-based active learning setting. if set to None, FixedUncertaintyBudgetManager will be used by default. The budget manager will be initialized based on the following conditions: If only a budget is given the default budget manager is initialized with the given budget. If only a budget manager is given use the budget manager. If both are not given the default budget manager with the default budget. If both are given and the budget differs from budgetmanager.budget a warning is thrown. random_state : int, RandomState instance, default=None Controls the randomness of the estimator. References ---------- [1] Zliobaite, <NAME>, Albert & Pfahringer, Bernhard & Holmes, Geoffrey. (2014). Active Learning With Drifting Streaming Data. Neural Networks and Learning Systems, IEEE Transactions on. 25. 27-39. """ def __init__( self, budget_manager=None, budget=None, random_state=None, ): super().__init__(budget=budget, random_state=random_state) self.budget_manager = budget_manager def query( self, candidates, clf, X=None, y=None, sample_weight=None, fit_clf=False, return_utilities=False, ): """Ask the query strategy which instances in candidates to acquire. Please note that, when the decisions from this function may differ from the final sampling, simulate=True can be set, so that the query strategy can be updated later with update(...) with the final sampling. This is especially helpful when developing wrapper query strategies. Parameters ---------- candidates : {array-like, sparse matrix} of shape (n_samples, n_features) The instances which may be queried. Sparse matrices are accepted only if they are supported by the base query strategy. clf : SkactivemlClassifier Model implementing the methods `fit` and `predict_freq`. X : array-like of shape (n_samples, n_features), optional Input samples used to fit the classifier. y : array-like of shape (n_samples), optional Labels of the input samples 'X'. There may be missing labels. sample_weight : array-like of shape (n_samples,), optional Sample weights for X, used to fit the clf. fit_clf : bool, If true, refit the classifier also requires X and y to be given. return_utilities : bool, optional If true, also return the utilities based on the query strategy. The default is False. Returns ------- queried_indices : ndarray of shape (n_queried_instances,) The indices of instances in candidates which should be queried, with 0 <= n_queried_instances <= n_samples. utilities: ndarray of shape (n_samples,), optional The utilities based on the query strategy. Only provided if return_utilities is True. """ ( candidates, clf, X, y, sample_weight, fit_clf, return_utilities, ) = self._validate_data( candidates, clf=clf, X=X, y=y, sample_weight=sample_weight, fit_clf=fit_clf, return_utilities=return_utilities, ) predict_proba = clf.predict_proba(candidates) utilities = np.max(predict_proba, axis=1) queried_indices = self.budget_manager_.query_by_utility(utilities) if return_utilities: return queried_indices, utilities else: return queried_indices def update( self, candidates, queried_indices, budget_manager_param_dict=None ): """Updates the budget manager and the count for seen and queried instances Parameters ---------- candidates : {array-like, sparse matrix} of shape (n_samples, n_features) The instances which could be queried. Sparse matrices are accepted only if they are supported by the base query strategy. queried_indices : array-like of shape (n_samples,) Indicates which instances from candidates have been queried. budget_manager_param_dict : kwargs Optional kwargs for budget manager. Returns ------- self : UncertaintyZliobaite The UncertaintyZliobaite returns itself, after it is updated. """ # check if a budgetmanager is set if not hasattr(self, "budget_manager_"): check_type( self.budget_manager, "budget_manager_", BudgetManager, type(None), ) self.budget_manager_ = check_budget_manager( self.budget, self.budget_manager, self._get_default_budget_manager(), ) budget_manager_param_dict = ( {} if budget_manager_param_dict is None else budget_manager_param_dict ) call_func( self.budget_manager_.update, candidates=candidates, queried_indices=queried_indices, **budget_manager_param_dict ) return self def _validate_data( self, candidates, clf, X, y, sample_weight, fit_clf, return_utilities, reset=True, **check_candidates_params ): """Validate input data and set or check the `n_features_in_` attribute. Parameters ---------- candidates: array-like of shape (n_candidates, n_features) The instances which may be queried. Sparse matrices are accepted only if they are supported by the base query strategy. clf : SkactivemlClassifier Model implementing the methods `fit` and `predict_freq`. X : array-like of shape (n_samples, n_features) Input samples used to fit the classifier. y : array-like of shape (n_samples) Labels of the input samples 'X'. There may be missing labels. sample_weight : array-like of shape (n_samples,) (default=None) Sample weights for X, used to fit the clf. return_utilities : bool, If true, also return the utilities based on the query strategy. fit_clf : bool, If true, refit the classifier also requires X and y to be given. reset : bool, default=True Whether to reset the `n_features_in_` attribute. If False, the input will be checked for consistency with data provided when reset was last True. **check_candidates_params : kwargs Parameters passed to :func:`sklearn.utils.check_array`. Returns ------- candidates: np.ndarray, shape (n_candidates, n_features) Checked candidate samples clf : SkactivemlClassifier Checked model implementing the methods `fit` and `predict_freq`. X: np.ndarray, shape (n_samples, n_features) Checked training samples y: np.ndarray, shape (n_candidates) Checked training labels sampling_weight: np.ndarray, shape (n_candidates) Checked training sample weight fit_clf : bool, Checked boolean value of `fit_clf` candidates: np.ndarray, shape (n_candidates, n_features) Checked candidate samples return_utilities : bool, Checked boolean value of `return_utilities`. """ candidates, return_utilities = super()._validate_data( candidates, return_utilities, reset=reset, **check_candidates_params ) self._validate_random_state() X, y, sample_weight = self._validate_X_y_sample_weight( X=X, y=y, sample_weight=sample_weight ) clf = self._validate_clf(clf, X, y, sample_weight, fit_clf) # check if a budgetmanager is set if not hasattr(self, "budget_manager_"): check_type( self.budget_manager, "budget_manager_", BudgetManager, type(None), ) self.budget_manager_ = check_budget_manager( self.budget, self.budget_manager, self._get_default_budget_manager(), ) return candidates, clf, X, y, sample_weight, fit_clf, return_utilities def _validate_clf(self, clf, X, y, sample_weight, fit_clf): """Validate if clf is a valid SkactivemlClassifier. If clf is untrained, clf is trained using X, y and sample_weight. Parameters ---------- clf : SkactivemlClassifier Model implementing the methods `fit` and `predict_freq`. X : array-like of shape (n_samples, n_features) Input samples used to fit the classifier. y : array-like of shape (n_samples) Labels of the input samples 'X'. There may be missing labels. sample_weight : array-like of shape (n_samples,) (default=None) Sample weights for X, used to fit the clf. fit_clf : bool, If true, refit the classifier also requires X and y to be given. Returns ------- clf : SkactivemlClassifier Checked model implementing the methods `fit` and `predict_freq`. """ # Check if the classifier and its arguments are valid. check_type(clf, "clf", SkactivemlClassifier) check_type(fit_clf, "fit_clf", bool) if fit_clf: clf = clone(clf).fit(X, y, sample_weight) return clf def _validate_X_y_sample_weight(self, X, y, sample_weight): """Validate if X, y and sample_weight are numeric and of equal length. Parameters ---------- X : array-like of shape (n_samples, n_features) Input samples used to fit the classifier. y : array-like of shape (n_samples) Labels of the input samples 'X'. There may be missing labels. sample_weight : array-like of shape (n_samples,) (default=None) Sample weights for X, used to fit the clf. Returns ------- X : array-like of shape (n_samples, n_features) Checked Input samples. y : array-like of shape (n_samples) Checked Labels of the input samples 'X'. Converts y to a numpy array """ if sample_weight is not None: sample_weight = np.array(sample_weight) check_consistent_length(sample_weight, y) if X is not None and y is not None: X = check_array(X) y = np.array(y) check_consistent_length(X, y) return X, y, sample_weight class FixedUncertainty(UncertaintyZliobaite): """The FixedUncertainty (Fixed-Uncertainty in [1]) query strategy samples instances based on the classifiers uncertainty assessed based on the classifier's predictions. The instance is queried when the probability of the most likely class exceeds a threshold calculated based on the budget and the number of classes. Parameters ---------- budget : float, default=None The budget which models the budgeting constraint used in the stream-based active learning setting. budgetmanager : BudgetManager, default=None The BudgetManager which models the budgeting constraint used in the stream-based active learning setting. if set to None, FixedUncertaintyBudgetManager will be used by default. The budget manager will be initialized based on the following conditions: If only a budget is given the default budget manager is initialized with the given budget. If only a budget manager is given use the budget manager. If both are not given the default budget manager with the default budget. If both are given and the budget differs from budget manager.budget a warning is thrown. random_state : int, RandomState instance, default=None Controls the randomness of the estimator. References ---------- [1] Zliobaite, Indre & Bifet, Albert & Pfahringer, <NAME>, Geoffrey. (2014). Active Learning With Drifting Streaming Data. Neural Networks and Learning Systems, IEEE Transactions on. 25. 27-39. """ def _get_default_budget_manager(self): """Provide the budget manager that will be used as default. Returns ------- budgetmanager : BudgetManager The BudgetManager that should be used by default. """ return FixedUncertaintyBudgetManager class VariableUncertainty(UncertaintyZliobaite): """The VariableUncertainty (Var-Uncertainty in [1]) query strategy samples instances based on the classifiers uncertainty assessed based on the classifier's predictions. The instance is queried when the probability of the most likely class exceeds a time-dependent threshold calculated based on the budget, the number of classes and the number of observed and acquired samples. Parameters ---------- budget : float, default=None The budget which models the budgeting constraint used in the stream-based active learning setting. budgetmanager : BudgetManager, default=None The BudgetManager which models the budgeting constraint used in the stream-based active learning setting. if set to None, FixedUncertaintyBudgetManager will be used by default. The budget manager will be initialized based on the following conditions: If only a budget is given the default budgetmanager is initialized with the given budget. If only a budgetmanager is given use the budgetmanager. If both are not given the default budgetmanager with the default budget. If both are given and the budget differs from budgetmanager.budget a warning is thrown. random_state : int, RandomState instance, default=None Controls the randomness of the estimator. References ---------- [1] Zliobaite, <NAME>, Albert & Pfahringer, Bernhard & Holmes, Geoffrey. (2014). Active Learning With Drifting Streaming Data. Neural Networks and Learning Systems, IEEE Transactions on. 25. 27-39. """ def _get_default_budget_manager(self): """Provide the budget manager that will be used as default. Returns ------- budgetmanager : BudgetManager The BudgetManager that should be used by default. """ return VariableUncertaintyBudgetManager class RandomVariableUncertainty(UncertaintyZliobaite): """The RandomVariableUncertainty (Ran-Var-Uncertainty in [1]) query strategy samples instances based on the classifier's uncertainty assessed based on the classifier's predictions. The instance is queried when the probability of the most likely class exceeds a time-dependent threshold calculated based on the budget, the number of classes and the number of observed and acquired samples. To better adapt at change detection the threshold is multiplied by a random number generator with N(1,delta). Parameters ---------- budget : float, default=None The budget which models the budgeting constraint used in the stream-based active learning setting. budgetmanager : BudgetManager, default=None The BudgetManager which models the budgeting constraint used in the stream-based active learning setting. if set to None, FixedUncertaintyBudgetManager will be used by default. The budget manager will be initialized based on the following conditions: If only a budget is given the default budgetmanager is initialized with the given budget. If only a budgetmanager is given use the budgetmanager. If both are not given the default budgetmanager with the default budget. If both are given and the budget differs from budgetmanager.budget a warning is thrown. random_state : int, RandomState instance, default=None Controls the randomness of the estimator. References ---------- [1] Zliobaite, <NAME>, Albert & Pfahringer, <NAME>, Geoffrey. (2014). Active Learning With Drifting Streaming Data. Neural Networks and Learning Systems, IEEE Transactions on. 25. 27-39. """ def _get_default_budget_manager(self): """Provide the budget manager that will be used as default. Returns ------- budgetmanager : BudgetManager The BudgetManager that should be used by default. """ return RandomVariableUncertaintyBudgetManager class Split(UncertaintyZliobaite): """The Split [1] query strategy samples in 100*v% of instances randomly and in 100*(1-v)% of cases according to VariableUncertainty. Parameters ---------- budget : float, default=None The budget which models the budgeting constraint used in the stream-based active learning setting. budgetmanager : BudgetManager, default=None The BudgetManager which models the budgeting constraint used in the stream-based active learning setting. if set to None, FixedUncertaintyBudgetManager will be used by default. The budget manager will be initialized based on the following conditions: If only a budget is given the default budget manager is initialized with the given budget. If only a budgetmanager is given use the budgetmanager. If both are not given the default budgetmanager with the default budget. If both are given and the budget differs from budgetmanager.budget a warning is thrown. random_state : int, RandomState instance, default=None Controls the randomness of the estimator. References ---------- [1] Zliobaite, <NAME>, Albert & Pfahringer, Bernhard & Holmes, Geoffrey. (2014). Active Learning With Drifting Streaming Data. Neural Networks and Learning Systems, IEEE Transactions on. 25. 27-39. """ def _get_default_budget_manager(self): return SplitBudgetManager
[ "sklearn.base.clone", "sklearn.utils.check_consistent_length", "numpy.max", "numpy.array", "sklearn.utils.check_array" ]
[((4935, 4964), 'numpy.max', 'np.max', (['predict_proba'], {'axis': '(1)'}), '(predict_proba, axis=1)\n', (4941, 4964), True, 'import numpy as np\n'), ((12170, 12193), 'numpy.array', 'np.array', (['sample_weight'], {}), '(sample_weight)\n', (12178, 12193), True, 'import numpy as np\n'), ((12206, 12247), 'sklearn.utils.check_consistent_length', 'check_consistent_length', (['sample_weight', 'y'], {}), '(sample_weight, y)\n', (12229, 12247), False, 'from sklearn.utils import check_array, check_consistent_length\n'), ((12308, 12322), 'sklearn.utils.check_array', 'check_array', (['X'], {}), '(X)\n', (12319, 12322), False, 'from sklearn.utils import check_array, check_consistent_length\n'), ((12339, 12350), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (12347, 12350), True, 'import numpy as np\n'), ((12363, 12392), 'sklearn.utils.check_consistent_length', 'check_consistent_length', (['X', 'y'], {}), '(X, y)\n', (12386, 12392), False, 'from sklearn.utils import check_array, check_consistent_length\n'), ((11236, 11246), 'sklearn.base.clone', 'clone', (['clf'], {}), '(clf)\n', (11241, 11246), False, 'from sklearn.base import clone\n')]
######################################################################## # # Created: April 30, 2021 # Author: The Blosc development team - <EMAIL> # ######################################################################## import numpy as np import pytest import blosc2 @pytest.mark.parametrize("size, dtype", [(1e6, None)]) def test_array(size, dtype): nparray = np.arange(size, dtype=dtype) parray = blosc2.pack_array(nparray) assert len(parray) < nparray.size * nparray.itemsize a2 = blosc2.unpack_array(parray) assert np.array_equal(nparray, a2)
[ "blosc2.pack_array", "pytest.mark.parametrize", "numpy.array_equal", "blosc2.unpack_array", "numpy.arange" ]
[((289, 348), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""size, dtype"""', '[(1000000.0, None)]'], {}), "('size, dtype', [(1000000.0, None)])\n", (312, 348), False, 'import pytest\n'), ((386, 414), 'numpy.arange', 'np.arange', (['size'], {'dtype': 'dtype'}), '(size, dtype=dtype)\n', (395, 414), True, 'import numpy as np\n'), ((428, 454), 'blosc2.pack_array', 'blosc2.pack_array', (['nparray'], {}), '(nparray)\n', (445, 454), False, 'import blosc2\n'), ((522, 549), 'blosc2.unpack_array', 'blosc2.unpack_array', (['parray'], {}), '(parray)\n', (541, 549), False, 'import blosc2\n'), ((561, 588), 'numpy.array_equal', 'np.array_equal', (['nparray', 'a2'], {}), '(nparray, a2)\n', (575, 588), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import geopandas as gpd from datetime import datetime from operator import itemgetter from ...utils import constants from ...utils.constants import UID, DATETIME, LATITUDE, LONGITUDE, GEOLIFE_SAMPLE from ...core.trajectorydataframe import TrajDataFrame from ...core.flowdataframe import FlowDataFrame from ...preprocessing import detection, clustering import shapely import folium import matplotlib import pytest EXPECTED_NUM_OF_COLUMNS_IN_TDF = 4 class TestTrajectoryDataFrame: def setup_method(self): self.default_data_list = [[1, 39.984094, 116.319236, '2008-10-23 13:53:05'], [1, 39.984198, 116.319322, '2008-10-23 13:53:06'], [1, 39.984224, 116.319402, '2008-10-23 13:53:11'], [1, 39.984211, 116.319389, '2008-10-23 13:53:16']] self.default_data_df = pd.DataFrame(self.default_data_list, columns=['user', 'latitude', 'lng', 'hour']) self.default_data_dict = self.default_data_df.to_dict(orient='list') # instantiate a TrajDataFrame lats_lngs = np.array([[39.978253, 116.327275], [40.013819, 116.306532], [39.878987, 116.126686], [40.013819, 116.306532], [39.979580, 116.313649], [39.978696, 116.326220], [39.981537, 116.310790], [39.978161, 116.327242], [39.900000, 116.000000]]) traj = pd.DataFrame(lats_lngs, columns=[constants.LATITUDE, constants.LONGITUDE]) traj[constants.DATETIME] = pd.to_datetime([ '20130101 8:34:04', '20130101 10:34:08', '20130105 10:34:08', '20130110 12:34:15', '20130101 1:34:28', '20130101 3:34:54', '20130101 4:34:55', '20130105 5:29:12', '20130115 00:29:12']) traj[constants.UID] = [1 for _ in range(5)] + [2 for _ in range(3)] + [3] self.tdf0 = TrajDataFrame(traj) self.stdf = detection.stops(self.tdf0) self.cstdf = clustering.cluster(self.stdf) # tessellation tess_features = {'type': 'FeatureCollection', 'features': [{'id': '0', 'type': 'Feature', 'properties': {'tile_ID': '0'}, 'geometry': {'type': 'Polygon', 'coordinates': [[[116.14407581909998, 39.8846396072], [116.14407581909998, 39.98795822127371], [116.27882311171793, 39.98795822127371], [116.27882311171793, 39.8846396072], [116.14407581909998, 39.8846396072]]]}}, {'id': '1', 'type': 'Feature', 'properties': {'tile_ID': '1'}, 'geometry': {'type': 'Polygon', 'coordinates': [[[116.14407581909998, 39.98795822127371], [116.14407581909998, 40.091120806035285], [116.27882311171793, 40.091120806035285], [116.27882311171793, 39.98795822127371], [116.14407581909998, 39.98795822127371]]]}}, {'id': '2', 'type': 'Feature', 'properties': {'tile_ID': '2'}, 'geometry': {'type': 'Polygon', 'coordinates': [[[116.27882311171793, 39.8846396072], [116.27882311171793, 39.98795822127371], [116.41357040433583, 39.98795822127371], [116.41357040433583, 39.8846396072], [116.27882311171793, 39.8846396072]]]}}, {'id': '3', 'type': 'Feature', 'properties': {'tile_ID': '3'}, 'geometry': {'type': 'Polygon', 'coordinates': [[[116.27882311171793, 39.98795822127371], [116.27882311171793, 40.091120806035285], [116.41357040433583, 40.091120806035285], [116.41357040433583, 39.98795822127371], [116.27882311171793, 39.98795822127371]]]}}]} self.tessellation = gpd.GeoDataFrame.from_features(tess_features, crs={"init": "epsg:4326"}) def perform_default_asserts(self, tdf): assert tdf._is_trajdataframe() assert tdf.shape == (4, EXPECTED_NUM_OF_COLUMNS_IN_TDF) assert tdf[UID][0] == 1 assert tdf[DATETIME][0] == datetime(2008, 10, 23, 13, 53, 5) assert tdf[LATITUDE][0] == 39.984094 assert tdf[LONGITUDE][3] == 116.319389 def test_tdf_from_list(self): tdf = TrajDataFrame(self.default_data_list, latitude=1, longitude=2, datetime=3, user_id=0) self.perform_default_asserts(tdf) print(tdf.head()) # raised TypeError: 'BlockManager' object is not iterable def test_tdf_from_df(self): tdf = TrajDataFrame(self.default_data_df, latitude='latitude', datetime='hour', user_id='user') self.perform_default_asserts(tdf) def test_tdf_from_dict(self): tdf = TrajDataFrame(self.default_data_dict, latitude='latitude', datetime='hour', user_id='user') self.perform_default_asserts(tdf) def test_tdf_from_csv_file(self): tdf = TrajDataFrame.from_file(GEOLIFE_SAMPLE, sep=',') assert tdf._is_trajdataframe() assert tdf.shape == (217653, EXPECTED_NUM_OF_COLUMNS_IN_TDF) assert list(tdf[UID].unique()) == [1, 5] def test_timezone_conversion(self): tdf = TrajDataFrame(self.default_data_df, latitude='latitude', datetime='hour', user_id='user') tdf.timezone_conversion(from_timezone='Europe/London', to_timezone='Europe/Berlin') assert tdf[DATETIME][0] == pd.Timestamp('2008-10-23 14:53:05') def test_slicing_a_tdf_returns_a_tdf(self): tdf = TrajDataFrame(self.default_data_df, latitude='latitude', datetime='hour', user_id='user') assert isinstance(tdf[tdf[UID] == 1][:1], TrajDataFrame) def test_sort_by_uid_and_datetime(self): # shuffle the TrajDataFrame rows tdf1 = self.tdf0.sample(frac=1) tdf = tdf1.sort_by_uid_and_datetime() assert isinstance(tdf, TrajDataFrame) assert np.all(tdf[[UID, DATETIME]].values == sorted(tdf1[[UID, DATETIME]].values, key=itemgetter(0, 1))) def test_plot_trajectory(self): map_f = self.tdf0.plot_trajectory() assert isinstance(map_f, folium.folium.Map) def test_plot_stops(self): map_f = self.stdf.plot_stops() assert isinstance(map_f, folium.folium.Map) def test_plot_diary(self): ax = self.cstdf.plot_diary(self.tdf0[UID].iloc[0]) assert isinstance(ax, matplotlib.axes._subplots.Subplot) @pytest.mark.parametrize('self_loops', [True, False]) def test_to_flowdataframe(self, self_loops): expected_flows = {'origin': {0: '2', 1: '2'}, 'destination': {0: '2', 1: '3'}, 'flow': {0: 3, 1: 1}} expected_fdf = FlowDataFrame(expected_flows, tessellation=self.tessellation) if not self_loops: expected_fdf.drop(0, inplace=True) fdf = self.tdf0.to_flowdataframe(self.tessellation, self_loops=self_loops) assert isinstance(fdf, FlowDataFrame) pd.testing.assert_frame_equal(expected_fdf, fdf) def test_to_geodataframe(self): assert isinstance(self.tdf0.to_geodataframe(), gpd.GeoDataFrame) @pytest.mark.parametrize('remove_na', [True, False]) def test_mapping(self, remove_na): mtdf = self.tdf0.mapping(self.tessellation, remove_na=remove_na) def _point_in_poly(x, tess): point = shapely.geometry.Point([x[constants.LONGITUDE], x[constants.LATITUDE]]) try: poly = tess[tess[constants.TILE_ID] == x[constants.TILE_ID]][['geometry']].values[0, 0] return poly.contains(point) except IndexError: poly = shapely.ops.unary_union(self.tessellation.geometry.values) return not poly.contains(point) assert np.all(mtdf.apply(lambda x: _point_in_poly(x, self.tessellation), axis=1).values)
[ "datetime.datetime", "shapely.ops.unary_union", "geopandas.GeoDataFrame.from_features", "operator.itemgetter", "shapely.geometry.Point", "pytest.mark.parametrize", "numpy.array", "pandas.DataFrame", "pandas.testing.assert_frame_equal", "pandas.Timestamp", "pandas.to_datetime" ]
[((7176, 7228), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""self_loops"""', '[True, False]'], {}), "('self_loops', [True, False])\n", (7199, 7228), False, 'import pytest\n'), ((7900, 7951), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""remove_na"""', '[True, False]'], {}), "('remove_na', [True, False])\n", (7923, 7951), False, 'import pytest\n'), ((921, 1006), 'pandas.DataFrame', 'pd.DataFrame', (['self.default_data_list'], {'columns': "['user', 'latitude', 'lng', 'hour']"}), "(self.default_data_list, columns=['user', 'latitude', 'lng',\n 'hour'])\n", (933, 1006), True, 'import pandas as pd\n'), ((1140, 1376), 'numpy.array', 'np.array', (['[[39.978253, 116.327275], [40.013819, 116.306532], [39.878987, 116.126686],\n [40.013819, 116.306532], [39.97958, 116.313649], [39.978696, 116.32622],\n [39.981537, 116.31079], [39.978161, 116.327242], [39.9, 116.0]]'], {}), '([[39.978253, 116.327275], [40.013819, 116.306532], [39.878987, \n 116.126686], [40.013819, 116.306532], [39.97958, 116.313649], [\n 39.978696, 116.32622], [39.981537, 116.31079], [39.978161, 116.327242],\n [39.9, 116.0]])\n', (1148, 1376), True, 'import numpy as np\n'), ((1631, 1705), 'pandas.DataFrame', 'pd.DataFrame', (['lats_lngs'], {'columns': '[constants.LATITUDE, constants.LONGITUDE]'}), '(lats_lngs, columns=[constants.LATITUDE, constants.LONGITUDE])\n', (1643, 1705), True, 'import pandas as pd\n'), ((1741, 1953), 'pandas.to_datetime', 'pd.to_datetime', (["['20130101 8:34:04', '20130101 10:34:08', '20130105 10:34:08',\n '20130110 12:34:15', '20130101 1:34:28', '20130101 3:34:54',\n '20130101 4:34:55', '20130105 5:29:12', '20130115 00:29:12']"], {}), "(['20130101 8:34:04', '20130101 10:34:08',\n '20130105 10:34:08', '20130110 12:34:15', '20130101 1:34:28',\n '20130101 3:34:54', '20130101 4:34:55', '20130105 5:29:12',\n '20130115 00:29:12'])\n", (1755, 1953), True, 'import pandas as pd\n'), ((4603, 4675), 'geopandas.GeoDataFrame.from_features', 'gpd.GeoDataFrame.from_features', (['tess_features'], {'crs': "{'init': 'epsg:4326'}"}), "(tess_features, crs={'init': 'epsg:4326'})\n", (4633, 4675), True, 'import geopandas as gpd\n'), ((7735, 7783), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (['expected_fdf', 'fdf'], {}), '(expected_fdf, fdf)\n', (7764, 7783), True, 'import pandas as pd\n'), ((4891, 4924), 'datetime.datetime', 'datetime', (['(2008)', '(10)', '(23)', '(13)', '(53)', '(5)'], {}), '(2008, 10, 23, 13, 53, 5)\n', (4899, 4924), False, 'from datetime import datetime\n'), ((6172, 6207), 'pandas.Timestamp', 'pd.Timestamp', (['"""2008-10-23 14:53:05"""'], {}), "('2008-10-23 14:53:05')\n", (6184, 6207), True, 'import pandas as pd\n'), ((8122, 8193), 'shapely.geometry.Point', 'shapely.geometry.Point', (['[x[constants.LONGITUDE], x[constants.LATITUDE]]'], {}), '([x[constants.LONGITUDE], x[constants.LATITUDE]])\n', (8144, 8193), False, 'import shapely\n'), ((8413, 8471), 'shapely.ops.unary_union', 'shapely.ops.unary_union', (['self.tessellation.geometry.values'], {}), '(self.tessellation.geometry.values)\n', (8436, 8471), False, 'import shapely\n'), ((6739, 6755), 'operator.itemgetter', 'itemgetter', (['(0)', '(1)'], {}), '(0, 1)\n', (6749, 6755), False, 'from operator import itemgetter\n')]
import numpy as np import quantumblur as qb import random def get_points (size, num_civs, r=1.2, theta=0.25, thresh=0.55): # coupling map for 27 qubit devices (Montreal, Paris, etc) coupling_map = [[0, 1], [1, 0], [1, 2], [1, 4], [2, 1], [2, 3], [3, 2], [3, 5], [4, 1], [4, 7], [5, 3], [5, 8], [6, 7], [7, 4], [7, 6], [7, 10], [8, 5], [8, 9], [8, 11], [9, 8], [10, 7], [10, 12], [11, 8], [11, 14], [12, 10], [12, 13], [12, 15], [13, 12], [13, 14], [14, 11], [14, 13], [14, 16], [15, 12], [15, 18], [16, 14], [16, 19], [17, 18], [18, 15], [18, 17], [18, 21], [19, 16], [19, 20], [19, 22], [20, 19], [21, 18], [21, 23], [22, 19], [22, 25], [23, 21], [23, 24], [24, 23], [24, 25], [25, 22], [25, 24], [25, 26], [26, 25]] # partitions for these devices ('a' and 'b' represent two bipartitions) half = [0,2,4,5,6,9,10,11,13,15,16,17,20,21,22,24,26] partition = {'none':[], 'a':[], 'b':[]} partition['all'] = list(range(num_civs)) for j in range(num_civs): if j in half: partition['a'].append(j) else: partition['b'].append(j) # postions for qubits such that neighbours are equidistant and nicely placed in the map points = {0: (0, 2), 1: (1, 3), 2: (0, 4), 3: (1, 5), 4: (2, 2), 5: (2, 6), 6: (3, 0), 7: (3, 1), 8: (3, 7), 9: (3, 8), 10: (4, 2), 11: (4, 6), 12: (5, 3), 13: (5, 4), 14: (5, 5), 15: (6, 2), 16: (6, 6), 17: (7, 0), 18: (7, 1), 19: (7, 7), 20: (7, 8), 21: (8, 2), 22: (8, 6), 23: (9, 3), 24: (10, 4), 25: (9, 5), 26: (10, 6)} scale = size/(10+2*r) for civ in points: x,y = points[civ] points[civ] = (int(scale*(x+r)),int(scale*(y+r+1))) # height values for the terrain (0 or sea and 1 for land) # first with just a circle of radius r around each point height = {} for x in range(size): for y in range(size): height[x,y] = 0 min_dist = np.Inf for (xx,yy) in points.values(): min_dist = min(np.sqrt((x-xx)**2+(y-yy)**2),min_dist) if min_dist<r*scale: height[x,y] = 1 # and then a quantum blur to spice things up if theta!=0: qc = qb.height2circuit(height) for qubit in range(qc.num_qubits): qc.rx(theta*(1+random.random())/2,qubit) height = qb.circuit2height(qc) for (x,y) in height: height[x,y] = int(height[x,y]>thresh) return points, coupling_map, partition, height
[ "quantumblur.circuit2height", "random.random", "numpy.sqrt", "quantumblur.height2circuit" ]
[((2174, 2199), 'quantumblur.height2circuit', 'qb.height2circuit', (['height'], {}), '(height)\n', (2191, 2199), True, 'import quantumblur as qb\n'), ((2313, 2334), 'quantumblur.circuit2height', 'qb.circuit2height', (['qc'], {}), '(qc)\n', (2330, 2334), True, 'import quantumblur as qb\n'), ((1991, 2029), 'numpy.sqrt', 'np.sqrt', (['((x - xx) ** 2 + (y - yy) ** 2)'], {}), '((x - xx) ** 2 + (y - yy) ** 2)\n', (1998, 2029), True, 'import numpy as np\n'), ((2270, 2285), 'random.random', 'random.random', ([], {}), '()\n', (2283, 2285), False, 'import random\n')]
import numpy as np import pytest from probnum import randprocs from tests.test_randprocs.test_markov.test_discrete import test_linear_gaussian class TestLTIGaussian(test_linear_gaussian.TestLinearGaussian): # Replacement for an __init__ in the pytest language. See: # https://stackoverflow.com/questions/21430900/py-test-skips-test-class-if-constructor-is-defined @pytest.fixture(autouse=True) def _setup( self, test_ndim, spdmat1, spdmat2, forw_impl_string_linear_gauss, backw_impl_string_linear_gauss, ): self.G_const = spdmat1 self.S_const = spdmat2 self.v_const = np.arange(test_ndim) self.transition = randprocs.markov.discrete.LTIGaussian( self.G_const, self.v_const, self.S_const, forward_implementation=forw_impl_string_linear_gauss, backward_implementation=backw_impl_string_linear_gauss, ) # Compatibility with superclass' test self.G = lambda t: self.G_const self.S = lambda t: self.S_const self.v = lambda t: self.v_const self.g = lambda t, x: self.G(t) @ x + self.v(t) self.dg = lambda t, x: self.G(t) # Test access to system matrices def test_state_transition_mat(self): received = self.transition.state_trans_mat expected = self.G_const np.testing.assert_allclose(received, expected) def test_shift_vec(self): received = self.transition.shift_vec expected = self.v_const np.testing.assert_allclose(received, expected) def test_process_noise_cov_mat(self): received = self.transition.proc_noise_cov_mat expected = self.S_const np.testing.assert_allclose(received, expected) def test_process_noise_cov_cholesky(self): received = self.transition.proc_noise_cov_cholesky expected = np.linalg.cholesky(self.S_const) np.testing.assert_allclose(received, expected)
[ "numpy.testing.assert_allclose", "probnum.randprocs.markov.discrete.LTIGaussian", "pytest.fixture", "numpy.linalg.cholesky", "numpy.arange" ]
[((381, 409), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (395, 409), False, 'import pytest\n'), ((665, 685), 'numpy.arange', 'np.arange', (['test_ndim'], {}), '(test_ndim)\n', (674, 685), True, 'import numpy as np\n'), ((712, 910), 'probnum.randprocs.markov.discrete.LTIGaussian', 'randprocs.markov.discrete.LTIGaussian', (['self.G_const', 'self.v_const', 'self.S_const'], {'forward_implementation': 'forw_impl_string_linear_gauss', 'backward_implementation': 'backw_impl_string_linear_gauss'}), '(self.G_const, self.v_const, self.\n S_const, forward_implementation=forw_impl_string_linear_gauss,\n backward_implementation=backw_impl_string_linear_gauss)\n', (749, 910), False, 'from probnum import randprocs\n'), ((1408, 1454), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['received', 'expected'], {}), '(received, expected)\n', (1434, 1454), True, 'import numpy as np\n'), ((1571, 1617), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['received', 'expected'], {}), '(received, expected)\n', (1597, 1617), True, 'import numpy as np\n'), ((1755, 1801), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['received', 'expected'], {}), '(received, expected)\n', (1781, 1801), True, 'import numpy as np\n'), ((1928, 1960), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['self.S_const'], {}), '(self.S_const)\n', (1946, 1960), True, 'import numpy as np\n'), ((1969, 2015), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['received', 'expected'], {}), '(received, expected)\n', (1995, 2015), True, 'import numpy as np\n')]