code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import os.path as osp import numpy as np import torch import torch.nn.functional as F from model.trainer.base import Trainer from model.trainer.SnaTCHer_helpers import ( get_dataloader, prepare_model, ) from model.utils import ( count_acc, ) from tqdm import tqdm from sklearn.metrics import roc_curve, roc_auc_score def calc_auroc(known_scores, unknown_scores): y_true = np.array([0] * len(known_scores) + [1] * len(unknown_scores)) y_score = np.concatenate([known_scores, unknown_scores]) fpr, tpr, thresholds = roc_curve(y_true, y_score) auc_score = roc_auc_score(y_true, y_score) return auc_score class FSLTrainer(Trainer): def __init__(self, args): super().__init__(args) emb_dim = 640 if args.backbone_class == 'Res12' else 512 self.emb_dim = emb_dim self.train_loader, self.val_loader, self.test_loader = get_dataloader(args) self.model, self.para_model = prepare_model(args) def prepare_label(self): args = self.args # prepare one-hot label label = torch.arange(args.way, dtype=torch.int16).repeat(args.query) label_aux = torch.arange(args.way, dtype=torch.int8).repeat(args.shot + args.query) label = label.type(torch.LongTensor) label_aux = label_aux.type(torch.LongTensor) if torch.cuda.is_available(): label = label.cuda() label_aux = label_aux.cuda() return label, label_aux def evaluate_test(self): # restore model args emb_dim = self.emb_dim args = self.args weights = torch.load(osp.join(self.args.save_path, self.args.weight_name)) model_weights = weights['params'] self.missing_keys, self.unexpected_keys = self.model.load_state_dict(model_weights, strict=False) self.model.eval() test_steps = 600 self.record = np.zeros((test_steps, 2)) # loss and acc self.auroc_record = np.zeros((test_steps, 10)) label = torch.arange(args.closed_way, dtype=torch.int16).repeat(args.eval_query) label = label.type(torch.LongTensor) if torch.cuda.is_available(): label = label.cuda() way = args.closed_way label = torch.arange(way).repeat(15).cuda() for i, batch in tqdm(enumerate(self.test_loader, 1)): if i > test_steps: break if torch.cuda.is_available(): data, dlabel = [_.cuda() for _ in batch] else: data = batch[0] self.probe_data = data self.probe_dlabel = dlabel with torch.no_grad(): _ = self.para_model(data) instance_embs = self.para_model.probe_instance_embs support_idx = self.para_model.probe_support_idx query_idx = self.para_model.probe_query_idx support = instance_embs[support_idx.flatten()].view(*(support_idx.shape + (-1,))) query = instance_embs[query_idx.flatten()].view( *(query_idx.shape + (-1,))) emb_dim = support.shape[-1] support = support[:, :, :way].contiguous() # get mean of the support bproto = support.mean(dim=1) # Ntask x NK x d proto = bproto kquery = query[:, :, :way].contiguous() uquery = query[:, :, way:].contiguous() # get mean of the support proto = self.para_model.slf_attn(proto, proto, proto) proto = proto[0] klogits = -(kquery.reshape(-1, 1, emb_dim) - proto).pow(2).sum(2) / 64.0 ulogits = -(uquery.reshape(-1, 1, emb_dim) - proto).pow(2).sum(2) / 64.0 loss = F.cross_entropy(klogits, label) acc = count_acc(klogits, label) """ Probability """ known_prob = F.softmax(klogits, 1).max(1)[0] unknown_prob = F.softmax(ulogits, 1).max(1)[0] known_scores = (known_prob).cpu().detach().numpy() unknown_scores = (unknown_prob).cpu().detach().numpy() known_scores = 1 - known_scores unknown_scores = 1 - unknown_scores auroc = calc_auroc(known_scores, unknown_scores) """ Distance """ kdist = -(klogits.max(1)[0]) udist = -(ulogits.max(1)[0]) kdist = kdist.cpu().detach().numpy() udist = udist.cpu().detach().numpy() dist_auroc = calc_auroc(kdist, udist) """ Snatcher """ with torch.no_grad(): snatch_known = [] for j in range(75): pproto = bproto.clone().detach() """ Algorithm 1 Line 1 """ c = klogits.argmax(1)[j] """ Algorithm 1 Line 2 """ pproto[0][c] = kquery.reshape(-1, emb_dim)[j] """ Algorithm 1 Line 3 """ pproto = self.para_model.slf_attn(pproto, pproto, pproto)[0] pdiff = (pproto - proto).pow(2).sum(-1).sum() / 64.0 """ pdiff: d_SnaTCHer in Algorithm 1 """ snatch_known.append(pdiff) snatch_unknown = [] for j in range(ulogits.shape[0]): pproto = bproto.clone().detach() """ Algorithm 1 Line 1 """ c = ulogits.argmax(1)[j] """ Algorithm 1 Line 2 """ pproto[0][c] = uquery.reshape(-1, emb_dim)[j] """ Algorithm 1 Line 3 """ pproto = self.para_model.slf_attn(pproto, pproto, pproto)[0] pdiff = (pproto - proto).pow(2).sum(-1).sum() / 64.0 """ pdiff: d_SnaTCHer in Algorithm 1 """ snatch_unknown.append(pdiff) pkdiff = torch.stack(snatch_known) pudiff = torch.stack(snatch_unknown) pkdiff = pkdiff.cpu().detach().numpy() pudiff = pudiff.cpu().detach().numpy() snatch_auroc = calc_auroc(pkdiff, pudiff) self.record[i-1, 0] = loss.item() self.record[i-1, 1] = acc self.auroc_record[i-1, 0] = auroc self.auroc_record[i-1, 1] = snatch_auroc self.auroc_record[i-1, 2] = dist_auroc if i % 100 == 0: vdata = self.record[:, 1] vdata = 1.0 * np.array(vdata) vdata = vdata[:i] va = np.mean(vdata) std = np.std(vdata) vap = 1.96 * (std / np.sqrt(i)) audata = self.auroc_record[:,0] audata = np.array(audata, np.float32) audata = audata[:i] aua = np.mean(audata) austd = np.std(audata) auap = 1.96 * (austd / np.sqrt(i)) sdata = self.auroc_record[:,1] sdata = np.array(sdata, np.float32) sdata = sdata[:i] sa = np.mean(sdata) sstd = np.std(sdata) sap = 1.96 * (sstd / np.sqrt(i)) ddata = self.auroc_record[:, 2] ddata = np.array(ddata, np.float32)[:i] da = np.mean(ddata) dstd = np.std(ddata) dap = 1.96 * (dstd / np.sqrt(i)) print("acc: {:.4f} + {:.4f} Prob: {:.4f} + {:.4f} Dist: {:.4f} + {:.4f} SnaTCHer: {:.4f} + {:.4f}"\ .format(va, vap, aua, auap, da, dap, sa, sap)) return
[ "numpy.mean", "model.trainer.SnaTCHer_helpers.get_dataloader", "numpy.sqrt", "numpy.std", "torch.stack", "os.path.join", "sklearn.metrics.roc_auc_score", "numpy.array", "numpy.zeros", "sklearn.metrics.roc_curve", "torch.cuda.is_available", "model.utils.count_acc", "model.trainer.SnaTCHer_hel...
[((463, 509), 'numpy.concatenate', 'np.concatenate', (['[known_scores, unknown_scores]'], {}), '([known_scores, unknown_scores])\n', (477, 509), True, 'import numpy as np\n'), ((537, 563), 'sklearn.metrics.roc_curve', 'roc_curve', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (546, 563), False, 'from sklearn.metrics import roc_curve, roc_auc_score\n'), ((580, 610), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (593, 610), False, 'from sklearn.metrics import roc_curve, roc_auc_score\n'), ((895, 915), 'model.trainer.SnaTCHer_helpers.get_dataloader', 'get_dataloader', (['args'], {}), '(args)\n', (909, 915), False, 'from model.trainer.SnaTCHer_helpers import get_dataloader, prepare_model\n'), ((954, 973), 'model.trainer.SnaTCHer_helpers.prepare_model', 'prepare_model', (['args'], {}), '(args)\n', (967, 973), False, 'from model.trainer.SnaTCHer_helpers import get_dataloader, prepare_model\n'), ((1367, 1392), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1390, 1392), False, 'import torch\n'), ((1953, 1978), 'numpy.zeros', 'np.zeros', (['(test_steps, 2)'], {}), '((test_steps, 2))\n', (1961, 1978), True, 'import numpy as np\n'), ((2022, 2048), 'numpy.zeros', 'np.zeros', (['(test_steps, 10)'], {}), '((test_steps, 10))\n', (2030, 2048), True, 'import numpy as np\n'), ((2194, 2219), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2217, 2219), False, 'import torch\n'), ((1661, 1713), 'os.path.join', 'osp.join', (['self.args.save_path', 'self.args.weight_name'], {}), '(self.args.save_path, self.args.weight_name)\n', (1669, 1713), True, 'import os.path as osp\n'), ((2505, 2530), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2528, 2530), False, 'import torch\n'), ((3974, 4005), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['klogits', 'label'], {}), '(klogits, label)\n', (3989, 4005), True, 'import torch.nn.functional as F\n'), ((4024, 4049), 'model.utils.count_acc', 'count_acc', (['klogits', 'label'], {}), '(klogits, label)\n', (4033, 4049), False, 'from model.utils import count_acc\n'), ((1087, 1128), 'torch.arange', 'torch.arange', (['args.way'], {'dtype': 'torch.int16'}), '(args.way, dtype=torch.int16)\n', (1099, 1128), False, 'import torch\n'), ((1168, 1208), 'torch.arange', 'torch.arange', (['args.way'], {'dtype': 'torch.int8'}), '(args.way, dtype=torch.int8)\n', (1180, 1208), False, 'import torch\n'), ((2065, 2113), 'torch.arange', 'torch.arange', (['args.closed_way'], {'dtype': 'torch.int16'}), '(args.closed_way, dtype=torch.int16)\n', (2077, 2113), False, 'import torch\n'), ((2756, 2771), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2769, 2771), False, 'import torch\n'), ((4827, 4842), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4840, 4842), False, 'import torch\n'), ((6105, 6130), 'torch.stack', 'torch.stack', (['snatch_known'], {}), '(snatch_known)\n', (6116, 6130), False, 'import torch\n'), ((6154, 6181), 'torch.stack', 'torch.stack', (['snatch_unknown'], {}), '(snatch_unknown)\n', (6165, 6181), False, 'import torch\n'), ((6821, 6835), 'numpy.mean', 'np.mean', (['vdata'], {}), '(vdata)\n', (6828, 6835), True, 'import numpy as np\n'), ((6858, 6871), 'numpy.std', 'np.std', (['vdata'], {}), '(vdata)\n', (6864, 6871), True, 'import numpy as np\n'), ((7010, 7038), 'numpy.array', 'np.array', (['audata', 'np.float32'], {}), '(audata, np.float32)\n', (7018, 7038), True, 'import numpy as np\n'), ((7097, 7112), 'numpy.mean', 'np.mean', (['audata'], {}), '(audata)\n', (7104, 7112), True, 'import numpy as np\n'), ((7137, 7151), 'numpy.std', 'np.std', (['audata'], {}), '(audata)\n', (7143, 7151), True, 'import numpy as np\n'), ((7291, 7318), 'numpy.array', 'np.array', (['sdata', 'np.float32'], {}), '(sdata, np.float32)\n', (7299, 7318), True, 'import numpy as np\n'), ((7374, 7388), 'numpy.mean', 'np.mean', (['sdata'], {}), '(sdata)\n', (7381, 7388), True, 'import numpy as np\n'), ((7412, 7425), 'numpy.std', 'np.std', (['sdata'], {}), '(sdata)\n', (7418, 7425), True, 'import numpy as np\n'), ((7617, 7631), 'numpy.mean', 'np.mean', (['ddata'], {}), '(ddata)\n', (7624, 7631), True, 'import numpy as np\n'), ((7655, 7668), 'numpy.std', 'np.std', (['ddata'], {}), '(ddata)\n', (7661, 7668), True, 'import numpy as np\n'), ((6750, 6765), 'numpy.array', 'np.array', (['vdata'], {}), '(vdata)\n', (6758, 6765), True, 'import numpy as np\n'), ((7564, 7591), 'numpy.array', 'np.array', (['ddata', 'np.float32'], {}), '(ddata, np.float32)\n', (7572, 7591), True, 'import numpy as np\n'), ((2317, 2334), 'torch.arange', 'torch.arange', (['way'], {}), '(way)\n', (2329, 2334), False, 'import torch\n'), ((4108, 4129), 'torch.nn.functional.softmax', 'F.softmax', (['klogits', '(1)'], {}), '(klogits, 1)\n', (4117, 4129), True, 'import torch.nn.functional as F\n'), ((4167, 4188), 'torch.nn.functional.softmax', 'F.softmax', (['ulogits', '(1)'], {}), '(ulogits, 1)\n', (4176, 4188), True, 'import torch.nn.functional as F\n'), ((6908, 6918), 'numpy.sqrt', 'np.sqrt', (['i'], {}), '(i)\n', (6915, 6918), True, 'import numpy as np\n'), ((7191, 7201), 'numpy.sqrt', 'np.sqrt', (['i'], {}), '(i)\n', (7198, 7201), True, 'import numpy as np\n'), ((7463, 7473), 'numpy.sqrt', 'np.sqrt', (['i'], {}), '(i)\n', (7470, 7473), True, 'import numpy as np\n'), ((7706, 7716), 'numpy.sqrt', 'np.sqrt', (['i'], {}), '(i)\n', (7713, 7716), True, 'import numpy as np\n')]
''' Created on 9 jul. 2017 @author: david ''' import rpyc import time import cv2 from engine.driver import Driver import numpy as np def show(): cap = cv2.VideoCapture(0) done = False while not done: # Take each frame _, frame = cap.read() frame = cv2.blur(frame,(5,5)) frame = cv2.flip(frame, 1) cv2.imshow('frame',frame) k = cv2.waitKey(5) & 0xFF done = k == 27 #ESC cap.release() cv2.destroyAllWindows() def getPureColor(): cap = cv2.VideoCapture(0) done = False while not done: # Take each frame _, frame = cap.read() frame = cv2.flip(frame, 1) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) frame[:,:,1]=255 frame[:,:,2]=64 frame = cv2.cvtColor(frame, cv2.COLOR_HSV2BGR) cv2.imshow('frame',frame) k = cv2.waitKey(5) & 0xFF done = k == 27 #ESC cap.release() cv2.destroyAllWindows() def _squareCosinePoints(p1, p2, p3): ''' Calculate square cosine of the angle defined within tree points p1 <- p2 -> p3 ''' v1 = (p1[0] - p2[0], p1[1] - p2[1]) v2 = (p3[0] - p2[0], p3[1] - p2[1]) d = (v1[0]*v1[0] + v1[1]*v1[1]) * (v2[0]*v2[0] + v2[1]*v2[1]) if d != 0: n = v1[0]*v2[0]+v1[1]*v2[1] sqrCos = (n*n)/d else: sqrCos = 1.0 return sqrCos def camTrack(): TRACK_ALPHA = 0.1 MIN_MATCH_COUNT = 7 LINE_AA = cv2.LINE_AA MAX_COSINE = 0.766 MAX_SQR_COSINE = MAX_COSINE ** 2 REMOTE_ADDRESS = "192.168.1.130" DRIVER_KP = 0.3 cap = cv2.VideoCapture(0) cv2.namedWindow("viewer") finder = cv2.ORB_create() FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) search_params = dict(checks = 50) #matcher = cv2.FlannBasedMatcher(index_params, search_params) matcher = cv2.BFMatcher(cv2.NORM_HAMMING2, crossCheck=True) #Init robot driver #connection = rpyc.classic.connect(REMOTE_ADDRESS) #driver = connection.modules["engine.driver"].Driver.createForRobot() #driver = connection.modules["engine.driver"].Driver.createForTesting() driver = Driver.createForTesting() driver.start() try: finish = False while not finish: #Identificar objeto w,h = 240, 180 x,y = (640-w)//2, (480-h)//2 driver.stop() identifyDone = False while not identifyDone: _, frame = cap.read() frame = cv2.flip(frame, 1) cv2.rectangle(frame, (x,y), (x+w, y+h), 255) cv2.imshow("viewer", frame) key = cv2.waitKey(1) & 0xFF if key != 0xFF: identifyDone = True #Obtener keypoints del objeto target = frame[y:y+h, x:x+w] kp1, des1 = finder.detectAndCompute(target, None) target = cv2.drawKeypoints(target, kp1, target, color=(0, 255, 255), flags= 0) cv2.imshow("target", target) cv2.moveWindow("target", 640, 0) targetCoords = [320,240] error = 0 driver.start() sdt = 0.0 count = 0 done = False while not done: t = time.time() _, frame = cap.read() frame = cv2.flip(frame, 1) kp2, des2 = finder.detectAndCompute(frame, None) try: #matches = matcher.knnMatch(np.asarray(des1,np.float32), np.asarray(des2, np.float32), k=2) matches = matcher.match(des1, des2) # Sort them in the order of their distance. goodMatches = sorted(matches, key = lambda x:x.distance)[:10] ''' goodMatches = [] for m,n in matches: if m.distance < 0.7*n.distance: goodMatches.append(m) ''' except: goodMatches=[] if len(goodMatches)>MIN_MATCH_COUNT: src_pts = np.float32([ kp1[m.queryIdx].pt for m in goodMatches ]).reshape(-1,1,2) dst_pts = np.float32([ kp2[m.trainIdx].pt for m in goodMatches ]).reshape(-1,1,2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0) #matchesMask = mask.ravel().tolist() h,w,_ = target.shape pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2) dst = np.int32(cv2.perspectiveTransform(pts,M)) #Calculate target coords #Check angles of sides in order to know if the target was actually found #Using square cosines instead of angles due to performance cosine1 = _squareCosinePoints(dst[3][0], dst[0][0], dst[1][0]) #cosine2 = _squareCosinePoints(dst[0][0], dst[1][0], dst[2][0]) cosine3 = _squareCosinePoints(dst[1][0], dst[2][0], dst[3][0]) #cosine4 = _squareCosinePoints(dst[2][0], dst[3][0], dst[0][0]) if cosine1 < MAX_SQR_COSINE and cosine3 < MAX_SQR_COSINE: newCoords = [0,0] for coord in dst: newCoords=[sum(x) for x in zip(*[newCoords, coord])] newCoords=[x//len(dst) for x in newCoords][0] targetCoords= [int(c[0]+TRACK_ALPHA*(c[1]-c[0])) for c in zip(*[targetCoords, newCoords])] error = targetCoords[0]-320 action = -error * DRIVER_KP if action < -100.0: action = -100.0 elif action > 100.0: action = 100.0 driver.setDirection(action) #Highlight target within frame cv2.polylines(frame,[dst],True,(0, 255, 0),2, LINE_AA) targetColor = (0,255,0) else: #driver.setDirection(0.0) cv2.polylines(frame,[dst],True,(0, 0, 255),2, LINE_AA) targetColor = (0,0,255) cv2.circle(frame, tuple(targetCoords), 2, targetColor) else: driver.setDirection(0.0) # Draw first N matches. for m in goodMatches: # draw the keypoints # print m.queryIdx, m.trainIdx, m.distance cv2.circle(frame, (int(kp2[m.trainIdx].pt[0]), int(kp2[m.trainIdx].pt[1])), 2, (0,255,255)) cv2.line(frame, (320, 0), (320, 480), (0, 255, 255), 1, LINE_AA) cv2.line(frame, (0, 240), (640, 240), (0, 255, 255), 1, LINE_AA) cv2.circle(frame, (320, 240), 2, (0,255,255)) cv2.putText(frame, "Error: {0}".format(error), (0, 16), cv2.FONT_HERSHEY_PLAIN,\ 1.0, (0, 255, 255), lineType=LINE_AA) cv2.imshow("viewer", frame) key = cv2.waitKey(1) & 0xFF if key != 0xFF: done = True cv2.destroyWindow("target") if key == ord("q"): finish = True sdt += time.time() - t count += 1 mt = sdt/count print("tiempo medio: {0:.3f} s; freq: {1:.3f} hz".format(mt, 1.0/mt)) finally: driver.stop() #connection.close() print("Finalizando") cv2.destroyAllWindows() cap.release() if __name__ == '__main__': camTrack()
[ "cv2.rectangle", "cv2.BFMatcher", "cv2.imshow", "cv2.destroyAllWindows", "cv2.moveWindow", "cv2.line", "cv2.ORB_create", "cv2.perspectiveTransform", "cv2.waitKey", "cv2.blur", "cv2.findHomography", "cv2.polylines", "engine.driver.Driver.createForTesting", "cv2.circle", "cv2.cvtColor", ...
[((165, 184), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (181, 184), False, 'import cv2\n'), ((490, 513), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (511, 513), False, 'import cv2\n'), ((550, 569), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (566, 569), False, 'import cv2\n'), ((1009, 1032), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1030, 1032), False, 'import cv2\n'), ((1703, 1722), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1719, 1722), False, 'import cv2\n'), ((1727, 1752), 'cv2.namedWindow', 'cv2.namedWindow', (['"""viewer"""'], {}), "('viewer')\n", (1742, 1752), False, 'import cv2\n'), ((1766, 1782), 'cv2.ORB_create', 'cv2.ORB_create', ([], {}), '()\n', (1780, 1782), False, 'import cv2\n'), ((2001, 2050), 'cv2.BFMatcher', 'cv2.BFMatcher', (['cv2.NORM_HAMMING2'], {'crossCheck': '(True)'}), '(cv2.NORM_HAMMING2, crossCheck=True)\n', (2014, 2050), False, 'import cv2\n'), ((2301, 2326), 'engine.driver.Driver.createForTesting', 'Driver.createForTesting', ([], {}), '()\n', (2324, 2326), False, 'from engine.driver import Driver\n'), ((314, 337), 'cv2.blur', 'cv2.blur', (['frame', '(5, 5)'], {}), '(frame, (5, 5))\n', (322, 337), False, 'import cv2\n'), ((352, 370), 'cv2.flip', 'cv2.flip', (['frame', '(1)'], {}), '(frame, 1)\n', (360, 370), False, 'import cv2\n'), ((379, 405), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (389, 405), False, 'import cv2\n'), ((694, 712), 'cv2.flip', 'cv2.flip', (['frame', '(1)'], {}), '(frame, 1)\n', (702, 712), False, 'import cv2\n'), ((738, 776), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HSV'], {}), '(frame, cv2.COLOR_BGR2HSV)\n', (750, 776), False, 'import cv2\n'), ((842, 880), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_HSV2BGR'], {}), '(frame, cv2.COLOR_HSV2BGR)\n', (854, 880), False, 'import cv2\n'), ((898, 924), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (908, 924), False, 'import cv2\n'), ((8636, 8659), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (8657, 8659), False, 'import cv2\n'), ((417, 431), 'cv2.waitKey', 'cv2.waitKey', (['(5)'], {}), '(5)\n', (428, 431), False, 'import cv2\n'), ((936, 950), 'cv2.waitKey', 'cv2.waitKey', (['(5)'], {}), '(5)\n', (947, 950), False, 'import cv2\n'), ((3142, 3210), 'cv2.drawKeypoints', 'cv2.drawKeypoints', (['target', 'kp1', 'target'], {'color': '(0, 255, 255)', 'flags': '(0)'}), '(target, kp1, target, color=(0, 255, 255), flags=0)\n', (3159, 3210), False, 'import cv2\n'), ((3237, 3265), 'cv2.imshow', 'cv2.imshow', (['"""target"""', 'target'], {}), "('target', target)\n", (3247, 3265), False, 'import cv2\n'), ((3278, 3310), 'cv2.moveWindow', 'cv2.moveWindow', (['"""target"""', '(640)', '(0)'], {}), "('target', 640, 0)\n", (3292, 3310), False, 'import cv2\n'), ((2693, 2711), 'cv2.flip', 'cv2.flip', (['frame', '(1)'], {}), '(frame, 1)\n', (2701, 2711), False, 'import cv2\n'), ((2728, 2777), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(255)'], {}), '(frame, (x, y), (x + w, y + h), 255)\n', (2741, 2777), False, 'import cv2\n'), ((2806, 2833), 'cv2.imshow', 'cv2.imshow', (['"""viewer"""', 'frame'], {}), "('viewer', frame)\n", (2816, 2833), False, 'import cv2\n'), ((3583, 3594), 'time.time', 'time.time', ([], {}), '()\n', (3592, 3594), False, 'import time\n'), ((3674, 3692), 'cv2.flip', 'cv2.flip', (['frame', '(1)'], {}), '(frame, 1)\n', (3682, 3692), False, 'import cv2\n'), ((7598, 7662), 'cv2.line', 'cv2.line', (['frame', '(320, 0)', '(320, 480)', '(0, 255, 255)', '(1)', 'LINE_AA'], {}), '(frame, (320, 0), (320, 480), (0, 255, 255), 1, LINE_AA)\n', (7606, 7662), False, 'import cv2\n'), ((7679, 7743), 'cv2.line', 'cv2.line', (['frame', '(0, 240)', '(640, 240)', '(0, 255, 255)', '(1)', 'LINE_AA'], {}), '(frame, (0, 240), (640, 240), (0, 255, 255), 1, LINE_AA)\n', (7687, 7743), False, 'import cv2\n'), ((7760, 7807), 'cv2.circle', 'cv2.circle', (['frame', '(320, 240)', '(2)', '(0, 255, 255)'], {}), '(frame, (320, 240), 2, (0, 255, 255))\n', (7770, 7807), False, 'import cv2\n'), ((8003, 8030), 'cv2.imshow', 'cv2.imshow', (['"""viewer"""', 'frame'], {}), "('viewer', frame)\n", (8013, 8030), False, 'import cv2\n'), ((2856, 2870), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2867, 2870), False, 'import cv2\n'), ((4755, 4808), 'cv2.findHomography', 'cv2.findHomography', (['src_pts', 'dst_pts', 'cv2.RANSAC', '(5.0)'], {}), '(src_pts, dst_pts, cv2.RANSAC, 5.0)\n', (4773, 4808), False, 'import cv2\n'), ((8070, 8084), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (8081, 8084), False, 'import cv2\n'), ((8188, 8215), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""target"""'], {}), "('target')\n", (8205, 8215), False, 'import cv2\n'), ((8342, 8353), 'time.time', 'time.time', ([], {}), '()\n', (8351, 8353), False, 'import time\n'), ((5048, 5080), 'cv2.perspectiveTransform', 'cv2.perspectiveTransform', (['pts', 'M'], {}), '(pts, M)\n', (5072, 5080), False, 'import cv2\n'), ((6695, 6753), 'cv2.polylines', 'cv2.polylines', (['frame', '[dst]', '(True)', '(0, 255, 0)', '(2)', 'LINE_AA'], {}), '(frame, [dst], True, (0, 255, 0), 2, LINE_AA)\n', (6708, 6753), False, 'import cv2\n'), ((6923, 6981), 'cv2.polylines', 'cv2.polylines', (['frame', '[dst]', '(True)', '(0, 0, 255)', '(2)', 'LINE_AA'], {}), '(frame, [dst], True, (0, 0, 255), 2, LINE_AA)\n', (6936, 6981), False, 'import cv2\n'), ((4534, 4587), 'numpy.float32', 'np.float32', (['[kp1[m.queryIdx].pt for m in goodMatches]'], {}), '([kp1[m.queryIdx].pt for m in goodMatches])\n', (4544, 4587), True, 'import numpy as np\n'), ((4636, 4689), 'numpy.float32', 'np.float32', (['[kp2[m.trainIdx].pt for m in goodMatches]'], {}), '([kp2[m.trainIdx].pt for m in goodMatches])\n', (4646, 4689), True, 'import numpy as np\n'), ((4949, 5009), 'numpy.float32', 'np.float32', (['[[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]'], {}), '([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]])\n', (4959, 5009), True, 'import numpy as np\n')]
r""" Implements a uniform distribution on an edge and a triangular distribution on an edge. The expected values of Z given X may be computed explicitly for these distributions. Some background mathematics: * The moment generating function of a truncated normal distribution ..math :: e^{\mu t + \sigma^2 t^2 / 2} \left[ \frac{\Phi(\alpha-\sigma t) - \Phi(\beta - \sigma t)}{ \Phi(\beta) - \Phi(\alpha)} \right] where * :math:`\mu` is the mean of the untruncated normal distribution, * :math:`\sigma` is the standard deviation, * :math:`(\alpha,\beta)` are the bounds of the distribution. """ import numpy as np from smm.rvs.uniformsimplexrv import UniformSimplexRV from smm.rvs.basesimplexrv import BaseSimplexRV from smm.helpfulfunctions import invsqrtS_logdetS_from_S from scipy.stats import norm Phi = norm.cdf def phi(x): return np.exp(-0.5 * np.square(x)) / (np.sqrt(2*np.pi)) class EdgeRV(UniformSimplexRV): r""" A class to generate points uniformly from an edge in :math:`\mathbb{R}^m`. """ def __init__(self, m, S, alpha=1.0): """ Parameters ---------- m : int the number of hidden features. S : pair of elements in range(m) the vertices of the simplex. """ if not len(S) == 2: raise ValueError("Must specify a pair of vertices") UniformSimplexRV.__init__(self, m, S) def __str__(self): return BaseSimplexRV.__str__(self) def __repr__(self): return BaseSimplexRV.__repr__(self) def U_sample(self, d, rnd=np.random.RandomState()): return np.random.rand(d, 1) def U_moments_given_Y(self, a, b, c): r""" For the latent variable U and function f with .. math:: f(U) = \exp(a + b U - \frac12 cU^2) calculate the following values: .. math:: &\log E = \log\mathbb{E}f(U), \\ &F = \frac{1}{E}\mathbb{E}_{U \mid Y} f(U)U \\ &G = \frac{1}{E}\mathbb{E}_{U \mid Y} f(U)UU^t. Note that F is the expected value of U with the distribution proportional to f, while G is the second moment. This distribution is a truncated normal distribution. Parameters ---------- a : (* shape1) ndarray array of constants, shape1 should be broadcastable with shape2 and shape3. b : (* shape2, 1) ndarray array of linear terms, shape2 should be broadcastable with shape1 and shape3. C : (1, 1, 1) ndarray array of quadratic terms. Returns ------- logE : (shape,) ndarray see above F : (shape, 1) ndarray see above G : (shape, 1, 1) ndarray see above """ cthreshold = 1e-12 zthreshold = 1e-12 c = c[0, 0, 0] if c > cthreshold: σ2 = 1 / c σ = np.sqrt(σ2) μ = b.reshape(b.shape[:-1]) * σ2 α = -μ / σ β = 1 / σ + α Z = Phi(β) - Phi(α) mask = Z < zthreshold # if σ or |μ| is large Z[mask] = zthreshold non_Z_part = a + μ**2 / (2*σ2) + 1/2 * np.log(2*np.pi) + np.log(σ) logE = non_Z_part + np.log(Z) EU = μ + σ * (phi(α) - phi(β)) / Z EUUt = σ2 * (1 + (α*phi(α) - β*phi(β)) / Z) + 2*μ*EU - μ**2 # If Z is small then use endpoints # (should find better approximation) EU[mask] = np.clip(μ[mask], 0, 1) EUUt[mask] = EU[mask] else: # We make the assumption that c can only be close to zero # if the unit interval is embedded at a single point, in # which case b is also zero. logE = a EU = np.zeros_like(a) + 0.5 # mean of uniform dist EUUt = np.zeros_like(a) + 1/3 # EU2 for uniform dist return logE, EU[:, None], EUUt[:, None, None] def pullback_quad_form(self, V, S, X): r""" For each row x of X, one has a quadratic form on u .. math:: \log \rho_S(VMu + Vm - x) = a + b u - \frac{1}{2} cu^2 where :math:`\rho_S` is the density function of the multivariate normal distribution with mean 0 and covariance matrix S. The formulae for the constants are .. math:: a &= -\frac{n}{2}\log(2\pi) - \frac{1}{2}\log\text{det} S -\frac{1}{2}(Vm - x)^tS^{-1}(Vm - x) \\ b &= -(VM)^t S^{-1} (Vm - x) \\ c &= (VM)^tS^{-1}VM """ N, n = X.shape logA = n / 2 * np.log(2.0*np.pi) Vm = self.Moffset.dot(V) VM = self.M.dot(V) invsqrtS, logdetS = invsqrtS_logdetS_from_S(S, n) if len(np.shape(S)) == 2: # full matrix case Y = (X - Vm).dot(invsqrtS) J = VM.dot(invsqrtS) if len(np.shape(S)) <= 1: # spherical or diagonal case Y = (X - Vm) * invsqrtS J = VM * invsqrtS a = -logA - logdetS / 2 - 0.5 * np.sum(np.square(Y), axis=-1) b = Y.dot(J.T) c = J.dot(J.T) return a, b, c.reshape((1, 1, 1)) def log_prob_X(self, V, S, X): r""" Given an array X of values in :math:`\mathbb{R}^n`, and conditional probabilities .. math:: P(X\mid Z) = \rho_S(X-VZ), where :math:`\rho_S` is the multivariate normal distribution with mean 0 and covariance :math:`S`, calculate the * logarithm of the probability density of each row of :math:`X`. Parameters ---------- V : (m, n) ndarray linear map :math:`\mathbb{R}^m \rightarrow\mathbb{R}^n` S : {(n, n) ndarray, (n,) ndarray, float} covariance in either matrix form, diagonal form, or spherical form. X : (N, n) ndarray data Returns ------- log_PX : (N,) ndarray logarithm of probability of :math:`X`. """ quad_forms = self.pullback_quad_form(V, S, X) log_PX, E_UgX, E_UUtgX = self.U_moments_given_Y(*quad_forms) self.saved_E_UgX = E_UgX # broadcastable to (N, k) self.saved_E_UUtgX = E_UUtgX # broadcastable to (N, k, k) return log_PX def mean_given_X(self): r""" Given probabilities for X of values in :math:`\mathbb{R}^n`, calculate the mean of :math:`Z` given :math:`X` using values pre-calculated by log_prob_X. Parameters ---------- None Returns ------- E_ZgX: (N,m) ndarray total of :math:`Z` from this distribution given :math:`X`. """ E_UgX = self.saved_E_UgX # broadcastable to (N, k) E_ZgX = self.Moffset + E_UgX.dot(self.M) return E_ZgX def moments_marg_over_X(self, weights, X): r""" Given weights for the array X of values in :math:`\mathbb{R}^n`, calculate * the expected value of :math:`Z` given :math:`X`, * the expected value of :math:`ZZ^t` given :math:`X`. using values pre-calculated by log_prob_X. Parameters ---------- weights : (N,) ndarray weights for the data points. X : (N, n) ndarray the data. Returns ------- qZZj: (N,m,m) ndarray total of :math:`ZZt` from this distribution given :math:`X`. qZXj: (N,m,n) ndarray total of :math:`ZX^t` from this distribution given :math:`X`. """ UgX = self.saved_E_UgX UUgX = self.saved_E_UUtgX total_weight = np.sum(weights) U = UgX.T.dot(weights) UU = UUgX.T.dot(weights) # NB Z = MU + m M, m = self.M, self.Moffset UMm = U.dot(M)[:, None] * m ZZj = m * m[:, None] * total_weight + M.T.dot(UU.dot(M)) + UMm + UMm.T UX = (UgX * weights[:, None]).T.dot(X) ZXj = M.T.dot(UX) + m[:, None] * weights.dot(X) return ZZj, ZXj __all__ = ["EdgeRV"]
[ "numpy.clip", "numpy.sqrt", "smm.rvs.basesimplexrv.BaseSimplexRV.__str__", "numpy.random.rand", "numpy.log", "smm.helpfulfunctions.invsqrtS_logdetS_from_S", "smm.rvs.uniformsimplexrv.UniformSimplexRV.__init__", "numpy.square", "numpy.sum", "smm.rvs.basesimplexrv.BaseSimplexRV.__repr__", "numpy.s...
[((904, 922), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (911, 922), True, 'import numpy as np\n'), ((1398, 1435), 'smm.rvs.uniformsimplexrv.UniformSimplexRV.__init__', 'UniformSimplexRV.__init__', (['self', 'm', 'S'], {}), '(self, m, S)\n', (1423, 1435), False, 'from smm.rvs.uniformsimplexrv import UniformSimplexRV\n'), ((1475, 1502), 'smm.rvs.basesimplexrv.BaseSimplexRV.__str__', 'BaseSimplexRV.__str__', (['self'], {}), '(self)\n', (1496, 1502), False, 'from smm.rvs.basesimplexrv import BaseSimplexRV\n'), ((1543, 1571), 'smm.rvs.basesimplexrv.BaseSimplexRV.__repr__', 'BaseSimplexRV.__repr__', (['self'], {}), '(self)\n', (1565, 1571), False, 'from smm.rvs.basesimplexrv import BaseSimplexRV\n'), ((1603, 1626), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (1624, 1626), True, 'import numpy as np\n'), ((1644, 1664), 'numpy.random.rand', 'np.random.rand', (['d', '(1)'], {}), '(d, 1)\n', (1658, 1664), True, 'import numpy as np\n'), ((4812, 4841), 'smm.helpfulfunctions.invsqrtS_logdetS_from_S', 'invsqrtS_logdetS_from_S', (['S', 'n'], {}), '(S, n)\n', (4835, 4841), False, 'from smm.helpfulfunctions import invsqrtS_logdetS_from_S\n'), ((7775, 7790), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (7781, 7790), True, 'import numpy as np\n'), ((2981, 2992), 'numpy.sqrt', 'np.sqrt', (['σ2'], {}), '(σ2)\n', (2988, 2992), True, 'import numpy as np\n'), ((3573, 3595), 'numpy.clip', 'np.clip', (['μ[mask]', '(0)', '(1)'], {}), '(μ[mask], 0, 1)\n', (3580, 3595), True, 'import numpy as np\n'), ((4704, 4723), 'numpy.log', 'np.log', (['(2.0 * np.pi)'], {}), '(2.0 * np.pi)\n', (4710, 4723), True, 'import numpy as np\n'), ((887, 899), 'numpy.square', 'np.square', (['x'], {}), '(x)\n', (896, 899), True, 'import numpy as np\n'), ((3282, 3291), 'numpy.log', 'np.log', (['σ'], {}), '(σ)\n', (3288, 3291), True, 'import numpy as np\n'), ((3322, 3331), 'numpy.log', 'np.log', (['Z'], {}), '(Z)\n', (3328, 3331), True, 'import numpy as np\n'), ((3862, 3878), 'numpy.zeros_like', 'np.zeros_like', (['a'], {}), '(a)\n', (3875, 3878), True, 'import numpy as np\n'), ((3928, 3944), 'numpy.zeros_like', 'np.zeros_like', (['a'], {}), '(a)\n', (3941, 3944), True, 'import numpy as np\n'), ((4858, 4869), 'numpy.shape', 'np.shape', (['S'], {}), '(S)\n', (4866, 4869), True, 'import numpy as np\n'), ((4984, 4995), 'numpy.shape', 'np.shape', (['S'], {}), '(S)\n', (4992, 4995), True, 'import numpy as np\n'), ((5146, 5158), 'numpy.square', 'np.square', (['Y'], {}), '(Y)\n', (5155, 5158), True, 'import numpy as np\n'), ((3264, 3281), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (3270, 3281), True, 'import numpy as np\n')]
import numpy as np def calcparams_desoto_ref(effective_irradiance, temperature_cell, alpha_sc, nNsVth, photocurrent, saturation_current, resistance_shunt, resistance_series, EgRef=1.121, dEgdT=-0.0002677, irrad_ref=1000, temperature_ref=25): ''' Calculates five parameter values for the single diode equation at reference effective irradiance and cell temperature using the De Soto et al. model described in [1]_. Inverse function of calparams_desoto. The five values returned by calcparams_desoto_ref can be used by singlediode to calculate an IV curve. Parameters ---------- effective_irradiance : numeric The irradiance (W/m2) that is converted to photocurrent. temperature_cell : numeric The average cell temperature of cells within a module in C. alpha_sc : float The short-circuit current temperature coefficient of the module in units of A/C. nNsVth : float The product of the usual diode ideality factor (n, unitless), number of cells in series (Ns), and cell thermal voltage at reference conditions, in units of V. I_L : float The light-generated current (or photocurrent) at reference conditions, in amperes. I_o : float The dark or diode reverse saturation current at reference conditions, in amperes. R_sh : float The shunt resistance at reference conditions, in ohms. R_s : float The series resistance at reference conditions, in ohms. EgRef : float The energy bandgap at reference temperature in units of eV. 1.121 eV for crystalline silicon. EgRef must be >0. For parameters from the SAM CEC module database, EgRef=1.121 is implicit for all cell types in the parameter estimation algorithm used by NREL. dEgdT : float The temperature dependence of the energy bandgap at reference conditions in units of 1/K. May be either a scalar value (e.g. -0.0002677 as in [1]_) or a DataFrame (this may be useful if dEgdT is a modeled as a function of temperature). For parameters from the SAM CEC module database, dEgdT=-0.0002677 is implicit for all cell types in the parameter estimation algorithm used by NREL. irrad_ref : float (optional, default=1000) Reference irradiance in W/m^2. temp_ref : float (optional, default=25) Reference cell temperature in C. Returns ------- Tuple of the following results: photocurrent_ref : numeric Light-generated current in amperes saturation_current_ref : numeric Diode saturation curent in amperes resistance_series_ref : float Series resistance in ohms resistance_shunt_ref : numeric Shunt resistance in ohms nNsVth_ref : numeric The product of the usual diode ideality factor (n, unitless), number of cells in series (Ns), and cell thermal voltage at specified effective irradiance and cell temperature. References ---------- .. [1] <NAME> et al., "Improvement and validation of a model for photovoltaic array performance", Solar Energy, vol 80, pp. 78-88, 2006. .. [2] System Advisor Model web page. https://sam.nrel.gov. .. [3] <NAME>, "An Improved Coefficient Calculator for the California Energy Commission 6 Parameter Photovoltaic Module Model", Journal of Solar Energy Engineering, vol 134, 2012. .. [4] <NAME>, "Semiconductors: Data Handbook, 3rd ed." ISBN 3-540-40488-0 See Also -------- singlediode retrieve_sam Notes ----- If the reference parameters in the ModuleParameters struct are read from a database or library of parameters (e.g. System Advisor Model), it is important to use the same EgRef and dEgdT values that were used to generate the reference parameters, regardless of the actual bandgap characteristics of the semiconductor. For example, in the case of the System Advisor Model library, created as described in [3], EgRef and dEgdT for all modules were 1.121 and -0.0002677, respectively. This table of reference bandgap energies (EgRef), bandgap energy temperature dependence (dEgdT), and "typical" airmass response (M) is provided purely as reference to those who may generate their own reference module parameters (a_ref, IL_ref, I0_ref, etc.) based upon the various PV semiconductors. Again, we stress the importance of using identical EgRef and dEgdT when generation reference parameters and modifying the reference parameters (for irradiance, temperature, and airmass) per DeSoto's equations. Crystalline Silicon (Si): * EgRef = 1.121 * dEgdT = -0.0002677 >>> M = np.polyval([-1.26E-4, 2.816E-3, -0.024459, 0.086257, 0.9181], ... AMa) # doctest: +SKIP Source: [1] Cadmium Telluride (CdTe): * EgRef = 1.475 * dEgdT = -0.0003 >>> M = np.polyval([-2.46E-5, 9.607E-4, -0.0134, 0.0716, 0.9196], ... AMa) # doctest: +SKIP Source: [4] Copper Indium diSelenide (CIS): * EgRef = 1.010 * dEgdT = -0.00011 >>> M = np.polyval([-3.74E-5, 0.00125, -0.01462, 0.0718, 0.9210], ... AMa) # doctest: +SKIP Source: [4] Copper Indium Gallium diSelenide (CIGS): * EgRef = 1.15 * dEgdT = ???? >>> M = np.polyval([-9.07E-5, 0.0022, -0.0202, 0.0652, 0.9417], ... AMa) # doctest: +SKIP Source: Wikipedia Gallium Arsenide (GaAs): * EgRef = 1.424 * dEgdT = -0.000433 * M = unknown Source: [4] ''' # Boltzmann constant in eV/K k = 8.617332478e-05 # reference temperature Tref_K = temperature_ref + 273.15 Tcell_K = temperature_cell + 273.15 E_g = EgRef * (1 + dEgdT*(Tcell_K - Tref_K)) # nNsVth = a_ref * (Tcell_K / Tref_K) nNsVth_ref = nNsVth * (Tref_K/Tcell_K) # In the equation for IL, the single factor effective_irradiance is # used, in place of the product S*M in [1]. effective_irradiance is # equivalent to the product of S (irradiance reaching a module's cells) * # M (spectral adjustment factor) as described in [1]. photocurrent_ref = photocurrent*irrad_ref/effective_irradiance - \ alpha_sc*(temperature_cell-temperature_ref) # IL = effective_irradiance / irrad_ref * \ # (I_L_ref + alpha_sc * (Tcell_K - Tref_K)) saturation_current_ref = saturation_current /( ((Tcell_K / Tref_K) ** 3) * (np.exp(EgRef / (k*(Tref_K)) - (E_g / (k*(Tcell_K)))))) # Note that the equation for Rsh differs from [1]. In [1] Rsh is given as # Rsh = Rsh_ref * (S_ref / S) where S is broadband irradiance reaching # the module's cells. If desired this model behavior can be duplicated # by applying reflection and soiling losses to broadband plane of array # irradiance and not applying a spectral loss modifier, i.e., # spectral_modifier = 1.0. # use errstate to silence divide by warning with np.errstate(divide='ignore'): resistance_shunt_ref = resistance_shunt * (effective_irradiance/irrad_ref) resistance_series_ref = resistance_series return photocurrent_ref, saturation_current_ref, resistance_series_ref,\ resistance_shunt_ref, nNsVth_ref
[ "numpy.exp", "numpy.errstate" ]
[((7287, 7315), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (7298, 7315), True, 'import numpy as np\n'), ((6774, 6824), 'numpy.exp', 'np.exp', (['(EgRef / (k * Tref_K) - E_g / (k * Tcell_K))'], {}), '(EgRef / (k * Tref_K) - E_g / (k * Tcell_K))\n', (6780, 6824), True, 'import numpy as np\n')]
"""Baseline for comparability: linear svm by SAGA. Uses structured format.""" import os from hashlib import sha1 import warnings from collections import Counter import dill import numpy as np from sklearn.base import clone from sklearn.metrics import f1_score from sklearn.preprocessing import LabelEncoder from sklearn.utils.class_weight import compute_sample_weight from sklearn.model_selection import KFold from lightning.classification import SAGAClassifier from marseille.custom_logging import logging from marseille.io import load_csr from marseille.argdoc import DocLabel, CdcpArgumentationDoc, UkpEssayArgumentationDoc from marseille.struct_models import BaseArgumentMixin from marseille.datasets import ukp_train_ids, cdcp_train_ids def saga_cv(which, alphas, l1_ratio): if which == 'cdcp': n_folds = 3 path = os.path.join("data", "process", "erule", "folds", "{}", "{}") elif which == 'ukp': n_folds = 5 path = os.path.join("data", "process", "ukp-essays", "folds", "{}", "{}") else: raise ValueError clf_link = SAGAClassifier(loss='smooth_hinge', penalty='l1', tol=1e-4, max_iter=100, random_state=0, verbose=0) clf_prop = clone(clf_link) link_scores = np.zeros((n_folds, len(alphas))) prop_scores = np.zeros_like(link_scores) for k in range(n_folds): X_tr_link, y_tr_link = load_csr(path.format(k, 'train.npz'), return_y=True) X_te_link, y_te_link = load_csr(path.format(k, 'val.npz'), return_y=True) X_tr_prop, y_tr_prop = load_csr(path.format(k, 'prop-train.npz'), return_y=True) X_te_prop, y_te_prop = load_csr(path.format(k, 'prop-val.npz'), return_y=True) le = LabelEncoder() y_tr_prop_enc = le.fit_transform(y_tr_prop) y_te_prop_enc = le.transform(y_te_prop) link_sw = compute_sample_weight('balanced', y_tr_link) for j, alpha in enumerate(alphas): beta = alpha * l1_ratio alpha *= 1 - l1_ratio clf_link.set_params(alpha=alpha, beta=beta) clf_prop.set_params(alpha=alpha, beta=beta) clf_link.fit(X_tr_link, y_tr_link, sample_weight=link_sw) y_pred_link = clf_link.predict(X_te_link) clf_prop.fit(X_tr_prop, y_tr_prop_enc) y_pred_prop = clf_prop.predict(X_te_prop) with warnings.catch_warnings() as w: warnings.simplefilter('ignore') link_f = f1_score(y_te_link, y_pred_link, average='binary') prop_f = f1_score(y_te_prop_enc, y_pred_prop, average='macro') link_scores[k, j] = link_f prop_scores[k, j] = prop_f return link_scores, prop_scores def saga_cv_cache(*args): arghash = sha1(repr(args).encode('utf-8')).hexdigest() fn = "res/baseline_linear_{}.dill".format(arghash) try: with open(fn, 'rb') as f: out = dill.load(f) logging.info("Loaded cached version.") except FileNotFoundError: logging.info("Computing...") out = saga_cv(*args) with open(fn, 'wb') as f: dill.dump(out, f) return out class BaselineStruct(BaseArgumentMixin): def __init__(self, alpha_link, alpha_prop, l1_ratio): self.alpha_link = alpha_link self.alpha_prop = alpha_prop self.l1_ratio = l1_ratio self.compat_features = False def initialize_labels(self, y_props_flat, y_links_flat): self.prop_encoder_ = LabelEncoder().fit(y_props_flat) self.link_encoder_ = LabelEncoder().fit(y_links_flat) self.n_prop_states = len(self.prop_encoder_.classes_) self.n_link_states = len(self.link_encoder_.classes_) def fit(self, X_link, y_link, X_prop, y_prop): self.initialize_labels(y_prop, y_link) y_link = self.link_encoder_.transform(y_link) y_prop = self.prop_encoder_.transform(y_prop) self.link_clf_ = SAGAClassifier(loss='smooth_hinge', penalty='l1', tol=1e-4, max_iter=500, random_state=0, verbose=0) self.prop_clf_ = clone(self.link_clf_) alpha_link = self.alpha_link * (1 - self.l1_ratio) beta_link = self.alpha_link * self.l1_ratio sw = compute_sample_weight('balanced', y_link) self.link_clf_.set_params(alpha=alpha_link, beta=beta_link) self.link_clf_.fit(X_link, y_link, sample_weight=sw) alpha_prop = self.alpha_prop * (1 - self.l1_ratio) beta_prop = self.alpha_prop * self.l1_ratio self.prop_clf_.set_params(alpha=alpha_prop, beta=beta_prop) self.prop_clf_.fit(X_prop, y_prop) return self def decision_function(self, X_link, X_prop, docs): link_offsets = np.cumsum([len(doc.features) for doc in docs]) y_link_flat = self.link_clf_.decision_function(X_link) y_link_marg = np.zeros((len(y_link_flat), len(self.link_encoder_.classes_))) link_on, = self.link_encoder_.transform([True]) y_link_marg[:, link_on] = y_link_flat.ravel() Y_link = [y_link_marg[start:end] for start, end in zip(np.append(0, link_offsets), link_offsets)] prop_offsets = np.cumsum([len(doc.prop_features) for doc in docs]) y_prop_marg = self.prop_clf_.decision_function(X_prop) Y_prop = [y_prop_marg[start:end] for start, end in zip(np.append(0, prop_offsets), prop_offsets)] Y_pred = [] for y_link, y_prop in zip(Y_link, Y_prop): Y_pred.append(DocLabel(y_prop, y_link)) assert len(Y_pred) == len(docs) return Y_pred def saga_score_struct(which, link_alpha, prop_alpha, l1_ratio, decode=False): if which == 'cdcp': n_folds = 3 ids = np.array(cdcp_train_ids) path = os.path.join("data", "process", "erule", "folds", "{}", "{}") _tpl = os.path.join("data", "process", "erule", "{}", "{:05d}") _load = lambda which, ks: (CdcpArgumentationDoc(_tpl.format(which, k)) for k in ks) elif which == 'ukp': n_folds = 5 ids = np.array(ukp_train_ids) path = os.path.join("data", "process", "ukp-essays", "folds", "{}", "{}") _tpl = os.path.join("data", "process", "ukp-essays", "essay{:03d}") _load = lambda which, ks: (UkpEssayArgumentationDoc(_tpl.format(k)) for k in ks) else: raise ValueError baseline = BaselineStruct(link_alpha, prop_alpha, l1_ratio) all_Y_pred = [] scores = [] for k, (tr, val) in enumerate(KFold(n_folds).split(ids)): val_docs = list(_load("train", ids[val])) Y_true = [] for doc in val_docs: y_prop = np.array([str(f['label_']) for f in doc.prop_features]) y_link = np.array([f['label_'] for f in doc.features]) Y_true.append(DocLabel(y_prop, y_link)) X_tr_link, y_tr_link = load_csr(path.format(k, 'train.npz'), return_y=True) X_te_link, y_te_link = load_csr(path.format(k, 'val.npz'), return_y=True) X_tr_prop, y_tr_prop = load_csr(path.format(k, 'prop-train.npz'), return_y=True) X_te_prop, y_te_prop = load_csr(path.format(k, 'prop-val.npz'), return_y=True) baseline.fit(X_tr_link, y_tr_link, X_tr_prop, y_tr_prop) Y_marg = baseline.decision_function(X_te_link, X_te_prop, val_docs) zero_compat = np.zeros((baseline.n_prop_states, baseline.n_prop_states, baseline.n_link_states)) if decode: statuses = Counter() Y_pred = [] for doc, y in zip(val_docs, Y_marg): doc.link_to_node_ = np.array( [(f['src__prop_id_'], f['trg__prop_id_']) for f in doc.features], dtype=np.intp) doc.second_order_ = [] potentials = (y.nodes, y.links, zero_compat, [], [] ,[]) y_decoded, status = baseline._inference(doc, potentials, relaxed=False, constraints=which) Y_pred.append(y_decoded) statuses[status] += 1 logging.info("Test inference status: " + ", ".join( "{:.1f}% {}".format(100 * val / len(val_docs), key) for key, val in statuses.most_common())) else: Y_pred = [baseline._round(y.nodes, y.links, inverse_transform=True) for y in Y_marg] all_Y_pred.extend(Y_pred) scores.append(baseline._score(Y_true, Y_pred)) return scores, all_Y_pred def saga_score_struct_cache(*args): arghash = sha1(repr(("score_struct",) + args).encode('utf-8')).hexdigest() fn = "res/baseline_linear_{}.dill".format(arghash) try: with open(fn, 'rb') as f: out = dill.load(f) logging.info("Loaded cached version.") except FileNotFoundError: logging.info("Computing...") out = saga_score_struct(*args) with open(fn, 'wb') as f: dill.dump(out, f) return out def main(): from docopt import docopt usage = """ Usage: baseline_linear (cdcp|ukp) [--l1-ratio=N --decode] Options: --l1-ratio=N amount of l1 [default: 0] """ args = docopt(usage) which = 'cdcp' if args['cdcp'] else 'ukp' l1_ratio = float(args['--l1-ratio']) decode = args['--decode'] n_alphas = 20 alphas = np.logspace(-8, 0, n_alphas) link_scores, prop_scores = saga_cv_cache(which, alphas, l1_ratio) link_alpha_ix = np.argmax(link_scores.mean(axis=0)) prop_alpha_ix = np.argmax(prop_scores.mean(axis=0)) print("Link alpha={}".format(alphas[link_alpha_ix])) print("Prop alpha={}".format(alphas[prop_alpha_ix])) alpha_link = alphas[link_alpha_ix] alpha_prop = alphas[prop_alpha_ix] scores, _ = saga_score_struct_cache(which, alpha_link, alpha_prop, l1_ratio, decode) link_macro, link_micro, node_macro, node_micro, acc = np.mean(scores, axis=0) print("Link: {:.3f}/{:.3f} Node: {:.3f}/{:.3f} accuracy {:.3f}".format( link_macro, link_micro, node_macro, node_micro, acc)) if __name__ == '__main__': main()
[ "sklearn.preprocessing.LabelEncoder", "numpy.array", "sklearn.model_selection.KFold", "docopt.docopt", "dill.load", "marseille.custom_logging.logging.info", "numpy.mean", "numpy.zeros_like", "warnings.simplefilter", "numpy.logspace", "marseille.argdoc.DocLabel", "sklearn.metrics.f1_score", "...
[((1114, 1220), 'lightning.classification.SAGAClassifier', 'SAGAClassifier', ([], {'loss': '"""smooth_hinge"""', 'penalty': '"""l1"""', 'tol': '(0.0001)', 'max_iter': '(100)', 'random_state': '(0)', 'verbose': '(0)'}), "(loss='smooth_hinge', penalty='l1', tol=0.0001, max_iter=100,\n random_state=0, verbose=0)\n", (1128, 1220), False, 'from lightning.classification import SAGAClassifier\n'), ((1260, 1275), 'sklearn.base.clone', 'clone', (['clf_link'], {}), '(clf_link)\n', (1265, 1275), False, 'from sklearn.base import clone\n'), ((1346, 1372), 'numpy.zeros_like', 'np.zeros_like', (['link_scores'], {}), '(link_scores)\n', (1359, 1372), True, 'import numpy as np\n'), ((10001, 10014), 'docopt.docopt', 'docopt', (['usage'], {}), '(usage)\n', (10007, 10014), False, 'from docopt import docopt\n'), ((10165, 10193), 'numpy.logspace', 'np.logspace', (['(-8)', '(0)', 'n_alphas'], {}), '(-8, 0, n_alphas)\n', (10176, 10193), True, 'import numpy as np\n'), ((10760, 10783), 'numpy.mean', 'np.mean', (['scores'], {'axis': '(0)'}), '(scores, axis=0)\n', (10767, 10783), True, 'import numpy as np\n'), ((846, 907), 'os.path.join', 'os.path.join', (['"""data"""', '"""process"""', '"""erule"""', '"""folds"""', '"""{}"""', '"""{}"""'], {}), "('data', 'process', 'erule', 'folds', '{}', '{}')\n", (858, 907), False, 'import os\n'), ((1920, 1934), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (1932, 1934), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((2054, 2098), 'sklearn.utils.class_weight.compute_sample_weight', 'compute_sample_weight', (['"""balanced"""', 'y_tr_link'], {}), "('balanced', y_tr_link)\n", (2075, 2098), False, 'from sklearn.utils.class_weight import compute_sample_weight\n'), ((3152, 3190), 'marseille.custom_logging.logging.info', 'logging.info', (['"""Loaded cached version."""'], {}), "('Loaded cached version.')\n", (3164, 3190), False, 'from marseille.custom_logging import logging\n'), ((4157, 4263), 'lightning.classification.SAGAClassifier', 'SAGAClassifier', ([], {'loss': '"""smooth_hinge"""', 'penalty': '"""l1"""', 'tol': '(0.0001)', 'max_iter': '(500)', 'random_state': '(0)', 'verbose': '(0)'}), "(loss='smooth_hinge', penalty='l1', tol=0.0001, max_iter=500,\n random_state=0, verbose=0)\n", (4171, 4263), False, 'from lightning.classification import SAGAClassifier\n'), ((4365, 4386), 'sklearn.base.clone', 'clone', (['self.link_clf_'], {}), '(self.link_clf_)\n', (4370, 4386), False, 'from sklearn.base import clone\n'), ((4512, 4553), 'sklearn.utils.class_weight.compute_sample_weight', 'compute_sample_weight', (['"""balanced"""', 'y_link'], {}), "('balanced', y_link)\n", (4533, 4553), False, 'from sklearn.utils.class_weight import compute_sample_weight\n'), ((6081, 6105), 'numpy.array', 'np.array', (['cdcp_train_ids'], {}), '(cdcp_train_ids)\n', (6089, 6105), True, 'import numpy as np\n'), ((6121, 6182), 'os.path.join', 'os.path.join', (['"""data"""', '"""process"""', '"""erule"""', '"""folds"""', '"""{}"""', '"""{}"""'], {}), "('data', 'process', 'erule', 'folds', '{}', '{}')\n", (6133, 6182), False, 'import os\n'), ((6198, 6254), 'os.path.join', 'os.path.join', (['"""data"""', '"""process"""', '"""erule"""', '"""{}"""', '"""{:05d}"""'], {}), "('data', 'process', 'erule', '{}', '{:05d}')\n", (6210, 6254), False, 'import os\n'), ((7939, 8026), 'numpy.zeros', 'np.zeros', (['(baseline.n_prop_states, baseline.n_prop_states, baseline.n_link_states)'], {}), '((baseline.n_prop_states, baseline.n_prop_states, baseline.\n n_link_states))\n', (7947, 8026), True, 'import numpy as np\n'), ((9561, 9599), 'marseille.custom_logging.logging.info', 'logging.info', (['"""Loaded cached version."""'], {}), "('Loaded cached version.')\n", (9573, 9599), False, 'from marseille.custom_logging import logging\n'), ((968, 1034), 'os.path.join', 'os.path.join', (['"""data"""', '"""process"""', '"""ukp-essays"""', '"""folds"""', '"""{}"""', '"""{}"""'], {}), "('data', 'process', 'ukp-essays', 'folds', '{}', '{}')\n", (980, 1034), False, 'import os\n'), ((3131, 3143), 'dill.load', 'dill.load', (['f'], {}), '(f)\n', (3140, 3143), False, 'import dill\n'), ((3229, 3257), 'marseille.custom_logging.logging.info', 'logging.info', (['"""Computing..."""'], {}), "('Computing...')\n", (3241, 3257), False, 'from marseille.custom_logging import logging\n'), ((6441, 6464), 'numpy.array', 'np.array', (['ukp_train_ids'], {}), '(ukp_train_ids)\n', (6449, 6464), True, 'import numpy as np\n'), ((6480, 6546), 'os.path.join', 'os.path.join', (['"""data"""', '"""process"""', '"""ukp-essays"""', '"""folds"""', '"""{}"""', '"""{}"""'], {}), "('data', 'process', 'ukp-essays', 'folds', '{}', '{}')\n", (6492, 6546), False, 'import os\n'), ((6590, 6650), 'os.path.join', 'os.path.join', (['"""data"""', '"""process"""', '"""ukp-essays"""', '"""essay{:03d}"""'], {}), "('data', 'process', 'ukp-essays', 'essay{:03d}')\n", (6602, 6650), False, 'import os\n'), ((7172, 7217), 'numpy.array', 'np.array', (["[f['label_'] for f in doc.features]"], {}), "([f['label_'] for f in doc.features])\n", (7180, 7217), True, 'import numpy as np\n'), ((8096, 8105), 'collections.Counter', 'Counter', ([], {}), '()\n', (8103, 8105), False, 'from collections import Counter\n'), ((9540, 9552), 'dill.load', 'dill.load', (['f'], {}), '(f)\n', (9549, 9552), False, 'import dill\n'), ((9638, 9666), 'marseille.custom_logging.logging.info', 'logging.info', (['"""Computing..."""'], {}), "('Computing...')\n", (9650, 9666), False, 'from marseille.custom_logging import logging\n'), ((2575, 2600), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (2598, 2600), False, 'import warnings\n'), ((2623, 2654), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (2644, 2654), False, 'import warnings\n'), ((2680, 2730), 'sklearn.metrics.f1_score', 'f1_score', (['y_te_link', 'y_pred_link'], {'average': '"""binary"""'}), "(y_te_link, y_pred_link, average='binary')\n", (2688, 2730), False, 'from sklearn.metrics import f1_score\n'), ((2756, 2809), 'sklearn.metrics.f1_score', 'f1_score', (['y_te_prop_enc', 'y_pred_prop'], {'average': '"""macro"""'}), "(y_te_prop_enc, y_pred_prop, average='macro')\n", (2764, 2809), False, 'from sklearn.metrics import f1_score\n'), ((3333, 3350), 'dill.dump', 'dill.dump', (['out', 'f'], {}), '(out, f)\n', (3342, 3350), False, 'import dill\n'), ((3704, 3718), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (3716, 3718), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((3766, 3780), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (3778, 3780), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((5830, 5854), 'marseille.argdoc.DocLabel', 'DocLabel', (['y_prop', 'y_link'], {}), '(y_prop, y_link)\n', (5838, 5854), False, 'from marseille.argdoc import DocLabel, CdcpArgumentationDoc, UkpEssayArgumentationDoc\n'), ((6947, 6961), 'sklearn.model_selection.KFold', 'KFold', (['n_folds'], {}), '(n_folds)\n', (6952, 6961), False, 'from sklearn.model_selection import KFold\n'), ((7244, 7268), 'marseille.argdoc.DocLabel', 'DocLabel', (['y_prop', 'y_link'], {}), '(y_prop, y_link)\n', (7252, 7268), False, 'from marseille.argdoc import DocLabel, CdcpArgumentationDoc, UkpEssayArgumentationDoc\n'), ((8215, 8308), 'numpy.array', 'np.array', (["[(f['src__prop_id_'], f['trg__prop_id_']) for f in doc.features]"], {'dtype': 'np.intp'}), "([(f['src__prop_id_'], f['trg__prop_id_']) for f in doc.features],\n dtype=np.intp)\n", (8223, 8308), True, 'import numpy as np\n'), ((9752, 9769), 'dill.dump', 'dill.dump', (['out', 'f'], {}), '(out, f)\n', (9761, 9769), False, 'import dill\n'), ((5426, 5452), 'numpy.append', 'np.append', (['(0)', 'link_offsets'], {}), '(0, link_offsets)\n', (5435, 5452), True, 'import numpy as np\n'), ((5689, 5715), 'numpy.append', 'np.append', (['(0)', 'prop_offsets'], {}), '(0, prop_offsets)\n', (5698, 5715), True, 'import numpy as np\n')]
#!/usr/bin/env python #Author: <NAME> (<EMAIL>) #Run: python lagr2hdf5.py "your_lgr_file".lgr ''' Usage: lagr2hdf5.py LAGER ''' import docopt import struct import xml.etree.ElementTree as et import h5py import numpy as np from collections import defaultdict import binascii args = docopt.docopt(__doc__) #from pysmt/defs.py type_map = { 'int8_t': 'b', 'uint8_t': 'B', 'int16_t': 'h', 'uint16_t': 'H', 'int32_t': 'i', 'uint32_t': 'I', 'int64_t': 'q', 'uint64_t': 'Q', 'float32': 'f', 'float64': 'd', } fmt_suffix_map = { 'int8_t': 'd', 'uint8_t': 'd', 'int16_t': 'd', 'uint16_t': 'd', 'int32_t': 'd', 'uint32_t': 'd', 'int64_t': 'd', 'uint64_t': 'd', 'float32': 'g', 'float64': 'g', } #uuid is in Item so that it knows where it comes from when adding to the dict #key is so that it knows which key to add when seperating it in a hdf5 file class Item(object): def __init__(self, name, offset, size, dtype, uuid, key): self.name = name self.offset = int(offset) self.size = int(size) self.dtype = dtype self.uuid = uuid self.key = key def __repr__(self): return '<Item:{} offset:{} size:{} type:{} uuid:{} key:{}>'.format(name, offset, size, dtype, uuid, key) class Format(object): def __init__(self, uuid, version, key): self.uuid = uuid self.version = version self.key = key def __repr__(self): return '<uuid:{} version:{} key:{}>'.format(uuid, version, key) with open(args['LAGER'], 'rb') as f: # uint16 b = bytes(f.read(2)) version = struct.unpack('!H', b)[0] # uint64 b = bytes(f.read(8)) dataoffset = struct.unpack('!Q', b)[0] print('Version: {version}, Offset: {offset}'.format(version=version, offset=dataoffset)) #** keep in case of bad/new data added # while True: # uuid = f.read(16).hex() # groupname = struct.unpack('!Q', bytes(f.read(8)))[0] # print(uuid) # print(groupname) # print(str(struct.unpack('!I', bytes(f.read(4)))[0])) #timestamp # print(str(struct.unpack('!I', bytes(f.read(4)))[0])) #timestamp f.seek(dataoffset) xmlformat = f.read() hf = h5py.File(args['LAGER'].split(".")[0] + "_converted.hdf5", 'w') hdf5 = {} root = et.fromstring(xmlformat) column_size = 0 items = [] keys = [] #add key to a list of keys #add item to list of items with the correct uuid #add those name | key combo as a string to a dictionary of lists for m in root.iter('format'): uuid = m.get('uuid') version = m.get('version') key = m.get('key') form = Format(uuid, version, key) keys.append(form) for n in m: name = n.get('name') offset = n.get('offset') size = n.get('size') dtype = n.get('type') i = Item(name, offset, size, dtype, uuid, key) items.append(i) column_size = column_size + i.size hdf5.setdefault(name + "|" + key, []) #header minwidth = 18 for i in items: if len(i.name) < minwidth: l = minwidth else: len(i.name) #go back to start of data f.seek(10, 0) #iterate through all formats/items while True: if f.tell() + column_size > dataoffset: break uuid = binascii.hexlify(f.read(16)) timestamp = struct.unpack('!Q', bytes(f.read(8)))[0] for i in items: if i.uuid.replace("-","") == uuid: b = bytes(f.read(i.size)) val = struct.unpack('!'+type_map[i.dtype], b)[0] if len(i.name) < minwidth: l = minwidth else: len(i.name) d1 = '{val:<{LEN}{suffix}}'.format(val=val, LEN=l, suffix=fmt_suffix_map[i.dtype]) hdf5[i.name + "|" + i.key].append(d1) #create hdf5 groups for g in keys: hf.create_group(g.key) #create hdf5 datasets and add them to the group for x, y in hdf5.items(): z = list(y) for i in items: if i.name+"|"+i.key == x: array = np.asarray(z, dtype=np.float32) hf.create_dataset("/" + i.key + "/" + x.split("|")[0],data=array) #close .hdf5 input hf.close()
[ "xml.etree.ElementTree.fromstring", "struct.unpack", "numpy.asarray", "docopt.docopt" ]
[((287, 309), 'docopt.docopt', 'docopt.docopt', (['__doc__'], {}), '(__doc__)\n', (300, 309), False, 'import docopt\n'), ((2352, 2376), 'xml.etree.ElementTree.fromstring', 'et.fromstring', (['xmlformat'], {}), '(xmlformat)\n', (2365, 2376), True, 'import xml.etree.ElementTree as et\n'), ((1646, 1668), 'struct.unpack', 'struct.unpack', (['"""!H"""', 'b'], {}), "('!H', b)\n", (1659, 1668), False, 'import struct\n'), ((1727, 1749), 'struct.unpack', 'struct.unpack', (['"""!Q"""', 'b'], {}), "('!Q', b)\n", (1740, 1749), False, 'import struct\n'), ((4267, 4298), 'numpy.asarray', 'np.asarray', (['z'], {'dtype': 'np.float32'}), '(z, dtype=np.float32)\n', (4277, 4298), True, 'import numpy as np\n'), ((3676, 3717), 'struct.unpack', 'struct.unpack', (["('!' + type_map[i.dtype])", 'b'], {}), "('!' + type_map[i.dtype], b)\n", (3689, 3717), False, 'import struct\n')]
import numpy as np import tensorflow as tf # reproducible np.random.seed(2) tf.set_random_seed(2) __all__ = ['PolicyGradient', 'Actor', 'Critic', 'ValueFunction'] """"REINFORCE""" class PolicyGradient: def __init__( self, n_actions, n_features, learning_rate=0.01, reward_decay=0.95, output_graph=False, ): self.n_actions = n_actions self.n_features = n_features self.lr = learning_rate self.gamma = reward_decay self.ep_obs, self.ep_as, self.ep_rs = [], [], [] self._build_net() self.sess = tf.Session() if output_graph: # $ tensorboard --logdir=logs # http://0.0.0.0:6006/ # tf.train.SummaryWriter soon be deprecated, use following tf.summary.FileWriter("logs/", self.sess.graph) self.sess.run(tf.global_variables_initializer()) def _build_net(self): with tf.name_scope('inputs'): self.tf_obs = tf.placeholder(tf.float32, [None, self.n_features], name="observations") self.tf_acts = tf.placeholder(tf.int32, [None, ], name="actions_num") self.tf_vt = tf.placeholder(tf.float32, [None, ], name="actions_value") # fc1 layer = tf.layers.dense( inputs=self.tf_obs, units=10, activation=tf.nn.tanh, # tanh activation kernel_initializer=tf.random_normal_initializer(mean=0, stddev=0.3), bias_initializer=tf.constant_initializer(0.1), name='fc1' ) # fc2 all_act = tf.layers.dense( inputs=layer, units=self.n_actions, activation=None, kernel_initializer=tf.random_normal_initializer(mean=0, stddev=0.3), bias_initializer=tf.constant_initializer(0.1), name='fc2' ) self.all_act_prob = tf.nn.softmax(all_act, name='act_prob') # use softmax to convert to probability with tf.name_scope('loss'): # to maximize total reward (log_p * R) is to minimize -(log_p * R), and the tf only have minimize(loss) self.neg_log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=all_act, labels=self.tf_acts) # this is negative log of chosen action # or in this way: # neg_log_prob = tf.reduce_sum(-tf.log(self.all_act_prob)*tf.one_hot(self.tf_acts, self.n_actions), axis=1) loss = tf.reduce_mean(self.neg_log_prob * self.tf_vt) # reward guided loss with tf.name_scope('train'): self.train_op = tf.train.AdamOptimizer(self.lr).minimize(loss) def choose_action(self, observation): prob_weights = self.sess.run(self.all_act_prob, feed_dict={self.tf_obs: observation[np.newaxis, :]}) action = np.random.choice(range(prob_weights.shape[1]), p=prob_weights.ravel()) # select action w.r.t the actions prob return action def store_transition(self, s, a, r): self.ep_obs.append(s) self.ep_as.append(a) self.ep_rs.append(r) def learn(self): # discount and normalize episode reward discounted_ep_rs_norm = self._discount_and_norm_rewards() # train on episode ng, _ = self.sess.run([self.neg_log_prob, self.train_op], feed_dict={ self.tf_obs: np.vstack(self.ep_obs), # shape=[None, n_obs] self.tf_acts: np.array(self.ep_as), # shape=[None, ] self.tf_vt: discounted_ep_rs_norm, # shape=[None, ] }) self.ep_obs, self.ep_as, self.ep_rs = [], [], [] # empty episode data return discounted_ep_rs_norm def _discount_and_norm_rewards(self): # discount episode rewards discounted_ep_rs = np.zeros_like(self.ep_rs) running_add = 0 for t in reversed(range(0, len(self.ep_rs))): running_add = running_add * self.gamma + self.ep_rs[t] discounted_ep_rs[t] = running_add # normalize episode rewards discounted_ep_rs -= np.mean(discounted_ep_rs) discounted_ep_rs /= np.std(discounted_ep_rs) return discounted_ep_rs class Actor(object): def __init__(self, sess, n_features, n_actions, lr=0.001): self.sess = sess self.s = tf.placeholder(tf.float32, [1, n_features], "state") self.a = tf.placeholder(tf.int32, None, "act") self.td_error = tf.placeholder(tf.float32, None, "td_error") # TD_error self.aa_q = tf.placeholder(tf.float32, None, "aa_q") with tf.variable_scope('Actor'): l1 = tf.layers.dense( inputs=self.s, units=20, # number of hidden units activation=tf.nn.relu, kernel_initializer=tf.random_normal_initializer(0., .1), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='l1' ) self.acts_prob = tf.layers.dense( inputs=l1, units=n_actions, # output units activation=tf.nn.softmax, # get action probabilities kernel_initializer=tf.random_normal_initializer(0., .1), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='acts_prob' ) with tf.variable_scope('exp_v'): log_prob = tf.log(self.acts_prob[0, self.a]) self.exp_v = tf.reduce_mean(log_prob * self.td_error) # advantage (TD_error) guided loss with tf.variable_scope('train'): self.train_op = tf.train.AdamOptimizer(lr).minimize(-self.exp_v) # minimize(-exp_v) = maximize(exp_v) with tf.variable_scope('allactions_train'): self.prob = self.acts_prob[0, :] self.aa_loss = tf.reduce_mean(self.prob * self.aa_q) self.aa_train_op = tf.train.AdamOptimizer(lr).minimize(- self.aa_loss) def learn(self, s, a, td): s = s[np.newaxis, :] feed_dict = {self.s: s, self.a: a, self.td_error: td} _, exp_v = self.sess.run([self.train_op, self.exp_v], feed_dict) return exp_v """all_action""" def aa_learn(self, s, a, td_error): s = s[np.newaxis, :] feed_dict = {self.s: s, self.a: a, self.aa_q: td_error} _, aa_loss, prob = self.sess.run([self.aa_train_op, self.aa_loss, self.prob], feed_dict) return aa_loss, prob def choose_action(self, s): s = s[np.newaxis, :] probs = self.sess.run(self.acts_prob, {self.s: s}) # get probabilities for all actions return np.random.choice(np.arange(probs.shape[1]), p=probs.ravel()), probs.ravel() # return a int class ValueFunction(object): def __init__(self, sess, n_features, n_actions, gamma, lr=0.01): self.sess = sess self.lr = lr self.S = tf.placeholder(tf.float32, [1, n_features], "state") self.Q_next = tf.placeholder(tf.float32, None, "q_next") self.R = tf.placeholder(tf.float32, None, 'r') self.A = tf.placeholder(tf.int32, None, 'action') self.action_one_hot = tf.one_hot(self.A, n_actions, 1.0, 0.0, name='action_one_hot') self.DONE = tf.placeholder(tf.float32, None, 'done') self.gamma = gamma with tf.variable_scope('actionValue'): l1 = tf.layers.dense( inputs=self.S, units=50, # number of hidden units activation=tf.nn.relu, # None # have to be linear to make sure the convergence of actor. # But linear approximator seems hardly learns the correct Q. kernel_initializer=tf.random_normal_initializer(0., .1), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='l1' ) l2 = tf.layers.dense( inputs=l1, units=100, # number of hidden units activation=tf.nn.relu, # None # have to be linear to make sure the convergence of actor. # But linear approximator seems hardly learns the correct Q. kernel_initializer=tf.random_normal_initializer(0., .1), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='l2' ) self.q = tf.layers.dense( inputs=l2, units=n_actions, # output units activation=None, kernel_initializer=tf.random_normal_initializer(0., .1), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='Q' ) with tf.variable_scope('Q_a'): self.Q_a = tf.reduce_sum(self.q * self.action_one_hot, reduction_indices=1) self.aa_td_error = self.q # - tf.reduce_sum(self.q, reduction_indices=1) # self.loss = tf.square(self.R + (1.-self.DONE) * self.Q_next - self.Q_a) with tf.variable_scope("Q-learning"): self.q_learning_loss = tf.reduce_mean(tf.squared_difference(self.R + self.gamma * (1.-self.DONE) *\ tf.reduce_max(self.Q_next, axis=1, name="Q_max"), self.Q_a)) with tf.variable_scope('train'): self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.q_learning_loss) def learn(self, s, r, s_next, done, a_vector): s, s_ = s[np.newaxis, :], s_next[np.newaxis, :] """Q-learning""" Q_next = self.sess.run(self.q, {self.S: s_}) aa_q, _ = self.sess.run([self.aa_td_error, self.train_op], {self.S: s, self.Q_next: Q_next, self.R: r, self.DONE: done, self.A: a_vector}) return aa_q[0] class Critic(object): def __init__(self, sess, n_features, lr=0.01): self.sess = sess self.s = tf.placeholder(tf.float32, [1, n_features], "state") self.v_ = tf.placeholder(tf.float32, [1, 1], "v_next") self.r = tf.placeholder(tf.float32, None, 'r') self.gamma = tf.placeholder(tf.float32, None, 'gamma') with tf.variable_scope('Critic'): l1 = tf.layers.dense( inputs=self.s, units=20, # number of hidden units activation=tf.nn.relu, # None # have to be linear to make sure the convergence of actor. # But linear approximator seems hardly learns the correct Q. kernel_initializer=tf.random_normal_initializer(0., .1), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='l1' ) self.v = tf.layers.dense( inputs=l1, units=1, # output units activation=None, kernel_initializer=tf.random_normal_initializer(0., .1), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='V' ) with tf.variable_scope('squared_TD_error'): self.td_error = self.r + self.gamma * self.v_ - self.v self.loss = tf.square(self.td_error) # TD_error = (r+gamma*V_next) - V_eval with tf.variable_scope('train'): self.train_op = tf.train.AdamOptimizer(lr).minimize(self.loss) def learn(self, s, r, s_, gamma): s, s_ = s[np.newaxis, :], s_[np.newaxis, :] v_ = self.sess.run(self.v, {self.s: s_}) td_error, _ = self.sess.run([self.td_error, self.train_op], {self.s: s, self.v_: v_, self.r: r, self.gamma: gamma}) return td_error
[ "tensorflow.reduce_sum", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "numpy.array", "tensorflow.nn.softmax", "tensorflow.reduce_mean", "tensorflow.set_random_seed", "tensorflow.log", "numpy.arange", "numpy.mean", "tensorflow.Session", "tensorflow.placeholder", "tensorflow.random_...
[((59, 76), 'numpy.random.seed', 'np.random.seed', (['(2)'], {}), '(2)\n', (73, 76), True, 'import numpy as np\n'), ((77, 98), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(2)'], {}), '(2)\n', (95, 98), True, 'import tensorflow as tf\n'), ((635, 647), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (645, 647), True, 'import tensorflow as tf\n'), ((1938, 1977), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['all_act'], {'name': '"""act_prob"""'}), "(all_act, name='act_prob')\n", (1951, 1977), True, 'import tensorflow as tf\n'), ((3796, 3821), 'numpy.zeros_like', 'np.zeros_like', (['self.ep_rs'], {}), '(self.ep_rs)\n', (3809, 3821), True, 'import numpy as np\n'), ((4078, 4103), 'numpy.mean', 'np.mean', (['discounted_ep_rs'], {}), '(discounted_ep_rs)\n', (4085, 4103), True, 'import numpy as np\n'), ((4132, 4156), 'numpy.std', 'np.std', (['discounted_ep_rs'], {}), '(discounted_ep_rs)\n', (4138, 4156), True, 'import numpy as np\n'), ((4318, 4370), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[1, n_features]', '"""state"""'], {}), "(tf.float32, [1, n_features], 'state')\n", (4332, 4370), True, 'import tensorflow as tf\n'), ((4388, 4425), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', 'None', '"""act"""'], {}), "(tf.int32, None, 'act')\n", (4402, 4425), True, 'import tensorflow as tf\n'), ((4450, 4494), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'None', '"""td_error"""'], {}), "(tf.float32, None, 'td_error')\n", (4464, 4494), True, 'import tensorflow as tf\n'), ((4527, 4567), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'None', '"""aa_q"""'], {}), "(tf.float32, None, 'aa_q')\n", (4541, 4567), True, 'import tensorflow as tf\n'), ((6901, 6953), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[1, n_features]', '"""state"""'], {}), "(tf.float32, [1, n_features], 'state')\n", (6915, 6953), True, 'import tensorflow as tf\n'), ((6976, 7018), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'None', '"""q_next"""'], {}), "(tf.float32, None, 'q_next')\n", (6990, 7018), True, 'import tensorflow as tf\n'), ((7036, 7073), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'None', '"""r"""'], {}), "(tf.float32, None, 'r')\n", (7050, 7073), True, 'import tensorflow as tf\n'), ((7091, 7131), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', 'None', '"""action"""'], {}), "(tf.int32, None, 'action')\n", (7105, 7131), True, 'import tensorflow as tf\n'), ((7162, 7224), 'tensorflow.one_hot', 'tf.one_hot', (['self.A', 'n_actions', '(1.0)', '(0.0)'], {'name': '"""action_one_hot"""'}), "(self.A, n_actions, 1.0, 0.0, name='action_one_hot')\n", (7172, 7224), True, 'import tensorflow as tf\n'), ((7245, 7285), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'None', '"""done"""'], {}), "(tf.float32, None, 'done')\n", (7259, 7285), True, 'import tensorflow as tf\n'), ((9951, 10003), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[1, n_features]', '"""state"""'], {}), "(tf.float32, [1, n_features], 'state')\n", (9965, 10003), True, 'import tensorflow as tf\n'), ((10022, 10066), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[1, 1]', '"""v_next"""'], {}), "(tf.float32, [1, 1], 'v_next')\n", (10036, 10066), True, 'import tensorflow as tf\n'), ((10084, 10121), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'None', '"""r"""'], {}), "(tf.float32, None, 'r')\n", (10098, 10121), True, 'import tensorflow as tf\n'), ((10143, 10184), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'None', '"""gamma"""'], {}), "(tf.float32, None, 'gamma')\n", (10157, 10184), True, 'import tensorflow as tf\n'), ((834, 881), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""logs/"""', 'self.sess.graph'], {}), "('logs/', self.sess.graph)\n", (855, 881), True, 'import tensorflow as tf\n'), ((905, 938), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (936, 938), True, 'import tensorflow as tf\n'), ((980, 1003), 'tensorflow.name_scope', 'tf.name_scope', (['"""inputs"""'], {}), "('inputs')\n", (993, 1003), True, 'import tensorflow as tf\n'), ((1031, 1103), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, self.n_features]'], {'name': '"""observations"""'}), "(tf.float32, [None, self.n_features], name='observations')\n", (1045, 1103), True, 'import tensorflow as tf\n'), ((1131, 1183), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""actions_num"""'}), "(tf.int32, [None], name='actions_num')\n", (1145, 1183), True, 'import tensorflow as tf\n'), ((1211, 1267), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""actions_value"""'}), "(tf.float32, [None], name='actions_value')\n", (1225, 1267), True, 'import tensorflow as tf\n'), ((2033, 2054), 'tensorflow.name_scope', 'tf.name_scope', (['"""loss"""'], {}), "('loss')\n", (2046, 2054), True, 'import tensorflow as tf\n'), ((2204, 2292), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'all_act', 'labels': 'self.tf_acts'}), '(logits=all_act, labels=self.\n tf_acts)\n', (2250, 2292), True, 'import tensorflow as tf\n'), ((2499, 2545), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(self.neg_log_prob * self.tf_vt)'], {}), '(self.neg_log_prob * self.tf_vt)\n', (2513, 2545), True, 'import tensorflow as tf\n'), ((2582, 2604), 'tensorflow.name_scope', 'tf.name_scope', (['"""train"""'], {}), "('train')\n", (2595, 2604), True, 'import tensorflow as tf\n'), ((4582, 4608), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Actor"""'], {}), "('Actor')\n", (4599, 4608), True, 'import tensorflow as tf\n'), ((5381, 5407), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""exp_v"""'], {}), "('exp_v')\n", (5398, 5407), True, 'import tensorflow as tf\n'), ((5432, 5465), 'tensorflow.log', 'tf.log', (['self.acts_prob[0, self.a]'], {}), '(self.acts_prob[0, self.a])\n', (5438, 5465), True, 'import tensorflow as tf\n'), ((5491, 5531), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(log_prob * self.td_error)'], {}), '(log_prob * self.td_error)\n', (5505, 5531), True, 'import tensorflow as tf\n'), ((5582, 5608), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""train"""'], {}), "('train')\n", (5599, 5608), True, 'import tensorflow as tf\n'), ((5739, 5776), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""allactions_train"""'], {}), "('allactions_train')\n", (5756, 5776), True, 'import tensorflow as tf\n'), ((5850, 5887), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(self.prob * self.aa_q)'], {}), '(self.prob * self.aa_q)\n', (5864, 5887), True, 'import tensorflow as tf\n'), ((7327, 7359), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""actionValue"""'], {}), "('actionValue')\n", (7344, 7359), True, 'import tensorflow as tf\n'), ((8743, 8767), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Q_a"""'], {}), "('Q_a')\n", (8760, 8767), True, 'import tensorflow as tf\n'), ((8792, 8856), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(self.q * self.action_one_hot)'], {'reduction_indices': '(1)'}), '(self.q * self.action_one_hot, reduction_indices=1)\n', (8805, 8856), True, 'import tensorflow as tf\n'), ((9043, 9074), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Q-learning"""'], {}), "('Q-learning')\n", (9060, 9074), True, 'import tensorflow as tf\n'), ((9320, 9346), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""train"""'], {}), "('train')\n", (9337, 9346), True, 'import tensorflow as tf\n'), ((10199, 10226), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Critic"""'], {}), "('Critic')\n", (10216, 10226), True, 'import tensorflow as tf\n'), ((11091, 11128), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""squared_TD_error"""'], {}), "('squared_TD_error')\n", (11108, 11128), True, 'import tensorflow as tf\n'), ((11221, 11245), 'tensorflow.square', 'tf.square', (['self.td_error'], {}), '(self.td_error)\n', (11230, 11245), True, 'import tensorflow as tf\n'), ((11301, 11327), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""train"""'], {}), "('train')\n", (11318, 11327), True, 'import tensorflow as tf\n'), ((1456, 1504), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'mean': '(0)', 'stddev': '(0.3)'}), '(mean=0, stddev=0.3)\n', (1484, 1504), True, 'import tensorflow as tf\n'), ((1535, 1563), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (1558, 1563), True, 'import tensorflow as tf\n'), ((1767, 1815), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'mean': '(0)', 'stddev': '(0.3)'}), '(mean=0, stddev=0.3)\n', (1795, 1815), True, 'import tensorflow as tf\n'), ((1846, 1874), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (1869, 1874), True, 'import tensorflow as tf\n'), ((6660, 6685), 'numpy.arange', 'np.arange', (['probs.shape[1]'], {}), '(probs.shape[1])\n', (6669, 6685), True, 'import numpy as np\n'), ((2634, 2665), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.lr'], {}), '(self.lr)\n', (2656, 2665), True, 'import tensorflow as tf\n'), ((3381, 3403), 'numpy.vstack', 'np.vstack', (['self.ep_obs'], {}), '(self.ep_obs)\n', (3390, 3403), True, 'import numpy as np\n'), ((3455, 3475), 'numpy.array', 'np.array', (['self.ep_as'], {}), '(self.ep_as)\n', (3463, 3475), True, 'import numpy as np\n'), ((4803, 4841), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (4831, 4841), True, 'import tensorflow as tf\n'), ((4887, 4915), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (4910, 4915), True, 'import tensorflow as tf\n'), ((5198, 5236), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (5226, 5236), True, 'import tensorflow as tf\n'), ((5280, 5308), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (5303, 5308), True, 'import tensorflow as tf\n'), ((5638, 5664), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['lr'], {}), '(lr)\n', (5660, 5664), True, 'import tensorflow as tf\n'), ((5919, 5945), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['lr'], {}), '(lr)\n', (5941, 5945), True, 'import tensorflow as tf\n'), ((7712, 7750), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (7740, 7750), True, 'import tensorflow as tf\n'), ((7794, 7822), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (7817, 7822), True, 'import tensorflow as tf\n'), ((8223, 8261), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (8251, 8261), True, 'import tensorflow as tf\n'), ((8305, 8333), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (8328, 8333), True, 'import tensorflow as tf\n'), ((8568, 8606), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (8596, 8606), True, 'import tensorflow as tf\n'), ((8650, 8678), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (8673, 8678), True, 'import tensorflow as tf\n'), ((9376, 9407), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.lr'], {}), '(self.lr)\n', (9398, 9407), True, 'import tensorflow as tf\n'), ((10579, 10617), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (10607, 10617), True, 'import tensorflow as tf\n'), ((10661, 10689), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (10684, 10689), True, 'import tensorflow as tf\n'), ((10916, 10954), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), '(0.0, 0.1)\n', (10944, 10954), True, 'import tensorflow as tf\n'), ((10998, 11026), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (11021, 11026), True, 'import tensorflow as tf\n'), ((11357, 11383), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['lr'], {}), '(lr)\n', (11379, 11383), True, 'import tensorflow as tf\n'), ((9245, 9293), 'tensorflow.reduce_max', 'tf.reduce_max', (['self.Q_next'], {'axis': '(1)', 'name': '"""Q_max"""'}), "(self.Q_next, axis=1, name='Q_max')\n", (9258, 9293), True, 'import tensorflow as tf\n')]
import pytest import numpy as np from PythonLinearNonlinearControl.models.two_wheeled import TwoWheeledModel from PythonLinearNonlinearControl.configs.two_wheeled \ import TwoWheeledConfigModule class TestTwoWheeledModel(): """ """ def test_step(self): config = TwoWheeledConfigModule() two_wheeled_model = TwoWheeledModel(config) curr_x = np.ones(config.STATE_SIZE) curr_x[-1] = np.pi / 6. u = np.ones((1, config.INPUT_SIZE)) next_x = two_wheeled_model.predict_traj(curr_x, u) pos_x = np.cos(curr_x[-1]) * u[0, 0] * config.DT + curr_x[0] pos_y = np.sin(curr_x[-1]) * u[0, 0] * config.DT + curr_x[1] expected = np.array([[1., 1., np.pi / 6.], [pos_x, pos_y, curr_x[-1] + u[0, 1] * config.DT]]) assert next_x == pytest.approx(expected) def test_predict_traj(self): config = TwoWheeledConfigModule() two_wheeled_model = TwoWheeledModel(config) curr_x = np.ones(config.STATE_SIZE) curr_x[-1] = np.pi / 6. u = np.ones((1, config.INPUT_SIZE)) pred_xs = two_wheeled_model.predict_traj(curr_x, u) u = np.tile(u, (1, 1, 1)) pred_xs_alltogether = two_wheeled_model.predict_traj(curr_x, u)[0] assert pred_xs_alltogether == pytest.approx(pred_xs) def test_gradient_state(self): config = TwoWheeledConfigModule() two_wheeled_model = TwoWheeledModel(config) xs = np.ones((1, config.STATE_SIZE)) xs[0, -1] = np.pi / 6. us = np.ones((1, config.INPUT_SIZE)) grad = two_wheeled_model.calc_f_x(xs, us, config.DT) # expected cost expected_grad = np.zeros((1, config.STATE_SIZE, config.STATE_SIZE)) eps = 1e-4 for i in range(config.STATE_SIZE): tmp_x = xs.copy() tmp_x[0, i] = xs[0, i] + eps forward = \ two_wheeled_model.predict_next_state(tmp_x[0], us[0]) tmp_x = xs.copy() tmp_x[0, i] = xs[0, i] - eps backward = \ two_wheeled_model.predict_next_state(tmp_x[0], us[0]) expected_grad[0, :, i] = (forward - backward) / (2. * eps) assert grad == pytest.approx(expected_grad) def test_gradient_input(self): config = TwoWheeledConfigModule() two_wheeled_model = TwoWheeledModel(config) xs = np.ones((1, config.STATE_SIZE)) xs[0, -1] = np.pi / 6. us = np.ones((1, config.INPUT_SIZE)) grad = two_wheeled_model.calc_f_u(xs, us, config.DT) # expected cost expected_grad = np.zeros((1, config.STATE_SIZE, config.INPUT_SIZE)) eps = 1e-4 for i in range(config.INPUT_SIZE): tmp_u = us.copy() tmp_u[0, i] = us[0, i] + eps forward = \ two_wheeled_model.predict_next_state(xs[0], tmp_u[0]) tmp_u = us.copy() tmp_u[0, i] = us[0, i] - eps backward = \ two_wheeled_model.predict_next_state(xs[0], tmp_u[0]) expected_grad[0, :, i] = (forward - backward) / (2. * eps) assert grad == pytest.approx(expected_grad)
[ "pytest.approx", "numpy.tile", "numpy.ones", "PythonLinearNonlinearControl.models.two_wheeled.TwoWheeledModel", "PythonLinearNonlinearControl.configs.two_wheeled.TwoWheeledConfigModule", "numpy.array", "numpy.zeros", "numpy.cos", "numpy.sin" ]
[((292, 316), 'PythonLinearNonlinearControl.configs.two_wheeled.TwoWheeledConfigModule', 'TwoWheeledConfigModule', ([], {}), '()\n', (314, 316), False, 'from PythonLinearNonlinearControl.configs.two_wheeled import TwoWheeledConfigModule\n'), ((345, 368), 'PythonLinearNonlinearControl.models.two_wheeled.TwoWheeledModel', 'TwoWheeledModel', (['config'], {}), '(config)\n', (360, 368), False, 'from PythonLinearNonlinearControl.models.two_wheeled import TwoWheeledModel\n'), ((387, 413), 'numpy.ones', 'np.ones', (['config.STATE_SIZE'], {}), '(config.STATE_SIZE)\n', (394, 413), True, 'import numpy as np\n'), ((458, 489), 'numpy.ones', 'np.ones', (['(1, config.INPUT_SIZE)'], {}), '((1, config.INPUT_SIZE))\n', (465, 489), True, 'import numpy as np\n'), ((709, 798), 'numpy.array', 'np.array', (['[[1.0, 1.0, np.pi / 6.0], [pos_x, pos_y, curr_x[-1] + u[0, 1] * config.DT]]'], {}), '([[1.0, 1.0, np.pi / 6.0], [pos_x, pos_y, curr_x[-1] + u[0, 1] *\n config.DT]])\n', (717, 798), True, 'import numpy as np\n'), ((927, 951), 'PythonLinearNonlinearControl.configs.two_wheeled.TwoWheeledConfigModule', 'TwoWheeledConfigModule', ([], {}), '()\n', (949, 951), False, 'from PythonLinearNonlinearControl.configs.two_wheeled import TwoWheeledConfigModule\n'), ((980, 1003), 'PythonLinearNonlinearControl.models.two_wheeled.TwoWheeledModel', 'TwoWheeledModel', (['config'], {}), '(config)\n', (995, 1003), False, 'from PythonLinearNonlinearControl.models.two_wheeled import TwoWheeledModel\n'), ((1022, 1048), 'numpy.ones', 'np.ones', (['config.STATE_SIZE'], {}), '(config.STATE_SIZE)\n', (1029, 1048), True, 'import numpy as np\n'), ((1093, 1124), 'numpy.ones', 'np.ones', (['(1, config.INPUT_SIZE)'], {}), '((1, config.INPUT_SIZE))\n', (1100, 1124), True, 'import numpy as np\n'), ((1199, 1220), 'numpy.tile', 'np.tile', (['u', '(1, 1, 1)'], {}), '(u, (1, 1, 1))\n', (1206, 1220), True, 'import numpy as np\n'), ((1424, 1448), 'PythonLinearNonlinearControl.configs.two_wheeled.TwoWheeledConfigModule', 'TwoWheeledConfigModule', ([], {}), '()\n', (1446, 1448), False, 'from PythonLinearNonlinearControl.configs.two_wheeled import TwoWheeledConfigModule\n'), ((1477, 1500), 'PythonLinearNonlinearControl.models.two_wheeled.TwoWheeledModel', 'TwoWheeledModel', (['config'], {}), '(config)\n', (1492, 1500), False, 'from PythonLinearNonlinearControl.models.two_wheeled import TwoWheeledModel\n'), ((1515, 1546), 'numpy.ones', 'np.ones', (['(1, config.STATE_SIZE)'], {}), '((1, config.STATE_SIZE))\n', (1522, 1546), True, 'import numpy as np\n'), ((1591, 1622), 'numpy.ones', 'np.ones', (['(1, config.INPUT_SIZE)'], {}), '((1, config.INPUT_SIZE))\n', (1598, 1622), True, 'import numpy as np\n'), ((1734, 1785), 'numpy.zeros', 'np.zeros', (['(1, config.STATE_SIZE, config.STATE_SIZE)'], {}), '((1, config.STATE_SIZE, config.STATE_SIZE))\n', (1742, 1785), True, 'import numpy as np\n'), ((2379, 2403), 'PythonLinearNonlinearControl.configs.two_wheeled.TwoWheeledConfigModule', 'TwoWheeledConfigModule', ([], {}), '()\n', (2401, 2403), False, 'from PythonLinearNonlinearControl.configs.two_wheeled import TwoWheeledConfigModule\n'), ((2432, 2455), 'PythonLinearNonlinearControl.models.two_wheeled.TwoWheeledModel', 'TwoWheeledModel', (['config'], {}), '(config)\n', (2447, 2455), False, 'from PythonLinearNonlinearControl.models.two_wheeled import TwoWheeledModel\n'), ((2470, 2501), 'numpy.ones', 'np.ones', (['(1, config.STATE_SIZE)'], {}), '((1, config.STATE_SIZE))\n', (2477, 2501), True, 'import numpy as np\n'), ((2546, 2577), 'numpy.ones', 'np.ones', (['(1, config.INPUT_SIZE)'], {}), '((1, config.INPUT_SIZE))\n', (2553, 2577), True, 'import numpy as np\n'), ((2689, 2740), 'numpy.zeros', 'np.zeros', (['(1, config.STATE_SIZE, config.INPUT_SIZE)'], {}), '((1, config.STATE_SIZE, config.INPUT_SIZE))\n', (2697, 2740), True, 'import numpy as np\n'), ((847, 870), 'pytest.approx', 'pytest.approx', (['expected'], {}), '(expected)\n', (860, 870), False, 'import pytest\n'), ((1335, 1357), 'pytest.approx', 'pytest.approx', (['pred_xs'], {}), '(pred_xs)\n', (1348, 1357), False, 'import pytest\n'), ((2284, 2312), 'pytest.approx', 'pytest.approx', (['expected_grad'], {}), '(expected_grad)\n', (2297, 2312), False, 'import pytest\n'), ((3239, 3267), 'pytest.approx', 'pytest.approx', (['expected_grad'], {}), '(expected_grad)\n', (3252, 3267), False, 'import pytest\n'), ((567, 585), 'numpy.cos', 'np.cos', (['curr_x[-1]'], {}), '(curr_x[-1])\n', (573, 585), True, 'import numpy as np\n'), ((636, 654), 'numpy.sin', 'np.sin', (['curr_x[-1]'], {}), '(curr_x[-1])\n', (642, 654), True, 'import numpy as np\n')]
import argparse import torch import numpy as np from PIL import Image from torchreid.data.transforms import build_transforms import torchreid from torchreid.utils import load_pretrained_weights from default_config import get_default_config def main(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--config-file', type=str, default='', help='path to config file') parser.add_argument('--output_name', type=str, default='model') parser.add_argument('opts', default=None, nargs=argparse.REMAINDER, help='Modify config options using the command-line') args = parser.parse_args() cfg = get_default_config() cfg.use_gpu = torch.cuda.is_available() if args.config_file: cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) model = torchreid.models.build_model( name=cfg.model.name, num_classes=2, loss=cfg.loss.name, pretrained=cfg.model.pretrained, use_gpu=cfg.use_gpu, dropout_prob=cfg.model.dropout_prob, feature_dim=cfg.model.feature_dim, activation=cfg.model.activation, in_first=cfg.model.in_first ) load_pretrained_weights(model, cfg.model.load_weights) model.eval() _, transform = build_transforms(cfg.data.height, cfg.data.width) input_size = (cfg.data.height, cfg.data.width, 3) img = np.random.rand(*input_size).astype(np.float32) img = np.uint8(img*255) im = Image.fromarray(img) blob = transform(im).unsqueeze(0) torch.onnx.export(model, blob, args.output_name + '.onnx', verbose=True, export_params=True) if __name__ == '__main__': main()
[ "numpy.uint8", "PIL.Image.fromarray", "torchreid.data.transforms.build_transforms", "numpy.random.rand", "argparse.ArgumentParser", "torchreid.utils.load_pretrained_weights", "default_config.get_default_config", "torchreid.models.build_model", "torch.cuda.is_available", "torch.onnx.export" ]
[((271, 350), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (294, 350), False, 'import argparse\n'), ((677, 697), 'default_config.get_default_config', 'get_default_config', ([], {}), '()\n', (695, 697), False, 'from default_config import get_default_config\n'), ((716, 741), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (739, 741), False, 'import torch\n'), ((861, 1146), 'torchreid.models.build_model', 'torchreid.models.build_model', ([], {'name': 'cfg.model.name', 'num_classes': '(2)', 'loss': 'cfg.loss.name', 'pretrained': 'cfg.model.pretrained', 'use_gpu': 'cfg.use_gpu', 'dropout_prob': 'cfg.model.dropout_prob', 'feature_dim': 'cfg.model.feature_dim', 'activation': 'cfg.model.activation', 'in_first': 'cfg.model.in_first'}), '(name=cfg.model.name, num_classes=2, loss=cfg.\n loss.name, pretrained=cfg.model.pretrained, use_gpu=cfg.use_gpu,\n dropout_prob=cfg.model.dropout_prob, feature_dim=cfg.model.feature_dim,\n activation=cfg.model.activation, in_first=cfg.model.in_first)\n', (889, 1146), False, 'import torchreid\n'), ((1220, 1274), 'torchreid.utils.load_pretrained_weights', 'load_pretrained_weights', (['model', 'cfg.model.load_weights'], {}), '(model, cfg.model.load_weights)\n', (1243, 1274), False, 'from torchreid.utils import load_pretrained_weights\n'), ((1312, 1361), 'torchreid.data.transforms.build_transforms', 'build_transforms', (['cfg.data.height', 'cfg.data.width'], {}), '(cfg.data.height, cfg.data.width)\n', (1328, 1361), False, 'from torchreid.data.transforms import build_transforms\n'), ((1484, 1503), 'numpy.uint8', 'np.uint8', (['(img * 255)'], {}), '(img * 255)\n', (1492, 1503), True, 'import numpy as np\n'), ((1511, 1531), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (1526, 1531), False, 'from PIL import Image\n'), ((1575, 1671), 'torch.onnx.export', 'torch.onnx.export', (['model', 'blob', "(args.output_name + '.onnx')"], {'verbose': '(True)', 'export_params': '(True)'}), "(model, blob, args.output_name + '.onnx', verbose=True,\n export_params=True)\n", (1592, 1671), False, 'import torch\n'), ((1427, 1454), 'numpy.random.rand', 'np.random.rand', (['*input_size'], {}), '(*input_size)\n', (1441, 1454), True, 'import numpy as np\n')]
#!/usr/bin/env python """ Copyright 2019 <NAME> (Johns Hopkins University) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ import os import argparse import time import logging import numpy as np # import av # import cv2 import h5py from retinaface import RetinaFace from face_model import FaceModel from scp_list import SCPList from face_utils import ( Namespace, read_img, save_facedet_image, save_facecrop_images, save_bbox, detect_faces_in_frame, extract_embed_in_frame_v4, ) def extract_face_embed( input_path, output_path, facedet_model_file, faceembed_model_file, min_faces, use_gpu, save_facedet_img, save_facecrop_img, part_idx, num_parts, ): scp = SCPList.load(input_path) if num_parts > 0: scp = scp.split(part_idx, num_parts) output_dir = os.path.dirname(output_path) gpu_id = 0 if use_gpu else -1 detector = RetinaFace(facedet_model_file, 0, gpu_id, "net3") f_bb = open(output_path + ".bbox", "w") f_scp = open(output_path + ".scp", "w") h5_file = output_path + ".h5" f_h5 = h5py.File(h5_file, "w") faceembed_model_file = "%s,0" % (faceembed_model_file) args_face_model = Namespace( threshold=1.24, model=faceembed_model_file, ga_model="", image_size="112,112", gpu=gpu_id, det=1, flip=0, ) embed_extractor = FaceModel(args_face_model) dummy_face = np.random.rand(3, 112, 112).astype(dtype=np.uint) x_i = embed_extractor.get_feature(dummy_face) x_dim = x_i.shape[0] logging.info("embed dim=%d", x_dim) facedet_dir = None facecrop_dir = None for key, file_path, _, _ in scp: if save_facedet_img: facedet_dir = "%s/img_facedet/%s" % (output_dir, key) if not os.path.exists(facedet_dir): os.makedirs(facedet_dir) if save_facecrop_img: facecrop_dir = "%s/img_facecrop/%s" % (output_dir, key) if not os.path.exists(facecrop_dir): os.makedirs(facecrop_dir) logging.info("loading video %s from path %s", key, file_path) t1 = time.time() frame = read_img(file_path) dt = time.time() - t1 logging.info("loading time %.2f", dt) threshold = 0.9 use_retina_landmarks = False while threshold > 0.01: retina_detect_faces = False logging.info( "processing file %s frame of shape=%s", key, str(frame.shape), ) faces, landmarks = detect_faces_in_frame(detector, frame, thresh=threshold) logging.info("file %s dectected %d faces", key, faces.shape[0]) if save_facedet_img: save_facedet_image(key, 0, frame, faces, landmarks, facedet_dir) if faces.shape[0] == 0: threshold -= 0.1 logging.info( "did not detect faces in file %s, reducing facedet threshold=%.1f", key, threshold, ) continue retina_detect_faces = True x, valid = extract_embed_in_frame_v4( embed_extractor, frame, faces, landmarks, thresh=threshold, use_retina=use_retina_landmarks, x_dim=x_dim, ) x = x[valid] faces = faces[valid] logging.info( "file %s extracted %d face embeds", key, faces.shape[0], ) if save_facecrop_img: save_facecrop_images(key, 0, frame, faces, facecrop_dir) save_bbox(key, 0, faces, f_bb) if min_faces == 0 or x.shape[0] >= min_faces: break if retina_detect_faces and not use_retina_landmarks: use_retina_landmarks = True logging.info( ( "retina face detected faces in file %s but mtcnn did not, " "using retina landmarks then" ), key, ) logging.info("file %s saving %d face embeds", key, x.shape[0]) f_scp.write("%s %s\n" % (key, h5_file)) f_h5.create_dataset(key, data=x.astype("float32")) f_bb.close() f_scp.close() f_h5.close() if __name__ == "__main__": parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Face detection with Insightface Retina model", ) parser.add_argument("--input-path", required=True) parser.add_argument("--output-path", required=True) parser.add_argument("--facedet-model-file", required=True) parser.add_argument("--faceembed-model-file", required=True) parser.add_argument("--use-gpu", default=False, action="store_true") parser.add_argument("--save-facedet-img", default=False, action="store_true") parser.add_argument("--save-facecrop-img", default=False, action="store_true") parser.add_argument("--min-faces", type=int, default=1) parser.add_argument("--part-idx", type=int, default=1) parser.add_argument("--num-parts", type=int, default=1) # parser.add_argument('-v', '--verbose', default=1, choices=[0, 1, 2, 3], type=int, # help='Verbose level') args = parser.parse_args() # config_logger(args.verbose) # del args.verbose # logging.debug(args) logging.basicConfig( level=2, format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s" ) extract_face_embed(**vars(args))
[ "numpy.random.rand", "scp_list.SCPList.load", "face_utils.extract_embed_in_frame_v4", "logging.info", "face_utils.Namespace", "os.path.exists", "argparse.ArgumentParser", "face_utils.save_facecrop_images", "retinaface.RetinaFace", "h5py.File", "face_utils.save_bbox", "os.path.dirname", "time...
[((753, 777), 'scp_list.SCPList.load', 'SCPList.load', (['input_path'], {}), '(input_path)\n', (765, 777), False, 'from scp_list import SCPList\n'), ((863, 891), 'os.path.dirname', 'os.path.dirname', (['output_path'], {}), '(output_path)\n', (878, 891), False, 'import os\n'), ((942, 991), 'retinaface.RetinaFace', 'RetinaFace', (['facedet_model_file', '(0)', 'gpu_id', '"""net3"""'], {}), "(facedet_model_file, 0, gpu_id, 'net3')\n", (952, 991), False, 'from retinaface import RetinaFace\n'), ((1125, 1148), 'h5py.File', 'h5py.File', (['h5_file', '"""w"""'], {}), "(h5_file, 'w')\n", (1134, 1148), False, 'import h5py\n'), ((1231, 1350), 'face_utils.Namespace', 'Namespace', ([], {'threshold': '(1.24)', 'model': 'faceembed_model_file', 'ga_model': '""""""', 'image_size': '"""112,112"""', 'gpu': 'gpu_id', 'det': '(1)', 'flip': '(0)'}), "(threshold=1.24, model=faceembed_model_file, ga_model='',\n image_size='112,112', gpu=gpu_id, det=1, flip=0)\n", (1240, 1350), False, 'from face_utils import Namespace, read_img, save_facedet_image, save_facecrop_images, save_bbox, detect_faces_in_frame, extract_embed_in_frame_v4\n'), ((1432, 1458), 'face_model.FaceModel', 'FaceModel', (['args_face_model'], {}), '(args_face_model)\n', (1441, 1458), False, 'from face_model import FaceModel\n'), ((1606, 1641), 'logging.info', 'logging.info', (['"""embed dim=%d"""', 'x_dim'], {}), "('embed dim=%d', x_dim)\n", (1618, 1641), False, 'import logging\n'), ((4559, 4708), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter', 'description': '"""Face detection with Insightface Retina model"""'}), "(formatter_class=argparse.\n ArgumentDefaultsHelpFormatter, description=\n 'Face detection with Insightface Retina model')\n", (4582, 4708), False, 'import argparse\n'), ((5633, 5739), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': '(2)', 'format': '"""%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s"""'}), "(level=2, format=\n '%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s')\n", (5652, 5739), False, 'import logging\n'), ((2110, 2171), 'logging.info', 'logging.info', (['"""loading video %s from path %s"""', 'key', 'file_path'], {}), "('loading video %s from path %s', key, file_path)\n", (2122, 2171), False, 'import logging\n'), ((2185, 2196), 'time.time', 'time.time', ([], {}), '()\n', (2194, 2196), False, 'import time\n'), ((2213, 2232), 'face_utils.read_img', 'read_img', (['file_path'], {}), '(file_path)\n', (2221, 2232), False, 'from face_utils import Namespace, read_img, save_facedet_image, save_facecrop_images, save_bbox, detect_faces_in_frame, extract_embed_in_frame_v4\n'), ((2271, 2308), 'logging.info', 'logging.info', (['"""loading time %.2f"""', 'dt'], {}), "('loading time %.2f', dt)\n", (2283, 2308), False, 'import logging\n'), ((4293, 4355), 'logging.info', 'logging.info', (['"""file %s saving %d face embeds"""', 'key', 'x.shape[0]'], {}), "('file %s saving %d face embeds', key, x.shape[0])\n", (4305, 4355), False, 'import logging\n'), ((1477, 1504), 'numpy.random.rand', 'np.random.rand', (['(3)', '(112)', '(112)'], {}), '(3, 112, 112)\n', (1491, 1504), True, 'import numpy as np\n'), ((2246, 2257), 'time.time', 'time.time', ([], {}), '()\n', (2255, 2257), False, 'import time\n'), ((2624, 2680), 'face_utils.detect_faces_in_frame', 'detect_faces_in_frame', (['detector', 'frame'], {'thresh': 'threshold'}), '(detector, frame, thresh=threshold)\n', (2645, 2680), False, 'from face_utils import Namespace, read_img, save_facedet_image, save_facecrop_images, save_bbox, detect_faces_in_frame, extract_embed_in_frame_v4\n'), ((2693, 2756), 'logging.info', 'logging.info', (['"""file %s dectected %d faces"""', 'key', 'faces.shape[0]'], {}), "('file %s dectected %d faces', key, faces.shape[0])\n", (2705, 2756), False, 'import logging\n'), ((3223, 3359), 'face_utils.extract_embed_in_frame_v4', 'extract_embed_in_frame_v4', (['embed_extractor', 'frame', 'faces', 'landmarks'], {'thresh': 'threshold', 'use_retina': 'use_retina_landmarks', 'x_dim': 'x_dim'}), '(embed_extractor, frame, faces, landmarks, thresh=\n threshold, use_retina=use_retina_landmarks, x_dim=x_dim)\n', (3248, 3359), False, 'from face_utils import Namespace, read_img, save_facedet_image, save_facecrop_images, save_bbox, detect_faces_in_frame, extract_embed_in_frame_v4\n'), ((3552, 3621), 'logging.info', 'logging.info', (['"""file %s extracted %d face embeds"""', 'key', 'faces.shape[0]'], {}), "('file %s extracted %d face embeds', key, faces.shape[0])\n", (3564, 3621), False, 'import logging\n'), ((3806, 3836), 'face_utils.save_bbox', 'save_bbox', (['key', '(0)', 'faces', 'f_bb'], {}), '(key, 0, faces, f_bb)\n', (3815, 3836), False, 'from face_utils import Namespace, read_img, save_facedet_image, save_facecrop_images, save_bbox, detect_faces_in_frame, extract_embed_in_frame_v4\n'), ((1841, 1868), 'os.path.exists', 'os.path.exists', (['facedet_dir'], {}), '(facedet_dir)\n', (1855, 1868), False, 'import os\n'), ((1886, 1910), 'os.makedirs', 'os.makedirs', (['facedet_dir'], {}), '(facedet_dir)\n', (1897, 1910), False, 'import os\n'), ((2029, 2057), 'os.path.exists', 'os.path.exists', (['facecrop_dir'], {}), '(facecrop_dir)\n', (2043, 2057), False, 'import os\n'), ((2075, 2100), 'os.makedirs', 'os.makedirs', (['facecrop_dir'], {}), '(facecrop_dir)\n', (2086, 2100), False, 'import os\n'), ((2807, 2871), 'face_utils.save_facedet_image', 'save_facedet_image', (['key', '(0)', 'frame', 'faces', 'landmarks', 'facedet_dir'], {}), '(key, 0, frame, faces, landmarks, facedet_dir)\n', (2825, 2871), False, 'from face_utils import Namespace, read_img, save_facedet_image, save_facecrop_images, save_bbox, detect_faces_in_frame, extract_embed_in_frame_v4\n'), ((2958, 3059), 'logging.info', 'logging.info', (['"""did not detect faces in file %s, reducing facedet threshold=%.1f"""', 'key', 'threshold'], {}), "('did not detect faces in file %s, reducing facedet threshold=%.1f'\n , key, threshold)\n", (2970, 3059), False, 'import logging\n'), ((3736, 3792), 'face_utils.save_facecrop_images', 'save_facecrop_images', (['key', '(0)', 'frame', 'faces', 'facecrop_dir'], {}), '(key, 0, frame, faces, facecrop_dir)\n', (3756, 3792), False, 'from face_utils import Namespace, read_img, save_facedet_image, save_facecrop_images, save_bbox, detect_faces_in_frame, extract_embed_in_frame_v4\n'), ((4044, 4159), 'logging.info', 'logging.info', (['"""retina face detected faces in file %s but mtcnn did not, using retina landmarks then"""', 'key'], {}), "(\n 'retina face detected faces in file %s but mtcnn did not, using retina landmarks then'\n , key)\n", (4056, 4159), False, 'import logging\n')]
# Tests if delta calculator is working properly with simple assertion function from finetuna.calcs import DeltaCalc from ase.calculators.emt import EMT import numpy as np import copy from ase.build import fcc100, add_adsorbate, molecule from ase.constraints import FixAtoms from ase.build import bulk from ase.utils.eos import EquationOfState from finetuna.base_calcs.morse import MultiMorse parent_calculator = EMT() energies = [] volumes = [] LC = [3.5, 3.55, 3.6, 3.65, 3.7, 3.75] for a in LC: cu_bulk = bulk("Cu", "fcc", a=a) calc = EMT() cu_bulk.set_calculator(calc) e = cu_bulk.get_potential_energy() energies.append(e) volumes.append(cu_bulk.get_volume()) eos = EquationOfState(volumes, energies) v0, e0, B = eos.fit() aref = 3.6 vref = bulk("Cu", "fcc", a=aref).get_volume() copper_lattice_constant = (v0 / vref) ** (1 / 3) * aref slab = fcc100("Cu", a=copper_lattice_constant, size=(2, 2, 3)) ads = molecule("C") add_adsorbate(slab, ads, 2, offset=(1, 1)) cons = FixAtoms(indices=[atom.index for atom in slab if (atom.tag == 3)]) slab.set_constraint(cons) slab.center(vacuum=13.0, axis=2) slab.set_pbc(True) slab.wrap(pbc=[True] * 3) slab.set_calculator(copy.copy(parent_calculator)) slab.set_initial_magnetic_moments() images = [slab] parent_energy = parent_ref = slab.get_potential_energy() Gs = { "default": { "G2": { "etas": np.logspace(np.log10(0.05), np.log10(5.0), num=4), "rs_s": [0], }, "G4": {"etas": [0.005], "zetas": [1.0, 4.0], "gammas": [1.0, -1.0]}, "cutoff": 6, }, } # create image with base calculator attached cutoff = Gs["default"]["cutoff"] base_calc = MultiMorse(images, cutoff, combo="mean") slab_base = slab.copy() slab_base.set_calculator(base_calc) base_energy = base_ref = slab_base.get_potential_energy() # Add delta_calc = DeltaCalc([parent_calculator, base_calc], "add", [slab, slab_base]) # Set slab calculator to delta calc and evaluate energy slab_add = slab.copy() slab_add.set_calculator(delta_calc) add_energy = slab_add.get_potential_energy() # Sub delta_calc = DeltaCalc([parent_calculator, base_calc], "sub", [slab, slab_base]) # Set slab calculator to delta calc and evaluate energy slab_sub = slab.copy() slab_sub.set_calculator(delta_calc) sub_energy = slab_sub.get_potential_energy() def test_delta_sub(): assert sub_energy == ( (parent_energy - base_energy) + (-parent_ref + base_ref) ), "Energies don't match!" def test_delta_add(): assert ( np.abs(add_energy - ((base_energy + parent_energy) + (parent_ref - base_ref))) < 1e-5 ), "Energies don't match!"
[ "numpy.abs", "numpy.log10", "ase.build.add_adsorbate", "ase.utils.eos.EquationOfState", "copy.copy", "ase.calculators.emt.EMT", "ase.build.fcc100", "finetuna.base_calcs.morse.MultiMorse", "ase.build.molecule", "ase.build.bulk", "finetuna.calcs.DeltaCalc", "ase.constraints.FixAtoms" ]
[((413, 418), 'ase.calculators.emt.EMT', 'EMT', ([], {}), '()\n', (416, 418), False, 'from ase.calculators.emt import EMT\n'), ((697, 731), 'ase.utils.eos.EquationOfState', 'EquationOfState', (['volumes', 'energies'], {}), '(volumes, energies)\n', (712, 731), False, 'from ase.utils.eos import EquationOfState\n'), ((874, 929), 'ase.build.fcc100', 'fcc100', (['"""Cu"""'], {'a': 'copper_lattice_constant', 'size': '(2, 2, 3)'}), "('Cu', a=copper_lattice_constant, size=(2, 2, 3))\n", (880, 929), False, 'from ase.build import fcc100, add_adsorbate, molecule\n'), ((936, 949), 'ase.build.molecule', 'molecule', (['"""C"""'], {}), "('C')\n", (944, 949), False, 'from ase.build import fcc100, add_adsorbate, molecule\n'), ((950, 992), 'ase.build.add_adsorbate', 'add_adsorbate', (['slab', 'ads', '(2)'], {'offset': '(1, 1)'}), '(slab, ads, 2, offset=(1, 1))\n', (963, 992), False, 'from ase.build import fcc100, add_adsorbate, molecule\n'), ((1000, 1064), 'ase.constraints.FixAtoms', 'FixAtoms', ([], {'indices': '[atom.index for atom in slab if atom.tag == 3]'}), '(indices=[atom.index for atom in slab if atom.tag == 3])\n', (1008, 1064), False, 'from ase.constraints import FixAtoms\n'), ((1677, 1717), 'finetuna.base_calcs.morse.MultiMorse', 'MultiMorse', (['images', 'cutoff'], {'combo': '"""mean"""'}), "(images, cutoff, combo='mean')\n", (1687, 1717), False, 'from finetuna.base_calcs.morse import MultiMorse\n'), ((1856, 1923), 'finetuna.calcs.DeltaCalc', 'DeltaCalc', (['[parent_calculator, base_calc]', '"""add"""', '[slab, slab_base]'], {}), "([parent_calculator, base_calc], 'add', [slab, slab_base])\n", (1865, 1923), False, 'from finetuna.calcs import DeltaCalc\n'), ((2105, 2172), 'finetuna.calcs.DeltaCalc', 'DeltaCalc', (['[parent_calculator, base_calc]', '"""sub"""', '[slab, slab_base]'], {}), "([parent_calculator, base_calc], 'sub', [slab, slab_base])\n", (2114, 2172), False, 'from finetuna.calcs import DeltaCalc\n'), ((513, 535), 'ase.build.bulk', 'bulk', (['"""Cu"""', '"""fcc"""'], {'a': 'a'}), "('Cu', 'fcc', a=a)\n", (517, 535), False, 'from ase.build import bulk\n'), ((547, 552), 'ase.calculators.emt.EMT', 'EMT', ([], {}), '()\n', (550, 552), False, 'from ase.calculators.emt import EMT\n'), ((1191, 1219), 'copy.copy', 'copy.copy', (['parent_calculator'], {}), '(parent_calculator)\n', (1200, 1219), False, 'import copy\n'), ((772, 797), 'ase.build.bulk', 'bulk', (['"""Cu"""', '"""fcc"""'], {'a': 'aref'}), "('Cu', 'fcc', a=aref)\n", (776, 797), False, 'from ase.build import bulk\n'), ((2525, 2601), 'numpy.abs', 'np.abs', (['(add_energy - (base_energy + parent_energy + (parent_ref - base_ref)))'], {}), '(add_energy - (base_energy + parent_energy + (parent_ref - base_ref)))\n', (2531, 2601), True, 'import numpy as np\n'), ((1404, 1418), 'numpy.log10', 'np.log10', (['(0.05)'], {}), '(0.05)\n', (1412, 1418), True, 'import numpy as np\n'), ((1420, 1433), 'numpy.log10', 'np.log10', (['(5.0)'], {}), '(5.0)\n', (1428, 1433), True, 'import numpy as np\n')]
from scipy import linalg import numpy as np import matplotlib.cm as cm from matplotlib.mlab import bivariate_normal import matplotlib.pyplot as plt # %matplotlib inline # == Set up the Gaussian prior density p == # Σ = [[0.3**2, 0.0], [0.0, 0.3**2]] Σ = np.matrix(Σ) x_hat = np.matrix([0.5, -0.5]).T # == Define the matrices G and R from the equation y = G x + N(0, R) == # G = [[1, 0], [0, 1]] G = np.matrix(G) R = 0.5 * Σ # == The matrices A and Q == # A = [[1.0, 0], [0, 1.0]] A = np.matrix(A) Q = 0.3 * Σ # == The observed value of y == # y = np.matrix([2.3, -1.9]).T # == Set up grid for plotting == # x_grid = np.linspace(-1.5, 2.9, 100) y_grid = np.linspace(-3.1, 1.7, 100) X, Y = np.meshgrid(x_grid, y_grid) def gen_gaussian_plot_vals(μ, C): "Z values for plotting the bivariate Gaussian N(μ, C)" m_x, m_y = float(μ[0]), float(μ[1]) s_x, s_y = np.sqrt(C[0, 0]), np.sqrt(C[1, 1]) s_xy = C[0, 1] return bivariate_normal(X, Y, s_x, s_y, m_x, m_y, s_xy) fig, ax = plt.subplots(figsize=(10, 8)) ax.grid() # Plot the figure # Density 1 Z = gen_gaussian_plot_vals(x_hat, Σ) cs1 = ax.contour(X, Y, Z, 6, colors="black") ax.clabel(cs1, inline=1, fontsize=10) # Density 2 #<NAME> K = Σ * G.T * linalg.inv(G * Σ * G.T + R) # Update the state estimate x_hat_F = x_hat + K*(y - G * x_hat) #update covariance estimation Σ_F = Σ - K * G * Σ Z_F = gen_gaussian_plot_vals(x_hat_F, Σ_F) cs2 = ax.contour(X, Y, Z_F, 6, colors="black") ax.clabel(cs2, inline=1, fontsize=10) # Density 3 # Predict next state of the feature with the last state and predicted motion #https://stackoverflow.com/questions/14058340/adding-noise-to-a-signal-in-python new_x_hat = A * x_hat_F # print(new_x_hat) #predict next covariance new_Σ = A * Σ_F * A.T + Q new_Z = gen_gaussian_plot_vals(new_x_hat, new_Σ) cs3 = ax.contour(X, Y, new_Z, 6, colors="black") ax.clabel(cs3, inline=1, fontsize=10) ax.contourf(X, Y, new_Z, 6, alpha=0.6, cmap=cm.jet) ax.text(float(y[0]), float(y[1]), "$y$", fontsize=20, color="black") plt.show() dt = 33.3e-3 #state update matrices A = np.matrix( ((1, 0, dt, 0),(0, 1, 0, dt),(0, 0, 1, 0),(0, 0, 0, 1)) ) Q = np.matrix( (30, 68, 0, 0) ).transpose() B = np.matrix( ((dt**2/2),(dt**2/2), dt, dt)).transpose() C = np.matrix( ((1,0,0,0),(0,1,0,0)) ) #this is our measurement function C, that we apply to the state estimate Q to get our expect next/new measurement Q_estimate = Q u = .005 #define acceleration magnitude marker_noise_mag = .1; #process noise: the variability in how fast the Hexbug is speeding up (stdv of acceleration: meters/sec^2) tkn_x = 1; #measurement noise in the horizontal direction (x axis). tkn_y = 1; #measurement noise in the horizontal direction (y axis). Ez = np.matrix(((tkn_x,0),(0,tkn_y))) Ex = np.matrix( ((dt**4/4,0,dt**3/2,0),(0,dt**4/4,0,dt**3/2),(dt**3/2,0,dt**2,0),(0,dt**3/2,0,dt**2)) )*marker_noise_mag**2# Ex convert the process noise (stdv) into covariance matrix P = Ex; # estimate of initial Hexbug position variance (covariance matrix) # Predict next state of the Hexbug with the last state and predicted motion. Q_estimate = A*Q_estimate + B*u; # predic_state = [predic_state; Q_estimate(1)] ; # predict next covariance P = A*P*A.T + Ex; # predic_var = [predic_var; P] ; # predicted Ninja measurement covariance # Kalman Gain K = P*C.T*linalg.inv(C*P*C.T + Ez); # Update the state estimate x_avg = 32 y_avg = 70 Q_loc_meas = np.matrix( (x_avg, y_avg) ).transpose() Q_estimate = Q_estimate + K * (Q_loc_meas - C*Q_estimate); print(Q_estimate) # update covariance estimation. P = (np.identity(4) - K*C)*P; import csv float_list = [1.13, 0.25, 3.28] # with open('ANN_0.csv', "w") as file: # writer = csv.writer(file, delimiter=',') # writer.writerow(Ez) outfile = open('./ANN_0.csv','w') writer=csv.writer(outfile) writer.writerow(float_list) # writer.writerow(['SNo', 'States', 'Dist', 'Population']) # writer.writerows(list_of_rows) writer.writerow(float_list) writer.writerow(float_list) writer.writerow(float_list) writer.writerow(float_list)
[ "numpy.identity", "numpy.sqrt", "matplotlib.mlab.bivariate_normal", "csv.writer", "numpy.linspace", "numpy.meshgrid", "numpy.matrix", "scipy.linalg.inv", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((256, 268), 'numpy.matrix', 'np.matrix', (['Σ'], {}), '(Σ)\n', (265, 268), True, 'import numpy as np\n'), ((402, 414), 'numpy.matrix', 'np.matrix', (['G'], {}), '(G)\n', (411, 414), True, 'import numpy as np\n'), ((487, 499), 'numpy.matrix', 'np.matrix', (['A'], {}), '(A)\n', (496, 499), True, 'import numpy as np\n'), ((620, 647), 'numpy.linspace', 'np.linspace', (['(-1.5)', '(2.9)', '(100)'], {}), '(-1.5, 2.9, 100)\n', (631, 647), True, 'import numpy as np\n'), ((657, 684), 'numpy.linspace', 'np.linspace', (['(-3.1)', '(1.7)', '(100)'], {}), '(-3.1, 1.7, 100)\n', (668, 684), True, 'import numpy as np\n'), ((692, 719), 'numpy.meshgrid', 'np.meshgrid', (['x_grid', 'y_grid'], {}), '(x_grid, y_grid)\n', (703, 719), True, 'import numpy as np\n'), ((995, 1024), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (1007, 1024), True, 'import matplotlib.pyplot as plt\n'), ((2019, 2029), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2027, 2029), True, 'import matplotlib.pyplot as plt\n'), ((2070, 2139), 'numpy.matrix', 'np.matrix', (['((1, 0, dt, 0), (0, 1, 0, dt), (0, 0, 1, 0), (0, 0, 0, 1))'], {}), '(((1, 0, dt, 0), (0, 1, 0, dt), (0, 0, 1, 0), (0, 0, 0, 1)))\n', (2079, 2139), True, 'import numpy as np\n'), ((2245, 2284), 'numpy.matrix', 'np.matrix', (['((1, 0, 0, 0), (0, 1, 0, 0))'], {}), '(((1, 0, 0, 0), (0, 1, 0, 0)))\n', (2254, 2284), True, 'import numpy as np\n'), ((2723, 2758), 'numpy.matrix', 'np.matrix', (['((tkn_x, 0), (0, tkn_y))'], {}), '(((tkn_x, 0), (0, tkn_y)))\n', (2732, 2758), True, 'import numpy as np\n'), ((3786, 3805), 'csv.writer', 'csv.writer', (['outfile'], {}), '(outfile)\n', (3796, 3805), False, 'import csv\n'), ((278, 300), 'numpy.matrix', 'np.matrix', (['[0.5, -0.5]'], {}), '([0.5, -0.5])\n', (287, 300), True, 'import numpy as np\n'), ((550, 572), 'numpy.matrix', 'np.matrix', (['[2.3, -1.9]'], {}), '([2.3, -1.9])\n', (559, 572), True, 'import numpy as np\n'), ((935, 983), 'matplotlib.mlab.bivariate_normal', 'bivariate_normal', (['X', 'Y', 's_x', 's_y', 'm_x', 'm_y', 's_xy'], {}), '(X, Y, s_x, s_y, m_x, m_y, s_xy)\n', (951, 983), False, 'from matplotlib.mlab import bivariate_normal\n'), ((1226, 1253), 'scipy.linalg.inv', 'linalg.inv', (['(G * Σ * G.T + R)'], {}), '(G * Σ * G.T + R)\n', (1236, 1253), False, 'from scipy import linalg\n'), ((2762, 2906), 'numpy.matrix', 'np.matrix', (['((dt ** 4 / 4, 0, dt ** 3 / 2, 0), (0, dt ** 4 / 4, 0, dt ** 3 / 2), (dt **\n 3 / 2, 0, dt ** 2, 0), (0, dt ** 3 / 2, 0, dt ** 2))'], {}), '(((dt ** 4 / 4, 0, dt ** 3 / 2, 0), (0, dt ** 4 / 4, 0, dt ** 3 / \n 2), (dt ** 3 / 2, 0, dt ** 2, 0), (0, dt ** 3 / 2, 0, dt ** 2)))\n', (2771, 2906), True, 'import numpy as np\n'), ((3318, 3346), 'scipy.linalg.inv', 'linalg.inv', (['(C * P * C.T + Ez)'], {}), '(C * P * C.T + Ez)\n', (3328, 3346), False, 'from scipy import linalg\n'), ((870, 886), 'numpy.sqrt', 'np.sqrt', (['C[0, 0]'], {}), '(C[0, 0])\n', (877, 886), True, 'import numpy as np\n'), ((888, 904), 'numpy.sqrt', 'np.sqrt', (['C[1, 1]'], {}), '(C[1, 1])\n', (895, 904), True, 'import numpy as np\n'), ((2143, 2168), 'numpy.matrix', 'np.matrix', (['(30, 68, 0, 0)'], {}), '((30, 68, 0, 0))\n', (2152, 2168), True, 'import numpy as np\n'), ((2187, 2232), 'numpy.matrix', 'np.matrix', (['(dt ** 2 / 2, dt ** 2 / 2, dt, dt)'], {}), '((dt ** 2 / 2, dt ** 2 / 2, dt, dt))\n', (2196, 2232), True, 'import numpy as np\n'), ((3407, 3432), 'numpy.matrix', 'np.matrix', (['(x_avg, y_avg)'], {}), '((x_avg, y_avg))\n', (3416, 3432), True, 'import numpy as np\n'), ((3561, 3575), 'numpy.identity', 'np.identity', (['(4)'], {}), '(4)\n', (3572, 3575), True, 'import numpy as np\n')]
import numpy as np import argparse import os import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.path import Path from matplotlib.gridspec import GridSpec from PIL import Image import csv import sys sys.path.append("/home/wuminghu/3D_vision/SMOKE/3d-bounding-box-estimation-for-autonomous-driving/utils") from read_dir import ReadDir from config import config as cfg from correspondece_constraint import * VIEW_WIDTH = 1920//2 VIEW_HEIGHT = 1080//2 def compute_birdviewbox(line, shape, scale): npline = [np.float64(line[i]) for i in range(1, len(line))] h = npline[7] * scale w = npline[8] * scale l = npline[9] * scale x = npline[10] * scale y = npline[11] * scale z = npline[12] * scale rot_y = npline[13] R = np.array([[-np.cos(rot_y), np.sin(rot_y)], [np.sin(rot_y), np.cos(rot_y)]]) t = np.array([x, z]).reshape(1, 2).T x_corners = [0, l, l, 0] # -l/2 z_corners = [w, w, 0, 0] # -w/2 x_corners += -w / 2 z_corners += -l / 2 # bounding box in object coordinate corners_2D = np.array([x_corners, z_corners]) # rotate corners_2D = R.dot(corners_2D) # translation corners_2D = t - corners_2D # in camera coordinate corners_2D[0] += int(shape/2) corners_2D = (corners_2D).astype(np.int16) corners_2D = corners_2D.T return np.vstack((corners_2D, corners_2D[0,:])) def draw_birdeyes(ax2, line_gt, line_p, shape): # shape = 900 scale = 15 pred_corners_2d = compute_birdviewbox(line_p, shape, scale) gt_corners_2d = compute_birdviewbox(line_gt, shape, scale) codes = [Path.LINETO] * gt_corners_2d.shape[0] codes[0] = Path.MOVETO codes[-1] = Path.CLOSEPOLY pth = Path(gt_corners_2d, codes) p = patches.PathPatch(pth, fill=False, color='red', label='ground truth') ax2.add_patch(p) codes = [Path.LINETO] * pred_corners_2d.shape[0] codes[0] = Path.MOVETO codes[-1] = Path.CLOSEPOLY pth = Path(pred_corners_2d, codes) p = patches.PathPatch(pth, fill=False, color='green', label='prediction') ax2.add_patch(p) def draw_birdeyes_gt(ax2, line_gt, shape,scale): gt_corners_2d = compute_birdviewbox(line_gt, shape, scale) codes = [Path.LINETO] * gt_corners_2d.shape[0] codes[0] = Path.MOVETO codes[-1] = Path.CLOSEPOLY pth = Path(gt_corners_2d, codes) p = patches.PathPatch(pth, fill=False, color='red', label='ground truth') ax2.add_patch(p) def draw_birdeyes_pd(ax2, line_p, shape,scale): pred_corners_2d = compute_birdviewbox(line_p, shape, scale) codes = [Path.LINETO] * pred_corners_2d.shape[0] codes[0] = Path.MOVETO codes[-1] = Path.CLOSEPOLY pth = Path(pred_corners_2d, codes) p = patches.PathPatch(pth, fill=False, color='green', label='prediction') ax2.add_patch(p) def compute_3Dbox(P2, line): obj = detectionInfo(line) # Draw 2D Bounding Box xmin = int(obj.xmin) xmax = int(obj.xmax) ymin = int(obj.ymin) ymax = int(obj.ymax) # width = xmax - xmin # height = ymax - ymin # box_2d = patches.Rectangle((xmin, ymin), width, height, fill=False, color='red', linewidth='3') # ax.add_patch(box_2d) # Draw 3D Bounding Box R = np.array([[np.cos(obj.rot_global), 0, np.sin(obj.rot_global)], [0, 1, 0], [-np.sin(obj.rot_global), 0, np.cos(obj.rot_global)]]) x_corners = [0, obj.l, obj.l, obj.l, obj.l, 0, 0, 0] # -l/2 y_corners = [0, 0, obj.h, obj.h, 0, 0, obj.h, obj.h] # -h z_corners = [0, 0, 0, obj.w, obj.w, obj.w, obj.w, 0] # -w/2 x_corners = [i - obj.l / 2 for i in x_corners] y_corners = [i - obj.h for i in y_corners] z_corners = [i - obj.w / 2 for i in z_corners] corners_3D = np.array([x_corners, y_corners, z_corners]) corners_3D = R.dot(corners_3D) corners_3D += np.array([obj.tx, obj.ty, obj.tz]).reshape((3, 1)) # corners_3D_1 = np.vstack((corners_3D, np.ones((corners_3D.shape[-1])))) corners_2D = P2.dot(corners_3D) corners_2D = corners_2D / corners_2D[2] corners_2D = corners_2D[:2] return corners_2D def draw_3Dbox(ax, P2, line, color): corners_2D = compute_3Dbox(P2, line) width = corners_2D[:, 3][0] - corners_2D[:, 1][0] height = corners_2D[:, 2][1] - corners_2D[:, 1][1] # draw all lines through path # https://matplotlib.org/users/path_tutorial.html bb3d_lines_verts_idx = [0, 1, 2, 3, 4, 5, 6, 7, 0, 5, 4, 1, 2, 7, 6, 3] bb3d_on_2d_lines_verts = corners_2D[:, bb3d_lines_verts_idx] verts = bb3d_on_2d_lines_verts.T codes = [Path.LINETO] * verts.shape[0] codes[0] = Path.MOVETO # codes[-1] = Path.CLOSEPOLYq pth = Path(verts, codes) p = patches.PathPatch(pth, fill=False, color=color, linewidth=2) # put a mask on the front front_fill = patches.Rectangle((corners_2D[:, 1]), width, height, fill=True, color=color, alpha=0.4) ax.add_patch(p) ax.add_patch(front_fill) def visualization(args, image_path, label_path, calib_path, pred_path, dataset, VEHICLES): for index in range(start_frame, end_frame): image_file = os.path.join(image_path, dataset[index]+ '.png') label_file = os.path.join(label_path, dataset[index] + '.txt') prediction_file = os.path.join(pred_path, dataset[index]+ '.txt') # calibration_file = os.path.join(calib_path, dataset[index] + '.txt') # for line in open(calibration_file): # if 'P2' in line: # P2 = line.split(' ') # P2 = np.asarray([float(i) for i in P2[1:]]) # P2 = np.reshape(P2, (3, 4)) with open(os.path.join(calib_path, "%.6d.txt"%(0)), 'r') as csv_file: reader = csv.reader(csv_file, delimiter=' ') for line, row in enumerate(reader): if row[0] == 'P2:': P2 = row[1:] P2 = [float(i) for i in P2] P2 = np.array(P2, dtype=np.float32).reshape(3, 3) P2 = P2[:3, :3] break fig = plt.figure(figsize=(20.00, 5.12), dpi=100) # fig.tight_layout() gs = GridSpec(1, 4) gs.update(wspace=0) # set the spacing between axes. ax = fig.add_subplot(gs[0, :3]) ax2 = fig.add_subplot(gs[0, 2:]) # with writer.saving(fig, "kitti_30_20fps.mp4", dpi=100): image = Image.open(image_file).convert('RGB') shape = 900 birdimage = np.zeros((shape, shape, 3), np.uint8) with open(label_file) as f1, open(prediction_file) as f2: #################################################################################### for line_gt in f1: line_gt = line_gt.strip().split(' ') corners_2D = compute_3Dbox(P2, line_gt) width_half = (corners_2D[:, 3][0] - corners_2D[:, 1][0])/2 height_half = (corners_2D[:, 2][1] - corners_2D[:, 1][1])/2 # if corners_2D[:, 3][0]-width_half*0.9>VIEW_WIDTH or corners_2D[:, 2][1]-height_half>VIEW_HEIGHT or corners_2D[:, 1][0]+width_half*0.9<0 or corners_2D[:, 1][1]+height_half<0: # continue if corners_2D[:, 3][0]-width_half*0.9>VIEW_WIDTH or corners_2D[:, 2][1]-height_half>VIEW_HEIGHT: continue draw_3Dbox(ax, P2, line_gt, 'red') draw_birdeyes_gt(ax2, line_gt, shape,15) #################################################################################### for line_p in f2: line_p = line_p.strip().split(' ') corners_2D = compute_3Dbox(P2, line_p) width_half = (corners_2D[:, 3][0] - corners_2D[:, 1][0])/2 height_half = (corners_2D[:, 2][1] - corners_2D[:, 1][1])/2 # if corners_2D[:, 3][0]-width_half*0.9>VIEW_WIDTH or corners_2D[:, 2][1]-height_half>VIEW_HEIGHT or corners_2D[:, 1][0]+width_half*0.9<0 or corners_2D[:, 1][1]+height_half<0: # continue if corners_2D[:, 3][0]-width_half*0.9>VIEW_WIDTH or corners_2D[:, 2][1]-height_half>VIEW_HEIGHT: continue draw_3Dbox(ax, P2, line_p, 'green') draw_birdeyes_pd(ax2, line_p, shape,15) #################################################################################### # for line_gt, line_p in zip(f1, f2): # import pdb; pdb.set_trace() # line_gt = line_gt.strip().split(' ') # line_p = line_p.strip().split(' ') # truncated = np.abs(float(line_p[1])) # occluded = np.abs(float(line_p[2])) # trunc_level = 1 if args.a == 'training' else 255 # # truncated object in dataset is not observable # if line_p[0] in VEHICLES and truncated < trunc_level: # color = 'green' # if line_p[0] == 'Cyclist': # color = 'yellow' # elif line_p[0] == 'Pedestrian': # color = 'cyan' # draw_3Dbox(ax, P2, line_p, color) # # draw_3Dbox(ax, P2, line_gt, 'yellow') # draw_birdeyes(ax2, line_gt, line_p, shape) ############################################################################################ # visualize 3D bounding box ax.imshow(image) ax.set_xticks([]) #remove axis value ax.set_yticks([]) # plot camera view range x1 = np.linspace(0, shape / 2) x2 = np.linspace(shape / 2, shape) ax2.plot(x1, shape / 2 - x1, ls='--', color='grey', linewidth=1, alpha=0.5) ax2.plot(x2, x2 - shape / 2, ls='--', color='grey', linewidth=1, alpha=0.5) ax2.plot(shape / 2, 0, marker='+', markersize=16, markeredgecolor='red') # visualize bird eye view ax2.imshow(birdimage, origin='lower') ax2.set_xticks([]) ax2.set_yticks([]) # add legend handles, labels = ax2.get_legend_handles_labels() legend = ax2.legend([handles[0], handles[-1]], [labels[0], labels[-1]], loc='lower right', fontsize='x-small', framealpha=0.2) for text in legend.get_texts(): plt.setp(text, color='w') print(dataset[index]) if args.save == False: plt.show() else: fig.savefig(os.path.join(args.path, dataset[index]), dpi=fig.dpi, bbox_inches='tight', pad_inches=0) # video_writer.write(np.uint8(fig)) def compute_location_loss(args, image_path, label_path, calib_path, pred_path, dataset, VEHICLES): sum_dis=0 count=0 sum_gt=0 sum_match=0 with open(os.path.join(calib_path, "%.6d.txt"%(0)), 'r') as csv_file: reader = csv.reader(csv_file, delimiter=' ') for line, row in enumerate(reader): if row[0] == 'P2:': P2 = row[1:] P2 = [float(i) for i in P2] P2 = np.array(P2, dtype=np.float32).reshape(3, 3) P2 = P2[:3, :3] break for index in range(start_frame, end_frame): label_file = os.path.join(label_path, dataset[index] + '.txt') prediction_file = os.path.join(pred_path, dataset[index]+ '.txt') with open(label_file) as f1, open(prediction_file) as f2: line_gts = [line_gt.strip().split(' ') for line_gt in f1] line_tem=[] for line_gt in line_gts: corners_2D = compute_3Dbox(P2, line_gt) width_half = (corners_2D[:, 3][0] - corners_2D[:, 1][0])/2 height_half = (corners_2D[:, 2][1] - corners_2D[:, 1][1])/2 # if corners_2D[:, 3][0]-width_half>VIEW_WIDTH or corners_2D[:, 2][1]-height_half>VIEW_HEIGHT or corners_2D[:, 1][0]+width_half<0 or corners_2D[:, 1][1]+height_half<0: # continue if corners_2D[:, 3][0]-width_half>VIEW_WIDTH or corners_2D[:, 2][1]-height_half>VIEW_HEIGHT : continue line_tem.append(line_gt) line_gts=line_tem obj_gts = [detectionInfo(line_gt) for line_gt in line_gts] line_ps = [line_p.strip().split(' ') for line_p in f2] line_tem=[] for line_p in line_ps: corners_2D = compute_3Dbox(P2, line_p) width_half = (corners_2D[:, 3][0] - corners_2D[:, 1][0])/2 height_half = (corners_2D[:, 2][1] - corners_2D[:, 1][1])/2 # if corners_2D[:, 3][0]-width_half>VIEW_WIDTH or corners_2D[:, 2][1]-height_half>VIEW_HEIGHT or corners_2D[:, 1][0]+width_half<0 or corners_2D[:, 1][1]+height_half<0: # continue if corners_2D[:, 3][0]-width_half>VIEW_WIDTH or corners_2D[:, 2][1]-height_half>VIEW_HEIGHT: continue line_tem.append(line_p) line_ps=line_tem obj_ps = [detectionInfo(line_p) for line_p in line_ps] # if len(line_ps)!=len(line_gts): # print(len(line_ps),len(line_gts)) g_xys=[np.array([obj_gt.tz,obj_gt.tx,obj_gt.rot_global]) for obj_gt in obj_gts if np.sqrt(obj_gt.tz**2+obj_gt.tx**2)>0 and np.sqrt(obj_gt.tz**2+obj_gt.tx**2)<20] p_xys=[np.array([obj_p.tz,obj_p.tx,obj_p.rot_global]) for obj_p in obj_ps] # dis=[[(np.linalg.norm(g_xy[:2]-p_xy[:2])+abs(g_xy[2]-p_xy[2])/10)for p_xy in p_xys] for g_xy in g_xys ] dis=[[np.linalg.norm(g_xy[:2]-p_xy[:2]) for p_xy in p_xys] for g_xy in g_xys ] dis_sorts=[sorted(miny_dis) for miny_dis in dis] sum_gt+=len(dis_sorts) # import pdb; pdb.set_trace() for dis_sort in dis_sorts: if len(dis_sort)==0 : continue if dis_sort[0]<0.5: sum_dis+=dis_sort[0] sum_match+=1 count+=1 if count==0: return return sum_dis/count,sum_match/sum_gt # if count!=0: # print(sum_dis/count) # print(sum_match/sum_gt) def main(args): # cams=['cam5','cam5','cam_mix_1_2'] cams=['cam7'] sum_locaton_error,sum_precision,sum_count=0,0,0 for cam in cams: base_dir = '/media/wuminghu/work/output/SMOKE/object1/' dir = ReadDir(base_dir=base_dir, subset=args.a, tracklet_date='2011_09_26', tracklet_file='2011_09_26_drive_0093_sync',cam=cam) label_path = dir.label_dir image_path = dir.image_dir calib_path = dir.calib_dir pred_path = dir.prediction_dir dataset = [name.split('.')[0] for name in sorted(os.listdir(pred_path))] # import pdb; pdb.set_trace() VEHICLES = cfg().KITTI_cat visualization(args, image_path, label_path, calib_path, pred_path,dataset, VEHICLES) # locaton_error,precision=compute_location_loss(args, image_path, label_path, calib_path, pred_path,dataset, VEHICLES) # sum_locaton_error+=locaton_error # sum_precision+=precision # sum_count+=1 # print(sum_locaton_error/sum_count,sum_precision/sum_count,sum_count) if __name__ == '__main__': start_frame = 0 end_frame = 5000 parser = argparse.ArgumentParser(description='Visualize 3D bounding box on images', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-a', '-dataset', type=str, default='training', help='training dataset or tracklet') parser.add_argument('-s', '--save', type=bool, default=True, help='Save Figure or not') parser.add_argument('-p', '--path', type=str, default='/media/wuminghu/work/output/SMOKE/bird_eye', help='Output Image folder') args = parser.parse_args() if not os.path.exists(args.path): os.mkdir(args.path) main(args)
[ "numpy.sqrt", "numpy.array", "numpy.linalg.norm", "numpy.sin", "sys.path.append", "os.path.exists", "matplotlib.path.Path", "os.listdir", "argparse.ArgumentParser", "numpy.float64", "matplotlib.gridspec.GridSpec", "numpy.linspace", "numpy.vstack", "os.mkdir", "csv.reader", "read_dir.Re...
[((233, 348), 'sys.path.append', 'sys.path.append', (['"""/home/wuminghu/3D_vision/SMOKE/3d-bounding-box-estimation-for-autonomous-driving/utils"""'], {}), "(\n '/home/wuminghu/3D_vision/SMOKE/3d-bounding-box-estimation-for-autonomous-driving/utils'\n )\n", (248, 348), False, 'import sys\n'), ((1105, 1137), 'numpy.array', 'np.array', (['[x_corners, z_corners]'], {}), '([x_corners, z_corners])\n', (1113, 1137), True, 'import numpy as np\n'), ((1386, 1427), 'numpy.vstack', 'np.vstack', (['(corners_2D, corners_2D[0, :])'], {}), '((corners_2D, corners_2D[0, :]))\n', (1395, 1427), True, 'import numpy as np\n'), ((1757, 1783), 'matplotlib.path.Path', 'Path', (['gt_corners_2d', 'codes'], {}), '(gt_corners_2d, codes)\n', (1761, 1783), False, 'from matplotlib.path import Path\n'), ((1792, 1861), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['pth'], {'fill': '(False)', 'color': '"""red"""', 'label': '"""ground truth"""'}), "(pth, fill=False, color='red', label='ground truth')\n", (1809, 1861), True, 'import matplotlib.patches as patches\n'), ((2005, 2033), 'matplotlib.path.Path', 'Path', (['pred_corners_2d', 'codes'], {}), '(pred_corners_2d, codes)\n', (2009, 2033), False, 'from matplotlib.path import Path\n'), ((2042, 2111), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['pth'], {'fill': '(False)', 'color': '"""green"""', 'label': '"""prediction"""'}), "(pth, fill=False, color='green', label='prediction')\n", (2059, 2111), True, 'import matplotlib.patches as patches\n'), ((2366, 2392), 'matplotlib.path.Path', 'Path', (['gt_corners_2d', 'codes'], {}), '(gt_corners_2d, codes)\n', (2370, 2392), False, 'from matplotlib.path import Path\n'), ((2401, 2470), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['pth'], {'fill': '(False)', 'color': '"""red"""', 'label': '"""ground truth"""'}), "(pth, fill=False, color='red', label='ground truth')\n", (2418, 2470), True, 'import matplotlib.patches as patches\n'), ((2727, 2755), 'matplotlib.path.Path', 'Path', (['pred_corners_2d', 'codes'], {}), '(pred_corners_2d, codes)\n', (2731, 2755), False, 'from matplotlib.path import Path\n'), ((2764, 2833), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['pth'], {'fill': '(False)', 'color': '"""green"""', 'label': '"""prediction"""'}), "(pth, fill=False, color='green', label='prediction')\n", (2781, 2833), True, 'import matplotlib.patches as patches\n'), ((3787, 3830), 'numpy.array', 'np.array', (['[x_corners, y_corners, z_corners]'], {}), '([x_corners, y_corners, z_corners])\n', (3795, 3830), True, 'import numpy as np\n'), ((4720, 4738), 'matplotlib.path.Path', 'Path', (['verts', 'codes'], {}), '(verts, codes)\n', (4724, 4738), False, 'from matplotlib.path import Path\n'), ((4747, 4807), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['pth'], {'fill': '(False)', 'color': 'color', 'linewidth': '(2)'}), '(pth, fill=False, color=color, linewidth=2)\n', (4764, 4807), True, 'import matplotlib.patches as patches\n'), ((4857, 4946), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['corners_2D[:, 1]', 'width', 'height'], {'fill': '(True)', 'color': 'color', 'alpha': '(0.4)'}), '(corners_2D[:, 1], width, height, fill=True, color=color,\n alpha=0.4)\n', (4874, 4946), True, 'import matplotlib.patches as patches\n'), ((15380, 15514), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Visualize 3D bounding box on images"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Visualize 3D bounding box on images',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (15403, 15514), False, 'import argparse\n'), ((546, 565), 'numpy.float64', 'np.float64', (['line[i]'], {}), '(line[i])\n', (556, 565), True, 'import numpy as np\n'), ((5174, 5223), 'os.path.join', 'os.path.join', (['image_path', "(dataset[index] + '.png')"], {}), "(image_path, dataset[index] + '.png')\n", (5186, 5223), False, 'import os\n'), ((5244, 5293), 'os.path.join', 'os.path.join', (['label_path', "(dataset[index] + '.txt')"], {}), "(label_path, dataset[index] + '.txt')\n", (5256, 5293), False, 'import os\n'), ((5320, 5368), 'os.path.join', 'os.path.join', (['pred_path', "(dataset[index] + '.txt')"], {}), "(pred_path, dataset[index] + '.txt')\n", (5332, 5368), False, 'import os\n'), ((6118, 6159), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20.0, 5.12)', 'dpi': '(100)'}), '(figsize=(20.0, 5.12), dpi=100)\n', (6128, 6159), True, 'import matplotlib.pyplot as plt\n'), ((6204, 6218), 'matplotlib.gridspec.GridSpec', 'GridSpec', (['(1)', '(4)'], {}), '(1, 4)\n', (6212, 6218), False, 'from matplotlib.gridspec import GridSpec\n'), ((6523, 6560), 'numpy.zeros', 'np.zeros', (['(shape, shape, 3)', 'np.uint8'], {}), '((shape, shape, 3), np.uint8)\n', (6531, 6560), True, 'import numpy as np\n'), ((9605, 9630), 'numpy.linspace', 'np.linspace', (['(0)', '(shape / 2)'], {}), '(0, shape / 2)\n', (9616, 9630), True, 'import numpy as np\n'), ((9644, 9673), 'numpy.linspace', 'np.linspace', (['(shape / 2)', 'shape'], {}), '(shape / 2, shape)\n', (9655, 9673), True, 'import numpy as np\n'), ((10899, 10934), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""" """'}), "(csv_file, delimiter=' ')\n", (10909, 10934), False, 'import csv\n'), ((11273, 11322), 'os.path.join', 'os.path.join', (['label_path', "(dataset[index] + '.txt')"], {}), "(label_path, dataset[index] + '.txt')\n", (11285, 11322), False, 'import os\n'), ((11349, 11397), 'os.path.join', 'os.path.join', (['pred_path', "(dataset[index] + '.txt')"], {}), "(pred_path, dataset[index] + '.txt')\n", (11361, 11397), False, 'import os\n'), ((14459, 14585), 'read_dir.ReadDir', 'ReadDir', ([], {'base_dir': 'base_dir', 'subset': 'args.a', 'tracklet_date': '"""2011_09_26"""', 'tracklet_file': '"""2011_09_26_drive_0093_sync"""', 'cam': 'cam'}), "(base_dir=base_dir, subset=args.a, tracklet_date='2011_09_26',\n tracklet_file='2011_09_26_drive_0093_sync', cam=cam)\n", (14466, 14585), False, 'from read_dir import ReadDir\n'), ((15924, 15949), 'os.path.exists', 'os.path.exists', (['args.path'], {}), '(args.path)\n', (15938, 15949), False, 'import os\n'), ((15959, 15978), 'os.mkdir', 'os.mkdir', (['args.path'], {}), '(args.path)\n', (15967, 15978), False, 'import os\n'), ((3884, 3918), 'numpy.array', 'np.array', (['[obj.tx, obj.ty, obj.tz]'], {}), '([obj.tx, obj.ty, obj.tz])\n', (3892, 3918), True, 'import numpy as np\n'), ((5771, 5806), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""" """'}), "(csv_file, delimiter=' ')\n", (5781, 5806), False, 'import csv\n'), ((10352, 10377), 'matplotlib.pyplot.setp', 'plt.setp', (['text'], {'color': '"""w"""'}), "(text, color='w')\n", (10360, 10377), True, 'import matplotlib.pyplot as plt\n'), ((10452, 10462), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10460, 10462), True, 'import matplotlib.pyplot as plt\n'), ((10822, 10862), 'os.path.join', 'os.path.join', (['calib_path', "('%.6d.txt' % 0)"], {}), "(calib_path, '%.6d.txt' % 0)\n", (10834, 10862), False, 'import os\n'), ((14885, 14890), 'config.config', 'cfg', ([], {}), '()\n', (14888, 14890), True, 'from config import config as cfg\n'), ((814, 827), 'numpy.sin', 'np.sin', (['rot_y'], {}), '(rot_y)\n', (820, 827), True, 'import numpy as np\n'), ((849, 862), 'numpy.sin', 'np.sin', (['rot_y'], {}), '(rot_y)\n', (855, 862), True, 'import numpy as np\n'), ((864, 877), 'numpy.cos', 'np.cos', (['rot_y'], {}), '(rot_y)\n', (870, 877), True, 'import numpy as np\n'), ((889, 905), 'numpy.array', 'np.array', (['[x, z]'], {}), '([x, z])\n', (897, 905), True, 'import numpy as np\n'), ((3271, 3293), 'numpy.cos', 'np.cos', (['obj.rot_global'], {}), '(obj.rot_global)\n', (3277, 3293), True, 'import numpy as np\n'), ((3298, 3320), 'numpy.sin', 'np.sin', (['obj.rot_global'], {}), '(obj.rot_global)\n', (3304, 3320), True, 'import numpy as np\n'), ((3399, 3421), 'numpy.cos', 'np.cos', (['obj.rot_global'], {}), '(obj.rot_global)\n', (3405, 3421), True, 'import numpy as np\n'), ((5690, 5730), 'os.path.join', 'os.path.join', (['calib_path', "('%.6d.txt' % 0)"], {}), "(calib_path, '%.6d.txt' % 0)\n", (5702, 5730), False, 'import os\n'), ((6445, 6467), 'PIL.Image.open', 'Image.open', (['image_file'], {}), '(image_file)\n', (6455, 6467), False, 'from PIL import Image\n'), ((10501, 10540), 'os.path.join', 'os.path.join', (['args.path', 'dataset[index]'], {}), '(args.path, dataset[index])\n', (10513, 10540), False, 'import os\n'), ((13239, 13290), 'numpy.array', 'np.array', (['[obj_gt.tz, obj_gt.tx, obj_gt.rot_global]'], {}), '([obj_gt.tz, obj_gt.tx, obj_gt.rot_global])\n', (13247, 13290), True, 'import numpy as np\n'), ((13413, 13461), 'numpy.array', 'np.array', (['[obj_p.tz, obj_p.tx, obj_p.rot_global]'], {}), '([obj_p.tz, obj_p.tx, obj_p.rot_global])\n', (13421, 13461), True, 'import numpy as np\n'), ((799, 812), 'numpy.cos', 'np.cos', (['rot_y'], {}), '(rot_y)\n', (805, 812), True, 'import numpy as np\n'), ((3372, 3394), 'numpy.sin', 'np.sin', (['obj.rot_global'], {}), '(obj.rot_global)\n', (3378, 3394), True, 'import numpy as np\n'), ((13617, 13652), 'numpy.linalg.norm', 'np.linalg.norm', (['(g_xy[:2] - p_xy[:2])'], {}), '(g_xy[:2] - p_xy[:2])\n', (13631, 13652), True, 'import numpy as np\n'), ((14803, 14824), 'os.listdir', 'os.listdir', (['pred_path'], {}), '(pred_path)\n', (14813, 14824), False, 'import os\n'), ((11105, 11135), 'numpy.array', 'np.array', (['P2'], {'dtype': 'np.float32'}), '(P2, dtype=np.float32)\n', (11113, 11135), True, 'import numpy as np\n'), ((5997, 6027), 'numpy.array', 'np.array', (['P2'], {'dtype': 'np.float32'}), '(P2, dtype=np.float32)\n', (6005, 6027), True, 'import numpy as np\n'), ((13314, 13354), 'numpy.sqrt', 'np.sqrt', (['(obj_gt.tz ** 2 + obj_gt.tx ** 2)'], {}), '(obj_gt.tz ** 2 + obj_gt.tx ** 2)\n', (13321, 13354), True, 'import numpy as np\n'), ((13355, 13395), 'numpy.sqrt', 'np.sqrt', (['(obj_gt.tz ** 2 + obj_gt.tx ** 2)'], {}), '(obj_gt.tz ** 2 + obj_gt.tx ** 2)\n', (13362, 13395), True, 'import numpy as np\n')]
## GUI for calibration #! Code doesn't work yet, use curve_fit.py from scipy.optimize import curve_fit import matplotlib.pyplot as plt import numpy as np import tkinter as tk # replace with tkinter for python 3 from matplotlib import colors from numba import jit from tkinter import ttk from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk) import matplotlib as mpl mpl.use("TkAgg") # real_weight=np.loadtxt("data.csv", delimiter=";") # fmu_weight=range(len(real_weight)) mpl.rcParams['toolbar'] = 'None' # erase buttons def f(x, a, b): return a*x+b def curvefit(ax, real_weight=np.array([0.0, 3.3, 21.0]), fmu_weight=np.array([6.8, 11.0, 24.6])): real_weight = real_weight*1E-3*9.81 # grams to Newtons fmu_weight = fmu_weight*1E-3*9.81 # grams to Newtons popt, pcov = curve_fit(f, fmu_weight, real_weight) ax.plot(fmu_weight, real_weight, 'o', label="data") ax.plot(fmu_weight, f(fmu_weight, *popt), 'r-', label='curve_fit: a=%5.3f, b=%5.3f' % tuple(popt)) # plt.errorbar(fmu_weight, real_weight, yerr=1, xerr= 0, fmt="none") LARGE_FONT = ("Verdana", 12) NORM_FONT = ("Verdana", 10) class base(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self, "Mandelbrot Renderer") container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, MainPage): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Start Page", font=LARGE_FONT) label.pack(pady=10, padx=10) label2 = tk.Label(self, text="How many weights?") label2.pack(side=tk.LEFT) input1 = tk.Entry(self) input1.pack(side=tk.LEFT) # button1 = tk.Button(self, text="Process",command=setNofWeights()) # button1.pack() button = tk.Button(self, text="Lets Begin", command=lambda: controller.show_frame(MainPage)) button.pack() class MainPage(tk.Frame): def var_states(self): # this is supposed to send code to run plot() again but it doesnt do it print(self.combobox.get()) print(self.colr) self.plot() def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Graph Page!", font=LARGE_FONT) label.pack(pady=10, padx=10) values = ['jet', 'rainbow', 'ocean', 'hot', 'cubehelix', 'gnuplot', 'terrain', 'prism', 'pink'] button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage)) button1.pack() button2 = tk.Button(self, text="Re-Render", command=self.plot) button2.pack() self.mvar = tk.IntVar() self.cbutton = tk.Checkbutton( self, text="shadow", onvalue=0, offvalue=1, variable=self.mvar) self.cbutton.pack() self.combobox = ttk.Combobox(self, values=values) self.combobox.current(0) self.combobox.pack(side=tk.TOP) self.numberInput = tk.Entry(self) self.numberInput.pack(side=tk.TOP) self.width, self.height = 10, 10 fig = Figure(figsize=(self.width, self.height)) self.ax = fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(fig, self) self.canvas.draw() toolbar = NavigationToolbar2Tk(self.canvas, self) toolbar.update() self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) self.plot() def plot(self): colr = self.combobox.get() number=self.numberInput.get() print(number) self.ax.clear() # mandelbrot_image(self.ax, -0.8, -0.7, 0, 0.1, cmap=colr) curvefit(self.ax,number,number) self.canvas.draw() app = base() app.geometry("800x600") app.mainloop()
[ "scipy.optimize.curve_fit", "tkinter.IntVar", "tkinter.Frame.__init__", "tkinter.Entry", "tkinter.Checkbutton", "matplotlib.backends.backend_tkagg.NavigationToolbar2Tk", "matplotlib.use", "matplotlib.figure.Figure", "tkinter.Button", "numpy.array", "tkinter.Tk.wm_title", "tkinter.Tk.__init__",...
[((448, 464), 'matplotlib.use', 'mpl.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (455, 464), True, 'import matplotlib as mpl\n'), ((667, 693), 'numpy.array', 'np.array', (['[0.0, 3.3, 21.0]'], {}), '([0.0, 3.3, 21.0])\n', (675, 693), True, 'import numpy as np\n'), ((706, 733), 'numpy.array', 'np.array', (['[6.8, 11.0, 24.6]'], {}), '([6.8, 11.0, 24.6])\n', (714, 733), True, 'import numpy as np\n'), ((873, 910), 'scipy.optimize.curve_fit', 'curve_fit', (['f', 'fmu_weight', 'real_weight'], {}), '(f, fmu_weight, real_weight)\n', (882, 910), False, 'from scipy.optimize import curve_fit\n'), ((1287, 1324), 'tkinter.Tk.__init__', 'tk.Tk.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (1301, 1324), True, 'import tkinter as tk\n'), ((1333, 1376), 'tkinter.Tk.wm_title', 'tk.Tk.wm_title', (['self', '"""Mandelbrot Renderer"""'], {}), "(self, 'Mandelbrot Renderer')\n", (1347, 1376), True, 'import tkinter as tk\n'), ((1398, 1412), 'tkinter.Frame', 'tk.Frame', (['self'], {}), '(self)\n', (1406, 1412), True, 'import tkinter as tk\n'), ((1984, 2015), 'tkinter.Frame.__init__', 'tk.Frame.__init__', (['self', 'parent'], {}), '(self, parent)\n', (2001, 2015), True, 'import tkinter as tk\n'), ((2032, 2082), 'tkinter.Label', 'tk.Label', (['self'], {'text': '"""Start Page"""', 'font': 'LARGE_FONT'}), "(self, text='Start Page', font=LARGE_FONT)\n", (2040, 2082), True, 'import tkinter as tk\n'), ((2138, 2178), 'tkinter.Label', 'tk.Label', (['self'], {'text': '"""How many weights?"""'}), "(self, text='How many weights?')\n", (2146, 2178), True, 'import tkinter as tk\n'), ((2231, 2245), 'tkinter.Entry', 'tk.Entry', (['self'], {}), '(self)\n', (2239, 2245), True, 'import tkinter as tk\n'), ((2801, 2832), 'tkinter.Frame.__init__', 'tk.Frame.__init__', (['self', 'parent'], {}), '(self, parent)\n', (2818, 2832), True, 'import tkinter as tk\n'), ((2850, 2901), 'tkinter.Label', 'tk.Label', (['self'], {'text': '"""Graph Page!"""', 'font': 'LARGE_FONT'}), "(self, text='Graph Page!', font=LARGE_FONT)\n", (2858, 2901), True, 'import tkinter as tk\n'), ((3237, 3289), 'tkinter.Button', 'tk.Button', (['self'], {'text': '"""Re-Render"""', 'command': 'self.plot'}), "(self, text='Re-Render', command=self.plot)\n", (3246, 3289), True, 'import tkinter as tk\n'), ((3361, 3372), 'tkinter.IntVar', 'tk.IntVar', ([], {}), '()\n', (3370, 3372), True, 'import tkinter as tk\n'), ((3396, 3474), 'tkinter.Checkbutton', 'tk.Checkbutton', (['self'], {'text': '"""shadow"""', 'onvalue': '(0)', 'offvalue': '(1)', 'variable': 'self.mvar'}), "(self, text='shadow', onvalue=0, offvalue=1, variable=self.mvar)\n", (3410, 3474), True, 'import tkinter as tk\n'), ((3541, 3574), 'tkinter.ttk.Combobox', 'ttk.Combobox', (['self'], {'values': 'values'}), '(self, values=values)\n', (3553, 3574), False, 'from tkinter import ttk\n'), ((3676, 3690), 'tkinter.Entry', 'tk.Entry', (['self'], {}), '(self)\n', (3684, 3690), True, 'import tkinter as tk\n'), ((3790, 3831), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(self.width, self.height)'}), '(figsize=(self.width, self.height))\n', (3796, 3831), False, 'from matplotlib.figure import Figure\n'), ((3894, 3922), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['fig', 'self'], {}), '(fig, self)\n', (3911, 3922), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n'), ((3968, 4007), 'matplotlib.backends.backend_tkagg.NavigationToolbar2Tk', 'NavigationToolbar2Tk', (['self.canvas', 'self'], {}), '(self.canvas, self)\n', (3988, 4007), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n')]
import datetime import h5py import numpy as np import os import pandas as pd import sys import time import localmodule # Define constants. data_dir = localmodule.get_data_dir() dataset_name = localmodule.get_dataset_name() models_dir = localmodule.get_models_dir() oldbird_models_dir = os.path.join(models_dir, "oldbird") units = localmodule.get_units() odfs = ["thrush", "tseep"] n_thresholds = 100 clip_suppressor_str = "clip-suppressor" # Print header. start_time = int(time.time()) print(str(datetime.datetime.now()) + " Start.") print("Running Old Bird clip suppressor on " + dataset_name + ".") print('h5py version: {:s}'.format(h5py.__version__)) print('numpy version: {:s}'.format(np.__version__)) print('pandas version: {:s}'.format(pd.__version__)) print("") # Loop over units. for unit_str in units: # Define input and output folder. unit_dir = os.path.join(oldbird_models_dir, unit_str) in_predictions_name = "_".join(["predictions", "no-clip-suppressor"]) in_predictions_dir = os.path.join(unit_dir, in_predictions_name) out_predictions_name = "_".join(["predictions", "clip-suppressor"]) out_predictions_dir = os.path.join(unit_dir, out_predictions_name) os.makedirs(out_predictions_dir, exist_ok=True) # Loop over ODFs (Thrush and Tseep) for odf_str in odfs: # Define suppressor count threshold and period. oldbird_data_name = "_".join([dataset_name, "oldbird"]) oldbird_data_dir = os.path.join(data_dir, oldbird_data_name) oldbird_data_path = os.path.join(oldbird_data_dir, unit_str + ".hdf5") oldbird_hdf5 = h5py.File(oldbird_data_path, "r") settings_key = "_".join([odf_str, "settings"]) settings = oldbird_hdf5[settings_key] suppressor_count_threshold = settings["suppressor_count_threshold"].value suppressor_period = settings["suppressor_period"].value # Loop over thresholds. for threshold_id in range(n_thresholds): # Define input prediction path. threshold_str = "th-" + str(threshold_id).zfill(2) in_prediction_name = "_".join( [dataset_name, "oldbird", odf_str, unit_str, threshold_str, "predictions.csv"]) in_prediction_path = os.path.join( in_predictions_dir, in_prediction_name) # Define output prediction path. out_prediction_name = "_".join( [dataset_name, "oldbird", odf_str, unit_str, threshold_str, "predictions_clip-suppressor.csv"]) out_prediction_path = os.path.join( out_predictions_dir, out_prediction_name) # Read input CSV file as Pandas DataFrame. in_df = pd.read_csv(in_prediction_path) # Convert column of timestamps to NumPy array in_times = np.array(in_df["Time (s)"]) # Initialize variables. n_rows = len(in_times) n = 0 out_times = [] # Loop over rows. while n < (n_rows-suppressor_count_threshold): current_time = in_times[n] next_n = n + suppressor_count_threshold if next_n >= n_rows: break next_time = in_times[next_n] time_difference = next_time - current_time if time_difference < suppressor_period: while time_difference < suppressor_period: next_n = next_n + 1 if next_n >= n_rows: break next_time = in_times[next_n] time_difference = next_time - current_time n = next_n else: out_times.append(current_time) n = n + 1 # Select rows in input DataFrame. out_df = in_df[in_df["Time (s)"].isin(out_times)] # Replace clip_suppressor column. out_df["Clip suppressor"] = clip_suppressor_str # Export output DataFrame to CSV. out_df.to_csv(out_prediction_path) # Print elapsed time. print(str(datetime.datetime.now()) + " Finish.") elapsed_time = time.time() - int(start_time) elapsed_hours = int(elapsed_time / (60 * 60)) elapsed_minutes = int((elapsed_time % (60 * 60)) / 60) elapsed_seconds = elapsed_time % 60. elapsed_str = "{:>02}:{:>02}:{:>05.2f}".format(elapsed_hours, elapsed_minutes, elapsed_seconds) print("Total elapsed time: " + elapsed_str + ".")
[ "localmodule.get_units", "localmodule.get_data_dir", "os.makedirs", "pandas.read_csv", "os.path.join", "h5py.File", "datetime.datetime.now", "numpy.array", "time.time", "localmodule.get_dataset_name", "localmodule.get_models_dir" ]
[((153, 179), 'localmodule.get_data_dir', 'localmodule.get_data_dir', ([], {}), '()\n', (177, 179), False, 'import localmodule\n'), ((195, 225), 'localmodule.get_dataset_name', 'localmodule.get_dataset_name', ([], {}), '()\n', (223, 225), False, 'import localmodule\n'), ((239, 267), 'localmodule.get_models_dir', 'localmodule.get_models_dir', ([], {}), '()\n', (265, 267), False, 'import localmodule\n'), ((289, 324), 'os.path.join', 'os.path.join', (['models_dir', '"""oldbird"""'], {}), "(models_dir, 'oldbird')\n", (301, 324), False, 'import os\n'), ((333, 356), 'localmodule.get_units', 'localmodule.get_units', ([], {}), '()\n', (354, 356), False, 'import localmodule\n'), ((478, 489), 'time.time', 'time.time', ([], {}), '()\n', (487, 489), False, 'import time\n'), ((872, 914), 'os.path.join', 'os.path.join', (['oldbird_models_dir', 'unit_str'], {}), '(oldbird_models_dir, unit_str)\n', (884, 914), False, 'import os\n'), ((1014, 1057), 'os.path.join', 'os.path.join', (['unit_dir', 'in_predictions_name'], {}), '(unit_dir, in_predictions_name)\n', (1026, 1057), False, 'import os\n'), ((1156, 1200), 'os.path.join', 'os.path.join', (['unit_dir', 'out_predictions_name'], {}), '(unit_dir, out_predictions_name)\n', (1168, 1200), False, 'import os\n'), ((1205, 1252), 'os.makedirs', 'os.makedirs', (['out_predictions_dir'], {'exist_ok': '(True)'}), '(out_predictions_dir, exist_ok=True)\n', (1216, 1252), False, 'import os\n'), ((4250, 4261), 'time.time', 'time.time', ([], {}), '()\n', (4259, 4261), False, 'import time\n'), ((1467, 1508), 'os.path.join', 'os.path.join', (['data_dir', 'oldbird_data_name'], {}), '(data_dir, oldbird_data_name)\n', (1479, 1508), False, 'import os\n'), ((1537, 1587), 'os.path.join', 'os.path.join', (['oldbird_data_dir', "(unit_str + '.hdf5')"], {}), "(oldbird_data_dir, unit_str + '.hdf5')\n", (1549, 1587), False, 'import os\n'), ((1611, 1644), 'h5py.File', 'h5py.File', (['oldbird_data_path', '"""r"""'], {}), "(oldbird_data_path, 'r')\n", (1620, 1644), False, 'import h5py\n'), ((501, 524), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (522, 524), False, 'import datetime\n'), ((2270, 2322), 'os.path.join', 'os.path.join', (['in_predictions_dir', 'in_prediction_name'], {}), '(in_predictions_dir, in_prediction_name)\n', (2282, 2322), False, 'import os\n'), ((2593, 2647), 'os.path.join', 'os.path.join', (['out_predictions_dir', 'out_prediction_name'], {}), '(out_predictions_dir, out_prediction_name)\n', (2605, 2647), False, 'import os\n'), ((2741, 2772), 'pandas.read_csv', 'pd.read_csv', (['in_prediction_path'], {}), '(in_prediction_path)\n', (2752, 2772), True, 'import pandas as pd\n'), ((2855, 2882), 'numpy.array', 'np.array', (["in_df['Time (s)']"], {}), "(in_df['Time (s)'])\n", (2863, 2882), True, 'import numpy as np\n'), ((4196, 4219), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4217, 4219), False, 'import datetime\n')]
# -*- coding: utf8 -*- # My imports from __future__ import division import numpy as np from scipy.interpolate import InterpolatedUnivariateSpline import os from astropy.io import fits import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt def mad(data, axis=None): '''Function to calculate the median average deviation. ''' return np.median(np.absolute(data - np.median(data, axis)), axis) def local_norm(obs_fname, r, snr, lol=1.0, plot=False): '''Very local Normalization function. Makes a linear fit from the maximum points of each segment. Input ----- obs_fname : observations file r : range of the interval plot: True to visual check if normalization is correct, default: False Output ------ wave : wavelength new_flux : normalized flux delta_l : wavelenghth spacing ''' # Define the area of Normalization start_norm = r[0] - 1.0 end_norm = r[1] + 1.0 # Transform SNR to noise if snr is None: noise = 0.0 else: snr = float(snr) noise = 1.0 / snr # Read observations wave_obs, flux_obs, delta_l = read_observations(obs_fname, start_norm, end_norm) flux_obs = flux_obs / np.median(flux_obs) # Clean for cosmic rays med = np.median(flux_obs) sig = mad(flux_obs) flux_clean = np.where(flux_obs < (med + (sig * 3.0)), flux_obs, med) flux_obs = flux_clean # Normalization process pol_fit = np.polyfit(wave_obs, flux_obs, 1) fit_line = np.poly1d(pol_fit) for i in range(5): condition = flux_obs - fit_line(wave_obs) + noise > 0 cont_wl = wave_obs[condition] cont_fl = flux_obs[condition] pol_fit_new = np.polyfit(cont_wl, cont_fl, 1) fit_line = np.poly1d(pol_fit_new) new_flux = flux_obs / fit_line(wave_obs) # Cut to original region wave = wave_obs[np.where((wave_obs >= float(r[0])) & (wave_obs <= float(r[1])))] new_flux = new_flux[np.where((wave_obs >= float(r[0])) & (wave_obs <= float(r[1])))] # This plot is silent if plot: plt.plot(wave_obs, flux_obs, label='raw spectrum') plt.plot(cont_points_wl, cont_points_fl, 'o') plt.xlabel(r'Wavelength $\AA{}$') plt.ylabel('Normalized flux') plt.legend(loc='best', frameon=False) plt.grid(True) plt.show() x = [start_norm, end_norm] y = [1.0, 1.0] plt.plot(x, y) plt.plot(wave, new_flux, label='normalized') plt.xlabel(r'Wavelength $\AA{}$') plt.ylabel('Normalized flux') plt.legend(loc='best', frameon=False) plt.grid(True) plt.show() return wave, new_flux, delta_l def read_observations(fname, start_synth, end_synth): '''Read observed spectrum of different types and return wavelength and flux. Input ----- fname : filename of the spectrum. These are the approved formats: '.dat', '.txt', '.spec', '.fits'. start_synth : starting wavelength where the observed spectrum is cut end_synth : ending wavelength where the observed spectrum is cut Output ----- wave_obs : raw observed wavelength flux_obs : raw observed flux ''' extension = ('.dat', '.txt', '.spec', '.fits') if fname.endswith(extension): if (fname[-4:] == '.dat') or (fname[-4:] == '.txt'): with open(fname, 'r') as f: lines = (line for line in f if not line[0].isalpha()) # skip header wave, flux = np.loadtxt(lines, unpack=True, usecols=(0, 1)) elif fname[-5:] == '.fits': hdulist = fits.open(fname) header = hdulist[0].header # Only 1-D spectrum accepted. flux = hdulist[0].data # flux data in the primary flux = np.array(flux, dtype=np.float64) start_wave = header['CRVAL1'] # initial wavelenght # step = header['CD1_1'] # step in wavelenght step = header['CDELT1'] # increment per pixel n = len(flux) w = start_wave + step * n wave = np.linspace(start_wave, w, n, endpoint=False) # These types are produced by FASMA (fits format). elif fname[-5:] == '.spec': hdulist = fits.open(fname) x = hdulist[1].data flux = x['flux'] wave = x['wavelength'] # Cut observations to the intervals of the synthesis delta_l = wave[1] - wave[0] wave_obs = wave[ np.where((wave >= float(start_synth)) & (wave <= float(end_synth))) ] flux_obs = flux[ np.where((wave >= float(start_synth)) & (wave <= float(end_synth))) ] else: print('Spectrum is not in acceptable format. Convert to ascii or fits.') wave_obs, flux_obs, delta_l = (None, None, None) return wave_obs, flux_obs, delta_l def read_obs_intervals(obs_fname, r, snr=None): '''Read only the spectral chunks from the observed spectrum and normalize the regions. Input ----- fname : filename of the spectrum. r : ranges of wavelength intervals where the observed spectrum is cut (starting and ending wavelength) snr: signal-to-noise Output ----- xobs : observed normalized wavelength yobs : observed normalized flux delta_l : wavelenghth spacing ''' lol = 1.0 # This is here for no reason. Just for fun # Obtain the normalized spectrum for all regions spec = [local_norm(obs_fname, ri, snr, lol) for ri in r] xobs = np.hstack(np.vstack(spec).T[0]) yobs = np.hstack(np.vstack(spec).T[1]) delta_l = spec[0][2] if any(i == 0 for i in yobs): print('Warning: Flux contains 0 values.') print('SNR: %s' % snr) return xobs, yobs, delta_l def plot(xobs, yobs, xinit, yinit, xfinal, yfinal, res=False): '''Function to plot synthetic and observed spectra. Input ----- xobs : observed wavelength yobs : observed flux xinit : synthetic wavelength with initial parameters yinit : synthetic flux with initial parameters xfinal : synthetic wavelength with final parameters yfinal : synthetic flux with final parameters res: Flag to plot residuals Output ------ plots ''' # if nothing exists, pass if (xobs is None) and (xinit is None): pass # if there is not observed spectrum, plot only synthetic (case 1, 3) if xobs is None: plt.plot(xinit, yinit, label='synthetic') # if all exist else: plt.plot(xinit, yinit, label='initial synthetic') plt.plot(xobs, yobs, label='observed') if xfinal is not None: plt.plot(xfinal, yfinal, label='final synthetic') if res: sl = InterpolatedUnivariateSpline(xfinal, yfinal, k=1) ymodel = sl(xobs) plt.plot(xobs, (yobs - ymodel) * 10, label='residuals x10') plt.xlabel(r'Wavelength $\AA{}$') plt.ylabel('Normalized flux') plt.legend(loc='best', frameon=False) plt.grid(True) plt.show() return def snr(fname, plot=False): '''Calculate SNR using for various intervals. Input ---- fname : spectrum plot : plot snr fit Output ----- snr : snr value averaged from the continuum intervals ''' from PyAstronomy import pyasl def sub_snr(snr_region): '''Measure the SNR on a small interval Input ----- interval : list Upper and lower limit on wavelength Output ------ SNR : float The SNR in the small interval ''' w1, w2 = snr_region wave_cut, flux_cut, l = read_observations(fname, w1, w2) if len(wave_cut) == 0: num_points = 0 else: # Clean for cosmic rays med = np.median(flux_cut) sig = mad(flux_cut) flux_obs = np.where(flux_cut < (med + (sig * 3.0)), flux_cut, med) pol_fit = np.polyfit(wave_cut, flux_obs, 1) fit_line = np.poly1d(pol_fit) for i in range(5): condition = abs(flux_obs - fit_line(wave_cut)) < 3 * sig cont_points_wl = wave_cut[condition] cont_points_fl = flux_obs[condition] num_points = int(len(cont_points_fl) / 2.0) if num_points != 0: snrEstimate = pyasl.estimateSNR( cont_points_wl, cont_points_fl, num_points, deg=2, controlPlot=plot ) return snrEstimate["SNR-Estimate"] else: return 0 # These regions are relatively free from absorption. snr_regions = [ [5744, 5746], [6048, 6052], [6068, 6076], [6682, 6686], [6649, 6652], [6614, 6616], [5438.5, 5440], [5449.5, 5051], [5458, 5459.25], [5498.3, 5500], [5541.5, 5542.5], ] snr = [sub_snr(snr_region) for snr_region in snr_regions] if len(snr): snr = [value for value in snr if value != 0] snr_clean = [value for value in snr if not np.isnan(value)] snr_total = np.median(snr_clean) snr = int(snr_total) return snr else: return None
[ "matplotlib.pyplot.grid", "numpy.polyfit", "matplotlib.pyplot.ylabel", "numpy.array", "PyAstronomy.pyasl.estimateSNR", "astropy.io.fits.open", "numpy.poly1d", "numpy.where", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.linspace", "numpy.vstack", "matplotlib.use", "numpy.isn...
[((204, 227), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (218, 227), False, 'import matplotlib\n'), ((1285, 1304), 'numpy.median', 'np.median', (['flux_obs'], {}), '(flux_obs)\n', (1294, 1304), True, 'import numpy as np\n'), ((1346, 1397), 'numpy.where', 'np.where', (['(flux_obs < med + sig * 3.0)', 'flux_obs', 'med'], {}), '(flux_obs < med + sig * 3.0, flux_obs, med)\n', (1354, 1397), True, 'import numpy as np\n'), ((1471, 1504), 'numpy.polyfit', 'np.polyfit', (['wave_obs', 'flux_obs', '(1)'], {}), '(wave_obs, flux_obs, 1)\n', (1481, 1504), True, 'import numpy as np\n'), ((1520, 1538), 'numpy.poly1d', 'np.poly1d', (['pol_fit'], {}), '(pol_fit)\n', (1529, 1538), True, 'import numpy as np\n'), ((6926, 6959), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Wavelength $\\\\AA{}$"""'], {}), "('Wavelength $\\\\AA{}$')\n", (6936, 6959), True, 'import matplotlib.pyplot as plt\n'), ((6964, 6993), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Normalized flux"""'], {}), "('Normalized flux')\n", (6974, 6993), True, 'import matplotlib.pyplot as plt\n'), ((6998, 7035), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'frameon': '(False)'}), "(loc='best', frameon=False)\n", (7008, 7035), True, 'import matplotlib.pyplot as plt\n'), ((7040, 7054), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (7048, 7054), True, 'import matplotlib.pyplot as plt\n'), ((7059, 7069), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7067, 7069), True, 'import matplotlib.pyplot as plt\n'), ((1227, 1246), 'numpy.median', 'np.median', (['flux_obs'], {}), '(flux_obs)\n', (1236, 1246), True, 'import numpy as np\n'), ((1722, 1753), 'numpy.polyfit', 'np.polyfit', (['cont_wl', 'cont_fl', '(1)'], {}), '(cont_wl, cont_fl, 1)\n', (1732, 1753), True, 'import numpy as np\n'), ((1773, 1795), 'numpy.poly1d', 'np.poly1d', (['pol_fit_new'], {}), '(pol_fit_new)\n', (1782, 1795), True, 'import numpy as np\n'), ((2093, 2143), 'matplotlib.pyplot.plot', 'plt.plot', (['wave_obs', 'flux_obs'], {'label': '"""raw spectrum"""'}), "(wave_obs, flux_obs, label='raw spectrum')\n", (2101, 2143), True, 'import matplotlib.pyplot as plt\n'), ((2152, 2197), 'matplotlib.pyplot.plot', 'plt.plot', (['cont_points_wl', 'cont_points_fl', '"""o"""'], {}), "(cont_points_wl, cont_points_fl, 'o')\n", (2160, 2197), True, 'import matplotlib.pyplot as plt\n'), ((2206, 2239), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Wavelength $\\\\AA{}$"""'], {}), "('Wavelength $\\\\AA{}$')\n", (2216, 2239), True, 'import matplotlib.pyplot as plt\n'), ((2248, 2277), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Normalized flux"""'], {}), "('Normalized flux')\n", (2258, 2277), True, 'import matplotlib.pyplot as plt\n'), ((2286, 2323), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'frameon': '(False)'}), "(loc='best', frameon=False)\n", (2296, 2323), True, 'import matplotlib.pyplot as plt\n'), ((2332, 2346), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2340, 2346), True, 'import matplotlib.pyplot as plt\n'), ((2355, 2365), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2363, 2365), True, 'import matplotlib.pyplot as plt\n'), ((2433, 2447), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (2441, 2447), True, 'import matplotlib.pyplot as plt\n'), ((2456, 2500), 'matplotlib.pyplot.plot', 'plt.plot', (['wave', 'new_flux'], {'label': '"""normalized"""'}), "(wave, new_flux, label='normalized')\n", (2464, 2500), True, 'import matplotlib.pyplot as plt\n'), ((2509, 2542), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Wavelength $\\\\AA{}$"""'], {}), "('Wavelength $\\\\AA{}$')\n", (2519, 2542), True, 'import matplotlib.pyplot as plt\n'), ((2551, 2580), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Normalized flux"""'], {}), "('Normalized flux')\n", (2561, 2580), True, 'import matplotlib.pyplot as plt\n'), ((2589, 2626), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'frameon': '(False)'}), "(loc='best', frameon=False)\n", (2599, 2626), True, 'import matplotlib.pyplot as plt\n'), ((2635, 2649), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2643, 2649), True, 'import matplotlib.pyplot as plt\n'), ((2658, 2668), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2666, 2668), True, 'import matplotlib.pyplot as plt\n'), ((6468, 6509), 'matplotlib.pyplot.plot', 'plt.plot', (['xinit', 'yinit'], {'label': '"""synthetic"""'}), "(xinit, yinit, label='synthetic')\n", (6476, 6509), True, 'import matplotlib.pyplot as plt\n'), ((6547, 6596), 'matplotlib.pyplot.plot', 'plt.plot', (['xinit', 'yinit'], {'label': '"""initial synthetic"""'}), "(xinit, yinit, label='initial synthetic')\n", (6555, 6596), True, 'import matplotlib.pyplot as plt\n'), ((6605, 6643), 'matplotlib.pyplot.plot', 'plt.plot', (['xobs', 'yobs'], {'label': '"""observed"""'}), "(xobs, yobs, label='observed')\n", (6613, 6643), True, 'import matplotlib.pyplot as plt\n'), ((9156, 9176), 'numpy.median', 'np.median', (['snr_clean'], {}), '(snr_clean)\n', (9165, 9176), True, 'import numpy as np\n'), ((6687, 6736), 'matplotlib.pyplot.plot', 'plt.plot', (['xfinal', 'yfinal'], {'label': '"""final synthetic"""'}), "(xfinal, yfinal, label='final synthetic')\n", (6695, 6736), True, 'import matplotlib.pyplot as plt\n'), ((6770, 6819), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpolatedUnivariateSpline', (['xfinal', 'yfinal'], {'k': '(1)'}), '(xfinal, yfinal, k=1)\n', (6798, 6819), False, 'from scipy.interpolate import InterpolatedUnivariateSpline\n'), ((6862, 6921), 'matplotlib.pyplot.plot', 'plt.plot', (['xobs', '((yobs - ymodel) * 10)'], {'label': '"""residuals x10"""'}), "(xobs, (yobs - ymodel) * 10, label='residuals x10')\n", (6870, 6921), True, 'import matplotlib.pyplot as plt\n'), ((7846, 7865), 'numpy.median', 'np.median', (['flux_cut'], {}), '(flux_cut)\n', (7855, 7865), True, 'import numpy as np\n'), ((7921, 7972), 'numpy.where', 'np.where', (['(flux_cut < med + sig * 3.0)', 'flux_cut', 'med'], {}), '(flux_cut < med + sig * 3.0, flux_cut, med)\n', (7929, 7972), True, 'import numpy as np\n'), ((7999, 8032), 'numpy.polyfit', 'np.polyfit', (['wave_cut', 'flux_obs', '(1)'], {}), '(wave_cut, flux_obs, 1)\n', (8009, 8032), True, 'import numpy as np\n'), ((8056, 8074), 'numpy.poly1d', 'np.poly1d', (['pol_fit'], {}), '(pol_fit)\n', (8065, 8074), True, 'import numpy as np\n'), ((8396, 8486), 'PyAstronomy.pyasl.estimateSNR', 'pyasl.estimateSNR', (['cont_points_wl', 'cont_points_fl', 'num_points'], {'deg': '(2)', 'controlPlot': 'plot'}), '(cont_points_wl, cont_points_fl, num_points, deg=2,\n controlPlot=plot)\n', (8413, 8486), False, 'from PyAstronomy import pyasl\n'), ((396, 417), 'numpy.median', 'np.median', (['data', 'axis'], {}), '(data, axis)\n', (405, 417), True, 'import numpy as np\n'), ((3515, 3561), 'numpy.loadtxt', 'np.loadtxt', (['lines'], {'unpack': '(True)', 'usecols': '(0, 1)'}), '(lines, unpack=True, usecols=(0, 1))\n', (3525, 3561), True, 'import numpy as np\n'), ((3620, 3636), 'astropy.io.fits.open', 'fits.open', (['fname'], {}), '(fname)\n', (3629, 3636), False, 'from astropy.io import fits\n'), ((3800, 3832), 'numpy.array', 'np.array', (['flux'], {'dtype': 'np.float64'}), '(flux, dtype=np.float64)\n', (3808, 3832), True, 'import numpy as np\n'), ((4097, 4142), 'numpy.linspace', 'np.linspace', (['start_wave', 'w', 'n'], {'endpoint': '(False)'}), '(start_wave, w, n, endpoint=False)\n', (4108, 4142), True, 'import numpy as np\n'), ((5562, 5577), 'numpy.vstack', 'np.vstack', (['spec'], {}), '(spec)\n', (5571, 5577), True, 'import numpy as np\n'), ((5605, 5620), 'numpy.vstack', 'np.vstack', (['spec'], {}), '(spec)\n', (5614, 5620), True, 'import numpy as np\n'), ((4260, 4276), 'astropy.io.fits.open', 'fits.open', (['fname'], {}), '(fname)\n', (4269, 4276), False, 'from astropy.io import fits\n'), ((9119, 9134), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (9127, 9134), True, 'import numpy as np\n')]
import gym import argparse import sys import os import csv import numpy as np from collections import deque from agents.dqn import DQNAgent from agents.ddqn import DDQNAgent from agents.duelingddqn import DuelingDDQNAgent from agents.perddqn import PERDDQNAgent from agents.test import TestAgent class Game: def __init__(self): game, model, render, episode_limit, batch_size, target_score, test_model = self._args() self.env = gym.make(game) self.render = render self.episode_limit = episode_limit self.batch_size = batch_size self.target_score = target_score self.observation_space = self.env.observation_space.shape[0] self.action_space = self.env.action_space.n self.agent = DQNAgent(game, self.observation_space, self.action_space) self.save_name = str(game) + '_' + str(model.lower()) + '/' + str(game) + '_' + str(model.lower()) if model.lower() == 'dqn': self.agent = DQNAgent(game, self.observation_space, self.action_space) elif model.lower() == 'ddqn': self.agent = DDQNAgent(game, self.observation_space, self.action_space) elif model.lower() == 'duelingddqn': self.agent = DuelingDDQNAgent(game, self.observation_space, self.action_space) elif model.lower() == 'perddqn': self.agent = PERDDQNAgent(game, self.observation_space, self.action_space) elif model.lower() == 'test': self.agent = TestAgent(game, self.observation_space, self.action_space) self.history = [('episode', 'score', 'average_score', 'steps', 'total_steps')] if test_model: self.agent.load_model(test_model) self.test() else: # make a directory to hold the saved files from this run if it doesn't exist try: os.mkdir(str(game) + '_' + str(model.lower())) except FileExistsError: pass self.train() def train(self): try: score_history = deque(maxlen=100) total_steps = 0 for episode in range(self.episode_limit): # reset state at beginning of game state = self.env.reset() state = np.reshape(state, [1, self.observation_space]) step = 0 score = 0 while True: # increment step for each frame step += 1 total_steps += 1 # render game if self.render: self.env.render() # decide what action to take action = self.agent.act(state) # advance game to next frame based on the chosen action next_state, reward, done, _ = self.env.step(action) next_state = np.reshape(next_state, [1, self.observation_space]) # adjust score score += reward # add to memory self.agent.remember(state, action, reward, next_state, done) # train agent with experience self.agent.replay(total_steps, self.batch_size) if done: score_history.append(score) average_score = np.mean(score_history) self.history.append((episode, score, average_score, step, total_steps)) # print episode, score, steps, and total steps and break loop print("Episode: {}/{}, Score: {}, Average Score: {:.2f}, Steps: {}, Total Steps: {}".format(episode, self.episode_limit, score, average_score, step, total_steps)) # check if goal has been met if self.target_score and average_score >= self.target_score: print('Target score reached after {} episodes and {} total steps!'.format(episode, total_steps)) filename = self.save_name + '_final.h5' print('Saving final model to ' + filename) self.agent.save_model(filename) self.exit() break # if not done make the next state the current state for the next iteration state = next_state # save model every 500 episodes if episode % 100 == 0: filename = self.save_name + '_' + str(episode) + '.h5' print('Saving model to ' + filename) self.agent.save_model(filename) self.exit() except KeyboardInterrupt: # Catch ctrl-c and gracefully end game filename = self.save_name + '_final.h5' print('Saving model to ' + filename) self.agent.save_model(filename) self.exit() except: self.env.close() sys.exit() def test(self): try: score_history = deque(maxlen=100) total_steps = 0 for episode in range(100): # reset state at beginning of game state = self.env.reset() state = np.reshape(state, [1, self.observation_space]) step = 0 score = 0 while True: # increment step for each frame step += 1 total_steps += 1 # render game if self.render: self.env.render() # decide what action to take action = self.agent.test_act(state) # advance game to next frame based on the chosen action next_state, reward, done, _ = self.env.step(action) next_state = np.reshape(next_state, [1, self.observation_space]) # adjust score score += reward if done: score_history.append(score) average_score = np.mean(score_history) self.history.append((episode, score, average_score, step, total_steps)) # print episode, score, steps, and total steps and break loop print("Episode: {}/99, Score: {}, Average Score: {:.2f}, Steps: {}, Total Steps: {}".format(episode, score, average_score, step, total_steps)) break # if not done make the next state the current state for the next iteration state = next_state self.env.close() except: # Catch ctrl-c and gracefully end game print('Killing game') self.env.close() sys.exit() def exit(self): filename = self.save_name + '_history.csv' print('Saving training history to csv ' + filename) with open(filename, 'w') as out: csv_out = csv.writer(out) for row in self.history: csv_out.writerow(row) print('Killing game') self.env.close() sys.exit() def _args(self): parser = argparse.ArgumentParser() parser.add_argument('-g', '--game', help='Name of the Open AI Gym game to play', default='CartPole-v1') parser.add_argument('-m', '--model', help='Name of the model agent to use', default='dqn') parser.add_argument('-r', '--render', help='Whether to render the game or not', default=False, type=bool) parser.add_argument('-el', '--episode_limit', help='Number of episodes to run', default=5000, type=int) parser.add_argument('-bs', '--batch_size', help='Batch size to use', default=32, type=int) parser.add_argument('-ts', '--target_score', help='Target average score over last 100 episodes to stop after reaching', default=None, type=int) parser.add_argument('-tm', '--test_model', help='Filename of model weights to test performance of', default=None) args = parser.parse_args() game = args.game model = args.model render = args.render episode_limit = args.episode_limit batch_size = args.batch_size target_score = args.target_score test_model = args.test_model return game, model, render, episode_limit, batch_size, target_score, test_model if __name__ == '__main__': Game()
[ "numpy.mean", "collections.deque", "numpy.reshape", "argparse.ArgumentParser", "csv.writer", "agents.duelingddqn.DuelingDDQNAgent", "agents.test.TestAgent", "agents.ddqn.DDQNAgent", "agents.perddqn.PERDDQNAgent", "sys.exit", "agents.dqn.DQNAgent", "gym.make" ]
[((449, 463), 'gym.make', 'gym.make', (['game'], {}), '(game)\n', (457, 463), False, 'import gym\n'), ((756, 813), 'agents.dqn.DQNAgent', 'DQNAgent', (['game', 'self.observation_space', 'self.action_space'], {}), '(game, self.observation_space, self.action_space)\n', (764, 813), False, 'from agents.dqn import DQNAgent\n'), ((7296, 7306), 'sys.exit', 'sys.exit', ([], {}), '()\n', (7304, 7306), False, 'import sys\n'), ((7346, 7371), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (7369, 7371), False, 'import argparse\n'), ((981, 1038), 'agents.dqn.DQNAgent', 'DQNAgent', (['game', 'self.observation_space', 'self.action_space'], {}), '(game, self.observation_space, self.action_space)\n', (989, 1038), False, 'from agents.dqn import DQNAgent\n'), ((2055, 2072), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (2060, 2072), False, 'from collections import deque\n'), ((5134, 5151), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (5139, 5151), False, 'from collections import deque\n'), ((7142, 7157), 'csv.writer', 'csv.writer', (['out'], {}), '(out)\n', (7152, 7157), False, 'import csv\n'), ((1102, 1160), 'agents.ddqn.DDQNAgent', 'DDQNAgent', (['game', 'self.observation_space', 'self.action_space'], {}), '(game, self.observation_space, self.action_space)\n', (1111, 1160), False, 'from agents.ddqn import DDQNAgent\n'), ((2271, 2317), 'numpy.reshape', 'np.reshape', (['state', '[1, self.observation_space]'], {}), '(state, [1, self.observation_space])\n', (2281, 2317), True, 'import numpy as np\n'), ((5061, 5071), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5069, 5071), False, 'import sys\n'), ((5335, 5381), 'numpy.reshape', 'np.reshape', (['state', '[1, self.observation_space]'], {}), '(state, [1, self.observation_space])\n', (5345, 5381), True, 'import numpy as np\n'), ((6936, 6946), 'sys.exit', 'sys.exit', ([], {}), '()\n', (6944, 6946), False, 'import sys\n'), ((1231, 1296), 'agents.duelingddqn.DuelingDDQNAgent', 'DuelingDDQNAgent', (['game', 'self.observation_space', 'self.action_space'], {}), '(game, self.observation_space, self.action_space)\n', (1247, 1296), False, 'from agents.duelingddqn import DuelingDDQNAgent\n'), ((2912, 2963), 'numpy.reshape', 'np.reshape', (['next_state', '[1, self.observation_space]'], {}), '(next_state, [1, self.observation_space])\n', (2922, 2963), True, 'import numpy as np\n'), ((5981, 6032), 'numpy.reshape', 'np.reshape', (['next_state', '[1, self.observation_space]'], {}), '(next_state, [1, self.observation_space])\n', (5991, 6032), True, 'import numpy as np\n'), ((1363, 1424), 'agents.perddqn.PERDDQNAgent', 'PERDDQNAgent', (['game', 'self.observation_space', 'self.action_space'], {}), '(game, self.observation_space, self.action_space)\n', (1375, 1424), False, 'from agents.perddqn import PERDDQNAgent\n'), ((3395, 3417), 'numpy.mean', 'np.mean', (['score_history'], {}), '(score_history)\n', (3402, 3417), True, 'import numpy as np\n'), ((6227, 6249), 'numpy.mean', 'np.mean', (['score_history'], {}), '(score_history)\n', (6234, 6249), True, 'import numpy as np\n'), ((1488, 1546), 'agents.test.TestAgent', 'TestAgent', (['game', 'self.observation_space', 'self.action_space'], {}), '(game, self.observation_space, self.action_space)\n', (1497, 1546), False, 'from agents.test import TestAgent\n')]
"""Data frame seleção condicional""" import pandas as pd import numpy as np from numpy.random import randn SEPARATOR = '#' * 40 np.random.seed(50) df = pd.DataFrame(randn(5,4), index='A B C D E'.split(), columns='W X Y Z'.split()) print(df) """print(SEPARATOR) bol = df > 0 # verificando se os index são maior que 0 print(bol) print(SEPARATOR) # resetando o index df.reset_index() print(df) # para ficar fixo o resete, é necessário passar como parâmetro o inplace=True print(SEPARATOR) df.reset_index(inplace=True) print(df) print(SEPARATOR) """ # inserindo uma nova coluna no df col = 'SP SC RJ BH PE'.split() print(col) df['Estado'] = col print(df) print(SEPARATOR) """ # inserindo a coluna nova Estado como index, deixando ela em primeiro df.set_index('Estado', inplace=True) print(df) print(SEPARATOR) """
[ "numpy.random.randn", "numpy.random.seed" ]
[((132, 150), 'numpy.random.seed', 'np.random.seed', (['(50)'], {}), '(50)\n', (146, 150), True, 'import numpy as np\n'), ((170, 181), 'numpy.random.randn', 'randn', (['(5)', '(4)'], {}), '(5, 4)\n', (175, 181), False, 'from numpy.random import randn\n')]
import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import dash_katex import numpy as np import plotly.express as px from scipy import stats from app import app layout = html.Div([ dash_katex.DashKatex( expression=r''' f_X(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x - \mu)^2}{2\sigma^2}\right) ''', displayMode=True ), dcc.Graph(id='normal_graph'), dash_katex.DashKatex(expression=r'\mu'), dcc.Slider( id='normal_mean', value=0, min=-5, max=5, marks={x: str(x) for x in range(-5, 6)}, step=0.01, tooltip={'placement': 'top'} ), dash_katex.DashKatex(expression=r'\sigma^2'), dcc.Slider( id='normal_variance', value=1, min=0.01, max=10, marks={x: str(x) for x in range(11)}, step=0.01, tooltip={'placement': 'top'} ) ]) @app.callback( Output('normal_graph', 'figure'), [Input('normal_mean', 'value'), Input('normal_variance', 'value')] ) def plot(mean, variance): std = np.sqrt(variance) x = np.linspace(-10, 10, 1000) y = stats.norm.pdf(x, mean, std) range_x = [-10, 10] range_y = [-0.2, max(1.2, max(y) + 0.2)] figure = px.line(x=x, y=y, range_x=range_x, range_y=range_y) return figure
[ "numpy.sqrt", "dash.dependencies.Output", "dash.dependencies.Input", "plotly.express.line", "numpy.linspace", "scipy.stats.norm.pdf", "dash_katex.DashKatex", "dash_core_components.Graph" ]
[((1162, 1179), 'numpy.sqrt', 'np.sqrt', (['variance'], {}), '(variance)\n', (1169, 1179), True, 'import numpy as np\n'), ((1188, 1214), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', '(1000)'], {}), '(-10, 10, 1000)\n', (1199, 1214), True, 'import numpy as np\n'), ((1223, 1251), 'scipy.stats.norm.pdf', 'stats.norm.pdf', (['x', 'mean', 'std'], {}), '(x, mean, std)\n', (1237, 1251), False, 'from scipy import stats\n'), ((1334, 1385), 'plotly.express.line', 'px.line', ([], {'x': 'x', 'y': 'y', 'range_x': 'range_x', 'range_y': 'range_y'}), '(x=x, y=y, range_x=range_x, range_y=range_y)\n', (1341, 1385), True, 'import plotly.express as px\n'), ((1014, 1046), 'dash.dependencies.Output', 'Output', (['"""normal_graph"""', '"""figure"""'], {}), "('normal_graph', 'figure')\n", (1020, 1046), False, 'from dash.dependencies import Input, Output\n'), ((252, 449), 'dash_katex.DashKatex', 'dash_katex.DashKatex', ([], {'expression': '"""\n f_X(x) = \\\\frac{1}{\\\\sqrt{2\\\\pi\\\\sigma^2}}\n \\\\exp\\\\left(-\\\\frac{(x - \\\\mu)^2}{2\\\\sigma^2}\\\\right)\n """', 'displayMode': '(True)'}), '(expression=\n """\n f_X(x) = \\\\frac{1}{\\\\sqrt{2\\\\pi\\\\sigma^2}}\n \\\\exp\\\\left(-\\\\frac{(x - \\\\mu)^2}{2\\\\sigma^2}\\\\right)\n """\n , displayMode=True)\n', (272, 449), False, 'import dash_katex\n'), ((458, 486), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""normal_graph"""'}), "(id='normal_graph')\n", (467, 486), True, 'import dash_core_components as dcc\n'), ((492, 531), 'dash_katex.DashKatex', 'dash_katex.DashKatex', ([], {'expression': '"""\\\\mu"""'}), "(expression='\\\\mu')\n", (512, 531), False, 'import dash_katex\n'), ((739, 783), 'dash_katex.DashKatex', 'dash_katex.DashKatex', ([], {'expression': '"""\\\\sigma^2"""'}), "(expression='\\\\sigma^2')\n", (759, 783), False, 'import dash_katex\n'), ((1053, 1082), 'dash.dependencies.Input', 'Input', (['"""normal_mean"""', '"""value"""'], {}), "('normal_mean', 'value')\n", (1058, 1082), False, 'from dash.dependencies import Input, Output\n'), ((1089, 1122), 'dash.dependencies.Input', 'Input', (['"""normal_variance"""', '"""value"""'], {}), "('normal_variance', 'value')\n", (1094, 1122), False, 'from dash.dependencies import Input, Output\n')]
import os from copy import deepcopy import dill import numpy as np import pyspiel from darkhex.utils.cell_state import cellState def cell_connections(cell, num_cols, num_rows): """ Returns the neighbours of the given cell. args: cell - The location on the board to check the neighboring cells for. returns: positions - List of all the neighbouring cells to the cell. Elements are in the format [row, column]. """ row = cell // num_cols col = cell % num_cols positions = [] if col + 1 < num_cols: positions.append(pos_by_coord(num_cols, row, col + 1)) if col - 1 >= 0: positions.append(pos_by_coord(num_cols, row, col - 1)) if row + 1 < num_rows: positions.append(pos_by_coord(num_cols, row + 1, col)) if col - 1 >= 0: positions.append(pos_by_coord(num_cols, row + 1, col - 1)) if row - 1 >= 0: positions.append(pos_by_coord(num_cols, row - 1, col)) if col + 1 < num_cols: positions.append(pos_by_coord(num_cols, row - 1, col + 1)) return positions def game_over(board_state): """ Check if the game is over. - board_state: The current refree board state. """ return (board_state.count(cellState.kBlackWin) + board_state.count(cellState.kWhiteWin) == 1) def updated_board(board_state, cell, color, num_rows, num_cols): """ Update the board state with the move. - board_state: The current board state. - move: The move to be made. (int) - piece: The piece to be placed on the board. """ # Work on a list version of the board state. updated_board_state = list(deepcopy(board_state)) # If the move is illegal return false. # - Illegal if the move is out of bounds. # - Illegal if the move is already taken. if (cell < 0 or cell >= len(updated_board_state) or updated_board_state[cell] != cellState.kEmpty): return False # Update the board state with the move. if color == cellState.kBlack: north_connected = False south_connected = False if cell < num_cols: # First row north_connected = True elif cell >= num_cols * (num_rows - 1): # Last row south_connected = True for neighbour in cell_connections(cell, num_cols, num_rows): if updated_board_state[neighbour] == cellState.kBlackNorth: north_connected = True elif updated_board_state[neighbour] == cellState.kBlackSouth: south_connected = True if north_connected and south_connected: updated_board_state[cell] = cellState.kBlackWin elif north_connected: updated_board_state[cell] = cellState.kBlackNorth elif south_connected: updated_board_state[cell] = cellState.kBlackSouth else: updated_board_state[cell] = cellState.kBlack elif color == cellState.kWhite: east_connected = False west_connected = False if cell % num_cols == 0: # First column west_connected = True elif cell % num_cols == num_cols - 1: # Last column east_connected = True for neighbour in cell_connections(cell, num_cols, num_rows): if updated_board_state[neighbour] == cellState.kWhiteWest: west_connected = True elif updated_board_state[neighbour] == cellState.kWhiteEast: east_connected = True if east_connected and west_connected: updated_board_state[cell] = cellState.kWhiteWin elif east_connected: updated_board_state[cell] = cellState.kWhiteEast elif west_connected: updated_board_state[cell] = cellState.kWhiteWest else: updated_board_state[cell] = cellState.kWhite if updated_board_state[cell] in [cellState.kBlackWin, cellState.kWhiteWin]: return updated_board_state[cell] elif updated_board_state[cell] not in [cellState.kBlack, cellState.kWhite]: # The cell is connected to an edge but not a win position. # We need to use flood-fill to find the connected edges. flood_stack = [cell] latest_cell = 0 while len(flood_stack) != 0: latest_cell = flood_stack.pop() for neighbour in cell_connections(latest_cell, num_cols, num_rows): if updated_board_state[neighbour] == color: updated_board_state[neighbour] = updated_board_state[cell] flood_stack.append(neighbour) # Flood-fill is complete. # Convert list back to string return "".join(updated_board_state) def replace_action(board, action, new_value): """ Replaces the action on the board with the new value. """ new_board = list(deepcopy(board)) new_board[action] = new_value return "".join(new_board) def play_action(game, player, action): """ Plays the action on the game board. """ new_game = deepcopy(game) if new_game["board"][action] != cellState.kEmpty: opponent = cellState.kBlack if player == cellState.kWhite else cellState.kWhite new_game["boards"][player] = replace_action(new_game["boards"][player], action, opponent) return new_game, True else: res = updated_board(new_game["board"], action, player, game["num_cols"], game["num_rows"]) if res == cellState.kBlackWin or res == cellState.kWhiteWin: # The game is over. return res, False new_game["board"] = res new_game["boards"][player] = replace_action(new_game["boards"][player], action, new_game["board"][action]) s = "" opponent = cellState.kBlack if player == cellState.kWhite else cellState.kWhite for r in new_game["boards"][player]: if r in cellState.black_pieces: s += cellState.kBlack elif r in cellState.white_pieces: s += cellState.kWhite else: s += r new_game["boards"][player] = s return new_game, False def load_file(filename): """ Loads a file and returns the content. """ try: return dill.load(open(filename, "rb")) except IOError: raise IOError(f"File not found: {filename}") def save_file(content, file_path): """ Saves the content to a file. """ # Create the directory if it doesn't exist. directory = os.path.dirname(file_path) if not os.path.exists(directory): os.makedirs(directory) dill.dump(content, open(file_path, "wb")) def pos_by_coord(num_cols, r, c): return num_cols * r + c def conv_alphapos(pos, num_cols): """ Converts a position to a letter and number pos: int """ col = pos % num_cols row = pos // num_cols return "{}{}".format(chr(ord("a") + col), row + 1) def greedify(strategy, multiple_actions_allowed=False): """ Greedifies the given strategy. -1 is the minumum value and 1 is the maximum. Args: strategy: The strategy to greedify. multiple_actions_allowed: Whether multiple actions are allowed. Returns: A greedified version of the strategy. """ greedy_strategy = {} for board_state, action_val in strategy.items(): mx_value = -1 actions = [] for action, value in action_val.items(): if value > mx_value: mx_value = value actions = [action] elif value == mx_value and multiple_actions_allowed: actions.append(action) greedy_strategy[board_state] = [ (actions[i], 1 / len(actions)) for i in range(len(actions)) ] return greedy_strategy def calculate_turn(state: str): """ Calculates which player's turn it is given board state. """ num_black = 0 num_white = 0 for cell in state: if cell in cellState.black_pieces: num_black += 1 elif cell in cellState.white_pieces: num_white += 1 return 1 if num_black > num_white else 0 def num_action(action, num_cols): """ Converts the action in the form of alpha-numeric row column sequence to numeric actions. i.e. a2 -> 3 for 3x3 board. """ # If not alpha-numeric, return the action as is. action = action.lower().strip() try: if not action[0].isalpha(): return action row = int(action[1:]) - 1 # for column a -> 0, b -> 1 ... col = ord(action[0]) - ord("a") return pos_by_coord(num_cols, row, col) except ValueError: log.error("Invalid action: {}".format(action)) return False def random_selection(board_state): pos_moves = [i for i, x in enumerate(board_state) if x == cellState.kEmpty] return [np.random.choice(pos_moves)], [1.0] def convert_to_xo(str_board): """ Convert the board state to only x and o. """ for p in cellState.black_pieces: str_board = str_board.replace(p, cellState.kBlack) for p in cellState.white_pieces: str_board = str_board.replace(p, cellState.kWhite) return str_board def get_open_spiel_state(game: pyspiel.Game, initial_state: str) -> pyspiel.State: """ Setup the game state, -start is same as given initial state """ game_state = game.new_initial_state() black_stones_loc = [] white_stones_loc = [] for i in range(len(initial_state)): if initial_state[i] in cellState.black_pieces: black_stones_loc.append(i) if initial_state[i] in cellState.white_pieces: white_stones_loc.append(i) black_loc = 0 white_loc = 0 for _ in range(len(black_stones_loc) + len(white_stones_loc)): cur_player = game_state.current_player() if cur_player == 0: game_state.apply_action(black_stones_loc[black_loc]) game_state.apply_action(black_stones_loc[black_loc]) black_loc += 1 else: game_state.apply_action(white_stones_loc[white_loc]) game_state.apply_action(white_stones_loc[white_loc]) white_loc += 1 return game_state def convert_os_str(str_board: str, num_cols: int, player: int = -1): """ Convert the board state to pyspiel format. ie. P{player} firstrowsecondrow """ if player == -1: new_board = "" else: new_board = f"P{player} " for i, cell in enumerate(str_board): if cell in cellState.black_pieces: new_board += cellState.kBlack elif cell in cellState.white_pieces: new_board += cellState.kWhite else: new_board += cellState.kEmpty return new_board def convert_os_strategy(strategy: dict, num_cols: int, player: int) -> dict: """ Convert the strategy from open_spiel to the format of the game. """ new_strat = {} for board_state, actions in strategy.items(): new_strat[convert_os_str(board_state, num_cols, player)] = actions return new_strat class dotdict(dict): """dict with dot access""" __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def safe_normalize(y, out=None): """ Returns +y+/||+y+||_1 or indmax y if ||+y+||_1 = 0. Assumes that +y+ >= 0. """ if out is None: out = y.copy() z = np.sum(y) if z > 0: out[:] = y / z else: a = y.argmax() out[:] = 0 out[a] = 1. return out def flood_fill(state: list, init_pos: int, num_rows: int, num_cols: int) -> list: player = cellState.kBlack \ if state[init_pos] in cellState.black_pieces \ else cellState.kWhite flood_stack = [init_pos] while len(flood_stack) > 0: latest_cell = flood_stack.pop() for n in cell_connections(latest_cell, num_cols, num_rows): if state[n] == player: state[n] = state[latest_cell] flood_stack.append(n) return state def convert_to_infostate(board_state: str, player: int) -> str: board_ls = list(board_state) board_ls.insert(0, "P{} ".format(player)) return "".join(board_ls)
[ "os.path.exists", "os.makedirs", "numpy.random.choice", "os.path.dirname", "numpy.sum", "copy.deepcopy" ]
[((5063, 5077), 'copy.deepcopy', 'deepcopy', (['game'], {}), '(game)\n', (5071, 5077), False, 'from copy import deepcopy\n'), ((6708, 6734), 'os.path.dirname', 'os.path.dirname', (['file_path'], {}), '(file_path)\n', (6723, 6734), False, 'import os\n'), ((11677, 11686), 'numpy.sum', 'np.sum', (['y'], {}), '(y)\n', (11683, 11686), True, 'import numpy as np\n'), ((1697, 1718), 'copy.deepcopy', 'deepcopy', (['board_state'], {}), '(board_state)\n', (1705, 1718), False, 'from copy import deepcopy\n'), ((4870, 4885), 'copy.deepcopy', 'deepcopy', (['board'], {}), '(board)\n', (4878, 4885), False, 'from copy import deepcopy\n'), ((6746, 6771), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (6760, 6771), False, 'import os\n'), ((6781, 6803), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (6792, 6803), False, 'import os\n'), ((9080, 9107), 'numpy.random.choice', 'np.random.choice', (['pos_moves'], {}), '(pos_moves)\n', (9096, 9107), True, 'import numpy as np\n')]
# Code modified from https://github.com/seungeunrho/minimalRL/blob/master/a3c.py import gym import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.distributions import Categorical import torch.multiprocessing as mp import time, sys import gym_multi_car_racing from gym_multi_car_racing import MultiCarRacing import numpy as np sys.path.insert(0, '../../benchmarking') from model_tester import TesterAgent # Hyperparameters n_train_processes = 6 learning_rate = 0.0001 beta = 0.01 update_interval = 5 gamma = 0.99 max_train_ep = 700 max_test_ep = 800 num_frames = 5 max_temp = 5.0 SCALE = 10.0 # Track scale PLAYFIELD = 2000 / SCALE # Game over boundary ACTIONS = [ (-1, 1, 0.2), (0, 1, 0.2), (1, 1, 0.2), # Action Space Structure (-1, 1, 0), (0, 1, 0), (1, 1, 0), # (Steering Wheel, Gas, Break) (-1, 0, 0.2), (0, 0, 0.2), (1, 0, 0.2), # Range -1~1 0~1 0~1 (-1, 0, 0), (0, 0, 0), (1, 0, 0) ] VELOCITY_REWARD_PROPORTIONAL = 0.0 VELOCITY_REWARD_LOW = -10.0 ANGLE_DIFF_REWARD = 0.0 ON_GRASS_REWARD = -1.0 BACKWARD_REWARD = 0.0 def to_grayscale(img): return np.dot(img, [0.299, 0.587, 0.144]) def zero_center(img): return (img - 127.0) / 256.0 def crop(img, bottom=12, left=6, right=6): height, width = img.shape return img[0: height - bottom, left: width - right] class ActorCritic(nn.Module): def __init__(self, num_of_inputs, num_of_actions): super().__init__() self.conv1 = nn.Conv2d(num_of_inputs, 16, 8, stride=4) self.conv2 = nn.Conv2d(16, 32, 3, stride=2) self.linear1 = nn.Linear(32*9*9, 256) self.policy = nn.Linear(256, num_of_actions) self.value = nn.Linear(256, 1) self.num_of_actions = num_of_actions def forward(self, x, t=1.0): conv1_out = F.relu(self.conv1(x)) conv2_out = F.relu(self.conv2(conv1_out)) flattened = torch.flatten(conv2_out, start_dim=1) # N x 9*9*32 linear1_out = self.linear1(flattened) policy_output = self.policy(linear1_out) value_output = self.value(linear1_out).squeeze(-1) probs = F.softmax(policy_output / t, dim=-1) log_probs = F.log_softmax(policy_output, dim=-1) return probs.float(), log_probs.float(), value_output.float() def preprocess_state(s, car_id): s = s[car_id, ...] s = to_grayscale(s) s = zero_center(s) s = crop(s) return torch.from_numpy(s.astype(np.float32)).unsqueeze(0).unsqueeze(0) # N, C, H, W tensor def add_frame(s_new, s_stack): s_stack = torch.roll(s_stack, shifts=-1, dims=1) s_stack[:, -1, :, :] = s_new return s_stack def action_space_setup(env): env.cont_action_space = ACTIONS env.action_space = gym.spaces.Discrete(len(env.cont_action_space)) def get_reward(env, action): step_reward = np.zeros(env.num_agents) step_reward += env.track_reward for car_id, car in enumerate(env.cars): # First step without action, called from reset() velocity = abs(env.all_feats[car_id, 47]) step_reward[car_id] += (VELOCITY_REWARD_LOW if velocity < 2.0 else velocity * VELOCITY_REWARD_PROPORTIONAL) # normalize the velocity later step_reward[car_id] += abs(env.all_feats[car_id, 3]) * ANGLE_DIFF_REWARD # normalize angle diff later step_reward[car_id] += float(env.all_feats[car_id, 4]) * ON_GRASS_REWARD # driving on grass step_reward[car_id] += float(env.all_feats[car_id, 5]) * BACKWARD_REWARD # driving backward return step_reward def episode_end(env, car_id): done = False x, y = env.cars[car_id].hull.position if (abs(x) > PLAYFIELD or abs(y) > PLAYFIELD) or (env.driving_backward[car_id]): done = True return done def train(global_model, rank): car_id = 0 # Change this for multi-agent caseß local_model = ActorCritic(num_frames, global_model.num_of_actions) local_model.load_state_dict(global_model.state_dict()) optimizer = optim.Adam(global_model.parameters(), lr=learning_rate) env = gym.make("MultiCarRacing-v0", num_agents=1, direction='CCW', use_random_direction=True, backwards_flag=True, h_ratio=0.25, use_ego_color=False, setup_action_space_func=action_space_setup, get_reward_func=get_reward, episode_end_func=episode_end, observation_type='frames') for n_epi in range(max_train_ep): done = False # Initialize state with repeated first frame s = env.reset() s = preprocess_state(s, car_id) s = s.repeat(1, num_frames, 1, 1) temperature = np.exp(-(n_epi - max_train_ep) / max_train_ep * np.log(max_temp)) #print('Temperature: ', temperature) while not done: s_lst, a_lst, r_lst = [], [], [] for t in range(update_interval): prob = local_model(s, t=temperature)[0] m = Categorical(prob) a = m.sample().item() action_vec = np.array(ACTIONS[a]) s_prime, r, done, _ = env.step(action_vec) r = r[0] r /= 100. s_prime = preprocess_state(s_prime, car_id) s_lst.append(s) a_lst.append([a]) r_lst.append(r.astype(np.float32)) s = add_frame(s_prime, s) if done: break s_final = s R = 0.0 if done else local_model(s_final, t=temperature)[2].item() td_target_lst = [] for reward in r_lst[::-1]: R = gamma * R + reward td_target_lst.append(R) td_target_lst.reverse() s_batch, a_batch, td_target = torch.cat(s_lst, dim=0), torch.tensor(a_lst).squeeze(-1), \ torch.tensor(td_target_lst).squeeze(-1).float() advantage = td_target - local_model(s_batch, t=temperature)[2] pi = local_model(s_batch, t=temperature)[0] pi_a = pi.gather(1, a_batch.unsqueeze(-1)).squeeze(-1) entropy_loss = -(pi * torch.log(pi + 1e-20)).sum(dim=1).mean().float() policy_loss = (-torch.log(pi_a) * advantage.detach()).mean().float() value_loss = F.smooth_l1_loss(local_model(s_batch, t=temperature)[2], td_target.detach()).float() loss = 1.0 * policy_loss + \ 0.5 * value_loss + \ -beta * entropy_loss #print('Probs:{}, E:{}'.format(pi.detach(), entropy_loss.detach())) optimizer.zero_grad() loss.backward() for global_param, local_param in zip(global_model.parameters(), local_model.parameters()): global_param._grad = local_param.grad optimizer.step() local_model.load_state_dict(global_model.state_dict()) print('Rank {}, episode {}, loss {}'.format(rank, n_epi, loss.mean().detach())) env.close() print("Training process {} reached maximum episode.".format(rank)) def test(global_model): env = gym.make("MultiCarRacing-v0", num_agents=1, direction='CCW', use_random_direction=True, backwards_flag=True, h_ratio=0.25, use_ego_color=False, setup_action_space_func=action_space_setup, get_reward_func=get_reward, episode_end_func=episode_end, observation_type='frames', ) score = 0.0 print_interval = 10 car_id = 0 best_score = -100000000.0 for n_epi in range(max_test_ep): done = False s = env.reset() s = preprocess_state(s, car_id) s = s.repeat(1, num_frames, 1, 1) while not done: prob = global_model(s)[0] a = Categorical(prob).sample().item() action_vec = np.array(ACTIONS[a]) s_prime, r, done, info = env.step(action_vec) r = r[0] s_prime = preprocess_state(s_prime, car_id) s = add_frame(s_prime, s) score += r env.render() print('Final score: ', info['total_score']) if n_epi % print_interval == 0 and n_epi != 0: avg_score = score / print_interval print("# of episode :{}, avg score : {}".format(n_epi, avg_score)) if avg_score > best_score: best_score = avg_score print('Saving best model.') torch.save(global_model.state_dict(), '../a3c_agent.pth') score = 0.0 time.sleep(1) env.close() class A3CTesterAgent(TesterAgent): def __init__(self, model_path='../saved_models/A3C/a3c_12actions_T_5_ent_0_01.pth', car_id=0, num_frames=5, actions=ACTIONS, **kwargs ): super().__init__(**kwargs) self.car_id = car_id self.frame_buffer = None self.num_frames = num_frames self.actions = actions self.agent = self._load_model(model_path) def _load_model(self, model_path): agent = ActorCritic(self.num_frames, len(self.actions)) agent.load_state_dict(torch.load(model_path)) agent.eval() return agent def _update_frame_buffer(self, new_frame): if self.frame_buffer is None: self.frame_buffer = new_frame.repeat(1, self.num_frames, 1, 1) else: self.frame_buffer = add_frame(new_frame, self.frame_buffer) def state_to_action(self, s): """ This function should take the most recent state and return the action vector in the exact same form it is needed for the environment. If you are using frame buffer see example in _update_frame_buffer how to take care of that. """ s = preprocess_state(s, self.car_id) self._update_frame_buffer(s) prob = self.agent(self.frame_buffer)[0] a = Categorical(prob).sample().item() action_vec = np.array(self.actions[a]) return action_vec @staticmethod def setup_action_space(env): """ This should be the same action space setup function that you used for training. Make sure that the actions set here are the same as the ones used to train the model. """ env.cont_action_space = ACTIONS env.action_space = gym.spaces.Discrete(len(env.cont_action_space)) @staticmethod def get_observation_type(): """ Simply return 'frames' or 'features' """ return 'frames' if __name__ == '__main__': global_model = ActorCritic(num_frames, len(ACTIONS)) global_model.share_memory() processes = [] for rank in range(n_train_processes + 1): # + 1 for test process if rank == 0: p = mp.Process(target=test, args=(global_model,)) else: p = mp.Process(target=train, args=(global_model, rank,)) p.start() processes.append(p) for p in processes: p.join()
[ "sys.path.insert", "torch.distributions.Categorical", "numpy.log", "time.sleep", "numpy.array", "torch.nn.functional.softmax", "gym.make", "numpy.dot", "torch.roll", "torch.multiprocessing.Process", "torch.nn.functional.log_softmax", "torch.cat", "torch.log", "torch.load", "torch.nn.Conv...
[((378, 418), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../benchmarking"""'], {}), "(0, '../../benchmarking')\n", (393, 418), False, 'import time, sys\n'), ((1171, 1205), 'numpy.dot', 'np.dot', (['img', '[0.299, 0.587, 0.144]'], {}), '(img, [0.299, 0.587, 0.144])\n', (1177, 1205), True, 'import numpy as np\n'), ((2607, 2645), 'torch.roll', 'torch.roll', (['s_stack'], {'shifts': '(-1)', 'dims': '(1)'}), '(s_stack, shifts=-1, dims=1)\n', (2617, 2645), False, 'import torch\n'), ((2883, 2907), 'numpy.zeros', 'np.zeros', (['env.num_agents'], {}), '(env.num_agents)\n', (2891, 2907), True, 'import numpy as np\n'), ((4083, 4371), 'gym.make', 'gym.make', (['"""MultiCarRacing-v0"""'], {'num_agents': '(1)', 'direction': '"""CCW"""', 'use_random_direction': '(True)', 'backwards_flag': '(True)', 'h_ratio': '(0.25)', 'use_ego_color': '(False)', 'setup_action_space_func': 'action_space_setup', 'get_reward_func': 'get_reward', 'episode_end_func': 'episode_end', 'observation_type': '"""frames"""'}), "('MultiCarRacing-v0', num_agents=1, direction='CCW',\n use_random_direction=True, backwards_flag=True, h_ratio=0.25,\n use_ego_color=False, setup_action_space_func=action_space_setup,\n get_reward_func=get_reward, episode_end_func=episode_end,\n observation_type='frames')\n", (4091, 4371), False, 'import gym\n'), ((7228, 7516), 'gym.make', 'gym.make', (['"""MultiCarRacing-v0"""'], {'num_agents': '(1)', 'direction': '"""CCW"""', 'use_random_direction': '(True)', 'backwards_flag': '(True)', 'h_ratio': '(0.25)', 'use_ego_color': '(False)', 'setup_action_space_func': 'action_space_setup', 'get_reward_func': 'get_reward', 'episode_end_func': 'episode_end', 'observation_type': '"""frames"""'}), "('MultiCarRacing-v0', num_agents=1, direction='CCW',\n use_random_direction=True, backwards_flag=True, h_ratio=0.25,\n use_ego_color=False, setup_action_space_func=action_space_setup,\n get_reward_func=get_reward, episode_end_func=episode_end,\n observation_type='frames')\n", (7236, 7516), False, 'import gym\n'), ((1530, 1571), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_of_inputs', '(16)', '(8)'], {'stride': '(4)'}), '(num_of_inputs, 16, 8, stride=4)\n', (1539, 1571), True, 'import torch.nn as nn\n'), ((1593, 1623), 'torch.nn.Conv2d', 'nn.Conv2d', (['(16)', '(32)', '(3)'], {'stride': '(2)'}), '(16, 32, 3, stride=2)\n', (1602, 1623), True, 'import torch.nn as nn\n'), ((1647, 1673), 'torch.nn.Linear', 'nn.Linear', (['(32 * 9 * 9)', '(256)'], {}), '(32 * 9 * 9, 256)\n', (1656, 1673), True, 'import torch.nn as nn\n'), ((1692, 1722), 'torch.nn.Linear', 'nn.Linear', (['(256)', 'num_of_actions'], {}), '(256, num_of_actions)\n', (1701, 1722), True, 'import torch.nn as nn\n'), ((1744, 1761), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(1)'], {}), '(256, 1)\n', (1753, 1761), True, 'import torch.nn as nn\n'), ((1954, 1991), 'torch.flatten', 'torch.flatten', (['conv2_out'], {'start_dim': '(1)'}), '(conv2_out, start_dim=1)\n', (1967, 1991), False, 'import torch\n'), ((2178, 2214), 'torch.nn.functional.softmax', 'F.softmax', (['(policy_output / t)'], {'dim': '(-1)'}), '(policy_output / t, dim=-1)\n', (2187, 2214), True, 'import torch.nn.functional as F\n'), ((2235, 2271), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['policy_output'], {'dim': '(-1)'}), '(policy_output, dim=-1)\n', (2248, 2271), True, 'import torch.nn.functional as F\n'), ((10292, 10317), 'numpy.array', 'np.array', (['self.actions[a]'], {}), '(self.actions[a])\n', (10300, 10317), True, 'import numpy as np\n'), ((8098, 8118), 'numpy.array', 'np.array', (['ACTIONS[a]'], {}), '(ACTIONS[a])\n', (8106, 8118), True, 'import numpy as np\n'), ((8806, 8819), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (8816, 8819), False, 'import time, sys\n'), ((9465, 9487), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (9475, 9487), False, 'import torch\n'), ((11108, 11153), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'test', 'args': '(global_model,)'}), '(target=test, args=(global_model,))\n', (11118, 11153), True, 'import torch.multiprocessing as mp\n'), ((11184, 11235), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'train', 'args': '(global_model, rank)'}), '(target=train, args=(global_model, rank))\n', (11194, 11235), True, 'import torch.multiprocessing as mp\n'), ((4836, 4852), 'numpy.log', 'np.log', (['max_temp'], {}), '(max_temp)\n', (4842, 4852), True, 'import numpy as np\n'), ((5089, 5106), 'torch.distributions.Categorical', 'Categorical', (['prob'], {}), '(prob)\n', (5100, 5106), False, 'from torch.distributions import Categorical\n'), ((5174, 5194), 'numpy.array', 'np.array', (['ACTIONS[a]'], {}), '(ACTIONS[a])\n', (5182, 5194), True, 'import numpy as np\n'), ((5909, 5932), 'torch.cat', 'torch.cat', (['s_lst'], {'dim': '(0)'}), '(s_lst, dim=0)\n', (5918, 5932), False, 'import torch\n'), ((5934, 5953), 'torch.tensor', 'torch.tensor', (['a_lst'], {}), '(a_lst)\n', (5946, 5953), False, 'import torch\n'), ((10237, 10254), 'torch.distributions.Categorical', 'Categorical', (['prob'], {}), '(prob)\n', (10248, 10254), False, 'from torch.distributions import Categorical\n'), ((8039, 8056), 'torch.distributions.Categorical', 'Categorical', (['prob'], {}), '(prob)\n', (8050, 8056), False, 'from torch.distributions import Categorical\n'), ((5985, 6012), 'torch.tensor', 'torch.tensor', (['td_target_lst'], {}), '(td_target_lst)\n', (5997, 6012), False, 'import torch\n'), ((6343, 6358), 'torch.log', 'torch.log', (['pi_a'], {}), '(pi_a)\n', (6352, 6358), False, 'import torch\n'), ((6266, 6287), 'torch.log', 'torch.log', (['(pi + 1e-20)'], {}), '(pi + 1e-20)\n', (6275, 6287), False, 'import torch\n')]
from matplotlib import pyplot as plt from CHECLabPy.utils.mapping import get_tm_mapping, get_clp_mapping_from_version from CHECLabPy.plotting.camera import CameraImage from matplotlib.patches import Rectangle, Circle from matplotlib.collections import PatchCollection import numpy as np from ctapipe.image.toymodel import Gaussian, RingGaussian from ctapipe.image.hillas import camera_to_shower_coordinates from astropy import units as u from IPython import embed def print_formats(input): print(input, hex(input), np.binary_repr(input, width=8)) xpix = [ -1.5, -0.5, 0.5, 1.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, -1.5, -0.5, 0.5, 1.5, ] ypix = [ 2.5, 2.5, 2.5, 2.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -1.5, -1.5, -1.5, -1.5, -1.5, -1.5, -2.5, -2.5, -2.5, -2.5, ] size = 0.9 n_pixels = 32 patches = [] for xx, yy in zip(xpix, ypix): rr = size poly = Rectangle( (xx - rr / 2., yy - rr / 2.), width=rr, height=rr, fill=True, ) patches.append(poly) fig, ax = plt.subplots() pixels = PatchCollection(patches, linewidth=0) ax.add_collection(pixels) pixels.set_array(np.zeros(n_pixels)) ax.set_aspect('equal', 'datalim') ax.set_xlabel("X position (m)") ax.set_ylabel("Y position (m)") ax.autoscale_view() ax.axis('off') colorbar = ax.figure.colorbar( pixels, pad=-0.2, ax=ax ) xpix = np.array(xpix) * u.m ypix = np.array(ypix) * u.m def convert(a, t): return f"0x{hex(a << 4 | (t & 0xF))[2:].zfill(2)}" z_next = False for i in range(30): rand = np.random.RandomState(i) x = rand.uniform(-1, 1, 1)[0] * u.m y = rand.uniform(-1, 1, 1)[0] * u.m length = rand.uniform(1, 2.5, 1)[0] * u.m width = rand.uniform(0.5, 0.9, 1)[0] * u.m psi = rand.uniform(0, 360, 1)[0] * u.deg radius = 2.2 * u.m sigma = 0.3 * u.m max_time = rand.uniform(7, 12, 1)[0] max_amp = 15#rand.uniform(10, 15, 1)[0] longi, trans = camera_to_shower_coordinates(xpix, ypix, x, y, psi) time = longi - longi.min() time = np.round(time * max_time / time.max()).value.astype(np.int) type_rand = np.round(rand.uniform(1, 20, 1)[0]) if z_next: image = np.zeros(32, dtype=np.int) image[[5, 6, 7, 8, 13, 18, 25, 24, 23, 26]] = 5 time = np.full(32, 5, dtype=np.int) z_next = False elif type_rand == 3: image = np.zeros(32, dtype=np.int) image[[5, 6, 7, 8, 13, 19, 25, 24, 23]] = 5 time = np.full(32, 5, dtype=np.int) z_next = True elif type_rand == 7: ring = RingGaussian(x, y, radius, sigma) image = ring.pdf(xpix, ypix) image = np.round(image * max_amp / image.max()).astype(np.int) time = np.full(32, 5, dtype=np.int) else: gaussian = Gaussian(x, y, length, width, psi) image = gaussian.pdf(xpix, ypix) image = np.round(image * max_amp / image.max()).astype(np.int) array = [convert(a, t) for a, t in zip(image, time)] print( f" {{{array[0]},{array[1]},{array[2]},{array[3]},\n" f"{array[4]},{array[5]},{array[6]},{array[7]},{array[8]},{array[9]},\n" f"{array[10]},{array[11]},{array[12]},{array[13]},{array[14]},{array[15]},\n" f"{array[16]},{array[17]},{array[18]},{array[19]},{array[20]},{array[21]},\n" f"{array[22]},{array[23]},{array[24]},{array[25]},{array[26]},{array[27]},\n" f" {array[28]},{array[29]},{array[30]},{array[31]}}}," ) # pixels.set_array(np.ma.masked_invalid(image)) # pixels.changed() # ax.figure.canvas.draw() # # pixels.autoscale() # plt.pause(1)
[ "matplotlib.patches.Rectangle", "numpy.binary_repr", "matplotlib.collections.PatchCollection", "numpy.array", "numpy.zeros", "ctapipe.image.toymodel.Gaussian", "ctapipe.image.hillas.camera_to_shower_coordinates", "ctapipe.image.toymodel.RingGaussian", "numpy.full", "matplotlib.pyplot.subplots", ...
[((1257, 1271), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1269, 1271), True, 'from matplotlib import pyplot as plt\n'), ((1282, 1319), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['patches'], {'linewidth': '(0)'}), '(patches, linewidth=0)\n', (1297, 1319), False, 'from matplotlib.collections import PatchCollection\n'), ((1110, 1183), 'matplotlib.patches.Rectangle', 'Rectangle', (['(xx - rr / 2.0, yy - rr / 2.0)'], {'width': 'rr', 'height': 'rr', 'fill': '(True)'}), '((xx - rr / 2.0, yy - rr / 2.0), width=rr, height=rr, fill=True)\n', (1119, 1183), False, 'from matplotlib.patches import Rectangle, Circle\n'), ((1363, 1381), 'numpy.zeros', 'np.zeros', (['n_pixels'], {}), '(n_pixels)\n', (1371, 1381), True, 'import numpy as np\n'), ((1587, 1601), 'numpy.array', 'np.array', (['xpix'], {}), '(xpix)\n', (1595, 1601), True, 'import numpy as np\n'), ((1615, 1629), 'numpy.array', 'np.array', (['ypix'], {}), '(ypix)\n', (1623, 1629), True, 'import numpy as np\n'), ((1759, 1783), 'numpy.random.RandomState', 'np.random.RandomState', (['i'], {}), '(i)\n', (1780, 1783), True, 'import numpy as np\n'), ((2153, 2204), 'ctapipe.image.hillas.camera_to_shower_coordinates', 'camera_to_shower_coordinates', (['xpix', 'ypix', 'x', 'y', 'psi'], {}), '(xpix, ypix, x, y, psi)\n', (2181, 2204), False, 'from ctapipe.image.hillas import camera_to_shower_coordinates\n'), ((520, 550), 'numpy.binary_repr', 'np.binary_repr', (['input'], {'width': '(8)'}), '(input, width=8)\n', (534, 550), True, 'import numpy as np\n'), ((2391, 2417), 'numpy.zeros', 'np.zeros', (['(32)'], {'dtype': 'np.int'}), '(32, dtype=np.int)\n', (2399, 2417), True, 'import numpy as np\n'), ((2489, 2517), 'numpy.full', 'np.full', (['(32)', '(5)'], {'dtype': 'np.int'}), '(32, 5, dtype=np.int)\n', (2496, 2517), True, 'import numpy as np\n'), ((2582, 2608), 'numpy.zeros', 'np.zeros', (['(32)'], {'dtype': 'np.int'}), '(32, dtype=np.int)\n', (2590, 2608), True, 'import numpy as np\n'), ((2676, 2704), 'numpy.full', 'np.full', (['(32)', '(5)'], {'dtype': 'np.int'}), '(32, 5, dtype=np.int)\n', (2683, 2704), True, 'import numpy as np\n'), ((2767, 2800), 'ctapipe.image.toymodel.RingGaussian', 'RingGaussian', (['x', 'y', 'radius', 'sigma'], {}), '(x, y, radius, sigma)\n', (2779, 2800), False, 'from ctapipe.image.toymodel import Gaussian, RingGaussian\n'), ((2924, 2952), 'numpy.full', 'np.full', (['(32)', '(5)'], {'dtype': 'np.int'}), '(32, 5, dtype=np.int)\n', (2931, 2952), True, 'import numpy as np\n'), ((2982, 3016), 'ctapipe.image.toymodel.Gaussian', 'Gaussian', (['x', 'y', 'length', 'width', 'psi'], {}), '(x, y, length, width, psi)\n', (2990, 3016), False, 'from ctapipe.image.toymodel import Gaussian, RingGaussian\n')]
import numpy as np cube4 = np.full([4,4,4,3],-1,np.int32) # x, y, z, [x,y,z] cube4[0,0,0] = [-1,-1,-1] cube4[1,0,0] = [24,-1,-1] cube4[2,0,0] = [24,-1,-1] cube4[3,0,0] = [-1,-1,-1] cube4[0,1,0] = [-1,25,-1] cube4[1,1,0] = [27,28,-1] cube4[2,1,0] = [29,30,-1] cube4[3,1,0] = [-1,25,-1] cube4[0,2,0] = [-1,25,-1] cube4[1,2,0] = [33,34,-1] cube4[2,2,0] = [31,32,-1] cube4[3,2,0] = [-1,25,-1] cube4[0,3,0] = [-1,-1,-1] cube4[1,3,0] = [24,-1,-1] cube4[2,3,0] = [24,-1,-1] cube4[3,3,0] = [-1,-1,-1] cube4[0,0,1] = [-1,-1,26] cube4[1,0,1] = [43,-1,44] cube4[2,0,1] = [45,-1,46] cube4[3,0,1] = [-1,-1,26] cube4[0,1,1] = [-1,35,36] cube4[1,1,1] = [0,1,2] cube4[2,1,1] = [3,4,5] cube4[3,1,1] = [-1,35,36] cube4[0,2,1] = [-1,37,38] cube4[1,2,1] = [9,10,11] cube4[2,2,1] = [6,7,8] cube4[3,2,1] = [-1,37,38] cube4[0,3,1] = [-1,-1,26] cube4[1,3,1] = [43,-1,44] cube4[2,3,1] = [45,-1,46] cube4[3,3,1] = [-1,-1,26] cube4[0,0,2] = [-1,-1,26] cube4[1,0,2] = [49,-1,50] cube4[2,0,2] = [47,-1,48] cube4[3,0,2] = [-1,-1,26] cube4[0,1,2] = [-1,41,42] cube4[1,1,2] = [12,13,14] cube4[2,1,2] = [15,16,17] cube4[3,1,2] = [-1,41,42] cube4[0,2,2] = [-1,39,40] cube4[1,2,2] = [21,22,23] cube4[2,2,2] = [18,19,20] cube4[3,2,2] = [-1,39,40] cube4[0,3,2] = [-1,-1,26] cube4[1,3,2] = [49,-1,50] cube4[2,3,2] = [47,-1,48] cube4[3,3,2] = [-1,-1,26] cube4[0,0,3] = [-1,-1,-1] cube4[1,0,3] = [24,-1,-1] cube4[2,0,3] = [24,-1,-1] cube4[3,0,3] = [-1,-1,-1] cube4[0,1,3] = [-1,25,-1] cube4[1,1,3] = [27,28,-1] cube4[2,1,3] = [29,30,-1] cube4[3,1,3] = [-1,25,-1] cube4[0,2,3] = [-1,25,-1] cube4[1,2,3] = [33,34,-1] cube4[2,2,3] = [31,32,-1] cube4[3,2,3] = [-1,25,-1] cube4[0,3,3] = [-1,-1,-1] cube4[1,3,3] = [24,-1,-1] cube4[2,3,3] = [24,-1,-1] cube4[3,3,3] = [-1,-1,-1] #print(np.transpose(cube4[1,:,:,0])) #X_slices #print(np.transpose(cube4[2,:,:,0])) #print(np.transpose(cube4[:,1,:,1])) #Y_slices #print(np.transpose(cube4[:,2,:,1])) #print(np.transpose(cube4[:,:,1,2])) #Z_slices #print(np.transpose(cube4[:,:,2,2])) def get_slice(i,j,k,dim): idx = cube4[i,j,k,dim] if idx<0: if dim==0: if i==0: return 0 if i==3: return 1 if dim==1: if j==0: return 0 if j==3: return 1 if dim==2: if k==0: return 0 if k==3: return 1 else: sss = "[:,"+str(idx)+"," if i==3: sss += "1:," else: sss += ":-1," if j==3: sss += "1:," else: sss += ":-1," if k==3: sss += "1:]" else: sss += ":-1]" return sss out_str = "" counter = 0 #X_slices for i in [1,2]: for k in range(3): for j in range(3): v00_idx_str = get_slice(i,j,k,0) v10_idx_str = get_slice(i,j,k+1,0) v11_idx_str = get_slice(i,j+1,k+1,0) v01_idx_str = get_slice(i,j+1,k,0) counter += 1 out_str += "torch.sum( ( (pred_output_float"+v00_idx_str+"-pred_output_float"+v10_idx_str+")**2 )*torch.min(gt_output_float_mask"+v00_idx_str+",gt_output_float_mask"+v10_idx_str+" )*( torch.abs(gt_output_float"+v00_idx_str+"-gt_output_float"+v10_idx_str+")<2e-4 ).float() ) + " counter += 1 out_str += "torch.sum( ( (pred_output_float"+v00_idx_str+"-pred_output_float"+v01_idx_str+")**2 )*torch.min(gt_output_float_mask"+v00_idx_str+",gt_output_float_mask"+v01_idx_str+" )*( torch.abs(gt_output_float"+v00_idx_str+"-gt_output_float"+v01_idx_str+")<2e-4 ).float() ) + " #Y_slices for j in [1,2]: for k in range(3): for i in range(3): v00_idx_str = get_slice(i,j,k,1) v10_idx_str = get_slice(i,j,k+1,1) v11_idx_str = get_slice(i+1,j,k+1,1) v01_idx_str = get_slice(i+1,j,k,1) counter += 1 out_str += "torch.sum( ( (pred_output_float"+v00_idx_str+"-pred_output_float"+v10_idx_str+")**2 )*torch.min(gt_output_float_mask"+v00_idx_str+",gt_output_float_mask"+v10_idx_str+" )*( torch.abs(gt_output_float"+v00_idx_str+"-gt_output_float"+v10_idx_str+")<2e-4 ).float() ) + " counter += 1 out_str += "torch.sum( ( (pred_output_float"+v00_idx_str+"-pred_output_float"+v01_idx_str+")**2 )*torch.min(gt_output_float_mask"+v00_idx_str+",gt_output_float_mask"+v01_idx_str+" )*( torch.abs(gt_output_float"+v00_idx_str+"-gt_output_float"+v01_idx_str+")<2e-4 ).float() ) + " #Z_slices for k in [1,2]: for j in range(3): for i in range(3): v00_idx_str = get_slice(i,j,k,2) v10_idx_str = get_slice(i,j+1,k,2) v11_idx_str = get_slice(i+1,j+1,k,2) v01_idx_str = get_slice(i+1,j,k,2) counter += 1 out_str += "torch.sum( ( (pred_output_float"+v00_idx_str+"-pred_output_float"+v10_idx_str+")**2 )*torch.min(gt_output_float_mask"+v00_idx_str+",gt_output_float_mask"+v10_idx_str+" )*( torch.abs(gt_output_float"+v00_idx_str+"-gt_output_float"+v10_idx_str+")<2e-4 ).float() ) + " counter += 1 out_str += "torch.sum( ( (pred_output_float"+v00_idx_str+"-pred_output_float"+v01_idx_str+")**2 )*torch.min(gt_output_float_mask"+v00_idx_str+",gt_output_float_mask"+v01_idx_str+" )*( torch.abs(gt_output_float"+v00_idx_str+"-gt_output_float"+v01_idx_str+")<2e-4 ).float() ) + " fout = open("loss_float_gradient_code.py",'w') fout.write("import torch\ndef get_loss_float_gradient(pred_output_float,gt_output_float,gt_output_float_mask):\n return ") fout.write(out_str[:-3]) fout.close() print(counter)
[ "numpy.full" ]
[((29, 64), 'numpy.full', 'np.full', (['[4, 4, 4, 3]', '(-1)', 'np.int32'], {}), '([4, 4, 4, 3], -1, np.int32)\n', (36, 64), True, 'import numpy as np\n')]
#!/usr/bin/env python """ Given a matrix of integers x that represent the number of connections between row i and column j (where x[i, i] = 0) and starting with the indices i and j for which x[i, j]+x[j, i] is maximal over all (i, j), order the pairs of indices (i, j) such that each x[i_curr, j_curr]+x[j_curr, i_curr] increases the total sum of x[i, j]+x[j, i] over already seen indices by the maximum amount possible for the remaining index pairs. """ import itertools import numpy as np def interleave(a, b): """ Interleave elements of two lists of equal length. """ return list(itertools.chain.from_iterable(itertools.izip(a, b))) def get_index_order(x): x = np.asarray(x) assert x.shape[0] == x.shape[1] N = x.shape[0] # Find indices (i, j) of elements x[i, j], x[j, i] such that x[i, j]+x[j, i] is # maximized (elements x[i, i] are ignored): first = [(i, j) for i, j in itertools.product(xrange(N), xrange(N)) if i > j] second = [(j, i) for i, j in itertools.product(xrange(N), xrange(N)) if i > j] inds = interleave(first, second) x_ordered = [x[i, j] for i, j in inds] x_ordered_summed = [a+b for a, b in zip(x_ordered[::2], x_ordered[1::2])] i_ordered_summed_max = np.argmax(x_ordered_summed) i_ordered_max = i_ordered_summed_max*2 ind_max = inds[i_ordered_max] # Indices already added: added_inds = [ind_max[0], ind_max[1]] # Remaining indices to consider: remaining_inds = range(N) for ind in added_inds: remaining_inds.remove(ind) while remaining_inds: # For each remaining index i and each index j already added, compute # increase due to adding values x[i, j]+x[j, i]: sums = [] for i in remaining_inds: s = sum([x[i, j]+x[j, i] for j in added_inds]) sums.append(s) # Add the index corresponding to the maximum increase to added_inds and # remove it from remaining_inds: i_max = np.argmax(sums) added_inds.append(remaining_inds[i_max]) del remaining_inds[i_max] return np.asarray(added_inds) if __name__ == '__main__': # Create example matrix: N = 10 x = np.random.randint(0, 20, (N, N)) for i in xrange(N): x[i, i] = 0 add_inds = get_index_order(x)
[ "numpy.random.randint", "numpy.asarray", "numpy.argmax", "itertools.izip" ]
[((692, 705), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (702, 705), True, 'import numpy as np\n'), ((1245, 1272), 'numpy.argmax', 'np.argmax', (['x_ordered_summed'], {}), '(x_ordered_summed)\n', (1254, 1272), True, 'import numpy as np\n'), ((2099, 2121), 'numpy.asarray', 'np.asarray', (['added_inds'], {}), '(added_inds)\n', (2109, 2121), True, 'import numpy as np\n'), ((2198, 2230), 'numpy.random.randint', 'np.random.randint', (['(0)', '(20)', '(N, N)'], {}), '(0, 20, (N, N))\n', (2215, 2230), True, 'import numpy as np\n'), ((1989, 2004), 'numpy.argmax', 'np.argmax', (['sums'], {}), '(sums)\n', (1998, 2004), True, 'import numpy as np\n'), ((636, 656), 'itertools.izip', 'itertools.izip', (['a', 'b'], {}), '(a, b)\n', (650, 656), False, 'import itertools\n')]
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''' from numpy.testing import assert_allclose import pytest import pandas as pd from thermo.lennard_jones import * def test_LJ_data(): # Two instances of 174899-66-2 were present; # the apparently more common one, [Bmim][CF 3SO 3], was kept. tot = MagalhaesLJ_data['epsilon'].abs().sum() assert_allclose(tot, 187099.82029999999) tot = MagalhaesLJ_data['sigma'].abs().sum() assert_allclose(tot, 1995.8174799999997) assert MagalhaesLJ_data.index.is_unique assert MagalhaesLJ_data.shape == (322, 3) def test_molecular_diameter_CSP(): # Example from DIPPR 1983 Manual for Predicting Chemical Process Design # Data, Data Prediction Manual, page 10-B2, Procedure 10B. # Example is shown only for Monofluorobenzene and hydrogen. # The Monofluorobenzene example is adapted here to all methods. # All functions have had their units and formulas checked and are relatively # similar in their outputs. sigma = sigma_Flynn(0.000268) assert_allclose(sigma, 5.2506948422196285) sigma = sigma_Bird_Stewart_Lightfoot_critical_2(560.1, 4550000) assert_allclose(sigma, 5.658657684653222) sigma = sigma_Bird_Stewart_Lightfoot_critical_1(0.000268) assert_allclose(sigma, 5.422184116631474) sigma = sigma_Bird_Stewart_Lightfoot_boiling(0.0001015) assert_allclose(sigma, 5.439018856944655) sigma = sigma_Bird_Stewart_Lightfoot_melting(8.8e-05) assert_allclose(sigma, 5.435407341351406) sigma = sigma_Stiel_Thodos(0.271E-3, 0.265) assert_allclose(sigma, 5.94300853971033) sigma = sigma_Tee_Gotoh_Steward_1(560.1, 4550000) assert_allclose(sigma, 5.48402779790962) sigma = sigma_Tee_Gotoh_Steward_2(560.1, 4550000, 0.245) assert_allclose(sigma, 5.412104867264477) sigma = sigma_Silva_Liu_Macedo(560.1, 4550000) assert_allclose(sigma, 5.164483998730177) assert None == sigma_Silva_Liu_Macedo(1084, 3.84E5) def test_stockmayer_function(): # Use the default method for each chemical in this file Stockmayers = [Stockmayer(CASRN=i) for i in MagalhaesLJ_data.index] Stockmayer_default_sum = pd.Series(Stockmayers).sum() assert_allclose(Stockmayer_default_sum, 187099.82029999999) assert_allclose(1291.41, Stockmayer(CASRN='64-17-5')) methods = Stockmayer(Tm=178.075, Tb=341.87, Tc=507.6, Zc=0.2638, omega=0.2975, CASRN='110-54-3', AvailableMethods=True) assert methods[0:-1] == Stockmayer_methods values_calc = [Stockmayer(Tm=178.075, Tb=341.87, Tc=507.6, Zc=0.2638, omega=0.2975, CASRN='110-54-3', Method=i) for i in methods[0:-1]] values = [434.76, 427.33156230000003, 318.10801442820025, 390.85200000000003, 392.8824, 393.15049999999997, 341.90399999999994, 273.54201582027196] assert_allclose(values_calc, values) # Error handling assert None == Stockmayer(CASRN='BADCAS') with pytest.raises(Exception): Stockmayer(CASRN='98-01-1', Method='BADMETHOD') def test_molecular_diameter_function(): # Use the default method for each chemical in this file MDs = [molecular_diameter(CASRN=i) for i in MagalhaesLJ_data.index] MDs_sum = pd.Series(MDs).sum() assert_allclose(MDs_sum, 1995.8174799999997) assert_allclose(4.23738, molecular_diameter(CASRN='64-17-5')) methods = molecular_diameter(Tc=507.6, Pc=3025000.0, Vc=0.000368, Zc=0.2638, omega=0.2975, Vm=0.000113, Vb=0.000140, CASRN='110-54-3', AvailableMethods=True) assert methods[0:-1] == molecular_diameter_methods values_calc = [molecular_diameter(Tc=507.6, Pc=3025000.0, Vc=0.000368, Zc=0.2638, omega=0.2975, Vm=0.000113, Vb=0.000140, CASRN='110-54-3', Method=i) for i in methods[0:-1]] values = [5.61841, 5.989061939666203, 5.688003783388763, 6.27423491655056, 6.080607912773406, 6.617051217297049, 5.960764840627408, 6.0266865190488215, 6.054448122758386, 5.9078666913304225] assert_allclose(values_calc, values) # Error handling assert None == molecular_diameter(CASRN='BADCAS') with pytest.raises(Exception): molecular_diameter(CASRN='98-01-1', Method='BADMETHOD') def test_stockmayer(): epsilon_k = epsilon_Flynn(560.1) assert_allclose(epsilon_k, 345.2984087011443) epsilon_k = epsilon_Bird_Stewart_Lightfoot_critical(560.1) assert_allclose(epsilon_k, 431.27700000000004) epsilon_k = epsilon_Bird_Stewart_Lightfoot_boiling(357.85) assert_allclose(epsilon_k, 411.5275) epsilon_k = epsilon_Bird_Stewart_Lightfoot_melting(231.15) assert_allclose(epsilon_k, 443.808) epsilon_k = epsilon_Stiel_Thodos(358.5, 0.265) assert_allclose(epsilon_k, 196.3755830305783) epsilon_k = epsilon_Tee_Gotoh_Steward_1(560.1) assert_allclose(epsilon_k, 433.5174) epsilon_k = epsilon_Tee_Gotoh_Steward_2(560.1, 0.245) assert_allclose(epsilon_k, 466.55125785) def test_collision_integral(): lss = [(1,1), (1,2), (1,3), (2,2), (2,3), (2,4), (2,5), (2,6), (4,4)] omega = collision_integral_Neufeld_Janzen_Aziz(100, 1, 1) assert_allclose(omega, 0.516717697672334) # Calculated points for each (l,s) at 0.3 and 100, nothing to use for comparison omegas_03_calc = [collision_integral_Neufeld_Janzen_Aziz(0.3, l, s) for (l,s) in lss] omegas_03 = [2.6501763610977873, 2.2569797090694452, 1.9653064255878911, 2.8455432577357387, 2.583328280612125, 2.3647890577440056, 2.171747217180612, 2.001780269583615, 2.5720716122665257] assert_allclose(omegas_03_calc, omegas_03) with pytest.raises(Exception): collision_integral_Neufeld_Janzen_Aziz(0.3, l=8, s=22) # Example 1.6 p 21 in <NAME> - 2009 - Principles and Modern Applications of Mass Transfer Operations omega = collision_integral_Neufeld_Janzen_Aziz(1.283) assert_allclose(omega, 1.282, atol=0.0001) # More accurate formulation omega = collision_integral_Kim_Monroe(400, 1, 1) assert_allclose(omega, 0.4141818082392228) # Series of points listed in [1]_ for values of l and s for comparison with # the Hirschfelder et al correlation omegas_03_calc = [collision_integral_Kim_Monroe(0.3, l, s) for (l,s) in lss] omegas_03 = [2.65, 2.2568, 1.9665, 2.8436, 2.5806, 2.3623, 2.1704, 2.0011, 2.571] assert_allclose(omegas_03_calc, omegas_03, rtol=1e-4) omegas_400_calc = [collision_integral_Kim_Monroe(400, l, s) for (l,s) in lss] omegas_400 = [0.41418, 0.3919, 0.37599, 0.47103, 0.45228, 0.43778, 0.42604, 0.41622, 0.4589] assert_allclose(omegas_400_calc, omegas_400, rtol=1e-4) with pytest.raises(Exception): collision_integral_Kim_Monroe(0.3, l=8, s=22) def test_Tstar(): Tst1 = Tstar(T=318.2, epsilon_k=308.43) Tst2 = Tstar(T=318.2, epsilon=4.2583342302359994e-21) assert_allclose([Tst1, Tst2], [1.0316765554582887]*2) with pytest.raises(Exception): Tstar(300)
[ "pandas.Series", "numpy.testing.assert_allclose", "pytest.raises" ]
[((1470, 1503), 'numpy.testing.assert_allclose', 'assert_allclose', (['tot', '(187099.8203)'], {}), '(tot, 187099.8203)\n', (1485, 1503), False, 'from numpy.testing import assert_allclose\n'), ((1564, 1604), 'numpy.testing.assert_allclose', 'assert_allclose', (['tot', '(1995.8174799999997)'], {}), '(tot, 1995.8174799999997)\n', (1579, 1604), False, 'from numpy.testing import assert_allclose\n'), ((2157, 2199), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.2506948422196285)'], {}), '(sigma, 5.2506948422196285)\n', (2172, 2199), False, 'from numpy.testing import assert_allclose\n'), ((2273, 2314), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.658657684653222)'], {}), '(sigma, 5.658657684653222)\n', (2288, 2314), False, 'from numpy.testing import assert_allclose\n'), ((2382, 2423), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.422184116631474)'], {}), '(sigma, 5.422184116631474)\n', (2397, 2423), False, 'from numpy.testing import assert_allclose\n'), ((2489, 2530), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.439018856944655)'], {}), '(sigma, 5.439018856944655)\n', (2504, 2530), False, 'from numpy.testing import assert_allclose\n'), ((2594, 2635), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.435407341351406)'], {}), '(sigma, 5.435407341351406)\n', (2609, 2635), False, 'from numpy.testing import assert_allclose\n'), ((2689, 2729), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.94300853971033)'], {}), '(sigma, 5.94300853971033)\n', (2704, 2729), False, 'from numpy.testing import assert_allclose\n'), ((2789, 2829), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.48402779790962)'], {}), '(sigma, 5.48402779790962)\n', (2804, 2829), False, 'from numpy.testing import assert_allclose\n'), ((2896, 2937), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.412104867264477)'], {}), '(sigma, 5.412104867264477)\n', (2911, 2937), False, 'from numpy.testing import assert_allclose\n'), ((2994, 3035), 'numpy.testing.assert_allclose', 'assert_allclose', (['sigma', '(5.164483998730177)'], {}), '(sigma, 5.164483998730177)\n', (3009, 3035), False, 'from numpy.testing import assert_allclose\n'), ((3320, 3372), 'numpy.testing.assert_allclose', 'assert_allclose', (['Stockmayer_default_sum', '(187099.8203)'], {}), '(Stockmayer_default_sum, 187099.8203)\n', (3335, 3372), False, 'from numpy.testing import assert_allclose\n'), ((3908, 3944), 'numpy.testing.assert_allclose', 'assert_allclose', (['values_calc', 'values'], {}), '(values_calc, values)\n', (3923, 3944), False, 'from numpy.testing import assert_allclose\n'), ((4318, 4362), 'numpy.testing.assert_allclose', 'assert_allclose', (['MDs_sum', '(1995.8174799999997)'], {}), '(MDs_sum, 1995.8174799999997)\n', (4333, 4362), False, 'from numpy.testing import assert_allclose\n'), ((5026, 5062), 'numpy.testing.assert_allclose', 'assert_allclose', (['values_calc', 'values'], {}), '(values_calc, values)\n', (5041, 5062), False, 'from numpy.testing import assert_allclose\n'), ((5305, 5350), 'numpy.testing.assert_allclose', 'assert_allclose', (['epsilon_k', '(345.2984087011443)'], {}), '(epsilon_k, 345.2984087011443)\n', (5320, 5350), False, 'from numpy.testing import assert_allclose\n'), ((5419, 5465), 'numpy.testing.assert_allclose', 'assert_allclose', (['epsilon_k', '(431.27700000000004)'], {}), '(epsilon_k, 431.27700000000004)\n', (5434, 5465), False, 'from numpy.testing import assert_allclose\n'), ((5534, 5570), 'numpy.testing.assert_allclose', 'assert_allclose', (['epsilon_k', '(411.5275)'], {}), '(epsilon_k, 411.5275)\n', (5549, 5570), False, 'from numpy.testing import assert_allclose\n'), ((5639, 5674), 'numpy.testing.assert_allclose', 'assert_allclose', (['epsilon_k', '(443.808)'], {}), '(epsilon_k, 443.808)\n', (5654, 5674), False, 'from numpy.testing import assert_allclose\n'), ((5731, 5776), 'numpy.testing.assert_allclose', 'assert_allclose', (['epsilon_k', '(196.3755830305783)'], {}), '(epsilon_k, 196.3755830305783)\n', (5746, 5776), False, 'from numpy.testing import assert_allclose\n'), ((5833, 5869), 'numpy.testing.assert_allclose', 'assert_allclose', (['epsilon_k', '(433.5174)'], {}), '(epsilon_k, 433.5174)\n', (5848, 5869), False, 'from numpy.testing import assert_allclose\n'), ((5933, 5973), 'numpy.testing.assert_allclose', 'assert_allclose', (['epsilon_k', '(466.55125785)'], {}), '(epsilon_k, 466.55125785)\n', (5948, 5973), False, 'from numpy.testing import assert_allclose\n'), ((6148, 6189), 'numpy.testing.assert_allclose', 'assert_allclose', (['omega', '(0.516717697672334)'], {}), '(omega, 0.516717697672334)\n', (6163, 6189), False, 'from numpy.testing import assert_allclose\n'), ((6565, 6607), 'numpy.testing.assert_allclose', 'assert_allclose', (['omegas_03_calc', 'omegas_03'], {}), '(omegas_03_calc, omegas_03)\n', (6580, 6607), False, 'from numpy.testing import assert_allclose\n'), ((6875, 6917), 'numpy.testing.assert_allclose', 'assert_allclose', (['omega', '(1.282)'], {'atol': '(0.0001)'}), '(omega, 1.282, atol=0.0001)\n', (6890, 6917), False, 'from numpy.testing import assert_allclose\n'), ((7009, 7051), 'numpy.testing.assert_allclose', 'assert_allclose', (['omega', '(0.4141818082392228)'], {}), '(omega, 0.4141818082392228)\n', (7024, 7051), False, 'from numpy.testing import assert_allclose\n'), ((7346, 7401), 'numpy.testing.assert_allclose', 'assert_allclose', (['omegas_03_calc', 'omegas_03'], {'rtol': '(0.0001)'}), '(omegas_03_calc, omegas_03, rtol=0.0001)\n', (7361, 7401), False, 'from numpy.testing import assert_allclose\n'), ((7584, 7641), 'numpy.testing.assert_allclose', 'assert_allclose', (['omegas_400_calc', 'omegas_400'], {'rtol': '(0.0001)'}), '(omegas_400_calc, omegas_400, rtol=0.0001)\n', (7599, 7641), False, 'from numpy.testing import assert_allclose\n'), ((7855, 7910), 'numpy.testing.assert_allclose', 'assert_allclose', (['[Tst1, Tst2]', '([1.0316765554582887] * 2)'], {}), '([Tst1, Tst2], [1.0316765554582887] * 2)\n', (7870, 7910), False, 'from numpy.testing import assert_allclose\n'), ((4023, 4047), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (4036, 4047), False, 'import pytest\n'), ((5149, 5173), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (5162, 5173), False, 'import pytest\n'), ((6618, 6642), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (6631, 6642), False, 'import pytest\n'), ((7650, 7674), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (7663, 7674), False, 'import pytest\n'), ((7919, 7943), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (7932, 7943), False, 'import pytest\n'), ((3287, 3309), 'pandas.Series', 'pd.Series', (['Stockmayers'], {}), '(Stockmayers)\n', (3296, 3309), True, 'import pandas as pd\n'), ((4293, 4307), 'pandas.Series', 'pd.Series', (['MDs'], {}), '(MDs)\n', (4302, 4307), True, 'import pandas as pd\n')]
import numpy as np import configparser, os from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from pdb import set_trace from utmLib import utils from utmLib.ml.potential import CLG from transforms import * def pca_analysis(data, percentiles): D = data.shape[1] obj = PCA().fit(data) acc_sum = [] ; S = 0 for v in obj.explained_variance_ratio_: S += v acc_sum.append(S) acc_sum = np.array(acc_sum) ret = [] for p in percentiles: left = np.sum(acc_sum > p) - 1 num_p = D - left ret.append(num_p) return ret def analyze_correlation(data): # return the pairwise P-correlation of variables _,D = data.shape corr = np.zeros((D,D), dtype=float) for i,j in utils.halfprod(range(D)): corr[i,j] = CLG.corr_coef(data[:,(i,j)]) corr[j,i] = corr[i,j] return corr def compute_rmse(a, b): assert(a.shape == b.shape) sse = np.sum(np.square(a-b)) mse = sse / a.size rmse = np.sqrt(mse) return rmse def evaluate_result(truth, estimated, query = None, output_var = False): # evaluate the average rmse of query variables, missing is not considered here N, _ = truth.shape rmse = [] if query is None: query = [slice(None)] * N for i in range(N): idx = query[i] rmse.append(compute_rmse(truth[i,idx], estimated[i,idx] )) avg_rmse = np.mean(rmse) if not output_var: return avg_rmse else: std_rmse = np.std(rmse) return avg_rmse, std_rmse def logmass_statistic(logmass): # return the 25%, median, 75% percentile and average of logmass p25 = np.percentile(logmass, 25) median = np.median(logmass) p75 = np.percentile(logmass, 75) average = np.mean(logmass) return (p25, median, p75, average) def print_array(X): print('-------------------------------') for row in X: print(','.join(row.astype(str))) return def read_ini(fpath, section = 'expconf'): parser = configparser.ConfigParser() parser.read(fpath) parsed_conf = dict(parser[section]) return parsed_conf def load_exp_conf(fpath): parsed_conf = read_ini(fpath) if 'include' in parsed_conf: extra_ini = parsed_conf['include'].split(',') path_frag = fpath.split('/') for item in extra_ini: path_frag[-1] = item extra_fpath = '/'.join(path_frag) for k,v in read_ini(extra_fpath).items(): if k not in parsed_conf: parsed_conf[k] = v del parsed_conf['include'] conf_dict = {} for k,v in parsed_conf.items(): conf_dict[k] = eval(v) options = utils.dict2obj(conf_dict) # take care of root dir simplification if options.root_dir == 'auto': file_path = os.path.realpath(__file__) up2_dir = file_path.split('/')[0:-3] options.root_dir = '/'.join(up2_dir) return options def _do_mask_(data, query, missing): masked = data.copy() unknown = np.concatenate([query,missing], axis = 1) for i, r in enumerate(masked): u = unknown[i] r[u] = np.nan return masked def mask_dataset(data, Q, M): # create masked dataset give query and missing setting N, D = data.shape if isinstance(Q, list): # fix query var query = [Q] * N else: qsize = int(np.round(D*Q)) query = [np.random.choice(D, size=qsize, replace=False) for i in range(N)] msize = int(np.round(D*M)) missing = [] for i in range(N): pool = utils.notin(range(D), query[i]) missing.append( np.random.choice(pool, size=msize, replace=False) ) masked = _do_mask_(data, query, missing) return masked, query, missing # following function is experiemental, have known issues when Qr and Mr is None # do not use this function for now def mask_dataset_ex(data, Q, M, cond_var): N, D = data.shape Qs, Qr = Q Ms, Mr = M leaf_var = utils.notin(range(D), cond_var) if isinstance(Qs, list): assert( Qr is None ) query = [Qs] * N else: total_qsize = int(np.round(D*Qs)) if Qr is None: cond_qsize = [np.random.choice(total_qsize + 1) for i in range(N)] else: cond_qsize = [int(np.round(total_qsize * Qr))] * N query = [] for i in range(N): qs_cond = cond_qsize[i] qs_leaf = total_qsize - qs_cond qvar_cond = np.random.choice(cond_var, size=qs_cond, replace=False) qvar_leaf = np.random.choice(leaf_var, size=qs_leaf, replace=False) qvar = np.concatenate([qvar_cond, qvar_leaf]) query.append(qvar) total_msize = int(np.round(D*Ms)) if Mr is None: cond_msize = [np.random.choice(total_msize + 1) for i in range(N)] else: cond_msize = [int(np.round(total_msize * Mr))] * N missing = [] for i in range(N): ms_cond = cond_msize[i] pool = utils.notin(cond_var, query[i]) mvar_cond = np.random.choice(pool, size=ms_cond, replace=False) ms_leaf = total_msize - ms_cond pool = utils.notin(leaf_var, query[i]) mvar_leaf = np.random.choice(pool, size=ms_leaf, replace=False) mvar = np.concatenate([mvar_cond, mvar_leaf]) missing.append(mvar) masked = _do_mask_(data, query, missing) return masked, query, missing
[ "utmLib.utils.dict2obj", "numpy.mean", "numpy.median", "numpy.sqrt", "configparser.ConfigParser", "numpy.random.choice", "utmLib.ml.potential.CLG.corr_coef", "sklearn.decomposition.PCA", "utmLib.utils.notin", "numpy.square", "os.path.realpath", "numpy.array", "numpy.zeros", "numpy.sum", ...
[((484, 501), 'numpy.array', 'np.array', (['acc_sum'], {}), '(acc_sum)\n', (492, 501), True, 'import numpy as np\n'), ((776, 805), 'numpy.zeros', 'np.zeros', (['(D, D)'], {'dtype': 'float'}), '((D, D), dtype=float)\n', (784, 805), True, 'import numpy as np\n'), ((1074, 1086), 'numpy.sqrt', 'np.sqrt', (['mse'], {}), '(mse)\n', (1081, 1086), True, 'import numpy as np\n'), ((1497, 1510), 'numpy.mean', 'np.mean', (['rmse'], {}), '(rmse)\n', (1504, 1510), True, 'import numpy as np\n'), ((1754, 1780), 'numpy.percentile', 'np.percentile', (['logmass', '(25)'], {}), '(logmass, 25)\n', (1767, 1780), True, 'import numpy as np\n'), ((1795, 1813), 'numpy.median', 'np.median', (['logmass'], {}), '(logmass)\n', (1804, 1813), True, 'import numpy as np\n'), ((1825, 1851), 'numpy.percentile', 'np.percentile', (['logmass', '(75)'], {}), '(logmass, 75)\n', (1838, 1851), True, 'import numpy as np\n'), ((1867, 1883), 'numpy.mean', 'np.mean', (['logmass'], {}), '(logmass)\n', (1874, 1883), True, 'import numpy as np\n'), ((2125, 2152), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (2150, 2152), False, 'import configparser, os\n'), ((2827, 2852), 'utmLib.utils.dict2obj', 'utils.dict2obj', (['conf_dict'], {}), '(conf_dict)\n', (2841, 2852), False, 'from utmLib import utils\n'), ((3178, 3218), 'numpy.concatenate', 'np.concatenate', (['[query, missing]'], {'axis': '(1)'}), '([query, missing], axis=1)\n', (3192, 3218), True, 'import numpy as np\n'), ((868, 898), 'utmLib.ml.potential.CLG.corr_coef', 'CLG.corr_coef', (['data[:, (i, j)]'], {}), '(data[:, (i, j)])\n', (881, 898), False, 'from utmLib.ml.potential import CLG\n'), ((1022, 1038), 'numpy.square', 'np.square', (['(a - b)'], {}), '(a - b)\n', (1031, 1038), True, 'import numpy as np\n'), ((1591, 1603), 'numpy.std', 'np.std', (['rmse'], {}), '(rmse)\n', (1597, 1603), True, 'import numpy as np\n'), ((2956, 2982), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (2972, 2982), False, 'import configparser, os\n'), ((3671, 3686), 'numpy.round', 'np.round', (['(D * M)'], {}), '(D * M)\n', (3679, 3686), True, 'import numpy as np\n'), ((4937, 4953), 'numpy.round', 'np.round', (['(D * Ms)'], {}), '(D * Ms)\n', (4945, 4953), True, 'import numpy as np\n'), ((5213, 5244), 'utmLib.utils.notin', 'utils.notin', (['cond_var', 'query[i]'], {}), '(cond_var, query[i])\n', (5224, 5244), False, 'from utmLib import utils\n'), ((5266, 5317), 'numpy.random.choice', 'np.random.choice', (['pool'], {'size': 'ms_cond', 'replace': '(False)'}), '(pool, size=ms_cond, replace=False)\n', (5282, 5317), True, 'import numpy as np\n'), ((5375, 5406), 'utmLib.utils.notin', 'utils.notin', (['leaf_var', 'query[i]'], {}), '(leaf_var, query[i])\n', (5386, 5406), False, 'from utmLib import utils\n'), ((5428, 5479), 'numpy.random.choice', 'np.random.choice', (['pool'], {'size': 'ms_leaf', 'replace': '(False)'}), '(pool, size=ms_leaf, replace=False)\n', (5444, 5479), True, 'import numpy as np\n'), ((5496, 5534), 'numpy.concatenate', 'np.concatenate', (['[mvar_cond, mvar_leaf]'], {}), '([mvar_cond, mvar_leaf])\n', (5510, 5534), True, 'import numpy as np\n'), ((339, 344), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (342, 344), False, 'from sklearn.decomposition import PCA\n'), ((561, 580), 'numpy.sum', 'np.sum', (['(acc_sum > p)'], {}), '(acc_sum > p)\n', (567, 580), True, 'import numpy as np\n'), ((3553, 3568), 'numpy.round', 'np.round', (['(D * Q)'], {}), '(D * Q)\n', (3561, 3568), True, 'import numpy as np\n'), ((3586, 3632), 'numpy.random.choice', 'np.random.choice', (['D'], {'size': 'qsize', 'replace': '(False)'}), '(D, size=qsize, replace=False)\n', (3602, 3632), True, 'import numpy as np\n'), ((3801, 3850), 'numpy.random.choice', 'np.random.choice', (['pool'], {'size': 'msize', 'replace': '(False)'}), '(pool, size=msize, replace=False)\n', (3817, 3850), True, 'import numpy as np\n'), ((4328, 4344), 'numpy.round', 'np.round', (['(D * Qs)'], {}), '(D * Qs)\n', (4336, 4344), True, 'import numpy as np\n'), ((4684, 4739), 'numpy.random.choice', 'np.random.choice', (['cond_var'], {'size': 'qs_cond', 'replace': '(False)'}), '(cond_var, size=qs_cond, replace=False)\n', (4700, 4739), True, 'import numpy as np\n'), ((4765, 4820), 'numpy.random.choice', 'np.random.choice', (['leaf_var'], {'size': 'qs_leaf', 'replace': '(False)'}), '(leaf_var, size=qs_leaf, replace=False)\n', (4781, 4820), True, 'import numpy as np\n'), ((4841, 4879), 'numpy.concatenate', 'np.concatenate', (['[qvar_cond, qvar_leaf]'], {}), '([qvar_cond, qvar_leaf])\n', (4855, 4879), True, 'import numpy as np\n'), ((4996, 5029), 'numpy.random.choice', 'np.random.choice', (['(total_msize + 1)'], {}), '(total_msize + 1)\n', (5012, 5029), True, 'import numpy as np\n'), ((4395, 4428), 'numpy.random.choice', 'np.random.choice', (['(total_qsize + 1)'], {}), '(total_qsize + 1)\n', (4411, 4428), True, 'import numpy as np\n'), ((5087, 5113), 'numpy.round', 'np.round', (['(total_msize * Mr)'], {}), '(total_msize * Mr)\n', (5095, 5113), True, 'import numpy as np\n'), ((4494, 4520), 'numpy.round', 'np.round', (['(total_qsize * Qr)'], {}), '(total_qsize * Qr)\n', (4502, 4520), True, 'import numpy as np\n')]
import numpy as np from vg.compat import v2 as vg __all__ = [ "rectangular_prism", "cube", "triangular_prism", ] def _maybe_flatten(vertices, faces, ret_unique_vertices_and_faces): if ret_unique_vertices_and_faces: return vertices, faces else: return vertices[faces] def rectangular_prism(origin, size, ret_unique_vertices_and_faces=False): """ Tesselate an axis-aligned rectangular prism. One vertex is `origin`. The diametrically opposite vertex is `origin + size`. Args: origin (np.ndarray): A 3D point vector containing the point on the prism with the minimum x, y, and z coords. size (np.ndarray): A 3D vector specifying the prism's length, width, and height, which should be positive. ret_unique_vertices_and_faces (bool): When `True` return a vertex array containing the unique vertices and an array of faces (i.e. vertex indices). When `False`, return a flattened array of triangle coordinates. Returns: object: - With `ret_unique_vertices_and_faces=True`: a tuple containing an `8x3` array of vertices and a `12x3` array of triangle faces. - With `ret_unique_vertices_and_faces=False`: a `12x3x3` matrix of flattened triangle coordinates. """ from ..tri import quads_to_tris vg.shape.check(locals(), "origin", (3,)) vg.shape.check(locals(), "size", (3,)) lower_base_plane = np.array( [ # Lower base plane origin, origin + np.array([size[0], 0, 0]), origin + np.array([size[0], 0, size[2]]), origin + np.array([0, 0, size[2]]), ] ) upper_base_plane = lower_base_plane + np.array([0, size[1], 0]) vertices = np.vstack([lower_base_plane, upper_base_plane]) faces = np.array( quads_to_tris( np.array( [ [0, 1, 2, 3], # lower base (-y) [7, 6, 5, 4], # upper base (+y) [4, 5, 1, 0], # -z face [5, 6, 2, 1], # +x face [6, 7, 3, 2], # +z face [3, 7, 4, 0], # -x face ], ) ), ) return _maybe_flatten(vertices, faces, ret_unique_vertices_and_faces) def cube(origin, size, ret_unique_vertices_and_faces=False): """ Tesselate an axis-aligned cube. One vertex is `origin`. The diametrically opposite vertex is `size` units along `+x`, `+y`, and `+z`. Args: origin (np.ndarray): A 3D point vector containing the point on the prism with the minimum x, y, and z coords. size (float): The length, width, and height of the cube, which should be positive. ret_unique_vertices_and_faces (bool): When `True` return a vertex array containing the unique vertices and an array of faces (i.e. vertex indices). When `False`, return a flattened array of triangle coordinates. Returns: object: - With `ret_unique_vertices_and_faces=True`: a tuple containing an `8x3` array of vertices and a `12x3` array of triangle faces. - With `ret_unique_vertices_and_faces=False`: a `12x3x3` matrix of flattened triangle coordinates. """ vg.shape.check(locals(), "origin", (3,)) if not isinstance(size, float): raise ValueError("`size` should be a number") return rectangular_prism( origin, np.repeat(size, 3), ret_unique_vertices_and_faces=ret_unique_vertices_and_faces, ) def triangular_prism(p1, p2, p3, height, ret_unique_vertices_and_faces=False): """ Tesselate a triangular prism whose base is the triangle `p1`, `p2`, `p3`. If the vertices are oriented in a counterclockwise direction, the prism extends from behind them. Args: p1 (np.ndarray): A 3D point on the base of the prism. p2 (np.ndarray): A 3D point on the base of the prism. p3 (np.ndarray): A 3D point on the base of the prism. height (float): The height of the prism, which should be positive. ret_unique_vertices_and_faces (bool): When `True` return a vertex array containing the unique vertices and an array of faces (i.e. vertex indices). When `False`, return a flattened array of triangle coordinates. Returns: object: - With `ret_unique_vertices_and_faces=True`: a tuple containing an `6x3` array of vertices and a `8x3` array of triangle faces. - With `ret_unique_vertices_and_faces=False`: a `8x3x3` matrix of flattened triangle coordinates. """ from .. import Plane vg.shape.check(locals(), "p1", (3,)) vg.shape.check(locals(), "p2", (3,)) vg.shape.check(locals(), "p3", (3,)) if not isinstance(height, float): raise ValueError("`height` should be a number") base_plane = Plane.from_points(p1, p2, p3) lower_base_to_upper_base = height * -base_plane.normal vertices = np.vstack(([p1, p2, p3], [p1, p2, p3] + lower_base_to_upper_base)) faces = np.array( [ [0, 1, 2], # base [0, 3, 4], [0, 4, 1], # side 0, 3, 4, 1 [1, 4, 5], [1, 5, 2], # side 1, 4, 5, 2 [2, 5, 3], [2, 3, 0], # side 2, 5, 3, 0 [5, 4, 3], # base ], ) return _maybe_flatten(vertices, faces, ret_unique_vertices_and_faces)
[ "numpy.array", "numpy.repeat", "numpy.vstack" ]
[((1818, 1865), 'numpy.vstack', 'np.vstack', (['[lower_base_plane, upper_base_plane]'], {}), '([lower_base_plane, upper_base_plane])\n', (1827, 1865), True, 'import numpy as np\n'), ((5131, 5197), 'numpy.vstack', 'np.vstack', (['([p1, p2, p3], [p1, p2, p3] + lower_base_to_upper_base)'], {}), '(([p1, p2, p3], [p1, p2, p3] + lower_base_to_upper_base))\n', (5140, 5197), True, 'import numpy as np\n'), ((5211, 5313), 'numpy.array', 'np.array', (['[[0, 1, 2], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [2, 3, 0\n ], [5, 4, 3]]'], {}), '([[0, 1, 2], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3],\n [2, 3, 0], [5, 4, 3]])\n', (5219, 5313), True, 'import numpy as np\n'), ((1776, 1801), 'numpy.array', 'np.array', (['[0, size[1], 0]'], {}), '([0, size[1], 0])\n', (1784, 1801), True, 'import numpy as np\n'), ((3569, 3587), 'numpy.repeat', 'np.repeat', (['size', '(3)'], {}), '(size, 3)\n', (3578, 3587), True, 'import numpy as np\n'), ((1924, 2022), 'numpy.array', 'np.array', (['[[0, 1, 2, 3], [7, 6, 5, 4], [4, 5, 1, 0], [5, 6, 2, 1], [6, 7, 3, 2], [3, \n 7, 4, 0]]'], {}), '([[0, 1, 2, 3], [7, 6, 5, 4], [4, 5, 1, 0], [5, 6, 2, 1], [6, 7, 3,\n 2], [3, 7, 4, 0]])\n', (1932, 2022), True, 'import numpy as np\n'), ((1589, 1614), 'numpy.array', 'np.array', (['[size[0], 0, 0]'], {}), '([size[0], 0, 0])\n', (1597, 1614), True, 'import numpy as np\n'), ((1637, 1668), 'numpy.array', 'np.array', (['[size[0], 0, size[2]]'], {}), '([size[0], 0, size[2]])\n', (1645, 1668), True, 'import numpy as np\n'), ((1691, 1716), 'numpy.array', 'np.array', (['[0, 0, size[2]]'], {}), '([0, 0, size[2]])\n', (1699, 1716), True, 'import numpy as np\n')]
import math import random import numpy as np from util.data_util import pad_seq, pad_char_seq, pad_video_seq class TrainLoader: def __init__(self, dataset, visual_features, configs): super(TrainLoader, self).__init__() self.dataset = dataset self.visual_feats = visual_features self.extend = configs.extend self.batch_size = configs.batch_size def set_extend(self, extend): self.extend = extend def set_batch_size(self, batch_size): self.batch_size = batch_size def num_samples(self): return len(self.dataset) def num_batches(self): return math.ceil(len(self.dataset) / self.batch_size) def batch_iter(self): random.shuffle(self.dataset) # shuffle the train set first for index in range(0, len(self.dataset), self.batch_size): batch_data = self.dataset[index:(index + self.batch_size)] vfeats, vfeat_lens, word_ids, char_ids, s_labels, e_labels, h_labels = self.process_batch(batch_data) yield batch_data, vfeats, vfeat_lens, word_ids, char_ids, s_labels, e_labels, h_labels def process_batch(self, batch_data): vfeats, word_ids, char_ids, s_inds, e_inds = [], [], [], [], [] for data in batch_data: vfeat = self.visual_feats[data['vid']] vfeats.append(vfeat) word_ids.append(data['w_ids']) char_ids.append(data['c_ids']) s_inds.append(data['s_ind']) e_inds.append(data['e_ind']) batch_size = len(batch_data) # process word ids word_ids, _ = pad_seq(word_ids) word_ids = np.asarray(word_ids, dtype=np.int32) # (batch_size, w_seq_len) # process char ids char_ids, _ = pad_char_seq(char_ids) char_ids = np.asarray(char_ids, dtype=np.int32) # (batch_size, w_seq_len, c_seq_len) # process video features vfeats, vfeat_lens = pad_video_seq(vfeats) vfeats = np.asarray(vfeats, dtype=np.float32) # (batch_size, v_seq_len, v_dim) vfeat_lens = np.asarray(vfeat_lens, dtype=np.int32) # (batch_size, ) # process labels max_len = np.max(vfeat_lens) s_labels = np.zeros(shape=[batch_size, max_len], dtype=np.int32) e_labels = np.zeros(shape=[batch_size, max_len], dtype=np.int32) h_labels = np.zeros(shape=[batch_size, max_len], dtype=np.int32) for idx in range(batch_size): st, et = s_inds[idx], e_inds[idx] s_labels[idx][st] = 1 e_labels[idx][et] = 1 cur_max_len = vfeat_lens[idx] extend_len = round(self.extend * float(et - st + 1)) if extend_len > 0: st_ = max(0, st - extend_len) et_ = min(et + extend_len, cur_max_len - 1) h_labels[idx][st_:(et_ + 1)] = 1 else: h_labels[idx][st:(et + 1)] = 1 return vfeats, vfeat_lens, word_ids, char_ids, s_labels, e_labels, h_labels class TestLoader: def __init__(self, datasets, visual_features, configs): self.visual_feats = visual_features self.val_set = None if datasets['val_set'] is None else datasets['val_set'] self.test_set = datasets['test_set'] self.batch_size = configs.batch_size def set_batch_size(self, batch_size): self.batch_size = batch_size def num_samples(self, mode='test'): if mode == 'val': if self.val_set is None: return 0 return len(self.val_set) elif mode == 'test': return len(self.test_set) else: raise ValueError('Unknown mode!!! Only support [val | test | test_iid | test_ood].') def num_batches(self, mode='test'): if mode == 'val': if self.val_set is None: return 0 return math.ceil(len(self.val_set) / self.batch_size) elif mode == 'test': return math.ceil(len(self.test_set) / self.batch_size) else: raise ValueError('Unknown mode!!! Only support [val | test].') def test_iter(self, mode='test'): if mode not in ['val', 'test']: raise ValueError('Unknown mode!!! Only support [val | test].') test_sets = {'val': self.val_set, 'test': self.test_set} dataset = test_sets[mode] if mode == 'val' and dataset is None: raise ValueError('val set is not available!!!') for index in range(0, len(dataset), self.batch_size): batch_data = dataset[index:(index + self.batch_size)] vfeats, vfeat_lens, word_ids, char_ids = self.process_batch(batch_data) yield batch_data, vfeats, vfeat_lens, word_ids, char_ids def process_batch(self, batch_data): vfeats, word_ids, char_ids, s_inds, e_inds = [], [], [], [], [] for data in batch_data: vfeats.append(self.visual_feats[data['vid']]) word_ids.append(data['w_ids']) char_ids.append(data['c_ids']) s_inds.append(data['s_ind']) e_inds.append(data['e_ind']) # process word ids word_ids, _ = pad_seq(word_ids) word_ids = np.asarray(word_ids, dtype=np.int32) # (batch_size, w_seq_len) # process char ids char_ids, _ = pad_char_seq(char_ids) char_ids = np.asarray(char_ids, dtype=np.int32) # (batch_size, w_seq_len, c_seq_len) # process video features vfeats, vfeat_lens = pad_video_seq(vfeats) vfeats = np.asarray(vfeats, dtype=np.float32) # (batch_size, v_seq_len, v_dim) vfeat_lens = np.asarray(vfeat_lens, dtype=np.int32) # (batch_size, ) return vfeats, vfeat_lens, word_ids, char_ids
[ "random.shuffle", "numpy.asarray", "util.data_util.pad_seq", "numpy.max", "numpy.zeros", "util.data_util.pad_video_seq", "util.data_util.pad_char_seq" ]
[((720, 748), 'random.shuffle', 'random.shuffle', (['self.dataset'], {}), '(self.dataset)\n', (734, 748), False, 'import random\n'), ((1615, 1632), 'util.data_util.pad_seq', 'pad_seq', (['word_ids'], {}), '(word_ids)\n', (1622, 1632), False, 'from util.data_util import pad_seq, pad_char_seq, pad_video_seq\n'), ((1652, 1688), 'numpy.asarray', 'np.asarray', (['word_ids'], {'dtype': 'np.int32'}), '(word_ids, dtype=np.int32)\n', (1662, 1688), True, 'import numpy as np\n'), ((1765, 1787), 'util.data_util.pad_char_seq', 'pad_char_seq', (['char_ids'], {}), '(char_ids)\n', (1777, 1787), False, 'from util.data_util import pad_seq, pad_char_seq, pad_video_seq\n'), ((1807, 1843), 'numpy.asarray', 'np.asarray', (['char_ids'], {'dtype': 'np.int32'}), '(char_ids, dtype=np.int32)\n', (1817, 1843), True, 'import numpy as np\n'), ((1944, 1965), 'util.data_util.pad_video_seq', 'pad_video_seq', (['vfeats'], {}), '(vfeats)\n', (1957, 1965), False, 'from util.data_util import pad_seq, pad_char_seq, pad_video_seq\n'), ((1983, 2019), 'numpy.asarray', 'np.asarray', (['vfeats'], {'dtype': 'np.float32'}), '(vfeats, dtype=np.float32)\n', (1993, 2019), True, 'import numpy as np\n'), ((2075, 2113), 'numpy.asarray', 'np.asarray', (['vfeat_lens'], {'dtype': 'np.int32'}), '(vfeat_lens, dtype=np.int32)\n', (2085, 2113), True, 'import numpy as np\n'), ((2175, 2193), 'numpy.max', 'np.max', (['vfeat_lens'], {}), '(vfeat_lens)\n', (2181, 2193), True, 'import numpy as np\n'), ((2213, 2266), 'numpy.zeros', 'np.zeros', ([], {'shape': '[batch_size, max_len]', 'dtype': 'np.int32'}), '(shape=[batch_size, max_len], dtype=np.int32)\n', (2221, 2266), True, 'import numpy as np\n'), ((2286, 2339), 'numpy.zeros', 'np.zeros', ([], {'shape': '[batch_size, max_len]', 'dtype': 'np.int32'}), '(shape=[batch_size, max_len], dtype=np.int32)\n', (2294, 2339), True, 'import numpy as np\n'), ((2359, 2412), 'numpy.zeros', 'np.zeros', ([], {'shape': '[batch_size, max_len]', 'dtype': 'np.int32'}), '(shape=[batch_size, max_len], dtype=np.int32)\n', (2367, 2412), True, 'import numpy as np\n'), ((5170, 5187), 'util.data_util.pad_seq', 'pad_seq', (['word_ids'], {}), '(word_ids)\n', (5177, 5187), False, 'from util.data_util import pad_seq, pad_char_seq, pad_video_seq\n'), ((5207, 5243), 'numpy.asarray', 'np.asarray', (['word_ids'], {'dtype': 'np.int32'}), '(word_ids, dtype=np.int32)\n', (5217, 5243), True, 'import numpy as np\n'), ((5320, 5342), 'util.data_util.pad_char_seq', 'pad_char_seq', (['char_ids'], {}), '(char_ids)\n', (5332, 5342), False, 'from util.data_util import pad_seq, pad_char_seq, pad_video_seq\n'), ((5362, 5398), 'numpy.asarray', 'np.asarray', (['char_ids'], {'dtype': 'np.int32'}), '(char_ids, dtype=np.int32)\n', (5372, 5398), True, 'import numpy as np\n'), ((5499, 5520), 'util.data_util.pad_video_seq', 'pad_video_seq', (['vfeats'], {}), '(vfeats)\n', (5512, 5520), False, 'from util.data_util import pad_seq, pad_char_seq, pad_video_seq\n'), ((5538, 5574), 'numpy.asarray', 'np.asarray', (['vfeats'], {'dtype': 'np.float32'}), '(vfeats, dtype=np.float32)\n', (5548, 5574), True, 'import numpy as np\n'), ((5630, 5668), 'numpy.asarray', 'np.asarray', (['vfeat_lens'], {'dtype': 'np.int32'}), '(vfeat_lens, dtype=np.int32)\n', (5640, 5668), True, 'import numpy as np\n')]
import os import os.path as osp import sys sys.path.append('../') import numpy as np import argparse import cv2 import time import configs from preprocessing.dataset import preprocessing from models import cpn as modellib from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from pycocotools import mask as COCOmask import keras.backend as K def test_net(model, dets, ranges, config): min_scores = 1e-10 min_box_size = 0. # 8 ** 2 all_res = [] dump_results = [] N = len(ranges) start_time = time.time() for index_ in range(N - 1): det_range = [ranges[index_], ranges[index_ + 1]] img_start = det_range[0] while img_start < det_range[1]: img_end = img_start + 1 im_info = dets[img_start] while img_end < det_range[1] and dets[img_end]['image_id'] == im_info['image_id']: img_end += 1 test_data = dets[img_start: img_end] img_start = img_end iter_avg_cost_time = (time.time() - start_time) / (img_end - ranges[0]) print('ran %.ds >> << left %.ds' % ( iter_avg_cost_time * (img_end - ranges[0]), iter_avg_cost_time * (ranges[-1] - img_end))) all_res.append([]) # get box detections cls_dets = np.zeros((len(test_data), 5), dtype=np.float32) for i in range(len(test_data)): bbox = np.asarray(test_data[i]['bbox']) cls_dets[i, :4] = np.array([bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]]) cls_dets[i, 4] = np.array(test_data[i]['score']) # nms and filter keep = np.where((cls_dets[:, 4] >= min_scores) & ((cls_dets[:, 3] - cls_dets[:, 1]) * (cls_dets[:, 2] - cls_dets[:, 0]) >= min_box_size))[0] cls_dets = cls_dets[keep] test_data = np.asarray(test_data)[keep] if len(keep) == 0: continue # crop and detect keypoints cls_skeleton = np.zeros((len(test_data), config.KEYPOINTS_NUM, 3)) crops = np.zeros((len(test_data), 4)) batch_size = 8 for test_id in range(0, len(test_data), batch_size): start_id = test_id end_id = min(len(test_data), test_id + batch_size) test_imgs = [] details = [] for ii_ in range(start_id, end_id): res_tmp = preprocessing(test_data[ii_], config, stage='test') test_imgs.append(res_tmp[0]) details.append(res_tmp[1]) details = np.asarray(details) feed = test_imgs for ii_ in range(end_id - start_id): ori_img = test_imgs[ii_][0] flip_img = cv2.flip(ori_img, 1) feed.append(flip_img[np.newaxis, ...]) feed = np.vstack(feed) ## model predict res = model.keras_model.predict([feed], verbose=0) res = res.transpose(0, 3, 1, 2) # [batch, kps, h, w] ## combine flip result for ii_ in range(end_id - start_id): fmp = res[end_id - start_id + ii_].transpose((1, 2, 0)) fmp = cv2.flip(fmp, 1) fmp = list(fmp.transpose((2, 0, 1))) for (q, w) in config.symmetry: fmp[q], fmp[w] = fmp[w], fmp[q] fmp = np.array(fmp) res[ii_] += fmp res[ii_] /= 2 for test_image_id in range(start_id, end_id): r0 = res[test_image_id - start_id].copy() r0 /= 255 r0 += 0.5 # ?? for w in range(config.KEYPOINTS_NUM): res[test_image_id - start_id, w] /= np.amax(res[test_image_id - start_id, w]) border = 10 dr = np.zeros((config.KEYPOINTS_NUM, config.OUTPUT_SHAPE[0] + 2 * border, config.OUTPUT_SHAPE[1] + 2 * border)) dr[:, border:-border, border:-border] = res[test_image_id - start_id][: config.KEYPOINTS_NUM].copy() for w in range(config.KEYPOINTS_NUM): dr[w] = cv2.GaussianBlur(dr[w], (21, 21), 0) ## find first max and second max one for w in range(config.KEYPOINTS_NUM): lb = dr[w].argmax() y, x = np.unravel_index(lb, dr[w].shape) dr[w, y, x] = 0 lb = dr[w].argmax() py, px = np.unravel_index(lb, dr[w].shape) y -= border x -= border py -= border + y px -= border + x ln = (px ** 2 + py ** 2) ** 0.5 delta = 0.25 if ln > 1e-3: x += delta * px / ln y += delta * py / ln x = max(0, min(x, config.OUTPUT_SHAPE[1] - 1)) y = max(0, min(y, config.OUTPUT_SHAPE[0] - 1)) cls_skeleton[test_image_id, w, :2] = (x * 4 + 2, y * 4 + 2) ## why add 2? cls_skeleton[test_image_id, w, 2] = r0[w, int(round(y) + 1e-10), int(round(x) + 1e-10)] # map back to original images crops[test_image_id, :] = details[test_image_id - start_id, :] for w in range(config.KEYPOINTS_NUM): cls_skeleton[test_image_id, w, 0] = cls_skeleton[test_image_id, w, 0] / config.DATA_SHAPE[1] * ( crops[test_image_id][2] - crops[test_image_id][0]) + crops[test_image_id][0] cls_skeleton[test_image_id, w, 1] = cls_skeleton[test_image_id, w, 1] / config.DATA_SHAPE[0] * ( crops[test_image_id][3] - crops[test_image_id][1]) + crops[test_image_id][1] all_res[-1] = [cls_skeleton.copy(), cls_dets.copy()] cls_partsco = cls_skeleton[:, :, 2].copy().reshape(-1, config.KEYPOINTS_NUM) cls_skeleton[:, :, 2] = 1 cls_scores = cls_dets[:, -1].copy() # rescore cls_dets[:, -1] = cls_scores * cls_partsco.mean(axis=1) cls_skeleton = np.concatenate( [cls_skeleton.reshape(-1, config.KEYPOINTS_NUM * 3), (cls_scores * cls_partsco.mean(axis=1))[:, np.newaxis]], axis=1) for i in range(len(cls_skeleton)): result = dict(image_id=im_info['image_id'], category_id=1, score=float(round(cls_skeleton[i][-1], 4)), keypoints=cls_skeleton[i][:-1].round(3).tolist()) dump_results.append(result) return all_res, dump_results def test(test_model, dets_path, gt_path): # loading model """ config_file = os.path.basename(args.cfg).split('.')[0] config_def = eval('configs.' + config_file + '.Config') config = config_def() config.GPUs = args.gpu_id os.environ["CUDA_VISIBLE_DEVICES"] = config.GPUs model = modellib.CPN(mode="inference", config=config, model_dir="") model.load_weights(test_model, by_name=True) """ eval_gt = COCO(gt_path) """ import json with open(dets_path, 'r') as f: dets = json.load(f) dets = [i for i in dets if i['image_id'] in eval_gt.imgs] dets = [i for i in dets if i['category_id'] == 1] dets.sort(key=lambda x: (x['image_id'], x['score']), reverse=True) for i in dets: i['imgpath'] = '../data/COCO/MSCOCO/val2014/COCO_val2014_000000%06d.jpg' % i['image_id'] img_num = len(np.unique([i['image_id'] for i in dets])) #from IPython import embed; embed() ranges = [0] img_start = 0 for run_img in range(img_num): img_end = img_start + 1 while img_end < len(dets) and dets[img_end]['image_id'] == dets[img_start]['image_id']: img_end += 1 if (run_img + 1) % config.IMAGES_PER_GPU == 0 or (run_img + 1) == img_num: ranges.append(img_end) img_start = img_end _, dump_results = test_net(model, dets, ranges, config) output_dir = "logs" if not os.path.exists(output_dir): os.mkdir(output_dir) result_path = osp.join(output_dir, 'results.json') with open(result_path, 'w') as f: json.dump(dump_results, f) """ result_path = osp.join("logs", 'results.json') eval_dt = eval_gt.loadRes(result_path) cocoEval = COCOeval(eval_gt, eval_dt, iouType='keypoints') cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() K.clear_session() if __name__ == '__main__': def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--gpu', '-d', type=str, dest='gpu_id') parser.add_argument('--model', '-m', required=True, type=str, dest='test_model') parser.add_argument('--cfg', '-c', required=True, type=str, dest='cfg') args = parser.parse_args() print(args.test_model) return args global args args = parse_args() dets_path = "../data/COCO/dets/person_detection_minival411_human553.json.coco" gt_path = "../data/COCO/MSCOCO/person_keypoints_minival2014.json" if args.test_model: test(args.test_model, dets_path, gt_path) #from IPython import embed; embed()
[ "preprocessing.dataset.preprocessing", "numpy.amax", "pycocotools.cocoeval.COCOeval", "argparse.ArgumentParser", "cv2.flip", "numpy.where", "os.path.join", "pycocotools.coco.COCO", "numpy.asarray", "numpy.array", "numpy.zeros", "keras.backend.clear_session", "numpy.vstack", "time.time", ...
[((43, 65), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (58, 65), False, 'import sys\n'), ((542, 553), 'time.time', 'time.time', ([], {}), '()\n', (551, 553), False, 'import time\n'), ((7432, 7445), 'pycocotools.coco.COCO', 'COCO', (['gt_path'], {}), '(gt_path)\n', (7436, 7445), False, 'from pycocotools.coco import COCO\n'), ((8612, 8644), 'os.path.join', 'osp.join', (['"""logs"""', '"""results.json"""'], {}), "('logs', 'results.json')\n", (8620, 8644), True, 'import os.path as osp\n'), ((8703, 8750), 'pycocotools.cocoeval.COCOeval', 'COCOeval', (['eval_gt', 'eval_dt'], {'iouType': '"""keypoints"""'}), "(eval_gt, eval_dt, iouType='keypoints')\n", (8711, 8750), False, 'from pycocotools.cocoeval import COCOeval\n'), ((8836, 8853), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (8851, 8853), True, 'import keras.backend as K\n'), ((8934, 8959), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (8957, 8959), False, 'import argparse\n'), ((1436, 1468), 'numpy.asarray', 'np.asarray', (["test_data[i]['bbox']"], {}), "(test_data[i]['bbox'])\n", (1446, 1468), True, 'import numpy as np\n'), ((1503, 1569), 'numpy.array', 'np.array', (['[bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]]'], {}), '([bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]])\n', (1511, 1569), True, 'import numpy as np\n'), ((1603, 1634), 'numpy.array', 'np.array', (["test_data[i]['score']"], {}), "(test_data[i]['score'])\n", (1611, 1634), True, 'import numpy as np\n'), ((1683, 1818), 'numpy.where', 'np.where', (['((cls_dets[:, 4] >= min_scores) & ((cls_dets[:, 3] - cls_dets[:, 1]) * (\n cls_dets[:, 2] - cls_dets[:, 0]) >= min_box_size))'], {}), '((cls_dets[:, 4] >= min_scores) & ((cls_dets[:, 3] - cls_dets[:, 1]\n ) * (cls_dets[:, 2] - cls_dets[:, 0]) >= min_box_size))\n', (1691, 1818), True, 'import numpy as np\n'), ((1903, 1924), 'numpy.asarray', 'np.asarray', (['test_data'], {}), '(test_data)\n', (1913, 1924), True, 'import numpy as np\n'), ((2666, 2685), 'numpy.asarray', 'np.asarray', (['details'], {}), '(details)\n', (2676, 2685), True, 'import numpy as np\n'), ((2954, 2969), 'numpy.vstack', 'np.vstack', (['feed'], {}), '(feed)\n', (2963, 2969), True, 'import numpy as np\n'), ((1029, 1040), 'time.time', 'time.time', ([], {}), '()\n', (1038, 1040), False, 'import time\n'), ((2492, 2543), 'preprocessing.dataset.preprocessing', 'preprocessing', (['test_data[ii_]', 'config'], {'stage': '"""test"""'}), "(test_data[ii_], config, stage='test')\n", (2505, 2543), False, 'from preprocessing.dataset import preprocessing\n'), ((2851, 2871), 'cv2.flip', 'cv2.flip', (['ori_img', '(1)'], {}), '(ori_img, 1)\n', (2859, 2871), False, 'import cv2\n'), ((3350, 3366), 'cv2.flip', 'cv2.flip', (['fmp', '(1)'], {}), '(fmp, 1)\n', (3358, 3366), False, 'import cv2\n'), ((3557, 3570), 'numpy.array', 'np.array', (['fmp'], {}), '(fmp)\n', (3565, 3570), True, 'import numpy as np\n'), ((4047, 4158), 'numpy.zeros', 'np.zeros', (['(config.KEYPOINTS_NUM, config.OUTPUT_SHAPE[0] + 2 * border, config.\n OUTPUT_SHAPE[1] + 2 * border)'], {}), '((config.KEYPOINTS_NUM, config.OUTPUT_SHAPE[0] + 2 * border, config\n .OUTPUT_SHAPE[1] + 2 * border))\n', (4055, 4158), True, 'import numpy as np\n'), ((3948, 3989), 'numpy.amax', 'np.amax', (['res[test_image_id - start_id, w]'], {}), '(res[test_image_id - start_id, w])\n', (3955, 3989), True, 'import numpy as np\n'), ((4365, 4401), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['dr[w]', '(21, 21)', '(0)'], {}), '(dr[w], (21, 21), 0)\n', (4381, 4401), False, 'import cv2\n'), ((4592, 4625), 'numpy.unravel_index', 'np.unravel_index', (['lb', 'dr[w].shape'], {}), '(lb, dr[w].shape)\n', (4608, 4625), True, 'import numpy as np\n'), ((4743, 4776), 'numpy.unravel_index', 'np.unravel_index', (['lb', 'dr[w].shape'], {}), '(lb, dr[w].shape)\n', (4759, 4776), True, 'import numpy as np\n')]
from rgbmaker import RGBMaker as rgbmaker from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt from rgbmaker.tgss_spidx import find_spidx from matplotlib import pyplot as plt from regions import PixCoord, EllipsePixelRegion from astropy.coordinates import Angle, SkyCoord from astropy import units as ut from matplotlib.collections import PatchCollection import matplotlib.patches as mpatches import numpy as np import io import urllib import base64 from time import perf_counter from os import path, makedirs import sys def query(name="", position="", radius=float(0.12), archives=1, imagesopt=2, kind='base64', spidx_file=None, px=480, annot=True): """ .. jupyter-execute:: from rgbmaker.fetch import query query(name='Avi', position='3C 33.1', radius=0.12, kind='plot') *Parameters* :name: (Optional) (default=Anonymous) (string) Your name will be displayed on the image enabling mentors, professors, fellow students to be able to recognize your work. Credit is important! :position: (Required) The object name or the coordinates of the object in the FK5 (J2000) system. Ex: "14 09 48.86 -03 02 32.6", M87, NGC1243, without quotes. :radius: (Required) (default = 0.12) (float) The size of the image in degrees, this size will be used for the `field of view <https://en.wikipedia.org/wiki/Field_of_view/>`_ in the resultant image. For reference, in the night sky, the moon is about 0.52 degrees across. :imagesopt: (default=2)(string)(values=1,2,3) This dropdown gives you a choice of the composite images you want to create. **IOU ROR Optical (option = 1)** *This option returns four images.* 1. There are two `ROR <https://radathomeindia.org/rgbmaker-info#what-is-iou-ror-and-rgb>_` *(Radio (TGSS ADR1) - Optical (DSS2Red) - Radio (NVSS))* images. One with TGSS Contours and another with NVSS Contours. 2. The third image is an `IOU <https://radathomeindia.org/rgbmaker-info#what-is-iou-ror-and-rgb>_` *(Infrared (WISE 22) - Optical (DSS2 Red) - Ultraviolet (Galex Near UV))* with TGSS Contours. 3. The final RGB image is an optical image with *(DSS2IR - DSS2Red - DSS2Blue)* with TGGSS Contours. **Composite Contours on DSS2R (option = 2)** *This option returns two images.* 1. The first is a `ROR <https://radathomeindia.org/rgbmaker-info#what-is-iou-ror-and-rgb>_` Image with TGSS contours. The various symbol seen on the image is the `catalog <https://en.wikipedia.org/wiki/List_of_astronomical_catalogues/>`_ data of the respective survey. 2. The second image is a composite image with DSS2Red background and contours of various radio surveys like TGSS, NVSS, and VLA First (if available). :archives: (default=1)(string) This dropdown currently offers access to the NVAS image archive. Selecting this option will return the top 5 results from NVAS (if exists). These can be downloaded as .imfits files (open with DS9) by using save as an option when right-clicked. :kind: (default='base64') choose from base64, plot, png, jpg to show base64 of resultant image, plot on output, save png/jpg files :spidx_file: (Default=None) enter path to spidx.fits file that contains spectral index data (see example 1). :px: (default=480) change pixel value for the final resulatant image. :annot: (default=True) remove any annotation by setting this to False. """ fetch_q = rgbmaker(name=name, position=position, radius=radius, archives=archives, imagesopt=imagesopt) name = fetch_q.name start = perf_counter() fetch_q.px = px val = fetch_q.submit_query() level_contour=4 if fetch_q.server_down: fetch_q.status, fetch_q.info = 'warning', 'SkyView is down!' return fetch_q.throw_output() else: fetch_q.otext.append({'Target center': fetch_q.c.to_string('hmsdms')}) if fetch_q.imagesopt == 1 and fetch_q.c: # --- using variables for readability -#--# tgss, dss2r, nvss, w22, gnuv, dss2i, dss2b = val['tgss']['data'], val[ 'dss2r']['data'], val['nvss']['data'], val['w22']['data'], val[ 'gnuv']['data'], val['dss2ir']['data'], val['dss2b']['data'] # --- creating images ----------#--# img1, lvlc1 = overlayc(tgss, dss2r, nvss, nvss, level_contour, 0.0015) # NVSS img2, lvlc2 = overlayc(tgss, dss2r, nvss, tgss, level_contour, 0.015) # TGSS img3 = overlayo(w22,dss2r,gnuv, kind='IOU') img4 = overlayo(dss2i,dss2r,dss2b, kind='Optical') if lvlc1 is not None: fetch_q.otext.append({'TGSS contour ': (str(np.round(lvlc2, 3)))}) # TGSS if lvlc2 is not None: fetch_q.otext.append({'NVSS contour ': (str(np.round(lvlc1, 4)))}) # NVSS # -------- plotting first plot -------------#--# plt.ioff() fig = plt.figure(figsize=(20, 20)) pl_RGBC(1, 2, 1, fetch_q.wcs, val['nvss']['data'], lvlc1, img1, fig, name,annot=annot) pl_RGBC(1, 2, 2, fetch_q.wcs, val['tgss']['data'], lvlc2, img2, fig, name,annot=annot) plt.subplots_adjust(wspace=0.01, hspace=0.01) #-------- Saving first plot ------#--# string = save_fig(plt, fig, kind) fetch_q.uri.append( {'img1': 'data:image/png;base64,' + urllib.parse.quote(string)}) #-------- plotting second plot -----#--# plt.ioff() fig1 = plt.figure(figsize=(20, 20)) pl_RGBC(1, 2, 1, fetch_q.wcs, val['tgss']['data'], lvlc2, img3, fig1, name, pkind='iou',annot=annot) pl_RGBC(1, 2, 2, fetch_q.wcs, val['tgss']['data'], lvlc2, img4, fig1, name, pkind='iou',annot=annot) plt.subplots_adjust(wspace=0.01, hspace=0.01) #-------- Saving second plot ------#--# string1 = save_fig(plt, fig1, kind) fetch_q.uri.append( {'img2': 'data:image/png;base64,' + urllib.parse.quote(string1)}) #-------- Output for success -----#--# time_taken = perf_counter()-start fetch_q.info = 'completed in ' + str(np.round(time_taken, 3))+". " fetch_q.status = "success" elif fetch_q.imagesopt == 2 and fetch_q.c: tgss, dss2r, nvss, first = val['tgss']['data'], val[ 'dss2r']['data'], val['nvss']['data'], val['first']['data'] # --- plots initialization ------#--# #img1, lvlc1 = overlayc(tgss, dss2r, nvss, tgss, level_contour, 0.015) if tgss.max() > 0.015: lvlct = np.arange(0.015, tgss.max(), ((tgss.max() - 0.015)/level_contour)) fetch_q.otext.append({'TGSS contour ': (str(np.round(lvlct.tolist(), 3)))}) else: lvlct = None if first.max() > 0.0005: lvlcf = np.arange(0.0005, first.max(), ((first.max() - 0.0005)/level_contour)) fetch_q.otext.append({'FIRST contour ': (str(np.round(lvlcf, 4)))}) else: lvlcf = None if nvss.max() > 0.0015: lvlcn = np.arange(0.0015, nvss.max(), ((nvss.max() - 0.0015)/level_contour)) fetch_q.otext.append({'NVSS contour ': (str(np.round(lvlcn.tolist(), 4)))}) else: lvlcn = None #--- plotting --------------------#--# plt.ioff() fig = plt.figure(figsize=(20, 20)) title = ' TGSS(GMRT)-NVSS(VLA)-DSS2R(DSS)' dss2r = sqrt(dss2r, scale_min=np.percentile( np.unique(dss2r), 1.), scale_max=np.percentile(np.unique(dss2r), 100.)) #--- RGBC plot -------------------#--# ax1 = fig.add_subplot(1,2,1, projection=fetch_q.wcs) pl_RGB(ax1, dss2r, title, name, annot) #--- vizier access ---------------#-- # TODO : return table in output tgss_viz, nvss_viz = fetch_q.vz_query() if tgss_viz is not None: tmaj, tmin, tPA, tcen, s_tgss, es_tgss = tgss_viz if nvss_viz is not None: nmaj, nmin, nPA, ncen, s_nvss, es_nvss = nvss_viz try: try: patch1 = [] for i in range(len(tcen[0])): x, y = tcen[0][i], tcen[1][i] ce = PixCoord(x, y) a = to_pixel(tmaj[i], fetch_q.r, px) b = to_pixel(tmin[i], fetch_q.r, px) theta =Angle(tPA[i], 'deg') + 90*ut.deg reg = EllipsePixelRegion(center=ce, width=a, height=b, angle=theta) ellipse = reg.as_artist(facecolor='none', edgecolor='magenta', lw=2) patch1.append(ellipse) #kwar = dict(arrowprops=dict(arrowstyle="->", ec=".5", # relpos=(0.5, 0.5)), # bbox=dict(boxstyle="round", ec="none", fc="w")) ax1.annotate(i+1, xy=(x,y), xytext=(0, 0), textcoords="offset points", color="magenta") #ha="right", va="top")#, **kwar) fetch_q.otext.append({f'S_TGSS-{i+1}': f'{s_tgss.tolist()[i]} {str(s_tgss.unit)}'}) fetch_q.otext.append({f'S_TGSS_e-{i+1}': f'{np.round(es_tgss.tolist()[i],3)} {str(es_tgss.unit)}'}) tgss_catalog = PatchCollection( patch1, edgecolor='magenta', facecolor='None') ax1.add_collection(tgss_catalog) finally: patch2 = [] for i in range(len(ncen[0])): x, y = ncen[0][i], ncen[1][i] ce = PixCoord(x, y) a = to_pixel(nmaj[i], fetch_q.r, px) b = to_pixel(nmin[i], fetch_q.r, px) if nPA[i] != 0 and nPA[i] != '--': theta = Angle(nPA[i], 'deg') + 90*ut.deg else: theta = 0*ut.deg + 90*ut.deg reg = EllipsePixelRegion( center=ce, width=a, height=b, angle=theta) ellipse = reg.as_artist( facecolor='none', edgecolor='cyan', lw=2) patch2.append(ellipse) ax1.annotate(i+1, xy=(x, y), xytext=(0, 0), textcoords="offset points", color="cyan", ha="right", va="top")#, **kwar) fetch_q.otext.append({f'S_NVSS-{i+1}': f'{s_nvss.tolist()[i]} {str(s_nvss.unit)}'}) fetch_q.otext.append({f'S_NVSS_e-{i+1}': f'{np.round(es_nvss.tolist()[i],3)} {str(es_nvss.unit)}'}) nvss_catalog = PatchCollection( patch2, edgecolor='cyan', facecolor='None') ax1.add_collection(nvss_catalog) except: fetch_q.info = "catalog data missing" finally: #ax1.legend(framealpha=0.0, labelcolor='white') if spidx_file is not None: kwargs = dict(arrowprops=dict(arrowstyle="->", ec=".5", relpos=(0.5, 0.5)), bbox=dict(boxstyle="round", ec="none", fc="w")) xi, yi, spidx = find_spidx(spidx_file, fetch_q.c, fetch_q.r) for ien in range(len(xi)): #print(ien) Xi, Yi = fetch_q.wcs.world_to_pixel(SkyCoord(xi[ien]*ut.deg, yi[ien]*ut.deg)) #print(Xi,Yi, spidx) ax1.annotate(f'{spidx[ien]}', xy=(Xi, Yi), xytext=(1, -40), textcoords="offset points", ha="right", va="top", **kwargs) #-------- single survey plot ---------#--# dss2r = sqrt(dss2r, scale_min=np.percentile( np.unique(dss2r), 1.), scale_max=np.percentile(np.unique(dss2r), 100.)) ax2 = fig.add_subplot(1, 2, 2, projection=fetch_q.wcs) pl_RGB(ax2, dss2r, title='TGSS(GMRT)-NVSS(VLA)-FIRST(VLA)-DSS2R(DSS)', name=name, annot=annot) ax2.contour(nvss, lvlcn, colors='cyan') ax2.contour(tgss, lvlct, colors='magenta') ax2.contour(first, lvlcf, colors='yellow') leg1 = mpatches.Patch(color='cyan', label='NVSS') leg2 = mpatches.Patch(color='magenta', label='TGSS') leg3 = mpatches.Patch(color='yellow', label='FIRST') leg4 = mpatches.Patch(color='white', label='DSS2R') ax2.legend(handles=[leg1, leg2, leg3, leg4], labelcolor='linecolor', framealpha=0.0,) ax2.autoscale(False) plt.subplots_adjust(wspace=0.01, hspace=0.01) #-------- Saving final plot ------#--# string1 = save_fig(plt, fig, kind) #-------- Output for success -----#--# fetch_q.uri.append( {'img1': 'data:image/png;base64,' + urllib.parse.quote(string1)}) time_taken = perf_counter()-start fetch_q.info = 'completed in ' + str(np.round(time_taken, 3))+". " fetch_q.status = "success" return fetch_q.throw_output() def save_fig(plt, fig, kind='base64', output='output.jpg'): if kind == 'base64': buf = io.BytesIO() fig.savefig(buf, format='png', bbox_inches='tight', transparent=True, pad_inches=0) buf.seek(0) string = base64.b64encode(buf.read()) plt.close() return string elif kind == 'plot': plt.show() return 'plotted' else : if not path.exists('output'): makedirs('output') newPath = 'output/'+output opt = newPath if path.exists(newPath): numb = 1 while path.exists(newPath): newPath = "{0}_{2}{1}".format( *path.splitext(opt) + (numb,)) try : if path.exists(newPath): numb += 1 except: pass fig.savefig(newPath, format=kind, bbox_inches='tight', pad_inches=0) print("saved {}".format(newPath)) plt.close() return newPath def help_o(): return( 'use without identifier: (name="", position="", radius=float(0.12), imagesopt=2) -> tuple[str, list, str, list]') def cli(): if sys.argv[1] == '-h': print(help(query)) sys.exit() else: try: imagesopt = 2 if len(sys.argv) > 4: if sys.argv[4] == 'ror-iou' or 1 or 'roriou' or 'iou' or 'ror': imagesopt = 1 q = query(name=str(sys.argv[1]), position=str( sys.argv[2]), radius=sys.argv[3], imagesopt=imagesopt, kind='jpg') print(str(q)) except Exception as e: print('error occured : {}'.format(e)) try: print( 'query(name={}, position={}, radius={}, archives={}, imagesopt={})'.format(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])) except: print(help_o()) if __name__ == "__main__": cli()
[ "io.BytesIO", "sys.exit", "rgbmaker.imgplt.pl_RGBC", "os.path.exists", "rgbmaker.tgss_spidx.find_spidx", "astropy.coordinates.Angle", "time.perf_counter", "matplotlib.pyplot.close", "rgbmaker.imgplt.overlayc", "numpy.round", "os.path.splitext", "matplotlib.pyplot.ioff", "rgbmaker.imgplt.to_p...
[((3899, 3996), 'rgbmaker.RGBMaker', 'rgbmaker', ([], {'name': 'name', 'position': 'position', 'radius': 'radius', 'archives': 'archives', 'imagesopt': 'imagesopt'}), '(name=name, position=position, radius=radius, archives=archives,\n imagesopt=imagesopt)\n', (3907, 3996), True, 'from rgbmaker import RGBMaker as rgbmaker\n'), ((4047, 4061), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (4059, 4061), False, 'from time import perf_counter\n'), ((14527, 14539), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (14537, 14539), False, 'import io\n'), ((14726, 14737), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (14735, 14737), True, 'from matplotlib import pyplot as plt\n'), ((15731, 15741), 'sys.exit', 'sys.exit', ([], {}), '()\n', (15739, 15741), False, 'import sys\n'), ((4791, 4847), 'rgbmaker.imgplt.overlayc', 'overlayc', (['tgss', 'dss2r', 'nvss', 'nvss', 'level_contour', '(0.0015)'], {}), '(tgss, dss2r, nvss, nvss, level_contour, 0.0015)\n', (4799, 4847), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((4881, 4936), 'rgbmaker.imgplt.overlayc', 'overlayc', (['tgss', 'dss2r', 'nvss', 'tgss', 'level_contour', '(0.015)'], {}), '(tgss, dss2r, nvss, tgss, level_contour, 0.015)\n', (4889, 4936), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((4963, 5001), 'rgbmaker.imgplt.overlayo', 'overlayo', (['w22', 'dss2r', 'gnuv'], {'kind': '"""IOU"""'}), "(w22, dss2r, gnuv, kind='IOU')\n", (4971, 5001), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((5019, 5064), 'rgbmaker.imgplt.overlayo', 'overlayo', (['dss2i', 'dss2r', 'dss2b'], {'kind': '"""Optical"""'}), "(dss2i, dss2r, dss2b, kind='Optical')\n", (5027, 5064), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((5385, 5395), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (5393, 5395), True, 'from matplotlib import pyplot as plt\n'), ((5414, 5442), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (5424, 5442), True, 'from matplotlib import pyplot as plt\n'), ((5456, 5547), 'rgbmaker.imgplt.pl_RGBC', 'pl_RGBC', (['(1)', '(2)', '(1)', 'fetch_q.wcs', "val['nvss']['data']", 'lvlc1', 'img1', 'fig', 'name'], {'annot': 'annot'}), "(1, 2, 1, fetch_q.wcs, val['nvss']['data'], lvlc1, img1, fig, name,\n annot=annot)\n", (5463, 5547), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((5555, 5646), 'rgbmaker.imgplt.pl_RGBC', 'pl_RGBC', (['(1)', '(2)', '(2)', 'fetch_q.wcs', "val['tgss']['data']", 'lvlc2', 'img2', 'fig', 'name'], {'annot': 'annot'}), "(1, 2, 2, fetch_q.wcs, val['tgss']['data'], lvlc2, img2, fig, name,\n annot=annot)\n", (5562, 5646), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((5654, 5699), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0.01)'}), '(wspace=0.01, hspace=0.01)\n', (5673, 5699), True, 'from matplotlib import pyplot as plt\n'), ((5990, 6000), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (5998, 6000), True, 'from matplotlib import pyplot as plt\n'), ((6020, 6048), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (6030, 6048), True, 'from matplotlib import pyplot as plt\n'), ((6061, 6166), 'rgbmaker.imgplt.pl_RGBC', 'pl_RGBC', (['(1)', '(2)', '(1)', 'fetch_q.wcs', "val['tgss']['data']", 'lvlc2', 'img3', 'fig1', 'name'], {'pkind': '"""iou"""', 'annot': 'annot'}), "(1, 2, 1, fetch_q.wcs, val['tgss']['data'], lvlc2, img3, fig1, name,\n pkind='iou', annot=annot)\n", (6068, 6166), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((6174, 6279), 'rgbmaker.imgplt.pl_RGBC', 'pl_RGBC', (['(1)', '(2)', '(2)', 'fetch_q.wcs', "val['tgss']['data']", 'lvlc2', 'img4', 'fig1', 'name'], {'pkind': '"""iou"""', 'annot': 'annot'}), "(1, 2, 2, fetch_q.wcs, val['tgss']['data'], lvlc2, img4, fig1, name,\n pkind='iou', annot=annot)\n", (6181, 6279), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((6303, 6348), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0.01)'}), '(wspace=0.01, hspace=0.01)\n', (6322, 6348), True, 'from matplotlib import pyplot as plt\n'), ((14793, 14803), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14801, 14803), True, 'from matplotlib import pyplot as plt\n'), ((14977, 14997), 'os.path.exists', 'path.exists', (['newPath'], {}), '(newPath)\n', (14988, 14997), False, 'from os import path, makedirs\n'), ((15471, 15482), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (15480, 15482), True, 'from matplotlib import pyplot as plt\n'), ((6654, 6668), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (6666, 6668), False, 'from time import perf_counter\n'), ((8041, 8051), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (8049, 8051), True, 'from matplotlib import pyplot as plt\n'), ((8070, 8098), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (8080, 8098), True, 'from matplotlib import pyplot as plt\n'), ((8429, 8467), 'rgbmaker.imgplt.pl_RGB', 'pl_RGB', (['ax1', 'dss2r', 'title', 'name', 'annot'], {}), '(ax1, dss2r, title, name, annot)\n', (8435, 8467), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((14855, 14876), 'os.path.exists', 'path.exists', (['"""output"""'], {}), "('output')\n", (14866, 14876), False, 'from os import path, makedirs\n'), ((14890, 14908), 'os.makedirs', 'makedirs', (['"""output"""'], {}), "('output')\n", (14898, 14908), False, 'from os import path, makedirs\n'), ((15038, 15058), 'os.path.exists', 'path.exists', (['newPath'], {}), '(newPath)\n', (15049, 15058), False, 'from os import path, makedirs\n'), ((13102, 13201), 'rgbmaker.imgplt.pl_RGB', 'pl_RGB', (['ax2', 'dss2r'], {'title': '"""TGSS(GMRT)-NVSS(VLA)-FIRST(VLA)-DSS2R(DSS)"""', 'name': 'name', 'annot': 'annot'}), "(ax2, dss2r, title='TGSS(GMRT)-NVSS(VLA)-FIRST(VLA)-DSS2R(DSS)', name\n =name, annot=annot)\n", (13108, 13201), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((13412, 13454), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""cyan"""', 'label': '"""NVSS"""'}), "(color='cyan', label='NVSS')\n", (13426, 13454), True, 'import matplotlib.patches as mpatches\n'), ((13478, 13523), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""magenta"""', 'label': '"""TGSS"""'}), "(color='magenta', label='TGSS')\n", (13492, 13523), True, 'import matplotlib.patches as mpatches\n'), ((13547, 13592), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""yellow"""', 'label': '"""FIRST"""'}), "(color='yellow', label='FIRST')\n", (13561, 13592), True, 'import matplotlib.patches as mpatches\n'), ((13616, 13660), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""white"""', 'label': '"""DSS2R"""'}), "(color='white', label='DSS2R')\n", (13630, 13660), True, 'import matplotlib.patches as mpatches\n'), ((13857, 13902), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0.01)'}), '(wspace=0.01, hspace=0.01)\n', (13876, 13902), True, 'from matplotlib import pyplot as plt\n'), ((5895, 5921), 'urllib.parse.quote', 'urllib.parse.quote', (['string'], {}), '(string)\n', (5913, 5921), False, 'import urllib\n'), ((6547, 6574), 'urllib.parse.quote', 'urllib.parse.quote', (['string1'], {}), '(string1)\n', (6565, 6574), False, 'import urllib\n'), ((6724, 6747), 'numpy.round', 'np.round', (['time_taken', '(3)'], {}), '(time_taken, 3)\n', (6732, 6747), True, 'import numpy as np\n'), ((10195, 10257), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['patch1'], {'edgecolor': '"""magenta"""', 'facecolor': '"""None"""'}), "(patch1, edgecolor='magenta', facecolor='None')\n", (10210, 10257), False, 'from matplotlib.collections import PatchCollection\n'), ((11710, 11769), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['patch2'], {'edgecolor': '"""cyan"""', 'facecolor': '"""None"""'}), "(patch2, edgecolor='cyan', facecolor='None')\n", (11725, 11769), False, 'from matplotlib.collections import PatchCollection\n'), ((12302, 12346), 'rgbmaker.tgss_spidx.find_spidx', 'find_spidx', (['spidx_file', 'fetch_q.c', 'fetch_q.r'], {}), '(spidx_file, fetch_q.c, fetch_q.r)\n', (12312, 12346), False, 'from rgbmaker.tgss_spidx import find_spidx\n'), ((14234, 14248), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (14246, 14248), False, 'from time import perf_counter\n'), ((15203, 15223), 'os.path.exists', 'path.exists', (['newPath'], {}), '(newPath)\n', (15214, 15223), False, 'from os import path, makedirs\n'), ((5157, 5175), 'numpy.round', 'np.round', (['lvlc2', '(3)'], {}), '(lvlc2, 3)\n', (5165, 5175), True, 'import numpy as np\n'), ((5281, 5299), 'numpy.round', 'np.round', (['lvlc1', '(4)'], {}), '(lvlc1, 4)\n', (5289, 5299), True, 'import numpy as np\n'), ((8227, 8243), 'numpy.unique', 'np.unique', (['dss2r'], {}), '(dss2r)\n', (8236, 8243), True, 'import numpy as np\n'), ((8274, 8290), 'numpy.unique', 'np.unique', (['dss2r'], {}), '(dss2r)\n', (8283, 8290), True, 'import numpy as np\n'), ((9036, 9050), 'regions.PixCoord', 'PixCoord', (['x', 'y'], {}), '(x, y)\n', (9044, 9050), False, 'from regions import PixCoord, EllipsePixelRegion\n'), ((9079, 9111), 'rgbmaker.imgplt.to_pixel', 'to_pixel', (['tmaj[i]', 'fetch_q.r', 'px'], {}), '(tmaj[i], fetch_q.r, px)\n', (9087, 9111), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((9140, 9172), 'rgbmaker.imgplt.to_pixel', 'to_pixel', (['tmin[i]', 'fetch_q.r', 'px'], {}), '(tmin[i], fetch_q.r, px)\n', (9148, 9172), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((9268, 9329), 'regions.EllipsePixelRegion', 'EllipsePixelRegion', ([], {'center': 'ce', 'width': 'a', 'height': 'b', 'angle': 'theta'}), '(center=ce, width=a, height=b, angle=theta)\n', (9286, 9329), False, 'from regions import PixCoord, EllipsePixelRegion\n'), ((10560, 10574), 'regions.PixCoord', 'PixCoord', (['x', 'y'], {}), '(x, y)\n', (10568, 10574), False, 'from regions import PixCoord, EllipsePixelRegion\n'), ((10603, 10635), 'rgbmaker.imgplt.to_pixel', 'to_pixel', (['nmaj[i]', 'fetch_q.r', 'px'], {}), '(nmaj[i], fetch_q.r, px)\n', (10611, 10635), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((10664, 10696), 'rgbmaker.imgplt.to_pixel', 'to_pixel', (['nmin[i]', 'fetch_q.r', 'px'], {}), '(nmin[i], fetch_q.r, px)\n', (10672, 10696), False, 'from rgbmaker.imgplt import pl_RGB, to_pixel, pl_RGBC, overlayc, overlayo, sqrt\n'), ((10943, 11004), 'regions.EllipsePixelRegion', 'EllipsePixelRegion', ([], {'center': 'ce', 'width': 'a', 'height': 'b', 'angle': 'theta'}), '(center=ce, width=a, height=b, angle=theta)\n', (10961, 11004), False, 'from regions import PixCoord, EllipsePixelRegion\n'), ((7639, 7657), 'numpy.round', 'np.round', (['lvlcf', '(4)'], {}), '(lvlcf, 4)\n', (7647, 7657), True, 'import numpy as np\n'), ((9204, 9224), 'astropy.coordinates.Angle', 'Angle', (['tPA[i]', '"""deg"""'], {}), "(tPA[i], 'deg')\n", (9209, 9224), False, 'from astropy.coordinates import Angle, SkyCoord\n'), ((12490, 12534), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['(xi[ien] * ut.deg)', '(yi[ien] * ut.deg)'], {}), '(xi[ien] * ut.deg, yi[ien] * ut.deg)\n', (12498, 12534), False, 'from astropy.coordinates import Angle, SkyCoord\n'), ((12943, 12959), 'numpy.unique', 'np.unique', (['dss2r'], {}), '(dss2r)\n', (12952, 12959), True, 'import numpy as np\n'), ((12990, 13006), 'numpy.unique', 'np.unique', (['dss2r'], {}), '(dss2r)\n', (12999, 13006), True, 'import numpy as np\n'), ((14175, 14202), 'urllib.parse.quote', 'urllib.parse.quote', (['string1'], {}), '(string1)\n', (14193, 14202), False, 'import urllib\n'), ((14308, 14331), 'numpy.round', 'np.round', (['time_taken', '(3)'], {}), '(time_taken, 3)\n', (14316, 14331), True, 'import numpy as np\n'), ((15128, 15146), 'os.path.splitext', 'path.splitext', (['opt'], {}), '(opt)\n', (15141, 15146), False, 'from os import path, makedirs\n'), ((10792, 10812), 'astropy.coordinates.Angle', 'Angle', (['nPA[i]', '"""deg"""'], {}), "(nPA[i], 'deg')\n", (10797, 10812), False, 'from astropy.coordinates import Angle, SkyCoord\n')]
"""Contains the functions used to print the trajectories and read input configurations (or even full status dump) as unformatted binary. Copyright (C) 2013, <NAME> and <NAME> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http.//www.gnu.org/licenses/>. Functions: print_bin: Prints an atomic configuration. """ __all__ = ['print_bin'] import os import numpy as np import math, sys from ipi.utils.depend import depstrip def print_bin(atoms, cell, filedesc = sys.stdout, title=""): """Prints the centroid configurations, into a binary file. Args: beads: An atoms object giving the centroid positions. cell: A cell object giving the system box. filedesc: An open writable file object. Defaults to standard output. title: This gives a string to be appended to the comment line. """ buff = filedesc # .buffer cell.h.tofile(buff) nat = np.asarray([atoms.natoms]) nat.tofile(buff) atoms.names.tofile(buff) atoms.q.tofile(buff)
[ "numpy.asarray" ]
[((1417, 1443), 'numpy.asarray', 'np.asarray', (['[atoms.natoms]'], {}), '([atoms.natoms])\n', (1427, 1443), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np import sys import random class VanillaRNN(object): def __init__(self, num_classes, state_size, seq_len, learning_rate=0.1, model_name='vanilla_rnn_model', ckpt_path='./ckpt/vanilla/'): self.num_classes = num_classes self.state_size = state_size self.seq_len = seq_len self.learning_rate = learning_rate self.model_name = model_name self.ckpt_path = ckpt_path # build graph sys.stdout.write('\nBuilding Graph...') tf.reset_default_graph() # set feed data self.xs_ = tf.placeholder(shape=[None, None], dtype=tf.int32) self.ys_ = tf.placeholder(shape=[None], dtype=tf.int32) # embeddings embs = tf.get_variable('emb', [self.num_classes, self.state_size]) rnn_inputs = tf.nn.embedding_lookup(embs, self.xs_) # initial hidden state self.init_state = tf.placeholder(shape=[None, self.state_size], dtype=tf.float32, name='initial_state') # initializer xav_init = tf.contrib.layers.xavier_initializer # define step operation: St = tanh(U * Xt + W * St-1) def __step__(h_prev, x_curr): w = tf.get_variable('W', shape=[self.state_size, self.state_size], initializer=xav_init()) u = tf.get_variable('U', shape=[self.state_size, self.state_size], initializer=xav_init()) b = tf.get_variable('b', shape=[self.state_size], initializer=tf.constant_initializer(0.0)) h = tf.tanh(tf.matmul(h_prev, w) + tf.matmul(x_curr, u) + b) return h # here comes the scan operation; tf.scan(fn, elems, initializer) # repeatedly applies the callable function (__step__) to a sequence of elements from first to last # ref: https://www.tensorflow.org/api_docs/python/tf/scan states = tf.scan(__step__, tf.transpose(rnn_inputs, [1, 0, 2]), initializer=self.init_state) # set last state self.last_state = states[-1] # predictions v = tf.get_variable('V', shape=[self.state_size, self.num_classes], initializer=xav_init()) bo = tf.get_variable('bo', shape=[self.num_classes], initializer=tf.constant_initializer(0.0)) # transpose and flatten states to 2d matrix for matmult with V states = tf.reshape(tf.transpose(states, [1, 0, 2]), [-1, self.state_size]) logits = tf.add(tf.matmul(states, v), bo) self.predictions = tf.nn.softmax(logits) # Yt = softmax(V * St) # optimization self.loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=self.ys_)) self.train_op = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss) sys.stdout.write(' Done...\n') # training operation def train(self, train_set, epochs=50, steps_per_epoch=500): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) train_loss = 0 epoch = 0 try: for epoch in range(epochs): for step in range(steps_per_epoch): xs, ys = train_set.__next__() batch_size = xs.shape[0] feed_dict = {self.xs_: xs, self.ys_: ys.reshape([batch_size * self.seq_len]), self.init_state: np.zeros([batch_size, self.state_size])} _, cur_loss = sess.run([self.train_op, self.loss], feed_dict=feed_dict) train_loss += cur_loss print('Epoch [{}], average loss : {}'.format(epoch, train_loss / steps_per_epoch)) train_loss = 0 except KeyboardInterrupt: print('interrupted by user at epoch ' + str(epoch)) saver = tf.train.Saver() saver.save(sess, self.ckpt_path + 'vanilla.ckpt', global_step=epoch) # generating operation def generate(self, idx2ch, ch2idx, num_words=100, separator=' '): # generate text random_init_word = random.choice(idx2ch) current_word = ch2idx[random_init_word] with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # restore session ckpt = tf.train.get_checkpoint_state(self.ckpt_path) saver = tf.train.Saver() if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) # generate operation words = [current_word] state = None state_ = None # set batch_size to 1 batch_size = 1 num_words = num_words if num_words else 111 # enter the loop for i in range(num_words): if state: feed_dict = {self.xs_: np.array(current_word).reshape([1, 1]), self.init_state: state_} else: feed_dict = {self.xs_: np.array(current_word).reshape([1, 1]), self.init_state: np.zeros([batch_size, self.state_size])} # forward propagation preds, state_ = sess.run([self.predictions, self.last_state], feed_dict=feed_dict) # set flag to true state = True # set new word current_word = np.random.choice(preds.shape[-1], 1, p=np.squeeze(preds))[0] # add to list of words words.append(current_word) return separator.join([idx2ch[w] for w in words])
[ "tensorflow.get_variable", "tensorflow.transpose", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "numpy.array", "tensorflow.nn.softmax", "tensorflow.nn.embedding_lookup", "tensorflow.placeholder", "tensorflow.Session", "tensorflow.matmul", "tensorflow.train.AdamOptimizer", "random.ch...
[((503, 545), 'sys.stdout.write', 'sys.stdout.write', (['"""\nBuilding Graph..."""'], {}), '("""\nBuilding Graph...""")\n', (519, 545), False, 'import sys\n'), ((551, 575), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (573, 575), True, 'import tensorflow as tf\n'), ((619, 669), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None, None]', 'dtype': 'tf.int32'}), '(shape=[None, None], dtype=tf.int32)\n', (633, 669), True, 'import tensorflow as tf\n'), ((689, 733), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None]', 'dtype': 'tf.int32'}), '(shape=[None], dtype=tf.int32)\n', (703, 733), True, 'import tensorflow as tf\n'), ((770, 829), 'tensorflow.get_variable', 'tf.get_variable', (['"""emb"""', '[self.num_classes, self.state_size]'], {}), "('emb', [self.num_classes, self.state_size])\n", (785, 829), True, 'import tensorflow as tf\n'), ((851, 889), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embs', 'self.xs_'], {}), '(embs, self.xs_)\n', (873, 889), True, 'import tensorflow as tf\n'), ((947, 1037), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None, self.state_size]', 'dtype': 'tf.float32', 'name': '"""initial_state"""'}), "(shape=[None, self.state_size], dtype=tf.float32, name=\n 'initial_state')\n", (961, 1037), True, 'import tensorflow as tf\n'), ((2484, 2505), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (2497, 2505), True, 'import tensorflow as tf\n'), ((2777, 2807), 'sys.stdout.write', 'sys.stdout.write', (['""" Done...\n"""'], {}), "(' Done...\\n')\n", (2793, 2807), False, 'import sys\n'), ((4109, 4130), 'random.choice', 'random.choice', (['idx2ch'], {}), '(idx2ch)\n', (4122, 4130), False, 'import random\n'), ((1898, 1933), 'tensorflow.transpose', 'tf.transpose', (['rnn_inputs', '[1, 0, 2]'], {}), '(rnn_inputs, [1, 0, 2])\n', (1910, 1933), True, 'import tensorflow as tf\n'), ((2351, 2382), 'tensorflow.transpose', 'tf.transpose', (['states', '[1, 0, 2]'], {}), '(states, [1, 0, 2])\n', (2363, 2382), True, 'import tensorflow as tf\n'), ((2431, 2451), 'tensorflow.matmul', 'tf.matmul', (['states', 'v'], {}), '(states, v)\n', (2440, 2451), True, 'import tensorflow as tf\n'), ((2588, 2666), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'self.ys_'}), '(logits=logits, labels=self.ys_)\n', (2634, 2666), True, 'import tensorflow as tf\n'), ((2911, 2923), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2921, 2923), True, 'import tensorflow as tf\n'), ((3862, 3878), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (3876, 3878), True, 'import tensorflow as tf\n'), ((4192, 4204), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (4202, 4204), True, 'import tensorflow as tf\n'), ((4319, 4364), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['self.ckpt_path'], {}), '(self.ckpt_path)\n', (4348, 4364), True, 'import tensorflow as tf\n'), ((4385, 4401), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (4399, 4401), True, 'import tensorflow as tf\n'), ((2222, 2250), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (2245, 2250), True, 'import tensorflow as tf\n'), ((2692, 2748), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'self.learning_rate'}), '(learning_rate=self.learning_rate)\n', (2714, 2748), True, 'import tensorflow as tf\n'), ((2954, 2987), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2985, 2987), True, 'import tensorflow as tf\n'), ((4235, 4268), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4266, 4268), True, 'import tensorflow as tf\n'), ((1492, 1520), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (1515, 1520), True, 'import tensorflow as tf\n'), ((1546, 1566), 'tensorflow.matmul', 'tf.matmul', (['h_prev', 'w'], {}), '(h_prev, w)\n', (1555, 1566), True, 'import tensorflow as tf\n'), ((1569, 1589), 'tensorflow.matmul', 'tf.matmul', (['x_curr', 'u'], {}), '(x_curr, u)\n', (1578, 1589), True, 'import tensorflow as tf\n'), ((5111, 5150), 'numpy.zeros', 'np.zeros', (['[batch_size, self.state_size]'], {}), '([batch_size, self.state_size])\n', (5119, 5150), True, 'import numpy as np\n'), ((3414, 3453), 'numpy.zeros', 'np.zeros', (['[batch_size, self.state_size]'], {}), '([batch_size, self.state_size])\n', (3422, 3453), True, 'import numpy as np\n'), ((5454, 5471), 'numpy.squeeze', 'np.squeeze', (['preds'], {}), '(preds)\n', (5464, 5471), True, 'import numpy as np\n'), ((4891, 4913), 'numpy.array', 'np.array', (['current_word'], {}), '(current_word)\n', (4899, 4913), True, 'import numpy as np\n'), ((5021, 5043), 'numpy.array', 'np.array', (['current_word'], {}), '(current_word)\n', (5029, 5043), True, 'import numpy as np\n')]
import pandas as pd from sklearn.metrics import confusion_matrix from utils.Code_dictionary import CodeDictionary import copy import numpy as np def wrap_confusion_matrix(cm_df): for i, col in enumerate(cm_df.columns): cm_df.loc['precision', col] = cm_df.iloc[i, i] / cm_df.iloc[:, i].sum() for i, idx in enumerate(cm_df.index): if idx == 'precision': continue cm_df.loc[idx, 'recall'] = cm_df.iloc[i, i] / cm_df.iloc[i, :].sum() return cm_df def generate_confusion_matrix(det_result_file, gt_result_file, output='confusion_matrix.xlsx', code_weight=None): det_df = pd.read_excel(det_result_file) gt_df = pd.read_excel(gt_result_file) merged_df = pd.merge(det_df, gt_df, on='image name') merged_df.loc[pd.isnull(merged_df['true code']), 'true code'] = merged_df['pred code'] merged_df.drop(merged_df[merged_df['true code'] == 1].index, axis=0, inplace=True) print('{} images merged \n{} images det \n{} images gt'.format(len(merged_df), len(det_df), len(gt_df))) y_pred = list(merged_df['pred code'].values.astype(str)) y_true = list(merged_df['true code'].values.astype(str)) labels = list(set(y_pred + y_true)) cm = confusion_matrix(y_true, y_pred, labels) cm_df = pd.DataFrame(cm, index=labels, columns=labels) if code_weight is not None: code_weight = np.array(code_weight) * 1000 print('output balanced confusion matrix') assert len(code_weight) == len(labels) cm_df_balanced = copy.deepcopy(cm_df) for i in range(len(code_weight)): sum = cm_df_balanced.iloc[i, :].sum() row_weight = code_weight[i] / sum cm_df_balanced.iloc[i, :] *= row_weight cm_df_balanced = wrap_confusion_matrix(cm_df_balanced) cm_df_balanced.to_excel(output.replace('.xlsx', '_balanced.xlsx')) cm_df = wrap_confusion_matrix(cm_df) print(cm_df) cm_df.to_csv(output) if __name__ == '__main__': det_result = r'/data/sdv1/whtm/result/1GE02/1GE02_v3_bt1.xlsx' gt_result = r'/data/sdv1/whtm/result/1GE02/1GE02_bt1_true.xlsx' generate_confusion_matrix(det_result, gt_result, output=r'/data/sdv1/whtm/result/1GE02/confusion_matrix_1GE02_bt.csv')
[ "pandas.isnull", "pandas.merge", "numpy.array", "pandas.read_excel", "copy.deepcopy", "pandas.DataFrame", "sklearn.metrics.confusion_matrix" ]
[((712, 742), 'pandas.read_excel', 'pd.read_excel', (['det_result_file'], {}), '(det_result_file)\n', (725, 742), True, 'import pandas as pd\n'), ((755, 784), 'pandas.read_excel', 'pd.read_excel', (['gt_result_file'], {}), '(gt_result_file)\n', (768, 784), True, 'import pandas as pd\n'), ((801, 841), 'pandas.merge', 'pd.merge', (['det_df', 'gt_df'], {'on': '"""image name"""'}), "(det_df, gt_df, on='image name')\n", (809, 841), True, 'import pandas as pd\n'), ((1302, 1342), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred', 'labels'], {}), '(y_true, y_pred, labels)\n', (1318, 1342), False, 'from sklearn.metrics import confusion_matrix\n'), ((1355, 1401), 'pandas.DataFrame', 'pd.DataFrame', (['cm'], {'index': 'labels', 'columns': 'labels'}), '(cm, index=labels, columns=labels)\n', (1367, 1401), True, 'import pandas as pd\n'), ((1607, 1627), 'copy.deepcopy', 'copy.deepcopy', (['cm_df'], {}), '(cm_df)\n', (1620, 1627), False, 'import copy\n'), ((861, 894), 'pandas.isnull', 'pd.isnull', (["merged_df['true code']"], {}), "(merged_df['true code'])\n", (870, 894), True, 'import pandas as pd\n'), ((1456, 1477), 'numpy.array', 'np.array', (['code_weight'], {}), '(code_weight)\n', (1464, 1477), True, 'import numpy as np\n')]
import numpy as np def get_features(conformer,S,bond_connectivity_list): conformer=np.array(conformer) nonbondcutoff = 6 bonds = generate_bondconnectivty_matrix(bond_connectivity_list) #Calculate the atomic environment vector for each atom atomic_envs = generate_atomic_env(bonds, S) #Calculate the sets of bonds and bond values bondlist, bonddistances = generate_bond_data(conformer, bonds) bondfeatures = generate_bond_features(bonddistances,bondlist,atomic_envs) #Calculate the 3 atom angle sets and angle values angles_list, angles = generate_angle_data(conformer, bonds) anglefeatures = generate_angle_features(angles,angles_list,atomic_envs,bondlist,bonddistances) #Calculate 4 atom dihedral sets and dihedral values dihedral_list, dihedral_angles = generate_dihedral_data(conformer,bonds) dihedralfeatures = generate_dihedralangle_features(dihedral_angles, dihedral_list, atomic_envs, bondlist, bonddistances, angles_list, angles) # Calculate the list of Non-bonds nonbond_list, nonbonddistances = generate_nonbond_data(conformer, bonds, nonbondcutoff) nonbondfeatures = generate_bond_features(nonbonddistances,nonbond_list,atomic_envs) # Zipping the data features = {} features['bonds'] = np.array(bondfeatures) features['angles'] = np.array(anglefeatures) features['nonbonds'] = np.array(nonbondfeatures) features['dihedrals'] = np.array(dihedralfeatures) return features def generate_bondconnectivty_matrix(bond_connectivity_list): bond_matrix = [[0 for i in range(len(bond_connectivity_list))] for j in range(len(bond_connectivity_list))] for i1 in range(len(bond_connectivity_list)): for i2 in bond_connectivity_list[i1]: bond_matrix[i1][i2] = 1 bond_matrix[i2][i1] = 1 return bond_matrix def generate_atomic_env(bonds, S): atomic_envs = [] for i in range(len(bonds)): atom_id = {'H':0, 'C':1, 'O':2, 'N':3 } atomtype = [0,0,0,0] atomtype[atom_id[S[i]]] = 1 immediate_neighbour_count = [0,0,0,0] for j in range(len(bonds[i])): if(bonds[i][j] > 0): immediate_neighbour_count[atom_id[S[j]]] += 1 atomic_envs.append(atomtype + immediate_neighbour_count) return atomic_envs def generate_bond_data(conformer,bonds): #Calculate the paiwise-distances among the atoms distance = [[0 for i in range(len(conformer))] for j in range(len(conformer))] for i in range(len(conformer)): for j in range(len(conformer)): distance[i][j] = np.linalg.norm(conformer[i]-conformer[j]) bondlist = [] bonddistances = [] for i in range(len(bonds)): for j in range(i): if(bonds[i][j] is 1): bondlist.append([i,j]) bonddistances.append(distance[i][j]) return bondlist, bonddistances def generate_bond_features(bonddistances, bondlist, atomtype): labels = [] for bond in range(len(bondlist)): bond_feature = [] if(atomtype[bondlist[bond][0]] > atomtype[bondlist[bond][1]]): bond_feature += atomtype[bondlist[bond][0]] + atomtype[bondlist[bond][1]] else: bond_feature += atomtype[bondlist[bond][1]] + atomtype[bondlist[bond][0]] bond_feature.append(bonddistances[bond]) labels.append(bond_feature) return labels def generate_angle_data(conformer,bonds): angles_list = [] for i in range(len(conformer)): for j in range(len(conformer)): for k in range(len(conformer)): if(j!=i and j!=k and i>k and bonds[i][j]!=0 and bonds[j][k]!=0): angles_list.append([i,j,k]) angles = [] for angle_triplet in angles_list: angle = get_angle(conformer[angle_triplet[0]], conformer[angle_triplet[1]], conformer[angle_triplet[2]]) angles.append(angle) return angles_list, angles def get_angle(coor1,coor2,coor3): ba =coor1 - coor2 bc = coor3 - coor2 cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) if cosine_angle > 1.0: cosine_angle=1.0 elif cosine_angle < -1.0: cosine_angle=-1.0 if cosine_angle <=1.0 and cosine_angle>=-1.0: angle = np.arccos(cosine_angle) if angle > np.pi: angle=2*(np.pi)-angle return angle def generate_angle_features(angles, angletype, atomtype,bondlist,bonddistances): labels = [] for angle in range(len(angletype)): anglefeature = [] if(atomtype[angletype[angle][0]] > atomtype[angletype[angle][2]]): anglefeature += atomtype[angletype[angle][0]] + atomtype[angletype[angle][2]] bondlen1 = get_bondlen(angletype[angle][0],angletype[angle][1],bondlist,bonddistances) bondlen2 = get_bondlen(angletype[angle][1],angletype[angle][2],bondlist,bonddistances) else: anglefeature += atomtype[angletype[angle][2]] + atomtype[angletype[angle][0]] bondlen1 = get_bondlen(angletype[angle][1],angletype[angle][2],bondlist,bonddistances) bondlen2 = get_bondlen(angletype[angle][0],angletype[angle][1],bondlist,bonddistances) anglefeature += atomtype[angletype[angle][1]] anglefeature += ([angles[angle],bondlen1,bondlen2]) labels.append(anglefeature) return labels def get_bondlen(i1,i2,bondtypelist,bondlenlist): try: index = bondtypelist.index([i1,i2]) except: index = bondtypelist.index([i2,i1]) return bondlenlist[index] def generate_nonbond_data(conformer,bonds,nonbondcutoff): #Calculate the paiwise-distances among the atoms distance = [[0 for i in range(len(conformer))] for j in range(len(conformer))] for i in range(len(conformer)): for j in range(len(conformer)): distance[i][j] = np.linalg.norm(conformer[i]-conformer[j]) nonbond_distances = [] nonbond_list = [] for i in range(len(conformer)): for j in range(len(conformer)): if(i > j and distance[i][j] < nonbondcutoff and (bonds[i][j] == 0 ) ): nonbond_list.append([i,j]) nonbond_distances.append(distance[i][j]) return nonbond_list, nonbond_distances def generate_dihedral_data(conformer,bonds): dihedral_list= [] for i in range(len(conformer)): for j in range(len(conformer)): for k in range(len(conformer)): for l in range(len(conformer)): if( i>l and i!=j and i!=k and j!=k and j!=l and k!=l and bonds[i][j] == 1 and bonds[j][k]==1 and bonds[k][l]==1): dihedral_list.append([i,j,k,l]) dihedrals = [] for dihed in dihedral_list: dihedral_angle = get_dihedral(conformer[dihed[0]],conformer[dihed[1]],conformer[dihed[2]],conformer[dihed[3]]) dihedrals.append(dihedral_angle) return dihedral_list,dihedrals def get_dihedral(p0, p1, p2, p3): b0=p0-p1 b1=p2-p1 b2=p3-p2 b0xb1 = np.cross(b0,b1) b1xb2 = np.cross(b2,b1) b0xb1_x_b1xb2 = np.cross(b0xb1,b1xb2) y = np.dot(b0xb1_x_b1xb2, b1)*(1.0/np.linalg.norm(b1)) x = np.dot(b0xb1, b1xb2) return np.arctan2(y, x) def get_angleval(i1,i2,i3,angletypelist,anglevallist): try: index = angletypelist.index([i1,i2,i3]) except: index = angletypelist.index([i3,i2,i1]) return anglevallist[index] def generate_dihedralangle_features(dihedral_angles, dihedral_list, atomtype,bondtypelist,bondlenlist,angletypelist,anglevallist): labels = [] for dihedral in range(len(dihedral_angles)): dihedral_feature = [] if(atomtype[dihedral_list[dihedral][0]] > atomtype[dihedral_list[dihedral][3]]): index1 = 0 index2 = 1 index3 = 2 index4 = 3 else: index1 = 3 index2 = 2 index3 = 1 index4 = 0 dihedral_feature += atomtype[dihedral_list[dihedral][index1]] + atomtype[dihedral_list[dihedral][index2]] dihedral_feature += atomtype[dihedral_list[dihedral][index3]] + atomtype[dihedral_list[dihedral][index4]] bondlen1 = get_bondlen(dihedral_list[dihedral][index1],dihedral_list[dihedral][index2],bondtypelist,bondlenlist) bondlen2 = get_bondlen(dihedral_list[dihedral][index2],dihedral_list[dihedral][index3],bondtypelist,bondlenlist) bondlen3 = get_bondlen(dihedral_list[dihedral][index3],dihedral_list[dihedral][index4],bondtypelist,bondlenlist) angleval1 = get_angleval(dihedral_list[dihedral][index1],dihedral_list[dihedral][index2],dihedral_list[dihedral][index3],angletypelist,anglevallist) angleval2 = get_angleval(dihedral_list[dihedral][index2],dihedral_list[dihedral][index3],dihedral_list[dihedral][index4],angletypelist,anglevallist) dihedral_feature += (dihedral_angles[dihedral],angleval1,angleval2,bondlen1,bondlen2,bondlen3) labels.append(dihedral_feature) return labels
[ "numpy.arccos", "numpy.cross", "numpy.array", "numpy.dot", "numpy.arctan2", "numpy.linalg.norm" ]
[((88, 107), 'numpy.array', 'np.array', (['conformer'], {}), '(conformer)\n', (96, 107), True, 'import numpy as np\n'), ((1295, 1317), 'numpy.array', 'np.array', (['bondfeatures'], {}), '(bondfeatures)\n', (1303, 1317), True, 'import numpy as np\n'), ((1343, 1366), 'numpy.array', 'np.array', (['anglefeatures'], {}), '(anglefeatures)\n', (1351, 1366), True, 'import numpy as np\n'), ((1394, 1419), 'numpy.array', 'np.array', (['nonbondfeatures'], {}), '(nonbondfeatures)\n', (1402, 1419), True, 'import numpy as np\n'), ((1448, 1474), 'numpy.array', 'np.array', (['dihedralfeatures'], {}), '(dihedralfeatures)\n', (1456, 1474), True, 'import numpy as np\n'), ((7078, 7094), 'numpy.cross', 'np.cross', (['b0', 'b1'], {}), '(b0, b1)\n', (7086, 7094), True, 'import numpy as np\n'), ((7106, 7122), 'numpy.cross', 'np.cross', (['b2', 'b1'], {}), '(b2, b1)\n', (7114, 7122), True, 'import numpy as np\n'), ((7147, 7169), 'numpy.cross', 'np.cross', (['b0xb1', 'b1xb2'], {}), '(b0xb1, b1xb2)\n', (7155, 7169), True, 'import numpy as np\n'), ((7236, 7256), 'numpy.dot', 'np.dot', (['b0xb1', 'b1xb2'], {}), '(b0xb1, b1xb2)\n', (7242, 7256), True, 'import numpy as np\n'), ((7268, 7284), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (7278, 7284), True, 'import numpy as np\n'), ((4078, 4092), 'numpy.dot', 'np.dot', (['ba', 'bc'], {}), '(ba, bc)\n', (4084, 4092), True, 'import numpy as np\n'), ((4311, 4334), 'numpy.arccos', 'np.arccos', (['cosine_angle'], {}), '(cosine_angle)\n', (4320, 4334), True, 'import numpy as np\n'), ((7177, 7202), 'numpy.dot', 'np.dot', (['b0xb1_x_b1xb2', 'b1'], {}), '(b0xb1_x_b1xb2, b1)\n', (7183, 7202), True, 'import numpy as np\n'), ((2623, 2666), 'numpy.linalg.norm', 'np.linalg.norm', (['(conformer[i] - conformer[j])'], {}), '(conformer[i] - conformer[j])\n', (2637, 2666), True, 'import numpy as np\n'), ((4096, 4114), 'numpy.linalg.norm', 'np.linalg.norm', (['ba'], {}), '(ba)\n', (4110, 4114), True, 'import numpy as np\n'), ((4117, 4135), 'numpy.linalg.norm', 'np.linalg.norm', (['bc'], {}), '(bc)\n', (4131, 4135), True, 'import numpy as np\n'), ((5899, 5942), 'numpy.linalg.norm', 'np.linalg.norm', (['(conformer[i] - conformer[j])'], {}), '(conformer[i] - conformer[j])\n', (5913, 5942), True, 'import numpy as np\n'), ((7208, 7226), 'numpy.linalg.norm', 'np.linalg.norm', (['b1'], {}), '(b1)\n', (7222, 7226), True, 'import numpy as np\n')]
import time import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from ecg_classify.constants import FEATURE_NUM from ecg_classify.gen_data import gen_label, read_data from sklearn.utils import shuffle from ecg_classify.gen_label import MultiLabel, SingleLabel def __load_data(force=False): start_time = time.time() df_train, df_test = read_data(force) end_time = time.time() print("consume time: %.2f s" % (end_time - start_time)) return df_train, df_test def __prepare_data(df_train, df_test, label, inter=True): X_train = df_train.drop(str(FEATURE_NUM), axis=1).values X_test = df_test.drop(str(FEATURE_NUM), axis=1).values y_train, y_test = label.gen() y_train[y_train == 2] = 1 y_test[y_test == 2] = 1 if inter: X_train, y_train = shuffle(X_train, y_train) X_test, y_test = shuffle(X_test, y_test) else: X = np.vstack((X_train, X_test)) y = np.concatenate((y_train, y_test)) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42) return X_train, y_train, X_test, y_test def inter_patient(): df_train, df_test = __load_data() X_train, y_train, X_test, y_test = __prepare_data( df_train, df_test, MultiLabel()) clf = RandomForestClassifier(n_estimators=200, max_depth=8, criterion='entropy') start_time = time.time() clf.fit(X_train, y_train) end_time = time.time() print("training time span: %.2f s" % (end_time - start_time)) y_pred = clf.predict(X_test) print(accuracy_score(y_true=y_test, y_pred=y_pred)) print(confusion_matrix(y_true=y_test, y_pred=y_pred)) def intra_patient(): df_train, df_test = __load_data() X_train, y_train, X_test, y_test = __prepare_data( df_train, df_test, MultiLabel(), inter=False) clf = RandomForestClassifier(n_estimators=100, max_depth=6, random_state=0) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) print(accuracy_score(y_true=y_test, y_pred=y_pred)) print(confusion_matrix(y_true=y_test, y_pred=y_pred)) def compute_dataset_shift(): df_train, df_test = __load_data() X_train, X_test, y_train, y_test = __prepare_data( df_train, df_test, SingleLabel(), inter=False) clf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) print(accuracy_score(y_true=y_test, y_pred=y_pred)) print(confusion_matrix(y_true=y_test, y_pred=y_pred)) plot_feature_importance(df_train, clf) def plot_feature_importance(df_train, clf): features = df_train.columns.values imp = clf.feature_importances_ indices = np.argsort(imp)[::-1][:8] # plot plt.figure(figsize=(8, 5)) plt.bar(range(len(indices)), imp[indices], color='b', align='center') plt.xticks(range(len(indices)), features[indices], rotation='vertical') plt.xlim([-1,len(indices)]) plt.show() def normalize_test(X_train, X_test): # normalize test mean_n = X_train[0: 4000].sum(axis=0) / 4000 mean_l = X_train[4000: 8000].sum(axis=0) / 4000 mean_r = X_train[8000: 12000].sum(axis=0) / 4000 mean_a = X_train[12000: 16000].sum(axis=0) / 4000 mean_v = X_train[16000: 20000].sum(axis=0) / 4000 mean_n_test = X_test[0: 1000].sum(axis=0) / 1000 mean_l_test = X_test[1000: 2000].sum(axis=0) / 1000 mean_r_test = X_test[2000: 3000].sum(axis=0) / 1000 mean_a_test = X_test[3000: 4000].sum(axis=0) / 1000 mean_v_test = X_test[4000: 5000].sum(axis=0) / 1000 X_test[0: 1000] = X_test[0: 1000] * mean_n / mean_n_test X_test[1000: 2000] = X_test[1000: 2000] * mean_l / mean_l_test X_test[2000: 3000] = X_test[2000: 3000] * mean_r / mean_r_test X_test[3000: 4000] = X_test[3000: 4000] * mean_a / mean_a_test X_test[4000: 5000] = X_test[4000: 5000] * mean_v / mean_v_test
[ "sklearn.metrics.confusion_matrix", "ecg_classify.gen_label.SingleLabel", "sklearn.model_selection.train_test_split", "sklearn.utils.shuffle", "sklearn.ensemble.RandomForestClassifier", "numpy.argsort", "matplotlib.pyplot.figure", "numpy.vstack", "numpy.concatenate", "ecg_classify.gen_data.read_da...
[((473, 484), 'time.time', 'time.time', ([], {}), '()\n', (482, 484), False, 'import time\n'), ((509, 525), 'ecg_classify.gen_data.read_data', 'read_data', (['force'], {}), '(force)\n', (518, 525), False, 'from ecg_classify.gen_data import gen_label, read_data\n'), ((541, 552), 'time.time', 'time.time', ([], {}), '()\n', (550, 552), False, 'import time\n'), ((1450, 1524), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(200)', 'max_depth': '(8)', 'criterion': '"""entropy"""'}), "(n_estimators=200, max_depth=8, criterion='entropy')\n", (1472, 1524), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((1542, 1553), 'time.time', 'time.time', ([], {}), '()\n', (1551, 1553), False, 'import time\n'), ((1599, 1610), 'time.time', 'time.time', ([], {}), '()\n', (1608, 1610), False, 'import time\n'), ((2006, 2075), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(100)', 'max_depth': '(6)', 'random_state': '(0)'}), '(n_estimators=100, max_depth=6, random_state=0)\n', (2028, 2075), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2442, 2511), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(100)', 'max_depth': '(5)', 'random_state': '(0)'}), '(n_estimators=100, max_depth=5, random_state=0)\n', (2464, 2511), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2908, 2934), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 5)'}), '(figsize=(8, 5))\n', (2918, 2934), True, 'import matplotlib.pyplot as plt\n'), ((3121, 3131), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3129, 3131), True, 'import matplotlib.pyplot as plt\n'), ((955, 980), 'sklearn.utils.shuffle', 'shuffle', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (962, 980), False, 'from sklearn.utils import shuffle\n'), ((1006, 1029), 'sklearn.utils.shuffle', 'shuffle', (['X_test', 'y_test'], {}), '(X_test, y_test)\n', (1013, 1029), False, 'from sklearn.utils import shuffle\n'), ((1052, 1080), 'numpy.vstack', 'np.vstack', (['(X_train, X_test)'], {}), '((X_train, X_test))\n', (1061, 1080), True, 'import numpy as np\n'), ((1093, 1126), 'numpy.concatenate', 'np.concatenate', (['(y_train, y_test)'], {}), '((y_train, y_test))\n', (1107, 1126), True, 'import numpy as np\n'), ((1170, 1224), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(42)'}), '(X, y, test_size=0.2, random_state=42)\n', (1186, 1224), False, 'from sklearn.model_selection import train_test_split\n'), ((1425, 1437), 'ecg_classify.gen_label.MultiLabel', 'MultiLabel', ([], {}), '()\n', (1435, 1437), False, 'from ecg_classify.gen_label import MultiLabel, SingleLabel\n'), ((1721, 1765), 'sklearn.metrics.accuracy_score', 'accuracy_score', ([], {'y_true': 'y_test', 'y_pred': 'y_pred'}), '(y_true=y_test, y_pred=y_pred)\n', (1735, 1765), False, 'from sklearn.metrics import accuracy_score, confusion_matrix\n'), ((1777, 1823), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', ([], {'y_true': 'y_test', 'y_pred': 'y_pred'}), '(y_true=y_test, y_pred=y_pred)\n', (1793, 1823), False, 'from sklearn.metrics import accuracy_score, confusion_matrix\n'), ((1968, 1980), 'ecg_classify.gen_label.MultiLabel', 'MultiLabel', ([], {}), '()\n', (1978, 1980), False, 'from ecg_classify.gen_label import MultiLabel, SingleLabel\n'), ((2149, 2193), 'sklearn.metrics.accuracy_score', 'accuracy_score', ([], {'y_true': 'y_test', 'y_pred': 'y_pred'}), '(y_true=y_test, y_pred=y_pred)\n', (2163, 2193), False, 'from sklearn.metrics import accuracy_score, confusion_matrix\n'), ((2205, 2251), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', ([], {'y_true': 'y_test', 'y_pred': 'y_pred'}), '(y_true=y_test, y_pred=y_pred)\n', (2221, 2251), False, 'from sklearn.metrics import accuracy_score, confusion_matrix\n'), ((2404, 2417), 'ecg_classify.gen_label.SingleLabel', 'SingleLabel', ([], {}), '()\n', (2415, 2417), False, 'from ecg_classify.gen_label import MultiLabel, SingleLabel\n'), ((2585, 2629), 'sklearn.metrics.accuracy_score', 'accuracy_score', ([], {'y_true': 'y_test', 'y_pred': 'y_pred'}), '(y_true=y_test, y_pred=y_pred)\n', (2599, 2629), False, 'from sklearn.metrics import accuracy_score, confusion_matrix\n'), ((2641, 2687), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', ([], {'y_true': 'y_test', 'y_pred': 'y_pred'}), '(y_true=y_test, y_pred=y_pred)\n', (2657, 2687), False, 'from sklearn.metrics import accuracy_score, confusion_matrix\n'), ((2866, 2881), 'numpy.argsort', 'np.argsort', (['imp'], {}), '(imp)\n', (2876, 2881), True, 'import numpy as np\n')]
""" Classes for Volume objects """ from enum import Enum, unique import numpy as np from scipy.interpolate import CubicSpline, interp1d from ..math.matrix import Matrix44 class Curve: """Creates a Curve object used to generate transfer function for volumes :param inputs: input volume intensities :type inputs: numpy.ndarray :param outputs: output colour alpha :type outputs: numpy.ndarray :param bounds: minimum and maximum intensity in volume :type bounds: Tuple[float, float] :param curve_type: Type of fir for curve :type curve_type: Curve.Type """ @unique class Type(Enum): """Type of curve""" Cubic = 'Cubic' Linear = 'Linear' def __init__(self, inputs, outputs, bounds, curve_type): self.inputs = inputs self.outputs = outputs self.bounds = bounds self.type = curve_type self.f = None self.transfer_function = np.tile(np.linspace(0.0, 1.0, num=256, dtype=np.float32)[:, None], (1, 4)) if len(inputs) > 1: if curve_type == self.Type.Cubic: self.f = CubicSpline(inputs, outputs) else: self.f = interp1d(inputs, outputs, kind='linear', bounds_error=False, assume_sorted=True) value = self.evaluate(np.linspace(bounds[0], bounds[-1], num=256)) self.transfer_function[:, 3] = value self.transfer_function = self.transfer_function.flatten() def evaluate(self, inputs): """Computes the outputs alpha values for the input intensity :param inputs: input volume intensities :type inputs: numpy.ndarray :return: output colour alpha :rtype: numpy.ndarray """ if self.f is None: outputs = np.clip(np.full(len(inputs), self.outputs[0]), 0.0, 1.0) else: outputs = np.clip(self.f(inputs), 0.0, 1.0) outputs[inputs < self.inputs[0]] = self.outputs[0] outputs[inputs > self.inputs[-1]] = self.outputs[-1] return outputs class Volume: """Creates a Volume object. This is the result of loading in a tomography scan, either from a nexus file, or a set of TIFF files. It is the equivalent of the mesh object but for tomography data :param data: N x M x L array of intensities, created by stacking L TIFF images, each of dimension N x M :type data: numpy.ndarray :param x: N array of pixel coordinates :type x: numpy.ndarray :param y: M array of pixel coordinates :type y: numpy.ndarray :param z: L array of pixel coordinates :type z: numpy.ndarray """ def __init__(self, data, x, y, z): self.data = data self.x = x self.y = y self.z = z self.histogram = np.histogram(data, bins=256) inputs = np.array([self.histogram[1][0], self.histogram[1][-1]]) outputs = np.array([0.0, 1.0]) if inputs[0] == inputs[1]: inputs = inputs[1:] outputs = outputs[1:] self.curve = Curve(inputs, outputs, inputs, Curve.Type.Cubic) x_spacing = (x[-1] - x[0]) / (len(x) - 1) y_spacing = (y[-1] - y[0]) / (len(y) - 1) z_spacing = (z[-1] - z[0]) / (len(z) - 1) x_origin = x[0] + (x[-1] - x[0]) / 2 y_origin = y[0] + (y[-1] - y[0]) / 2 z_origin = z[0] + (z[-1] - z[0]) / 2 self.voxel_size = np.array([x_spacing, y_spacing, z_spacing], np.float32) self.transform = Matrix44.fromTranslation([x_origin, y_origin, z_origin]) @property def shape(self): """Returns shape of volume i.e. width, height, depth :return: shape of volume :rtype: Tuple[int, int, int] """ return self.data.shape @property def extent(self): """Returns extent or diagonal of volume :return: extent of volume :rtype: numpy.ndarray[float] """ return self.voxel_size * self.shape
[ "numpy.histogram", "scipy.interpolate.CubicSpline", "scipy.interpolate.interp1d", "numpy.array", "numpy.linspace" ]
[((2769, 2797), 'numpy.histogram', 'np.histogram', (['data'], {'bins': '(256)'}), '(data, bins=256)\n', (2781, 2797), True, 'import numpy as np\n'), ((2815, 2870), 'numpy.array', 'np.array', (['[self.histogram[1][0], self.histogram[1][-1]]'], {}), '([self.histogram[1][0], self.histogram[1][-1]])\n', (2823, 2870), True, 'import numpy as np\n'), ((2889, 2909), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (2897, 2909), True, 'import numpy as np\n'), ((3397, 3452), 'numpy.array', 'np.array', (['[x_spacing, y_spacing, z_spacing]', 'np.float32'], {}), '([x_spacing, y_spacing, z_spacing], np.float32)\n', (3405, 3452), True, 'import numpy as np\n'), ((1304, 1347), 'numpy.linspace', 'np.linspace', (['bounds[0]', 'bounds[-1]'], {'num': '(256)'}), '(bounds[0], bounds[-1], num=256)\n', (1315, 1347), True, 'import numpy as np\n'), ((954, 1002), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)'], {'num': '(256)', 'dtype': 'np.float32'}), '(0.0, 1.0, num=256, dtype=np.float32)\n', (965, 1002), True, 'import numpy as np\n'), ((1120, 1148), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['inputs', 'outputs'], {}), '(inputs, outputs)\n', (1131, 1148), False, 'from scipy.interpolate import CubicSpline, interp1d\n'), ((1192, 1277), 'scipy.interpolate.interp1d', 'interp1d', (['inputs', 'outputs'], {'kind': '"""linear"""', 'bounds_error': '(False)', 'assume_sorted': '(True)'}), "(inputs, outputs, kind='linear', bounds_error=False, assume_sorted=True\n )\n", (1200, 1277), False, 'from scipy.interpolate import CubicSpline, interp1d\n')]
# Copyright 2020 AstroLab Software # Author: <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the 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 pandas as pd import numpy as np from gatspy import periodic import java import copy from astropy.time import Time import dash from dash.dependencies import Input, Output import plotly.graph_objects as go from apps.utils import convert_jd, readstamp, _data_stretch, convolve from apps.utils import apparent_flux, dc_mag from pyLIMA import event from pyLIMA import telescopes from pyLIMA import microlmodels, microltoolbox from pyLIMA.microloutputs import create_the_fake_telescopes from app import client, app colors_ = [ '#1f77b4', # muted blue '#ff7f0e', # safety orange '#2ca02c', # cooked asparagus green '#d62728', # brick red '#9467bd', # muted purple '#8c564b', # chestnut brown '#e377c2', # raspberry yogurt pink '#7f7f7f', # middle gray '#bcbd22', # curry yellow-green '#17becf' # blue-teal ] all_radio_options = { "Difference magnitude": ["Difference magnitude", "DC magnitude", "DC apparent flux"], "DC magnitude": ["Difference magnitude", "DC magnitude", "DC apparent flux"], "DC apparent flux": ["Difference magnitude", "DC magnitude", "DC apparent flux"] } layout_lightcurve = dict( automargin=True, margin=dict(l=50, r=30, b=0, t=0), hovermode="closest", legend=dict( font=dict(size=10), orientation="h", xanchor="right", x=1, bgcolor='rgba(0,0,0,0)' ), xaxis={ 'title': 'Observation date', 'automargin': True }, yaxis={ 'autorange': 'reversed', 'title': 'Magnitude', 'automargin': True } ) layout_phase = dict( autosize=True, automargin=True, margin=dict(l=50, r=30, b=40, t=25), hovermode="closest", legend=dict( font=dict(size=10), orientation="h", yanchor="bottom", y=0.02, xanchor="right", x=1, bgcolor='rgba(0,0,0,0)' ), xaxis={ 'title': 'Phase' }, yaxis={ 'autorange': 'reversed', 'title': 'Apparent DC Magnitude' }, title={ "text": "Phased data", "y": 1.01, "yanchor": "bottom" } ) layout_mulens = dict( autosize=True, automargin=True, margin=dict(l=50, r=30, b=40, t=25), hovermode="closest", legend=dict( font=dict(size=10), orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1, bgcolor='rgba(0,0,0,0)' ), xaxis={ 'title': 'Observation date' }, yaxis={ 'autorange': 'reversed', 'title': 'DC magnitude' }, title={ "text": "pyLIMA Fit (PSPL model)", "y": 1.01, "yanchor": "bottom" } ) layout_scores = dict( autosize=True, automargin=True, margin=dict(l=50, r=30, b=0, t=0), hovermode="closest", legend=dict(font=dict(size=10), orientation="h"), xaxis={ 'title': 'Observation date' }, yaxis={ 'title': 'Score', 'range': [0, 1] } ) def extract_scores(data: java.util.TreeMap) -> pd.DataFrame: """ Extract SN scores from the data """ values = ['i:jd', 'd:snn_snia_vs_nonia', 'd:snn_sn_vs_all', 'd:rfscore'] pdfs = pd.DataFrame.from_dict(data, orient='index') if pdfs.empty: return pdfs return pdfs[values] @app.callback( Output('switch-mag-flux-score', 'options'), [Input('switch-mag-flux', 'value')]) def set_radio2_options(selected_radio): return [{'label': i, 'value': i} for i in all_radio_options[selected_radio]] @app.callback( Output('switch-mag-flux-score', 'value'), [Input('switch-mag-flux-score', 'options'), Input('switch-mag-flux', 'value')]) def set_radio1_value(available_options, value): index = [available_options.index(i) for i in available_options if i['label'] == value][0] return available_options[index]['value'] @app.callback( [ Output('lightcurve_cutouts', 'figure'), Output('lightcurve_scores', 'figure') ], [ Input('switch-mag-flux', 'value'), Input('switch-mag-flux-score', 'value'), Input('url', 'pathname'), Input('object-data', 'children'), Input('object-upper', 'children') ]) def draw_lightcurve(switch1: int, switch2: int, pathname: str, object_data, object_upper) -> dict: """ Draw object lightcurve with errorbars Parameters ---------- switch{i}: int Choose: - 0 to display difference magnitude - 1 to display dc magnitude - 2 to display flux pathname: str Pathname of the current webpage (should be /ZTF19...). Returns ---------- figure: dict """ changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0] if 'switch-mag-flux-score' in changed_id: switch = switch2 else: switch = switch1 pdf_ = pd.read_json(object_data) cols = [ 'i:jd', 'i:magpsf', 'i:sigmapsf', 'i:fid', 'i:magnr', 'i:sigmagnr', 'i:magzpsci', 'i:isdiffpos' ] pdf = pdf_.loc[:, cols] # type conversion jd = pdf['i:jd'] jd = jd.apply(lambda x: convert_jd(float(x), to='iso')) # shortcuts mag = pdf['i:magpsf'] err = pdf['i:sigmapsf'] if switch == "Difference magnitude": layout_lightcurve['yaxis']['title'] = 'Difference magnitude' layout_lightcurve['yaxis']['autorange'] = 'reversed' elif switch == "DC magnitude": # inplace replacement mag, err = np.transpose( [ dc_mag(*args) for args in zip( pdf['i:fid'].values, mag.astype(float).values, err.astype(float).values, pdf['i:magnr'].astype(float).values, pdf['i:sigmagnr'].astype(float).values, pdf['i:magzpsci'].astype(float).values, pdf['i:isdiffpos'].values ) ] ) layout_lightcurve['yaxis']['title'] = 'Apparent DC magnitude' layout_lightcurve['yaxis']['autorange'] = 'reversed' elif switch == "DC apparent flux": # inplace replacement mag, err = np.transpose( [ apparent_flux(*args) for args in zip( pdf['i:fid'].astype(int).values, mag.astype(float).values, err.astype(float).values, pdf['i:magnr'].astype(float).values, pdf['i:sigmagnr'].astype(float).values, pdf['i:magzpsci'].astype(float).values, pdf['i:isdiffpos'].values ) ] ) layout_lightcurve['yaxis']['title'] = 'Apparent DC flux' layout_lightcurve['yaxis']['autorange'] = True figure = { 'data': [ { 'x': jd[pdf['i:fid'] == 1], 'y': mag[pdf['i:fid'] == 1], 'error_y': { 'type': 'data', 'array': err[pdf['i:fid'] == 1], 'visible': True, 'color': '#1f77b4' }, 'mode': 'markers', 'name': 'g band', 'text': jd[pdf['i:fid'] == 1], 'marker': { 'size': 12, 'color': '#1f77b4', 'symbol': 'o'} }, { 'x': jd[pdf['i:fid'] == 2], 'y': mag[pdf['i:fid'] == 2], 'error_y': { 'type': 'data', 'array': err[pdf['i:fid'] == 2], 'visible': True, 'color': '#ff7f0e' }, 'mode': 'markers', 'name': 'r band', 'text': jd[pdf['i:fid'] == 2], 'marker': { 'size': 12, 'color': '#ff7f0e', 'symbol': 'o'} } ], "layout": layout_lightcurve } if switch == "Difference magnitude": pdf_upper = pd.read_json(object_upper) if not pdf_upper.empty: pdf_upper['i:jd'] = pdf_upper['i:jd'].apply(lambda x: convert_jd(float(x), to='iso')) figure['data'].append( { 'x': pdf_upper['i:jd'][pdf_upper['i:fid'] == 1], 'y': pdf_upper['i:diffmaglim'][pdf_upper['i:fid'] == 1], 'mode': 'markers', 'marker': { 'color': '#1f77b4', 'symbol': 'triangle-down-open' }, 'showlegend': False } ) figure['data'].append( { 'x': pdf_upper['i:jd'][pdf_upper['i:fid'] == 2], 'y': pdf_upper['i:diffmaglim'][pdf_upper['i:fid'] == 2], 'mode': 'markers', 'marker': { 'color': '#ff7f0e', 'symbol': 'triangle-down-open' }, 'showlegend': False } ) return figure, figure def draw_scores(data: java.util.TreeMap) -> dict: """ Draw scores from SNN module Parameters ---------- data: java.util.TreeMap Results from a HBase client query Returns ---------- figure: dict TODO: memoise me """ pdf = extract_scores(data) jd = pdf['i:jd'] jd = jd.apply(lambda x: convert_jd(float(x), to='iso')) figure = { 'data': [ { 'x': jd, 'y': [0.5] * len(jd), 'mode': 'lines', 'showlegend': False, 'line': { 'color': 'black', 'width': 2.5, 'dash': 'dash' } }, { 'x': jd, 'y': pdf['d:snn_snia_vs_nonia'], 'mode': 'markers', 'name': 'SN Ia score', 'text': jd, 'marker': { 'size': 10, 'color': '#2ca02c', 'symbol': 'circle'} }, { 'x': jd, 'y': pdf['d:snn_sn_vs_all'], 'mode': 'markers', 'name': 'SNe score', 'text': jd, 'marker': { 'size': 10, 'color': '#d62728', 'symbol': 'square'} }, { 'x': jd, 'y': pdf['d:rfscore'], 'mode': 'markers', 'name': '<NAME>', 'text': jd, 'marker': { 'size': 10, 'color': '#9467bd', 'symbol': 'diamond'} } ], "layout": layout_scores } return figure def extract_cutout(object_data, time0, kind): """ Extract cutout data from the alert Parameters ---------- object_data: json Jsonified pandas DataFrame time0: str ISO time of the cutout to extract kind: str science, template, or difference Returns ---------- data: np.array 2D array containing cutout data """ values = [ 'i:jd', 'i:fid', 'b:cutout{}_stampData'.format(kind.capitalize()), ] pdf_ = pd.read_json(object_data) pdfs = pdf_.loc[:, values] pdfs = pdfs.sort_values('i:jd', ascending=False) if time0 is None: position = 0 else: # Round to avoid numerical precision issues jds = pdfs['i:jd'].apply(lambda x: np.round(x, 3)).values jd0 = np.round(Time(time0, format='iso').jd, 3) position = np.where(jds == jd0)[0][0] # Grab the cutout data cutout = readstamp( client.repository().get( pdfs['b:cutout{}_stampData'.format(kind.capitalize())].values[position] ) ) return cutout @app.callback( Output("science-stamps", "figure"), [ Input('lightcurve_cutouts', 'clickData'), Input('object-data', 'children'), ]) def draw_cutouts_science(clickData, object_data): """ Draw science cutout data based on lightcurve data """ if clickData is not None: # Draw the cutout associated to the clicked data points jd0 = clickData['points'][0]['x'] else: # draw the cutout of the last alert jd0 = None data = extract_cutout(object_data, jd0, kind='science') return draw_cutout(data, 'science') @app.callback( Output("template-stamps", "figure"), [ Input('lightcurve_cutouts', 'clickData'), Input('object-data', 'children'), ]) def draw_cutouts_template(clickData, object_data): """ Draw template cutout data based on lightcurve data """ if clickData is not None: jd0 = clickData['points'][0]['x'] else: jd0 = None data = extract_cutout(object_data, jd0, kind='template') return draw_cutout(data, 'template') @app.callback( Output("difference-stamps", "figure"), [ Input('lightcurve_cutouts', 'clickData'), Input('object-data', 'children'), ]) def draw_cutouts_difference(clickData, object_data): """ Draw difference cutout data based on lightcurve data """ if clickData is not None: jd0 = clickData['points'][0]['x'] else: jd0 = None data = extract_cutout(object_data, jd0, kind='difference') return draw_cutout(data, 'difference') def draw_cutout(data, title): """ Draw a cutout data """ # Update graph data for stamps size = len(data) data = np.nan_to_num(data) vmax = data[int(size / 2), int(size / 2)] vmin = np.min(data) + 0.2 * np.median(np.abs(data - np.median(data))) data = _data_stretch(data, vmin=vmin, vmax=vmax, stretch='asinh') data = data[::-1] data = convolve(data, smooth=1, kernel='gauss') fig = go.Figure( data=go.Heatmap( z=data, showscale=False, colorscale='Greys_r' ) ) # Greys_r axis_template = dict( autorange=True, showgrid=False, zeroline=False, linecolor='black', showticklabels=False, ticks='') fig.update_layout( title=title, margin=dict(t=0, r=0, b=0, l=0), xaxis=axis_template, yaxis=axis_template, showlegend=True, width=150, height=150, autosize=False) return fig @app.callback( Output('variable_plot', 'figure'), [ Input('nterms_base', 'value'), Input('nterms_band', 'value'), Input('manual_period', 'value'), Input('submit_variable', 'n_clicks'), Input('object-data', 'children') ]) def plot_variable_star(nterms_base, nterms_band, manual_period, n_clicks, object_data): """ Fit for the period of a star using gatspy See https://zenodo.org/record/47887 See https://ui.adsabs.harvard.edu/abs/2015ApJ...812...18V/abstract TODO: clean me """ if type(nterms_base) not in [int]: return {'data': [], "layout": layout_phase} if type(nterms_band) not in [int]: return {'data': [], "layout": layout_phase} if manual_period is not None and type(manual_period) not in [int, float]: return {'data': [], "layout": layout_phase} if n_clicks is not None: pdf_ = pd.read_json(object_data) cols = [ 'i:jd', 'i:magpsf', 'i:sigmapsf', 'i:fid', 'i:magnr', 'i:sigmagnr', 'i:magzpsci', 'i:isdiffpos', 'i:objectId' ] pdf = pdf_.loc[:, cols] pdf['i:fid'] = pdf['i:fid'].astype(str) pdf = pdf.sort_values('i:jd', ascending=False) mag_dc, err_dc = np.transpose( [ dc_mag(*args) for args in zip( pdf['i:fid'].astype(int).values, pdf['i:magpsf'].astype(float).values, pdf['i:sigmapsf'].astype(float).values, pdf['i:magnr'].astype(float).values, pdf['i:sigmagnr'].astype(float).values, pdf['i:magzpsci'].astype(float).values, pdf['i:isdiffpos'].values ) ] ) jd = pdf['i:jd'] fit_period = False if manual_period is not None else True model = periodic.LombScargleMultiband( Nterms_base=int(nterms_base), Nterms_band=int(nterms_band), fit_period=fit_period ) # Not sure about that... model.optimizer.period_range = (0.1, 1.2) model.optimizer.quiet = True model.fit( jd.astype(float), mag_dc, err_dc, pdf['i:fid'].astype(int) ) if fit_period: period = model.best_period else: period = manual_period phase = jd.astype(float).values % period tfit = np.linspace(0, period, 100) layout_phase_ = copy.deepcopy(layout_phase) layout_phase_['title']['text'] = 'Period: {} days'.format(period) if '1' in np.unique(pdf['i:fid'].values): plot_filt1 = { 'x': phase[pdf['i:fid'] == '1'], 'y': mag_dc[pdf['i:fid'] == '1'], 'error_y': { 'type': 'data', 'array': err_dc[pdf['i:fid'] == '1'], 'visible': True, 'color': '#1f77b4' }, 'mode': 'markers', 'name': 'g band', 'text': phase[pdf['i:fid'] == '1'], 'marker': { 'size': 12, 'color': '#1f77b4', 'symbol': 'o'} } fit_filt1 = { 'x': tfit, 'y': model.predict(tfit, period=period, filts=1), 'mode': 'lines', 'name': 'fit g band', 'showlegend': False, 'line': { 'color': '#1f77b4', } } else: plot_filt1 = {} fit_filt1 = {} if '2' in np.unique(pdf['i:fid'].values): plot_filt2 = { 'x': phase[pdf['i:fid'] == '2'], 'y': mag_dc[pdf['i:fid'] == '2'], 'error_y': { 'type': 'data', 'array': err_dc[pdf['i:fid'] == '2'], 'visible': True, 'color': '#ff7f0e' }, 'mode': 'markers', 'name': 'r band', 'text': phase[pdf['i:fid'] == '2'], 'marker': { 'size': 12, 'color': '#ff7f0e', 'symbol': 'o'} } fit_filt2 = { 'x': tfit, 'y': model.predict(tfit, period=period, filts=2), 'mode': 'lines', 'name': 'fit r band', 'showlegend': False, 'line': { 'color': '#ff7f0e', } } else: plot_filt2 = {} fit_filt2 = {} figure = { 'data': [ plot_filt1, fit_filt1, plot_filt2, fit_filt2 ], "layout": layout_phase_ } return figure return {'data': [], "layout": layout_phase} @app.callback( [ Output('mulens_plot', 'figure'), Output('mulens_params', 'children'), ], [ Input('submit_mulens', 'n_clicks'), Input('object-data', 'children') ]) def plot_mulens(n_clicks, object_data): """ Fit for microlensing event TODO: implement a fit using pyLIMA """ if n_clicks is not None: pdf_ = pd.read_json(object_data) cols = [ 'i:jd', 'i:magpsf', 'i:sigmapsf', 'i:fid', 'i:ra', 'i:dec', 'i:magnr', 'i:sigmagnr', 'i:magzpsci', 'i:isdiffpos', 'i:objectId' ] pdf = pdf_.loc[:, cols] pdf['i:fid'] = pdf['i:fid'].astype(str) pdf = pdf.sort_values('i:jd', ascending=False) mag_dc, err_dc = np.transpose( [ dc_mag(*args) for args in zip( pdf['i:fid'].astype(int).values, pdf['i:magpsf'].astype(float).values, pdf['i:sigmapsf'].astype(float).values, pdf['i:magnr'].astype(float).values, pdf['i:sigmagnr'].astype(float).values, pdf['i:magzpsci'].astype(float).values, pdf['i:isdiffpos'].values ) ] ) current_event = event.Event() current_event.name = pdf['i:objectId'].values[0] current_event.ra = pdf['i:ra'].values[0] current_event.dec = pdf['i:dec'].values[0] filts = {'1': 'g', '2': 'r'} for fid in np.unique(pdf['i:fid'].values): mask = pdf['i:fid'].values == fid telescope = telescopes.Telescope( name='ztf_{}'.format(filts[fid]), camera_filter=format(filts[fid]), light_curve_magnitude=np.transpose( [ pdf['i:jd'].values[mask], pdf['i:magpsf'].values[mask], pdf['i:sigmapsf'].values[mask] ] ), light_curve_magnitude_dictionnary={ 'time': 0, 'mag': 1, 'err_mag': 2 } ) current_event.telescopes.append(telescope) # Le modele le plus simple mulens_model = microlmodels.create_model('PSPL', current_event) current_event.fit(mulens_model, 'DE') # 4 parameters dof = len(pdf) - 4 - 1 results = current_event.fits[0] normalised_lightcurves = microltoolbox.align_the_data_to_the_reference_telescope(results, 0, results.fit_results) # Model create_the_fake_telescopes(results, results.fit_results) telescope_ = results.event.fake_telescopes[0] flux_model = mulens_model.compute_the_microlensing_model(telescope_, results.model.compute_pyLIMA_parameters(results.fit_results))[0] time = telescope_.lightcurve_flux[:, 0] magnitude = microltoolbox.flux_to_magnitude(flux_model) if '1' in np.unique(pdf['i:fid'].values): plot_filt1 = { 'x': [convert_jd(t, to='iso') for t in normalised_lightcurves[0][:, 0]], 'y': normalised_lightcurves[0][:, 1], 'error_y': { 'type': 'data', 'array': normalised_lightcurves[0][:, 2], 'visible': True, 'color': '#1f77b4' }, 'mode': 'markers', 'name': 'g band', 'text': [convert_jd(t, to='iso') for t in normalised_lightcurves[0][:, 0]], 'marker': { 'size': 12, 'color': '#1f77b4', 'symbol': 'o'} } else: plot_filt1 = {} if '2' in np.unique(pdf['i:fid'].values): plot_filt2 = { 'x': [convert_jd(t, to='iso') for t in normalised_lightcurves[1][:, 0]], 'y': normalised_lightcurves[1][:, 1], 'error_y': { 'type': 'data', 'array': normalised_lightcurves[1][:, 2], 'visible': True, 'color': '#ff7f0e' }, 'mode': 'markers', 'name': 'r band', 'text': [convert_jd(t, to='iso') for t in normalised_lightcurves[1][:, 0]], 'marker': { 'size': 12, 'color': '#ff7f0e', 'symbol': 'o'} } else: plot_filt2 = {} fit_filt = { 'x': [convert_jd(float(t), to='iso') for t in time], 'y': magnitude, 'mode': 'lines', 'name': 'fit', 'showlegend': False, 'line': { 'color': '#7f7f7f', } } figure = { 'data': [ fit_filt, plot_filt1, plot_filt2 ], "layout": layout_mulens } # fitted parameters names = results.model.model_dictionnary params = results.fit_results err = np.diag(np.sqrt(results.fit_covariance)) mulens_params = """ ```python # Fitted parameters t0: {} +/- {} (jd) tE: {} +/- {} (days) u0: {} +/- {} chi2/dof: {} ``` --- """.format( params[names['to']], err[names['to']], params[names['tE']], err[names['tE']], params[names['uo']], err[names['uo']], params[-1] / dof ) return figure, mulens_params mulens_params = """ ```python # Fitted parameters t0: None tE: None u0: None chi2: None ``` --- """ return {'data': [], "layout": layout_mulens}, mulens_params @app.callback( Output('aladin-lite-div', 'run'), Input('object-data', 'children')) def integrate_aladin_lite(object_data): """ Integrate aladin light in the 2nd Tab of the dashboard. the default parameters are: * PanSTARRS colors * FoV = 0.02 deg * SIMBAD catalig overlayed. Callbacks ---------- Input: takes the alert ID Output: Display a sky image around the alert position from aladin. Parameters ---------- alert_id: str ID of the alert """ pdf_ = pd.read_json(object_data) cols = ['i:jd', 'i:ra', 'i:dec'] pdf = pdf_.loc[:, cols] pdf = pdf.sort_values('i:jd', ascending=False) # Coordinate of the current alert ra0 = pdf['i:ra'].values[0] dec0 = pdf['i:dec'].values[0] # Javascript. Note the use {{}} for dictionary img = """ var aladin = A.aladin('#aladin-lite-div', {{ survey: 'P/PanSTARRS/DR1/color/z/zg/g', fov: 0.025, target: '{} {}', reticleColor: '#ff89ff', reticleSize: 32 }}); var cat = 'https://axel.u-strasbg.fr/HiPSCatService/Simbad'; var hips = A.catalogHiPS(cat, {{onClick: 'showTable', name: 'Simbad'}}); aladin.addCatalog(hips); """.format(ra0, dec0) # img cannot be executed directly because of formatting # We split line-by-line and remove comments img_to_show = [i for i in img.split('\n') if '// ' not in i] return " ".join(img_to_show)
[ "apps.utils._data_stretch", "numpy.sqrt", "pyLIMA.microlmodels.create_model", "dash.dependencies.Input", "pyLIMA.microloutputs.create_the_fake_telescopes", "copy.deepcopy", "plotly.graph_objects.Heatmap", "numpy.where", "dash.dependencies.Output", "pandas.DataFrame.from_dict", "numpy.linspace", ...
[((3820, 3864), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['data'], {'orient': '"""index"""'}), "(data, orient='index')\n", (3842, 3864), True, 'import pandas as pd\n'), ((3948, 3990), 'dash.dependencies.Output', 'Output', (['"""switch-mag-flux-score"""', '"""options"""'], {}), "('switch-mag-flux-score', 'options')\n", (3954, 3990), False, 'from dash.dependencies import Input, Output\n'), ((4175, 4215), 'dash.dependencies.Output', 'Output', (['"""switch-mag-flux-score"""', '"""value"""'], {}), "('switch-mag-flux-score', 'value')\n", (4181, 4215), False, 'from dash.dependencies import Input, Output\n'), ((5487, 5512), 'pandas.read_json', 'pd.read_json', (['object_data'], {}), '(object_data)\n', (5499, 5512), True, 'import pandas as pd\n'), ((12140, 12165), 'pandas.read_json', 'pd.read_json', (['object_data'], {}), '(object_data)\n', (12152, 12165), True, 'import pandas as pd\n'), ((12748, 12782), 'dash.dependencies.Output', 'Output', (['"""science-stamps"""', '"""figure"""'], {}), "('science-stamps', 'figure')\n", (12754, 12782), False, 'from dash.dependencies import Input, Output\n'), ((13334, 13369), 'dash.dependencies.Output', 'Output', (['"""template-stamps"""', '"""figure"""'], {}), "('template-stamps', 'figure')\n", (13340, 13369), False, 'from dash.dependencies import Input, Output\n'), ((13817, 13854), 'dash.dependencies.Output', 'Output', (['"""difference-stamps"""', '"""figure"""'], {}), "('difference-stamps', 'figure')\n", (13823, 13854), False, 'from dash.dependencies import Input, Output\n'), ((14423, 14442), 'numpy.nan_to_num', 'np.nan_to_num', (['data'], {}), '(data)\n', (14436, 14442), True, 'import numpy as np\n'), ((14574, 14632), 'apps.utils._data_stretch', '_data_stretch', (['data'], {'vmin': 'vmin', 'vmax': 'vmax', 'stretch': '"""asinh"""'}), "(data, vmin=vmin, vmax=vmax, stretch='asinh')\n", (14587, 14632), False, 'from apps.utils import convert_jd, readstamp, _data_stretch, convolve\n'), ((14666, 14706), 'apps.utils.convolve', 'convolve', (['data'], {'smooth': '(1)', 'kernel': '"""gauss"""'}), "(data, smooth=1, kernel='gauss')\n", (14674, 14706), False, 'from apps.utils import convert_jd, readstamp, _data_stretch, convolve\n'), ((15260, 15293), 'dash.dependencies.Output', 'Output', (['"""variable_plot"""', '"""figure"""'], {}), "('variable_plot', 'figure')\n", (15266, 15293), False, 'from dash.dependencies import Input, Output\n'), ((26727, 26752), 'pandas.read_json', 'pd.read_json', (['object_data'], {}), '(object_data)\n', (26739, 26752), True, 'import pandas as pd\n'), ((26211, 26243), 'dash.dependencies.Output', 'Output', (['"""aladin-lite-div"""', '"""run"""'], {}), "('aladin-lite-div', 'run')\n", (26217, 26243), False, 'from dash.dependencies import Input, Output\n'), ((26245, 26277), 'dash.dependencies.Input', 'Input', (['"""object-data"""', '"""children"""'], {}), "('object-data', 'children')\n", (26250, 26277), False, 'from dash.dependencies import Input, Output\n'), ((3997, 4030), 'dash.dependencies.Input', 'Input', (['"""switch-mag-flux"""', '"""value"""'], {}), "('switch-mag-flux', 'value')\n", (4002, 4030), False, 'from dash.dependencies import Input, Output\n'), ((4222, 4263), 'dash.dependencies.Input', 'Input', (['"""switch-mag-flux-score"""', '"""options"""'], {}), "('switch-mag-flux-score', 'options')\n", (4227, 4263), False, 'from dash.dependencies import Input, Output\n'), ((4265, 4298), 'dash.dependencies.Input', 'Input', (['"""switch-mag-flux"""', '"""value"""'], {}), "('switch-mag-flux', 'value')\n", (4270, 4298), False, 'from dash.dependencies import Input, Output\n'), ((8718, 8744), 'pandas.read_json', 'pd.read_json', (['object_upper'], {}), '(object_upper)\n', (8730, 8744), True, 'import pandas as pd\n'), ((4518, 4556), 'dash.dependencies.Output', 'Output', (['"""lightcurve_cutouts"""', '"""figure"""'], {}), "('lightcurve_cutouts', 'figure')\n", (4524, 4556), False, 'from dash.dependencies import Input, Output\n'), ((4566, 4603), 'dash.dependencies.Output', 'Output', (['"""lightcurve_scores"""', '"""figure"""'], {}), "('lightcurve_scores', 'figure')\n", (4572, 4603), False, 'from dash.dependencies import Input, Output\n'), ((4625, 4658), 'dash.dependencies.Input', 'Input', (['"""switch-mag-flux"""', '"""value"""'], {}), "('switch-mag-flux', 'value')\n", (4630, 4658), False, 'from dash.dependencies import Input, Output\n'), ((4668, 4707), 'dash.dependencies.Input', 'Input', (['"""switch-mag-flux-score"""', '"""value"""'], {}), "('switch-mag-flux-score', 'value')\n", (4673, 4707), False, 'from dash.dependencies import Input, Output\n'), ((4717, 4741), 'dash.dependencies.Input', 'Input', (['"""url"""', '"""pathname"""'], {}), "('url', 'pathname')\n", (4722, 4741), False, 'from dash.dependencies import Input, Output\n'), ((4751, 4783), 'dash.dependencies.Input', 'Input', (['"""object-data"""', '"""children"""'], {}), "('object-data', 'children')\n", (4756, 4783), False, 'from dash.dependencies import Input, Output\n'), ((4793, 4826), 'dash.dependencies.Input', 'Input', (['"""object-upper"""', '"""children"""'], {}), "('object-upper', 'children')\n", (4798, 4826), False, 'from dash.dependencies import Input, Output\n'), ((12798, 12838), 'dash.dependencies.Input', 'Input', (['"""lightcurve_cutouts"""', '"""clickData"""'], {}), "('lightcurve_cutouts', 'clickData')\n", (12803, 12838), False, 'from dash.dependencies import Input, Output\n'), ((12848, 12880), 'dash.dependencies.Input', 'Input', (['"""object-data"""', '"""children"""'], {}), "('object-data', 'children')\n", (12853, 12880), False, 'from dash.dependencies import Input, Output\n'), ((13385, 13425), 'dash.dependencies.Input', 'Input', (['"""lightcurve_cutouts"""', '"""clickData"""'], {}), "('lightcurve_cutouts', 'clickData')\n", (13390, 13425), False, 'from dash.dependencies import Input, Output\n'), ((13435, 13467), 'dash.dependencies.Input', 'Input', (['"""object-data"""', '"""children"""'], {}), "('object-data', 'children')\n", (13440, 13467), False, 'from dash.dependencies import Input, Output\n'), ((13870, 13910), 'dash.dependencies.Input', 'Input', (['"""lightcurve_cutouts"""', '"""clickData"""'], {}), "('lightcurve_cutouts', 'clickData')\n", (13875, 13910), False, 'from dash.dependencies import Input, Output\n'), ((13920, 13952), 'dash.dependencies.Input', 'Input', (['"""object-data"""', '"""children"""'], {}), "('object-data', 'children')\n", (13925, 13952), False, 'from dash.dependencies import Input, Output\n'), ((14500, 14512), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (14506, 14512), True, 'import numpy as np\n'), ((16149, 16174), 'pandas.read_json', 'pd.read_json', (['object_data'], {}), '(object_data)\n', (16161, 16174), True, 'import pandas as pd\n'), ((17710, 17737), 'numpy.linspace', 'np.linspace', (['(0)', 'period', '(100)'], {}), '(0, period, 100)\n', (17721, 17737), True, 'import numpy as np\n'), ((17763, 17790), 'copy.deepcopy', 'copy.deepcopy', (['layout_phase'], {}), '(layout_phase)\n', (17776, 17790), False, 'import copy\n'), ((15309, 15338), 'dash.dependencies.Input', 'Input', (['"""nterms_base"""', '"""value"""'], {}), "('nterms_base', 'value')\n", (15314, 15338), False, 'from dash.dependencies import Input, Output\n'), ((15348, 15377), 'dash.dependencies.Input', 'Input', (['"""nterms_band"""', '"""value"""'], {}), "('nterms_band', 'value')\n", (15353, 15377), False, 'from dash.dependencies import Input, Output\n'), ((15387, 15418), 'dash.dependencies.Input', 'Input', (['"""manual_period"""', '"""value"""'], {}), "('manual_period', 'value')\n", (15392, 15418), False, 'from dash.dependencies import Input, Output\n'), ((15428, 15464), 'dash.dependencies.Input', 'Input', (['"""submit_variable"""', '"""n_clicks"""'], {}), "('submit_variable', 'n_clicks')\n", (15433, 15464), False, 'from dash.dependencies import Input, Output\n'), ((15474, 15506), 'dash.dependencies.Input', 'Input', (['"""object-data"""', '"""children"""'], {}), "('object-data', 'children')\n", (15479, 15506), False, 'from dash.dependencies import Input, Output\n'), ((20645, 20670), 'pandas.read_json', 'pd.read_json', (['object_data'], {}), '(object_data)\n', (20657, 20670), True, 'import pandas as pd\n'), ((21546, 21559), 'pyLIMA.event.Event', 'event.Event', ([], {}), '()\n', (21557, 21559), False, 'from pyLIMA import event\n'), ((21775, 21805), 'numpy.unique', 'np.unique', (["pdf['i:fid'].values"], {}), "(pdf['i:fid'].values)\n", (21784, 21805), True, 'import numpy as np\n'), ((22566, 22614), 'pyLIMA.microlmodels.create_model', 'microlmodels.create_model', (['"""PSPL"""', 'current_event'], {}), "('PSPL', current_event)\n", (22591, 22614), False, 'from pyLIMA import microlmodels, microltoolbox\n'), ((22792, 22885), 'pyLIMA.microltoolbox.align_the_data_to_the_reference_telescope', 'microltoolbox.align_the_data_to_the_reference_telescope', (['results', '(0)', 'results.fit_results'], {}), '(results, 0, results\n .fit_results)\n', (22847, 22885), False, 'from pyLIMA import microlmodels, microltoolbox\n'), ((22906, 22962), 'pyLIMA.microloutputs.create_the_fake_telescopes', 'create_the_fake_telescopes', (['results', 'results.fit_results'], {}), '(results, results.fit_results)\n', (22932, 22962), False, 'from pyLIMA.microloutputs import create_the_fake_telescopes\n'), ((23230, 23273), 'pyLIMA.microltoolbox.flux_to_magnitude', 'microltoolbox.flux_to_magnitude', (['flux_model'], {}), '(flux_model)\n', (23261, 23273), False, 'from pyLIMA import microlmodels, microltoolbox\n'), ((20295, 20326), 'dash.dependencies.Output', 'Output', (['"""mulens_plot"""', '"""figure"""'], {}), "('mulens_plot', 'figure')\n", (20301, 20326), False, 'from dash.dependencies import Input, Output\n'), ((20336, 20371), 'dash.dependencies.Output', 'Output', (['"""mulens_params"""', '"""children"""'], {}), "('mulens_params', 'children')\n", (20342, 20371), False, 'from dash.dependencies import Input, Output\n'), ((20394, 20428), 'dash.dependencies.Input', 'Input', (['"""submit_mulens"""', '"""n_clicks"""'], {}), "('submit_mulens', 'n_clicks')\n", (20399, 20428), False, 'from dash.dependencies import Input, Output\n'), ((20438, 20470), 'dash.dependencies.Input', 'Input', (['"""object-data"""', '"""children"""'], {}), "('object-data', 'children')\n", (20443, 20470), False, 'from dash.dependencies import Input, Output\n'), ((14742, 14799), 'plotly.graph_objects.Heatmap', 'go.Heatmap', ([], {'z': 'data', 'showscale': '(False)', 'colorscale': '"""Greys_r"""'}), "(z=data, showscale=False, colorscale='Greys_r')\n", (14752, 14799), True, 'import plotly.graph_objects as go\n'), ((17884, 17914), 'numpy.unique', 'np.unique', (["pdf['i:fid'].values"], {}), "(pdf['i:fid'].values)\n", (17893, 17914), True, 'import numpy as np\n'), ((18943, 18973), 'numpy.unique', 'np.unique', (["pdf['i:fid'].values"], {}), "(pdf['i:fid'].values)\n", (18952, 18973), True, 'import numpy as np\n'), ((23293, 23323), 'numpy.unique', 'np.unique', (["pdf['i:fid'].values"], {}), "(pdf['i:fid'].values)\n", (23302, 23323), True, 'import numpy as np\n'), ((24088, 24118), 'numpy.unique', 'np.unique', (["pdf['i:fid'].values"], {}), "(pdf['i:fid'].values)\n", (24097, 24118), True, 'import numpy as np\n'), ((25470, 25501), 'numpy.sqrt', 'np.sqrt', (['results.fit_covariance'], {}), '(results.fit_covariance)\n', (25477, 25501), True, 'import numpy as np\n'), ((12445, 12470), 'astropy.time.Time', 'Time', (['time0'], {'format': '"""iso"""'}), "(time0, format='iso')\n", (12449, 12470), False, 'from astropy.time import Time\n'), ((12497, 12517), 'numpy.where', 'np.where', (['(jds == jd0)'], {}), '(jds == jd0)\n', (12505, 12517), True, 'import numpy as np\n'), ((12584, 12603), 'app.client.repository', 'client.repository', ([], {}), '()\n', (12601, 12603), False, 'from app import client, app\n'), ((16541, 16554), 'apps.utils.dc_mag', 'dc_mag', (['*args'], {}), '(*args)\n', (16547, 16554), False, 'from apps.utils import apparent_flux, dc_mag\n'), ((21054, 21067), 'apps.utils.dc_mag', 'dc_mag', (['*args'], {}), '(*args)\n', (21060, 21067), False, 'from apps.utils import apparent_flux, dc_mag\n'), ((6146, 6159), 'apps.utils.dc_mag', 'dc_mag', (['*args'], {}), '(*args)\n', (6152, 6159), False, 'from apps.utils import apparent_flux, dc_mag\n'), ((12399, 12413), 'numpy.round', 'np.round', (['x', '(3)'], {}), '(x, 3)\n', (12407, 12413), True, 'import numpy as np\n'), ((22037, 22144), 'numpy.transpose', 'np.transpose', (["[pdf['i:jd'].values[mask], pdf['i:magpsf'].values[mask], pdf['i:sigmapsf'].\n values[mask]]"], {}), "([pdf['i:jd'].values[mask], pdf['i:magpsf'].values[mask], pdf[\n 'i:sigmapsf'].values[mask]])\n", (22049, 22144), True, 'import numpy as np\n'), ((23374, 23397), 'apps.utils.convert_jd', 'convert_jd', (['t'], {'to': '"""iso"""'}), "(t, to='iso')\n", (23384, 23397), False, 'from apps.utils import convert_jd, readstamp, _data_stretch, convolve\n'), ((23811, 23834), 'apps.utils.convert_jd', 'convert_jd', (['t'], {'to': '"""iso"""'}), "(t, to='iso')\n", (23821, 23834), False, 'from apps.utils import convert_jd, readstamp, _data_stretch, convolve\n'), ((24169, 24192), 'apps.utils.convert_jd', 'convert_jd', (['t'], {'to': '"""iso"""'}), "(t, to='iso')\n", (24179, 24192), False, 'from apps.utils import convert_jd, readstamp, _data_stretch, convolve\n'), ((24606, 24629), 'apps.utils.convert_jd', 'convert_jd', (['t'], {'to': '"""iso"""'}), "(t, to='iso')\n", (24616, 24629), False, 'from apps.utils import convert_jd, readstamp, _data_stretch, convolve\n'), ((6838, 6858), 'apps.utils.apparent_flux', 'apparent_flux', (['*args'], {}), '(*args)\n', (6851, 6858), False, 'from apps.utils import apparent_flux, dc_mag\n'), ((14545, 14560), 'numpy.median', 'np.median', (['data'], {}), '(data)\n', (14554, 14560), True, 'import numpy as np\n')]
from matplotlib import pyplot,gridspec,colors,patches import numpy import os from diatom import Calculate import warnings from scipy import constants h = constants.h cwd = os.path.dirname(os.path.abspath(__file__)) def make_segments(x, y): ''' segment x and y points Create list of line segments from x and y coordinates, in the correct format for LineCollection: an array of the form numlines x (points per line) x 2 (x and y) array Args: x,y (numpy.ndarray -like ) - points on lines Returns: segments (numpy.ndarray) - array of numlines by points per line by 2 ''' points = numpy.array([x, y]).T.reshape(-1, 1, 2) segments = numpy.concatenate([points[:-1], points[1:]], axis=1) return segments def colorline(x, y, z=None, cmap=pyplot.get_cmap('copper'), norm=pyplot.Normalize(0.0, 1.0), linewidth=3, alpha=1.0, legend=False,ax=None): '''Plot a line shaded by an extra value. Plot a colored line with coordinates x and y Optionally specify colors in the array z Optionally specify a colormap, a norm function and a line width Args: x,y (list-like): x and y coordinates to plot kwargs: z (list): Optional third parameter to colour lines by cmap (matplotlib.cmap): colour mapping for z norm (): Normalisation function for mapping z values to colours linewidth (float): width of plotted lines (default =3) alpha (float): value of alpha channel (default = 1) legend (Bool): display a legend (default = False) ax (matplotlib.pyplot.axes): axis object to plot on Returns: lc (Collection) - collection of lines ''' if ax == None: ax = pyplot.gca() # Default colors equally spaced on [0,1]: if z is None: z = numpy.linspace(0.0, 1.0, len(x)) # Special case if a single number: if not hasattr(z, "__iter__"): # to check for numerical input -- this is a hack z = numpy.array([z]) z = numpy.asarray(z) segments = make_segments(x, y) lc = LineCollection(segments, array=z, cmap=cmap, norm=norm, linewidth=linewidth,zorder=1.25) ax.add_collection(lc) return lc def TDM_plot(energies,States,gs,Nmax,I1,I2,TDMs=None, pm = +1, Offset=0,fig=pyplot.gcf(), log=False,minf=None,maxf=None,prefactor=1e-3,col=None): ''' Create a TDM plot this function plots a series of energy levels and their transition dipole moments from a given ground state. In this version a lot of the plotting style is fixed. Args: energies (numpy.ndarray) - array of energy levels states (numpy.ndarray) - array of states corresponding to energies such that E[i] -> States[:,i] gs (int) - index for ground state of interest Nmax (int) - maximum rotational quantum number to include I1, I2 (float) - nuclear spins of nuclei 1 and 2 Kwargs: TDMs (list of numpy.ndarray) - optional precomputed transition dipole moments in [sigma-,pi,sigma+] order pm (float) - flag for if the transition increases or decreases N (default = 1) Offset (float) - yaxis offset (default = 0) fig (matplotlib.pyplot.figure) - figure object to draw on log (bool) - use logarithmic scaling for TDM plots minf (float) - minimum frequency to show maxf (float) - maximum frequency to show prefactor (float) - scaling factor for all energies col (list) - list of colours for lines (must be at least length 3 ) ''' gray ='xkcd:grey' if col == None: green ='xkcd:darkgreen' red ='xkcd:maroon' blue ='xkcd:azure' col=[red,blue,green] if TDMs == None and (Nmax == None or I1 == None or I2 == None): raise RuntimeError("TDMs or Quantum numbers must be supplied") elif (Nmax == None or I1 == None or I2 == None): TDMs = numpy.array(TDMs) dm = TDMs[0,:] dz = TDMs[1,:] dp = TDMs[2,:] elif TDMs == None: dm = numpy.round(Calculate.TDM(Nmax,I1,I2,+1,States,gs),6) dz = numpy.round(Calculate.TDM(Nmax,I1,I2,0,States,gs),6) dp = numpy.round(Calculate.TDM(Nmax,I1,I2,-1,States,gs),6) if abs(pm)>1: pm = int(pm/abs(pm)) widths = numpy.zeros(4)+1 widths[-1] = 1.4 fig.set_figheight(8) fig.set_figwidth(6) grid= gridspec.GridSpec(2,4,width_ratios=widths) N,MN = Calculate.LabelStates_N_MN(States,Nmax,I1,I2) #find the ground state that the user has put in N0 = N[gs] gs_E = energies[gs] lim =10 l1 = numpy.where(N==N0)[0] min_gs = prefactor*numpy.amin(energies[l1]-gs_E)/h max_gs = prefactor*numpy.amax(energies[l1]-gs_E)/h l2 = numpy.where(N==N0+pm)[0] if minf ==None: emin = numpy.amin(energies[l2]) minf = 10e4 f = prefactor*(emin-gs_E)/h - Offset minf = min([minf,f]) if maxf ==None: emax = numpy.amax(energies[l2]) maxf = 0 f = prefactor*(emax-gs_E)/h - Offset maxf = max([maxf,f]) if pm == 1: ax0 = fig.add_subplot(grid[1,:-1]) ax = [] for j in range(3): if j ==0: ax.append(fig.add_subplot(grid[0,j],zorder=1)) else: ax.append(fig.add_subplot(grid[0,j],sharey=ax[0],zorder=1)) elif pm == -1: ax0 = fig.add_subplot(grid[0,:-1]) ax = [] for j in range(3): if j ==0: ax.append(fig.add_subplot(grid[1,j],zorder=1)) else: ax.append(fig.add_subplot(grid[1,j],sharey=ax[0],zorder=1)) #plotting the energy levels for ground state for l in l1: f =prefactor*(energies[l]-gs_E)/h #- Offset if l ==gs: ax0.plot([-lim,lim],[f,f],color='k',zorder=1.2) else: ax0.plot([-lim,lim],[f,f],color=gray,zorder=0.8) lbl = ['$\sigma_-$',"$\pi$","$\sigma_+$"] for j,axis in enumerate(ax): #plotting for excited state for l in l2: f = prefactor*(energies[l]-gs_E)/h - Offset if dz[l]!=0 and j==1: axis.plot([-lim,lim],[f,f],color=blue,zorder=1.2) elif dp[l] !=0 and j ==2: axis.plot([-lim,lim],[f,f],color=green,zorder=1.2) elif dm[l] !=0 and j ==0: axis.plot([-lim,lim],[f,f],color=red,zorder=1.2) else: axis.plot([-lim,lim],[f,f],color=gray,zorder=0.8) if j ==0 : axis.tick_params(labelbottom=False,bottom=False,which='both') else: axis.tick_params(labelleft=False,left=False,labelbottom=False, bottom=False,which='both') axis.set_xlim(-lim,lim) axis.set_title(lbl[j],color=col[j]) # set the ticks so that only the left most has a frequency/energy axis # and none have an x axis ax0.tick_params(labelbottom=False,bottom=False,which='both') ax0.set_xlim(-lim,lim) #add the bar plot axis ax_bar = fig.add_subplot(grid[0,-1],sharey = ax[0]) ax_bar.tick_params(labelleft=False,left=False, which='both') #fix the ROI to be 300 kHz around the state the user has chosen ax0.set_ylim(min_gs,max_gs) f = prefactor*(energies-gs_E)/h-Offset #normalise function, returns a number between 0 and 1 Norm = colors.LogNorm(vmin=1e-3,vmax=1,clip=True) #how thick should a line be? max_width = 2 #setting where and how far apart the lines should all be in data coords ax1 = ax[0] ax2 = ax[1] ax3 = ax[2] disp = ax2.transData.transform((-lim,0)) x1a = ax0.transData.inverted().transform(disp)[0] disp = ax2.transData.transform((lim,0)) x1b = ax0.transData.inverted().transform(disp)[0] Nz = len(numpy.where(dz!=0)[0]) iz = 0 deltax = (x1b-x1a)/(Nz+1) x0 = x1a+deltax disp = ax3.transData.transform((-lim,0)) y1a = ax0.transData.inverted().transform(disp)[0] disp = ax3.transData.transform((lim,0)) y1b = ax0.transData.inverted().transform(disp)[0] Np = len(numpy.where(dp!=0)[0]) ip =0 deltay = (y1b-y1a)/(Np+1) y0 = y1a+deltay disp = ax1.transData.transform((-lim,0)) z1a = ax0.transData.inverted().transform(disp)[0] disp = ax1.transData.transform((lim,0)) z1b = ax0.transData.inverted().transform(disp)[0] Nm = len(numpy.where(dm!=0)[0]) im = 0 deltaz = (z1b-z1a)/(Nm+1) z0 = z1a+deltaz for j,d in enumerate(dz): #this block of code plots the dipole moments (or transition strengths) if abs(d)>0: width = max_width*Norm(3*numpy.abs(d)**2) x = x0 +iz*deltax # makes sure that the line is perfectly vertical in display coords disp = ax0.transData.transform((x,0)) x2 = ax2.transData.inverted().transform(disp)[0] p = patches.ConnectionPatch((x,0),(x2,f[j]),coordsA='data',coordsB='data', axesA=ax0,axesB=ax2,zorder=5,color='k', lw=width) #line object ax2.add_artist(p) # add line to axes iz+=1 #bar plot for transition strengths. Relative to spin-stretched TDM ax_bar.barh(f[j],numpy.abs(d),color=blue,height=5) d=dp[j] if abs(d)>0: width = max_width*Norm(3*numpy.abs(d)**2) y= y0 +ip*deltay # makes sure that the line is perfectly vertical in display coords disp = ax0.transData.transform((y,0)) y2 = ax3.transData.inverted().transform(disp)[0] p = patches.ConnectionPatch((y,0),(y2,f[j]),coordsA='data',coordsB='data', axesA=ax0,axesB=ax3,zorder=5,color='k', lw=width) #line object ax3.add_artist(p) ip+=1 #bar plot for transition strengths. Relative to spin-stretched TDM ax_bar.barh(f[j],numpy.abs(d),color=green,height=5) d=dm[j] if abs(d)>0: width = max_width*Norm(3*numpy.abs(d)**2) z = z0 +im*deltaz # makes sure that the line is perfectly vertical in display coords disp = ax0.transData.transform((z,0)) z2 = ax1.transData.inverted().transform(disp)[0] p = patches.ConnectionPatch((z,0),(z2,f[j]),coordsA='data',coordsB='data', axesA=ax0,axesB=ax1,zorder=5,color='k', lw=width)#line object ax1.add_artist(p) im +=1 #bar plot for transition strengths. Relative to spin-stretched TDM ax_bar.barh(f[j],numpy.abs(d),color=red,height = 5) #setup log axes for axis 4 (bar plots) if log: ax_bar.set_xscale('log') ax_bar.set_xticks([1e-6,1e-3,1]) ax_bar.set_xticks([1e-5,1e-4,1e-2,1e-1],minor=True) ax_bar.set_xticklabels(["10$^{-6}$","10$^{-3}$","1"]) ax_bar.set_xticklabels(["","","",""],minor=True) # now to rescale the other axes so that they have the same y scale ax1.set_ylim(minf-20,maxf+20) grid.set_height_ratios([(maxf-minf)+40,300]) pyplot.subplots_adjust(hspace=0.1) grid.update() #add some axis labels ax0.set_ylabel("Energy/$h$ (kHz)") if Offset != 0: ax[0].set_ylabel("Energy/$h$ (kHz) - {:.1f} MHz".format(Offset)) else: ax[0].set_ylabel("Energy/$h$ (Hz)") ax_bar.set_xlabel("TDM ($d_0$)") if __name__ == '__main__': from diatom import Hamiltonian,Calculate H0,Hz,HDC,HAC = Hamiltonian.Build_Hamiltonians(3,Hamiltonian.RbCs,zeeman=True) eigvals,eigstate = numpy.linalg.eigh(H0+181.5e-4*Hz) TDM_plot(eigvals,eigstate,1, Nmax = 3,I1 = Hamiltonian.RbCs['I1'], I2 = Hamiltonian.RbCs['I2'], Offset=980e3,prefactor=1e-3) fig = pyplot.figure(2) loc = 0 TDM_pi = Calculate.TDM(3,Hamiltonian.RbCs['I1'],Hamiltonian.RbCs['I2'],0,eigstate,loc) TDM_Sigma_plus = Calculate.TDM(3,Hamiltonian.RbCs['I1'],Hamiltonian.RbCs['I2'],-1,eigstate,loc) TDM_Sigma_minus = Calculate.TDM(3,Hamiltonian.RbCs['I1'],Hamiltonian.RbCs['I2'],+1,eigstate,loc) TDMs =[TDM_Sigma_minus,TDM_pi,TDM_Sigma_plus] TDM_plot(eigvals,eigstate,loc,3,Hamiltonian.RbCs['I1'],Hamiltonian.RbCs['I2'],Offset=980e3,fig=fig) pyplot.show()
[ "numpy.array", "diatom.Hamiltonian.Build_Hamiltonians", "matplotlib.colors.LogNorm", "diatom.Calculate.LabelStates_N_MN", "numpy.where", "matplotlib.pyplot.Normalize", "numpy.asarray", "diatom.Calculate.TDM", "matplotlib.gridspec.GridSpec", "numpy.concatenate", "matplotlib.patches.ConnectionPatc...
[((190, 215), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (205, 215), False, 'import os\n'), ((685, 737), 'numpy.concatenate', 'numpy.concatenate', (['[points[:-1], points[1:]]'], {'axis': '(1)'}), '([points[:-1], points[1:]], axis=1)\n', (702, 737), False, 'import numpy\n'), ((793, 818), 'matplotlib.pyplot.get_cmap', 'pyplot.get_cmap', (['"""copper"""'], {}), "('copper')\n", (808, 818), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((841, 867), 'matplotlib.pyplot.Normalize', 'pyplot.Normalize', (['(0.0)', '(1.0)'], {}), '(0.0, 1.0)\n', (857, 867), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((2041, 2057), 'numpy.asarray', 'numpy.asarray', (['z'], {}), '(z)\n', (2054, 2057), False, 'import numpy\n'), ((2359, 2371), 'matplotlib.pyplot.gcf', 'pyplot.gcf', ([], {}), '()\n', (2369, 2371), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((4470, 4514), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(2)', '(4)'], {'width_ratios': 'widths'}), '(2, 4, width_ratios=widths)\n', (4487, 4514), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((4525, 4573), 'diatom.Calculate.LabelStates_N_MN', 'Calculate.LabelStates_N_MN', (['States', 'Nmax', 'I1', 'I2'], {}), '(States, Nmax, I1, I2)\n', (4551, 4573), False, 'from diatom import Hamiltonian, Calculate\n'), ((7460, 7505), 'matplotlib.colors.LogNorm', 'colors.LogNorm', ([], {'vmin': '(0.001)', 'vmax': '(1)', 'clip': '(True)'}), '(vmin=0.001, vmax=1, clip=True)\n', (7474, 7505), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((11381, 11415), 'matplotlib.pyplot.subplots_adjust', 'pyplot.subplots_adjust', ([], {'hspace': '(0.1)'}), '(hspace=0.1)\n', (11403, 11415), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((11781, 11845), 'diatom.Hamiltonian.Build_Hamiltonians', 'Hamiltonian.Build_Hamiltonians', (['(3)', 'Hamiltonian.RbCs'], {'zeeman': '(True)'}), '(3, Hamiltonian.RbCs, zeeman=True)\n', (11811, 11845), False, 'from diatom import Hamiltonian, Calculate\n'), ((11868, 11904), 'numpy.linalg.eigh', 'numpy.linalg.eigh', (['(H0 + 0.01815 * Hz)'], {}), '(H0 + 0.01815 * Hz)\n', (11885, 11904), False, 'import numpy\n'), ((12051, 12067), 'matplotlib.pyplot.figure', 'pyplot.figure', (['(2)'], {}), '(2)\n', (12064, 12067), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((12094, 12180), 'diatom.Calculate.TDM', 'Calculate.TDM', (['(3)', "Hamiltonian.RbCs['I1']", "Hamiltonian.RbCs['I2']", '(0)', 'eigstate', 'loc'], {}), "(3, Hamiltonian.RbCs['I1'], Hamiltonian.RbCs['I2'], 0,\n eigstate, loc)\n", (12107, 12180), False, 'from diatom import Hamiltonian, Calculate\n'), ((12193, 12280), 'diatom.Calculate.TDM', 'Calculate.TDM', (['(3)', "Hamiltonian.RbCs['I1']", "Hamiltonian.RbCs['I2']", '(-1)', 'eigstate', 'loc'], {}), "(3, Hamiltonian.RbCs['I1'], Hamiltonian.RbCs['I2'], -1,\n eigstate, loc)\n", (12206, 12280), False, 'from diatom import Hamiltonian, Calculate\n'), ((12294, 12381), 'diatom.Calculate.TDM', 'Calculate.TDM', (['(3)', "Hamiltonian.RbCs['I1']", "Hamiltonian.RbCs['I2']", '(+1)', 'eigstate', 'loc'], {}), "(3, Hamiltonian.RbCs['I1'], Hamiltonian.RbCs['I2'], +1,\n eigstate, loc)\n", (12307, 12381), False, 'from diatom import Hamiltonian, Calculate\n'), ((12535, 12548), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (12546, 12548), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((1755, 1767), 'matplotlib.pyplot.gca', 'pyplot.gca', ([], {}), '()\n', (1765, 1767), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((2015, 2031), 'numpy.array', 'numpy.array', (['[z]'], {}), '([z])\n', (2026, 2031), False, 'import numpy\n'), ((4371, 4385), 'numpy.zeros', 'numpy.zeros', (['(4)'], {}), '(4)\n', (4382, 4385), False, 'import numpy\n'), ((4686, 4706), 'numpy.where', 'numpy.where', (['(N == N0)'], {}), '(N == N0)\n', (4697, 4706), False, 'import numpy\n'), ((4829, 4854), 'numpy.where', 'numpy.where', (['(N == N0 + pm)'], {}), '(N == N0 + pm)\n', (4840, 4854), False, 'import numpy\n'), ((4892, 4916), 'numpy.amin', 'numpy.amin', (['energies[l2]'], {}), '(energies[l2])\n', (4902, 4916), False, 'import numpy\n'), ((5049, 5073), 'numpy.amax', 'numpy.amax', (['energies[l2]'], {}), '(energies[l2])\n', (5059, 5073), False, 'import numpy\n'), ((3999, 4016), 'numpy.array', 'numpy.array', (['TDMs'], {}), '(TDMs)\n', (4010, 4016), False, 'import numpy\n'), ((4732, 4763), 'numpy.amin', 'numpy.amin', (['(energies[l1] - gs_E)'], {}), '(energies[l1] - gs_E)\n', (4742, 4763), False, 'import numpy\n'), ((4787, 4818), 'numpy.amax', 'numpy.amax', (['(energies[l1] - gs_E)'], {}), '(energies[l1] - gs_E)\n', (4797, 4818), False, 'import numpy\n'), ((7893, 7913), 'numpy.where', 'numpy.where', (['(dz != 0)'], {}), '(dz != 0)\n', (7904, 7913), False, 'import numpy\n'), ((8191, 8211), 'numpy.where', 'numpy.where', (['(dp != 0)'], {}), '(dp != 0)\n', (8202, 8211), False, 'import numpy\n'), ((8488, 8508), 'numpy.where', 'numpy.where', (['(dm != 0)'], {}), '(dm != 0)\n', (8499, 8508), False, 'import numpy\n'), ((8995, 9127), 'matplotlib.patches.ConnectionPatch', 'patches.ConnectionPatch', (['(x, 0)', '(x2, f[j])'], {'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax0', 'axesB': 'ax2', 'zorder': '(5)', 'color': '"""k"""', 'lw': 'width'}), "((x, 0), (x2, f[j]), coordsA='data', coordsB='data',\n axesA=ax0, axesB=ax2, zorder=5, color='k', lw=width)\n", (9018, 9127), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((9755, 9887), 'matplotlib.patches.ConnectionPatch', 'patches.ConnectionPatch', (['(y, 0)', '(y2, f[j])'], {'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax0', 'axesB': 'ax3', 'zorder': '(5)', 'color': '"""k"""', 'lw': 'width'}), "((y, 0), (y2, f[j]), coordsA='data', coordsB='data',\n axesA=ax0, axesB=ax3, zorder=5, color='k', lw=width)\n", (9778, 9887), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((10498, 10630), 'matplotlib.patches.ConnectionPatch', 'patches.ConnectionPatch', (['(z, 0)', '(z2, f[j])'], {'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax0', 'axesB': 'ax1', 'zorder': '(5)', 'color': '"""k"""', 'lw': 'width'}), "((z, 0), (z2, f[j]), coordsA='data', coordsB='data',\n axesA=ax0, axesB=ax1, zorder=5, color='k', lw=width)\n", (10521, 10630), False, 'from matplotlib import pyplot, gridspec, colors, patches\n'), ((630, 649), 'numpy.array', 'numpy.array', (['[x, y]'], {}), '([x, y])\n', (641, 649), False, 'import numpy\n'), ((9392, 9404), 'numpy.abs', 'numpy.abs', (['d'], {}), '(d)\n', (9401, 9404), False, 'import numpy\n'), ((10133, 10145), 'numpy.abs', 'numpy.abs', (['d'], {}), '(d)\n', (10142, 10145), False, 'import numpy\n'), ((10876, 10888), 'numpy.abs', 'numpy.abs', (['d'], {}), '(d)\n', (10885, 10888), False, 'import numpy\n'), ((4134, 4177), 'diatom.Calculate.TDM', 'Calculate.TDM', (['Nmax', 'I1', 'I2', '(+1)', 'States', 'gs'], {}), '(Nmax, I1, I2, +1, States, gs)\n', (4147, 4177), False, 'from diatom import Hamiltonian, Calculate\n'), ((4201, 4243), 'diatom.Calculate.TDM', 'Calculate.TDM', (['Nmax', 'I1', 'I2', '(0)', 'States', 'gs'], {}), '(Nmax, I1, I2, 0, States, gs)\n', (4214, 4243), False, 'from diatom import Hamiltonian, Calculate\n'), ((4267, 4310), 'diatom.Calculate.TDM', 'Calculate.TDM', (['Nmax', 'I1', 'I2', '(-1)', 'States', 'gs'], {}), '(Nmax, I1, I2, -1, States, gs)\n', (4280, 4310), False, 'from diatom import Hamiltonian, Calculate\n'), ((8741, 8753), 'numpy.abs', 'numpy.abs', (['d'], {}), '(d)\n', (8750, 8753), False, 'import numpy\n'), ((9501, 9513), 'numpy.abs', 'numpy.abs', (['d'], {}), '(d)\n', (9510, 9513), False, 'import numpy\n'), ((10243, 10255), 'numpy.abs', 'numpy.abs', (['d'], {}), '(d)\n', (10252, 10255), False, 'import numpy\n')]
"""@file cluster_toolkit.py Modeling using cluster_toolkit """ # Functions to model halo profiles import numpy as np import cluster_toolkit as ct from . import func_layer from . func_layer import * from .parent_class import CLMModeling from .. utils import _patch_rho_crit_to_cd2018 from .. cosmology.cluster_toolkit import AstroPyCosmology Cosmology = AstroPyCosmology __all__ = ['CTModeling', 'Modeling', 'Cosmology']+func_layer.__all__ def _assert_correct_type_ct(arg): """ Convert the argument to a type compatible with cluster_toolkit cluster_toolkit does not handle correctly scalar arguments that are not float or numpy array and others that contain non-float64 elements. It only convert lists to the correct type. To circumvent this we pre-convert all arguments going to cluster_toolkit to the appropriated types. Parameters ---------- arg : array_like or scalar Returns ------- scale_factor : array_like Scale factor """ if np.isscalar(arg): return float(arg) return np.array(arg).astype(np.float64, order='C', copy=False) class CTModeling(CLMModeling): r"""Object with functions for halo mass modeling Attributes ---------- backend: str Name of the backend being used massdef : str Profile mass definition (`mean`, `critical`, `virial` - letter case independent) delta_mdef : int Mass overdensity definition. halo_profile_model : str Profile model parameterization (`nfw`, `einasto`, `hernquist` - letter case independent) cosmo: Cosmology Cosmology object hdpm: Object Backend object with halo profiles mdef_dict: dict Dictionary with the definitions for mass hdpm_dict: dict Dictionary with the definitions for profile """ # pylint: disable=too-many-instance-attributes def __init__(self, massdef='mean', delta_mdef=200, halo_profile_model='nfw', validate_input=True): CLMModeling.__init__(self, validate_input) # Update class attributes self.backend = 'ct' self.mdef_dict = {'mean': 'mean'} self.hdpm_dict = {'nfw': 'nfw'} self.cosmo_class = AstroPyCosmology # Attributes exclusive to this class self.cor_factor = _patch_rho_crit_to_cd2018(2.77533742639e+11) # Set halo profile and cosmology self.set_halo_density_profile(halo_profile_model, massdef, delta_mdef) self.set_cosmo(None) def _set_halo_density_profile(self, halo_profile_model='nfw', massdef='mean', delta_mdef=200): """"set halo density profile""" # Update values self.halo_profile_model = halo_profile_model self.massdef = massdef self.delta_mdef = delta_mdef def _set_concentration(self, cdelta): """" set concentration""" self.cdelta = cdelta def _set_mass(self, mdelta): """" set mass""" self.mdelta = mdelta def _eval_3d_density(self, r3d, z_cl): """"eval 3d density""" h = self.cosmo['h'] Omega_m = self.cosmo.get_E2Omega_m(z_cl)*self.cor_factor return ct.density.rho_nfw_at_r( _assert_correct_type_ct(r3d)*h, self.mdelta*h, self.cdelta, Omega_m, delta=self.delta_mdef)*h**2 def _eval_surface_density(self, r_proj, z_cl): """"eval surface density""" h = self.cosmo['h'] Omega_m = self.cosmo.get_E2Omega_m(z_cl)*self.cor_factor return ct.deltasigma.Sigma_nfw_at_R( _assert_correct_type_ct(r_proj)*h, self.mdelta*h, self.cdelta, Omega_m, delta=self.delta_mdef)*h*1.0e12 # pc**-2 to Mpc**-2 def _eval_mean_surface_density(self, r_proj, z_cl): r''' Computes the mean value of surface density inside radius r_proj Parameters ---------- r_proj : array_like Projected radial position from the cluster center in :math:`M\!pc`. z_cl: float Redshift of the cluster Returns ------- array_like, float Excess surface density in units of :math:`M_\odot\ Mpc^{-2}`. Note ---- This function just adds eval_surface_density+eval_excess_surface_density ''' return (self.eval_surface_density(r_proj, z_cl) +self.eval_excess_surface_density(r_proj, z_cl)) def _eval_excess_surface_density(self, r_proj, z_cl): """"eval excess surface density""" if np.min(r_proj) < 1.e-11: raise ValueError( f"Rmin = {np.min(r_proj):.2e} Mpc!" " This value is too small and may cause computational issues.") Omega_m = self.cosmo.get_E2Omega_m(z_cl)*self.cor_factor h = self.cosmo['h'] r_proj = _assert_correct_type_ct(r_proj)*h # Computing sigma on a larger range than the radial range requested, # with at least 1000 points. sigma_r_proj = np.logspace(np.log10(np.min( r_proj))-1, np.log10(np.max(r_proj))+1, np.max([1000, 10*np.array(r_proj).size])) sigma = self.eval_surface_density( sigma_r_proj/h, z_cl)/(h*1e12) # rm norm for ct # ^ Note: Let's not use this naming convention when transfering ct to ccl.... return ct.deltasigma.DeltaSigma_at_R( r_proj, sigma_r_proj, sigma, self.mdelta*h, self.cdelta, Omega_m, delta=self.delta_mdef)*h*1.0e12 # pc**-2 to Mpc**-2 Modeling = CTModeling
[ "numpy.isscalar", "numpy.max", "numpy.array", "numpy.min", "cluster_toolkit.deltasigma.DeltaSigma_at_R" ]
[((1007, 1023), 'numpy.isscalar', 'np.isscalar', (['arg'], {}), '(arg)\n', (1018, 1023), True, 'import numpy as np\n'), ((1062, 1075), 'numpy.array', 'np.array', (['arg'], {}), '(arg)\n', (1070, 1075), True, 'import numpy as np\n'), ((4519, 4533), 'numpy.min', 'np.min', (['r_proj'], {}), '(r_proj)\n', (4525, 4533), True, 'import numpy as np\n'), ((5315, 5439), 'cluster_toolkit.deltasigma.DeltaSigma_at_R', 'ct.deltasigma.DeltaSigma_at_R', (['r_proj', 'sigma_r_proj', 'sigma', '(self.mdelta * h)', 'self.cdelta', 'Omega_m'], {'delta': 'self.delta_mdef'}), '(r_proj, sigma_r_proj, sigma, self.mdelta * h,\n self.cdelta, Omega_m, delta=self.delta_mdef)\n', (5344, 5439), True, 'import cluster_toolkit as ct\n'), ((5008, 5022), 'numpy.min', 'np.min', (['r_proj'], {}), '(r_proj)\n', (5014, 5022), True, 'import numpy as np\n'), ((5049, 5063), 'numpy.max', 'np.max', (['r_proj'], {}), '(r_proj)\n', (5055, 5063), True, 'import numpy as np\n'), ((4600, 4614), 'numpy.min', 'np.min', (['r_proj'], {}), '(r_proj)\n', (4606, 4614), True, 'import numpy as np\n'), ((5085, 5101), 'numpy.array', 'np.array', (['r_proj'], {}), '(r_proj)\n', (5093, 5101), True, 'import numpy as np\n')]
# modulo Ex_Kalman_Filter.py # filtro di kalman esteso import numpy as np import sistema as s def kalman( x, P, misure): x_pred = s.A @ x.T #X(k+1|k) p_new = s.A @ P @ s.A.T + s.F @ s.Q @ s.F.T #P(k+1|k) C = s.clineare(x_pred[0], x_pred[3], x_pred[6]) PCT = p_new@C.T K = PCT @ np.linalg.inv(C@PCT+s.R) #K(k+1) x_pred = x_pred + K@(misure.T - s.cnonlineare(x_pred[0], x_pred[3], x_pred[6]).T)#X(k+1) p_new = (np.eye(9) - K@C)@ p_new#p(k+1) return x_pred, p_new
[ "sistema.clineare", "numpy.eye", "numpy.linalg.inv", "sistema.cnonlineare" ]
[((224, 267), 'sistema.clineare', 's.clineare', (['x_pred[0]', 'x_pred[3]', 'x_pred[6]'], {}), '(x_pred[0], x_pred[3], x_pred[6])\n', (234, 267), True, 'import sistema as s\n'), ((304, 332), 'numpy.linalg.inv', 'np.linalg.inv', (['(C @ PCT + s.R)'], {}), '(C @ PCT + s.R)\n', (317, 332), True, 'import numpy as np\n'), ((443, 452), 'numpy.eye', 'np.eye', (['(9)'], {}), '(9)\n', (449, 452), True, 'import numpy as np\n'), ((373, 419), 'sistema.cnonlineare', 's.cnonlineare', (['x_pred[0]', 'x_pred[3]', 'x_pred[6]'], {}), '(x_pred[0], x_pred[3], x_pred[6])\n', (386, 419), True, 'import sistema as s\n')]
from hoomd import * from hoomd import hpmc import numpy as np import math import unittest import BlockAverage # Reference potential energy (U/N/eps) from MC simulations # https://mmlapps.nist.gov/srs/LJ_PURE/mc.htm # mean_Uref = -5.5121E+00; # sigma_Uref = 4.55E-04; # Interaction cut-off rcut = 3.0; # LJ length scale sigma = 1.0; # Tstar = 8.50E-01; # rho_star = 7.76E-01; # Diameter of particles diameter = sigma; # linear lattice dimension n = 8; class nvt_lj_sphere_energy(unittest.TestCase): def run_statepoint(self, Tstar, rho_star, mean_Uref, sigma_Uref, use_clusters, union): """ Tstar: Temperature (kT/eps) rho_star: Reduced density: rhostar = (N / V) * sigma**3 mean_Uref: reference energy sigma_Uref: standard deviation of the mean of reference energy """ context.initialize() eps = 1.0 / Tstar; # Particle volume V_p = math.pi/6.*diameter**3.; # lattice constant (sc) d_eff = (V_p*6/math.pi)**(1./3.); a = (d_eff**3.0/rho_star)**(1./3.); system = init.create_lattice(unitcell=lattice.sc(a=a), n=n); N = len(system.particles); mc = hpmc.integrate.sphere(d=0.3,seed=321); mc.shape_param.set('A',diameter=0) lennard_jones = """ float rsq = dot(r_ij, r_ij); float rcut = {}; if (rsq <= rcut*rcut) {{ float sigma = {}; float eps = {}; float sigmasq = sigma*sigma; float rsqinv = sigmasq / rsq; float r6inv = rsqinv*rsqinv*rsqinv; return 4.0f*eps*r6inv*(r6inv-1.0f); }} else {{ return 0.0f; }} """.format(rcut,sigma,eps); from hoomd import jit if not union: jit.patch.user(mc, r_cut=rcut, code=lennard_jones); else: u = jit.patch.user_union(mc,r_cut=rcut, code=lennard_jones) u.set_params('A', positions=[(0,0,0)],typeids=[0]) log = analyze.log(filename=None, quantities=['hpmc_overlap_count','hpmc_patch_energy'],period=100,overwrite=True); energy_val = []; def accumulate_energy(timestep): energy = log.query('hpmc_patch_energy') / float(N) / eps; # apply long range correction (used in reference data) energy += 8/9.0 * math.pi * rho_star * ((1/rcut)**9-3*(1/rcut)**3) energy_val.append(energy); if (timestep % 100 == 0): context.current.device.cpp_msg.notice(1,'energy = {:.5f}\n'.format(energy)); mc_tune = hpmc.util.tune(mc, tunables=['d','a'],max_val=[4,0.5],gamma=0.5,target=0.4); for i in range(5): run(100,quiet=True); d = mc.get_d(); translate_acceptance = mc.get_translate_acceptance(); print('d: {:3.2f} accept: {:3.2f}'.format(d,translate_acceptance)); mc_tune.update(); # Equilibrate run(500); if use_clusters: clusters = hpmc.update.clusters(mc, seed=99685) mc.set_params(d=0, a=0); # test cluster moves alone # Sample if use_clusters: run(5000,callback=accumulate_energy, callback_period=10) else: run(1000,callback=accumulate_energy, callback_period=10) block = BlockAverage.BlockAverage(energy_val) mean_U = np.mean(energy_val) i, sigma_U = block.get_error_estimate() context.current.device.cpp_msg.notice(1,'rho_star = {:.3f}\nU = {:.5f} +- {:.5f}\n'.format(rho_star,mean_U,sigma_U)) context.current.device.cpp_msg.notice(1,'Uref = {:.5f} +- {:.5f}\n'.format(mean_Uref,sigma_Uref)) # max error 0.5% self.assertLessEqual(sigma_U/mean_U,0.005) # 0.99 confidence interval ci = 2.576 # compare if 0 is within the confidence interval around the difference of the means sigma_diff = (sigma_U**2 + sigma_Uref**2)**(1/2.); self.assertLessEqual(math.fabs(mean_U - mean_Uref), ci*sigma_diff) def test_low_density_normal(self): self.run_statepoint(Tstar=8.50E-01, rho_star=5.00E-03, mean_Uref=-5.1901E-02, sigma_Uref=7.53E-05, use_clusters=False, union=False); self.run_statepoint(Tstar=8.50E-01, rho_star=7.00E-03, mean_Uref=-7.2834E-02, sigma_Uref=1.34E-04, use_clusters=False, union=False); self.run_statepoint(Tstar=8.50E-01, rho_star=9.00E-03, mean_Uref=-9.3973E-02, sigma_Uref=1.29E-04, use_clusters=False, union=False); def test_low_density_union(self): # test that the trivial union shape (a single point particle) also works self.run_statepoint(Tstar=8.50E-01, rho_star=5.00E-03, mean_Uref=-5.1901E-02, sigma_Uref=7.53E-05, use_clusters=False, union=True); self.run_statepoint(Tstar=8.50E-01, rho_star=7.00E-03, mean_Uref=-7.2834E-02, sigma_Uref=1.34E-04, use_clusters=False, union=True); self.run_statepoint(Tstar=8.50E-01, rho_star=9.00E-03, mean_Uref=-9.3973E-02, sigma_Uref=1.29E-04, use_clusters=False, union=True); def test_low_density_clusters(self): self.run_statepoint(Tstar=8.50E-01, rho_star=9.00E-03, mean_Uref=-9.3973E-02, sigma_Uref=1.29E-04, use_clusters=True, union=False); def test_moderate_density_normal(self): self.run_statepoint(Tstar=9.00E-01, rho_star=7.76E-01, mean_Uref=-5.4689E+00, sigma_Uref=4.20E-04, use_clusters=False, union=False); if __name__ == '__main__': unittest.main(argv = ['test.py', '-v'])
[ "numpy.mean", "hoomd.jit.patch.user", "BlockAverage.BlockAverage", "hoomd.hpmc.update.clusters", "hoomd.hpmc.integrate.sphere", "math.fabs", "unittest.main", "hoomd.hpmc.util.tune", "hoomd.jit.patch.user_union" ]
[((5953, 5990), 'unittest.main', 'unittest.main', ([], {'argv': "['test.py', '-v']"}), "(argv=['test.py', '-v'])\n", (5966, 5990), False, 'import unittest\n'), ((1195, 1233), 'hoomd.hpmc.integrate.sphere', 'hpmc.integrate.sphere', ([], {'d': '(0.3)', 'seed': '(321)'}), '(d=0.3, seed=321)\n', (1216, 1233), False, 'from hoomd import hpmc\n'), ((2863, 2948), 'hoomd.hpmc.util.tune', 'hpmc.util.tune', (['mc'], {'tunables': "['d', 'a']", 'max_val': '[4, 0.5]', 'gamma': '(0.5)', 'target': '(0.4)'}), "(mc, tunables=['d', 'a'], max_val=[4, 0.5], gamma=0.5, target=0.4\n )\n", (2877, 2948), False, 'from hoomd import hpmc\n'), ((3608, 3645), 'BlockAverage.BlockAverage', 'BlockAverage.BlockAverage', (['energy_val'], {}), '(energy_val)\n', (3633, 3645), False, 'import BlockAverage\n'), ((3663, 3682), 'numpy.mean', 'np.mean', (['energy_val'], {}), '(energy_val)\n', (3670, 3682), True, 'import numpy as np\n'), ((2082, 2132), 'hoomd.jit.patch.user', 'jit.patch.user', (['mc'], {'r_cut': 'rcut', 'code': 'lennard_jones'}), '(mc, r_cut=rcut, code=lennard_jones)\n', (2096, 2132), False, 'from hoomd import jit\n'), ((2164, 2220), 'hoomd.jit.patch.user_union', 'jit.patch.user_union', (['mc'], {'r_cut': 'rcut', 'code': 'lennard_jones'}), '(mc, r_cut=rcut, code=lennard_jones)\n', (2184, 2220), False, 'from hoomd import jit\n'), ((3295, 3331), 'hoomd.hpmc.update.clusters', 'hpmc.update.clusters', (['mc'], {'seed': '(99685)'}), '(mc, seed=99685)\n', (3315, 3331), False, 'from hoomd import hpmc\n'), ((4279, 4308), 'math.fabs', 'math.fabs', (['(mean_U - mean_Uref)'], {}), '(mean_U - mean_Uref)\n', (4288, 4308), False, 'import math\n')]
import logging import numpy as np import pytest import unittest from unittest.mock import Mock, MagicMock from ray.rllib.env.multi_agent_env import make_multi_agent from ray.rllib.examples.env.random_env import RandomEnv from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, \ check_multiagent_environments class TestGymCheckEnv(unittest.TestCase): @pytest.fixture(autouse=True) def inject_fixtures(self, caplog): caplog.set_level(logging.CRITICAL) def test_has_observation_and_action_space(self): env = Mock(spec=[]) with pytest.raises( AttributeError, match="Env must have observation_space."): check_gym_environments(env) env = Mock(spec=["observation_space"]) with pytest.raises( AttributeError, match="Env must have action_space."): check_gym_environments(env) def test_obs_and_action_spaces_are_gym_spaces(self): env = RandomEnv() observation_space = env.observation_space env.observation_space = "not a gym space" with pytest.raises( ValueError, match="Observation space must be a gym.space"): check_env(env) env.observation_space = observation_space env.action_space = "not an action space" with pytest.raises( ValueError, match="Action space must be a gym.space"): check_env(env) def test_sampled_observation_contained(self): env = RandomEnv() # check for observation that is out of bounds error = ".*A sampled observation from your env wasn't contained .*" env.observation_space.sample = MagicMock(return_value=5) with pytest.raises(ValueError, match=error): check_env(env) # check for observation that is in bounds, but the wrong type env.observation_space.sample = MagicMock(return_value=float(1)) with pytest.raises(ValueError, match=error): check_env(env) def test_sampled_action_contained(self): env = RandomEnv() error = ".*A sampled action from your env wasn't contained .*" env.action_space.sample = MagicMock(return_value=5) with pytest.raises(ValueError, match=error): check_env(env) # check for observation that is in bounds, but the wrong type env.action_space.sample = MagicMock(return_value=float(1)) with pytest.raises(ValueError, match=error): check_env(env) def test_reset(self): reset = MagicMock(return_value=5) env = RandomEnv() env.reset = reset # check reset with out of bounds fails error = ".*The observation collected from env.reset().*" with pytest.raises(ValueError, match=error): check_env(env) # check reset with obs of incorrect type fails reset = MagicMock(return_value=float(1)) env.reset = reset with pytest.raises(ValueError, match=error): check_env(env) def test_step(self): step = MagicMock(return_value=(5, 5, True, {})) env = RandomEnv() env.step = step error = ".*The observation collected from env.step.*" with pytest.raises(ValueError, match=error): check_env(env) # check reset that returns obs of incorrect type fails step = MagicMock(return_value=(float(1), 5, True, {})) env.step = step with pytest.raises(ValueError, match=error): check_env(env) # check step that returns reward of non float/int fails step = MagicMock(return_value=(1, "Not a valid reward", True, {})) env.step = step error = ("Your step function must return a reward that is integer or " "float.") with pytest.raises(AssertionError, match=error): check_env(env) # check step that returns a non bool fails step = MagicMock( return_value=(1, float(5), "not a valid done signal", {})) env.step = step error = "Your step function must return a done that is a boolean." with pytest.raises(AssertionError, match=error): check_env(env) # check step that returns a non dict fails step = MagicMock( return_value=(1, float(5), True, "not a valid env info")) env.step = step error = "Your step function must return a info that is a dict." with pytest.raises(AssertionError, match=error): check_env(env) class TestCheckMultiAgentEnv(unittest.TestCase): @pytest.fixture(autouse=True) def inject_fixtures(self, caplog): caplog.set_level(logging.CRITICAL) def test_check_env_not_correct_type_error(self): env = RandomEnv() with pytest.raises(ValueError, match="The passed env is not"): check_multiagent_environments(env) def test_check_env_reset_incorrect_error(self): reset = MagicMock(return_value=5) env = make_multi_agent("CartPole-v1")({"num_agents": 2}) env.reset = reset with pytest.raises(ValueError, match="The observation returned by "): check_env(env) def test_check_incorrect_space_contains_functions_error(self): def bad_contains_function(self, x): raise ValueError("This is a bad contains function") env = make_multi_agent("CartPole-v1")({"num_agents": 2}) bad_obs = { 0: np.array([np.inf, np.inf, np.inf, np.inf]), 1: np.array([np.inf, np.inf, np.inf, np.inf]) } env.reset = lambda *_: bad_obs with pytest.raises( ValueError, match="The observation collected from " "env"): check_env(env) env.observation_space_contains = bad_contains_function with pytest.raises( ValueError, match="Your observation_space_contains " "function has some"): check_env(env) env = make_multi_agent("CartPole-v1")({"num_agents": 2}) bad_action = {0: 2, 1: 2} env.action_space_sample = lambda *_: bad_action with pytest.raises( ValueError, match="The action collected from " "action_space_sample"): check_env(env) env.action_space_contains = bad_contains_function with pytest.raises( ValueError, match="Your action_space_contains " "function has some error"): check_env(env) def test_check_env_step_incorrect_error(self): step = MagicMock(return_value=(5, 5, True, {})) env = make_multi_agent("CartPole-v1")({"num_agents": 2}) sampled_obs = env.reset() env.step = step with pytest.raises( ValueError, match="The observation returned by env"): check_env(env) step = MagicMock(return_value=(sampled_obs, "Not a reward", True, {})) env.step = step with pytest.raises( AssertionError, match="Your step function must " "return a reward "): check_env(env) step = MagicMock(return_value=(sampled_obs, 5, "Not a bool", {})) env.step = step with pytest.raises( AssertionError, match="Your step function must " "return a done"): check_env(env) step = MagicMock(return_value=(sampled_obs, 5, False, "Not a Dict")) env.step = step with pytest.raises( AssertionError, match="Your step function must " "return a info"): check_env(env) if __name__ == "__main__": pytest.main()
[ "ray.rllib.utils.pre_checks.env.check_multiagent_environments", "unittest.mock.Mock", "ray.rllib.env.multi_agent_env.make_multi_agent", "unittest.mock.MagicMock", "pytest.main", "numpy.array", "pytest.raises", "pytest.fixture", "ray.rllib.examples.env.random_env.RandomEnv", "ray.rllib.utils.pre_ch...
[((385, 413), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (399, 413), False, 'import pytest\n'), ((4618, 4646), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (4632, 4646), False, 'import pytest\n'), ((7775, 7788), 'pytest.main', 'pytest.main', ([], {}), '()\n', (7786, 7788), False, 'import pytest\n'), ((564, 577), 'unittest.mock.Mock', 'Mock', ([], {'spec': '[]'}), '(spec=[])\n', (568, 577), False, 'from unittest.mock import Mock, MagicMock\n'), ((735, 767), 'unittest.mock.Mock', 'Mock', ([], {'spec': "['observation_space']"}), "(spec=['observation_space'])\n", (739, 767), False, 'from unittest.mock import Mock, MagicMock\n'), ((978, 989), 'ray.rllib.examples.env.random_env.RandomEnv', 'RandomEnv', ([], {}), '()\n', (987, 989), False, 'from ray.rllib.examples.env.random_env import RandomEnv\n'), ((1511, 1522), 'ray.rllib.examples.env.random_env.RandomEnv', 'RandomEnv', ([], {}), '()\n', (1520, 1522), False, 'from ray.rllib.examples.env.random_env import RandomEnv\n'), ((1692, 1717), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '(5)'}), '(return_value=5)\n', (1701, 1717), False, 'from unittest.mock import Mock, MagicMock\n'), ((2080, 2091), 'ray.rllib.examples.env.random_env.RandomEnv', 'RandomEnv', ([], {}), '()\n', (2089, 2091), False, 'from ray.rllib.examples.env.random_env import RandomEnv\n'), ((2197, 2222), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '(5)'}), '(return_value=5)\n', (2206, 2222), False, 'from unittest.mock import Mock, MagicMock\n'), ((2563, 2588), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '(5)'}), '(return_value=5)\n', (2572, 2588), False, 'from unittest.mock import Mock, MagicMock\n'), ((2603, 2614), 'ray.rllib.examples.env.random_env.RandomEnv', 'RandomEnv', ([], {}), '()\n', (2612, 2614), False, 'from ray.rllib.examples.env.random_env import RandomEnv\n'), ((3084, 3124), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '(5, 5, True, {})'}), '(return_value=(5, 5, True, {}))\n', (3093, 3124), False, 'from unittest.mock import Mock, MagicMock\n'), ((3139, 3150), 'ray.rllib.examples.env.random_env.RandomEnv', 'RandomEnv', ([], {}), '()\n', (3148, 3150), False, 'from ray.rllib.examples.env.random_env import RandomEnv\n'), ((3628, 3687), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': "(1, 'Not a valid reward', True, {})"}), "(return_value=(1, 'Not a valid reward', True, {}))\n", (3637, 3687), False, 'from unittest.mock import Mock, MagicMock\n'), ((4797, 4808), 'ray.rllib.examples.env.random_env.RandomEnv', 'RandomEnv', ([], {}), '()\n', (4806, 4808), False, 'from ray.rllib.examples.env.random_env import RandomEnv\n'), ((4996, 5021), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '(5)'}), '(return_value=5)\n', (5005, 5021), False, 'from unittest.mock import Mock, MagicMock\n'), ((6668, 6708), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '(5, 5, True, {})'}), '(return_value=(5, 5, True, {}))\n', (6677, 6708), False, 'from unittest.mock import Mock, MagicMock\n'), ((6973, 7036), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': "(sampled_obs, 'Not a reward', True, {})"}), "(return_value=(sampled_obs, 'Not a reward', True, {}))\n", (6982, 7036), False, 'from unittest.mock import Mock, MagicMock\n'), ((7249, 7307), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': "(sampled_obs, 5, 'Not a bool', {})"}), "(return_value=(sampled_obs, 5, 'Not a bool', {}))\n", (7258, 7307), False, 'from unittest.mock import Mock, MagicMock\n'), ((7502, 7563), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': "(sampled_obs, 5, False, 'Not a Dict')"}), "(return_value=(sampled_obs, 5, False, 'Not a Dict'))\n", (7511, 7563), False, 'from unittest.mock import Mock, MagicMock\n'), ((591, 662), 'pytest.raises', 'pytest.raises', (['AttributeError'], {'match': '"""Env must have observation_space."""'}), "(AttributeError, match='Env must have observation_space.')\n", (604, 662), False, 'import pytest\n'), ((693, 720), 'ray.rllib.utils.pre_checks.env.check_gym_environments', 'check_gym_environments', (['env'], {}), '(env)\n', (715, 720), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((781, 847), 'pytest.raises', 'pytest.raises', (['AttributeError'], {'match': '"""Env must have action_space."""'}), "(AttributeError, match='Env must have action_space.')\n", (794, 847), False, 'import pytest\n'), ((878, 905), 'ray.rllib.utils.pre_checks.env.check_gym_environments', 'check_gym_environments', (['env'], {}), '(env)\n', (900, 905), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((1103, 1175), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Observation space must be a gym.space"""'}), "(ValueError, match='Observation space must be a gym.space')\n", (1116, 1175), False, 'import pytest\n'), ((1206, 1220), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (1215, 1220), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((1333, 1400), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Action space must be a gym.space"""'}), "(ValueError, match='Action space must be a gym.space')\n", (1346, 1400), False, 'import pytest\n'), ((1431, 1445), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (1440, 1445), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((1731, 1769), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'error'}), '(ValueError, match=error)\n', (1744, 1769), False, 'import pytest\n'), ((1783, 1797), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (1792, 1797), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((1953, 1991), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'error'}), '(ValueError, match=error)\n', (1966, 1991), False, 'import pytest\n'), ((2005, 2019), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (2014, 2019), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((2236, 2274), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'error'}), '(ValueError, match=error)\n', (2249, 2274), False, 'import pytest\n'), ((2288, 2302), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (2297, 2302), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((2453, 2491), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'error'}), '(ValueError, match=error)\n', (2466, 2491), False, 'import pytest\n'), ((2505, 2519), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (2514, 2519), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((2766, 2804), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'error'}), '(ValueError, match=error)\n', (2779, 2804), False, 'import pytest\n'), ((2818, 2832), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (2827, 2832), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((2976, 3014), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'error'}), '(ValueError, match=error)\n', (2989, 3014), False, 'import pytest\n'), ((3028, 3042), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (3037, 3042), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((3250, 3288), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'error'}), '(ValueError, match=error)\n', (3263, 3288), False, 'import pytest\n'), ((3302, 3316), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (3311, 3316), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((3481, 3519), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'error'}), '(ValueError, match=error)\n', (3494, 3519), False, 'import pytest\n'), ((3533, 3547), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (3542, 3547), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((3831, 3873), 'pytest.raises', 'pytest.raises', (['AssertionError'], {'match': 'error'}), '(AssertionError, match=error)\n', (3844, 3873), False, 'import pytest\n'), ((3887, 3901), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (3896, 3901), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((4163, 4205), 'pytest.raises', 'pytest.raises', (['AssertionError'], {'match': 'error'}), '(AssertionError, match=error)\n', (4176, 4205), False, 'import pytest\n'), ((4219, 4233), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (4228, 4233), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((4491, 4533), 'pytest.raises', 'pytest.raises', (['AssertionError'], {'match': 'error'}), '(AssertionError, match=error)\n', (4504, 4533), False, 'import pytest\n'), ((4547, 4561), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (4556, 4561), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((4822, 4878), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""The passed env is not"""'}), "(ValueError, match='The passed env is not')\n", (4835, 4878), False, 'import pytest\n'), ((4892, 4926), 'ray.rllib.utils.pre_checks.env.check_multiagent_environments', 'check_multiagent_environments', (['env'], {}), '(env)\n', (4921, 4926), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((5036, 5067), 'ray.rllib.env.multi_agent_env.make_multi_agent', 'make_multi_agent', (['"""CartPole-v1"""'], {}), "('CartPole-v1')\n", (5052, 5067), False, 'from ray.rllib.env.multi_agent_env import make_multi_agent\n'), ((5126, 5189), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""The observation returned by """'}), "(ValueError, match='The observation returned by ')\n", (5139, 5189), False, 'import pytest\n'), ((5203, 5217), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (5212, 5217), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((5409, 5440), 'ray.rllib.env.multi_agent_env.make_multi_agent', 'make_multi_agent', (['"""CartPole-v1"""'], {}), "('CartPole-v1')\n", (5425, 5440), False, 'from ray.rllib.env.multi_agent_env import make_multi_agent\n'), ((5495, 5537), 'numpy.array', 'np.array', (['[np.inf, np.inf, np.inf, np.inf]'], {}), '([np.inf, np.inf, np.inf, np.inf])\n', (5503, 5537), True, 'import numpy as np\n'), ((5554, 5596), 'numpy.array', 'np.array', (['[np.inf, np.inf, np.inf, np.inf]'], {}), '([np.inf, np.inf, np.inf, np.inf])\n', (5562, 5596), True, 'import numpy as np\n'), ((5659, 5728), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""The observation collected from env"""'}), "(ValueError, match='The observation collected from env')\n", (5672, 5728), False, 'import pytest\n'), ((5778, 5792), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (5787, 5792), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((5869, 5958), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Your observation_space_contains function has some"""'}), "(ValueError, match=\n 'Your observation_space_contains function has some')\n", (5882, 5958), False, 'import pytest\n'), ((6019, 6033), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (6028, 6033), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((6048, 6079), 'ray.rllib.env.multi_agent_env.make_multi_agent', 'make_multi_agent', (['"""CartPole-v1"""'], {}), "('CartPole-v1')\n", (6064, 6079), False, 'from ray.rllib.env.multi_agent_env import make_multi_agent\n'), ((6202, 6287), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""The action collected from action_space_sample"""'}), "(ValueError, match='The action collected from action_space_sample'\n )\n", (6215, 6287), False, 'import pytest\n'), ((6348, 6362), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (6357, 6362), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((6435, 6525), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Your action_space_contains function has some error"""'}), "(ValueError, match=\n 'Your action_space_contains function has some error')\n", (6448, 6525), False, 'import pytest\n'), ((6586, 6600), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (6595, 6600), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((6723, 6754), 'ray.rllib.env.multi_agent_env.make_multi_agent', 'make_multi_agent', (['"""CartPole-v1"""'], {}), "('CartPole-v1')\n", (6739, 6754), False, 'from ray.rllib.env.multi_agent_env import make_multi_agent\n'), ((6845, 6911), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""The observation returned by env"""'}), "(ValueError, match='The observation returned by env')\n", (6858, 6911), False, 'import pytest\n'), ((6942, 6956), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (6951, 6956), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((7074, 7153), 'pytest.raises', 'pytest.raises', (['AssertionError'], {'match': '"""Your step function must return a reward """'}), "(AssertionError, match='Your step function must return a reward ')\n", (7087, 7153), False, 'import pytest\n'), ((7219, 7233), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (7228, 7233), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((7345, 7421), 'pytest.raises', 'pytest.raises', (['AssertionError'], {'match': '"""Your step function must return a done"""'}), "(AssertionError, match='Your step function must return a done')\n", (7358, 7421), False, 'import pytest\n'), ((7471, 7485), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (7480, 7485), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n'), ((7601, 7677), 'pytest.raises', 'pytest.raises', (['AssertionError'], {'match': '"""Your step function must return a info"""'}), "(AssertionError, match='Your step function must return a info')\n", (7614, 7677), False, 'import pytest\n'), ((7727, 7741), 'ray.rllib.utils.pre_checks.env.check_env', 'check_env', (['env'], {}), '(env)\n', (7736, 7741), False, 'from ray.rllib.utils.pre_checks.env import check_env, check_gym_environments, check_multiagent_environments\n')]
from __future__ import absolute_import from __future__ import print_function from __future__ import division import pickle import sys, os, glob import pdb import json import argparse import numpy as np import open3d as o3d sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal') sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal/source') import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init import torch.optim as optim from torch.optim import lr_scheduler from torch.autograd import Variable import smplx from human_body_prior.tools.model_loader import load_vposer import chamfer_pytorch.dist_chamfer as ext from cvae import BodyParamParser, GeometryTransformer from sklearn.cluster import KMeans def fitting(fittingconfig): input_data_file = fittingconfig['input_data_file'] with open(input_data_file, 'rb') as f: body_param_input = pickle.load(f) xh, _, _= BodyParamParser.body_params_parse_fitting(body_param_input) return xh.detach().cpu().numpy() if __name__=='__main__': gen_path = sys.argv[1] if 'proxe' in gen_path: scene_test_list = ['MPH16', 'MPH1Library','N0SittingBooth', 'N3OpenArea'] elif 'habitat' in gen_path: scene_test_list = ['17DRP5sb8fy-bedroom', '17DRP5sb8fy-familyroomlounge', '17DRP5sb8fy-livingroom', 'sKLMLpTHeUy-familyname_0_1', 'X7HyMhZNoso-livingroom_0_16', 'zsNo4HB9uLZ-bedroom0_0', 'zsNo4HB9uLZ-livingroom0_13'] xh_list = [] for scenename in scene_test_list: for ii in range(5000): input_data_file = os.path.join(gen_path,scenename+'/body_gen_{:06d}.pkl'.format(ii)) if not os.path.exists(input_data_file): continue fittingconfig={ 'input_data_file': input_data_file, 'scene_verts_path': '/home/yzhang/Videos/PROXE/scenes_downsampled/'+scenename+'.ply', 'scene_sdf_path': '/home/yzhang/Videos/PROXE/scenes_sdf/'+scenename, 'human_model_path': '/home/yzhang/body_models/VPoser', 'vposer_ckpt_path': '/home/yzhang/body_models/VPoser/vposer_v1_0', 'init_lr_h': 0.1, 'num_iter': 50, 'batch_size': 1, 'device': torch.device("cuda" if torch.cuda.is_available() else "cpu"), 'contact_id_folder': '/is/cluster/work/yzhang/PROX/body_segments', 'contact_part': ['back','butt','L_Hand','R_Hand','L_Leg','R_Leg','thighs'], 'verbose': False } xh = fitting(fittingconfig) xh_list.append(xh) ar = np.concatenate(xh_list, axis=0) ## k-means import scipy.cluster codes, dist = scipy.cluster.vq.kmeans(ar, 20) vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences from scipy.stats import entropy ee = entropy(counts) print('entropy:' + str(ee)) print('mean distance:' + str(np.mean(dist)) )
[ "os.path.exists", "numpy.mean", "scipy.stats.entropy", "pickle.load", "torch.cuda.is_available", "numpy.concatenate", "cvae.BodyParamParser.body_params_parse_fitting", "sys.path.append" ]
[((225, 292), 'sys.path.append', 'sys.path.append', (['"""/home/yzhang/workspaces/smpl-env-gen-3d-internal"""'], {}), "('/home/yzhang/workspaces/smpl-env-gen-3d-internal')\n", (240, 292), False, 'import sys, os, glob\n'), ((293, 367), 'sys.path.append', 'sys.path.append', (['"""/home/yzhang/workspaces/smpl-env-gen-3d-internal/source"""'], {}), "('/home/yzhang/workspaces/smpl-env-gen-3d-internal/source')\n", (308, 367), False, 'import sys, os, glob\n'), ((964, 1023), 'cvae.BodyParamParser.body_params_parse_fitting', 'BodyParamParser.body_params_parse_fitting', (['body_param_input'], {}), '(body_param_input)\n', (1005, 1023), False, 'from cvae import BodyParamParser, GeometryTransformer\n'), ((2728, 2759), 'numpy.concatenate', 'np.concatenate', (['xh_list'], {'axis': '(0)'}), '(xh_list, axis=0)\n', (2742, 2759), True, 'import numpy as np\n'), ((3048, 3063), 'scipy.stats.entropy', 'entropy', (['counts'], {}), '(counts)\n', (3055, 3063), False, 'from scipy.stats import entropy\n'), ((934, 948), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (945, 948), False, 'import pickle\n'), ((1755, 1786), 'os.path.exists', 'os.path.exists', (['input_data_file'], {}), '(input_data_file)\n', (1769, 1786), False, 'import sys, os, glob\n'), ((3129, 3142), 'numpy.mean', 'np.mean', (['dist'], {}), '(dist)\n', (3136, 3142), True, 'import numpy as np\n'), ((2384, 2409), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2407, 2409), False, 'import torch\n')]
# # Copyright 2012 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # from copperhead import * import numpy as np import unittest from create_tests import create_tests from recursive_equal import recursive_equal @cu def test_repl(x, n): return replicate(x, n) @cu def test_internal_tuple_repl(x, n): return replicate((x, x), n) @cu def test_internal_named_tuple_repl(x, n): a = x, x return replicate(a, n) class ReplicateTest(unittest.TestCase): def setUp(self): self.val = 3 self.size = 5 self.golden = [self.val] * self.size def run_test(self, target, x, n): with target: self.assertEqual(list(test_repl(x, n)), self.golden) @create_tests(*runtime.backends) def testRepl(self, target): self.run_test(target, np.int32(self.val), self.size) def testReplTuple(self): self.assertTrue(recursive_equal(test_repl((1,1), 2), [(1,1),(1,1)])) def testReplNestedTuple(self): a = test_repl(((1,2),3),2) self.assertTrue(recursive_equal( a, [((1,2),3),((1,2),3)])) def testReplInternalTuple(self): self.assertTrue(recursive_equal(test_internal_tuple_repl(1, 2), [(1, 1), (1, 1)])) def testReplInternalNamedTuple(self): self.assertTrue(recursive_equal(test_internal_named_tuple_repl(1, 2), [(1, 1), (1, 1)])) if __name__ == "__main__": unittest.main()
[ "unittest.main", "recursive_equal.recursive_equal", "numpy.int32", "create_tests.create_tests" ]
[((1254, 1285), 'create_tests.create_tests', 'create_tests', (['*runtime.backends'], {}), '(*runtime.backends)\n', (1266, 1285), False, 'from create_tests import create_tests\n'), ((2067, 2082), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2080, 2082), False, 'import unittest\n'), ((1348, 1366), 'numpy.int32', 'np.int32', (['self.val'], {}), '(self.val)\n', (1356, 1366), True, 'import numpy as np\n'), ((1581, 1627), 'recursive_equal.recursive_equal', 'recursive_equal', (['a', '[((1, 2), 3), ((1, 2), 3)]'], {}), '(a, [((1, 2), 3), ((1, 2), 3)])\n', (1596, 1627), False, 'from recursive_equal import recursive_equal\n')]
import paddle.fluid.dataloader as data import paddle from PIL import Image import os import os.path import numpy as np import random from numpy.random import randint from opts import parser args = parser.parse_args() class VideoRecord(object): def __init__(self, row): self._data = row @property def path(self): return self._data[0] @property def num_frames(self): return int(self._data[1]) @property def label(self): return int(self._data[2]) class TSNDataSet(object): def __init__(self, root_path, list_file, num_segments=3, new_length=1, modality='RGB', image_tmpl='img_{:05d}.jpg', transform=None, force_grayscale=False, random_shift=True, test_mode=False): self.root_path = root_path self.list_file = list_file self.num_segments = num_segments self.new_length = new_length self.modality = modality self.image_tmpl = image_tmpl self.transform = transform self.random_shift = random_shift self.test_mode = test_mode self.batch_size=args.batch_size if self.modality == 'RGBDiff': self.new_length += 1# Diff needs one more image to calculate diff self._parse_list() def _load_image(self, directory, idx): if self.modality == 'RGB' or self.modality == 'RGBDiff': return [Image.open(os.path.join(directory, self.image_tmpl.format(idx))).convert('RGB')] elif self.modality == 'Flow': x_img = Image.open(os.path.join(directory, self.image_tmpl.format('x', idx))).convert('L') y_img = Image.open(os.path.join(directory, self.image_tmpl.format('y', idx))).convert('L') return [x_img, y_img] def _parse_list(self): self.video_list = [VideoRecord(x.strip().split(' ')) for x in open(self.list_file)] def _sample_indices(self, record): """ :param record: VideoRecord :return: list """ average_duration = (record.num_frames - self.new_length + 1) // self.num_segments if average_duration > 0: offsets = np.multiply(list(range(self.num_segments)), average_duration) + randint(average_duration, size=self.num_segments) elif record.num_frames > self.num_segments: offsets = np.sort(randint(record.num_frames - self.new_length + 1, size=self.num_segments)) else: offsets = np.zeros((self.num_segments,)) return offsets + 1 def _get_val_indices(self, record): #print(record.num_frames > self.num_segments + self.new_length - 1) if record.num_frames > self.num_segments + self.new_length - 1: tick = (record.num_frames - self.new_length + 1) / float(self.num_segments) offsets = np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segments)]) else: offsets = np.zeros((self.num_segments,)) #print(offsets) #print(offsets+1) return offsets + 1 def _get_test_indices(self, record): tick = (record.num_frames - self.new_length + 1) / float(self.num_segments) offsets = np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segments)]) return offsets + 1 def __getitem__(self,index): batch = 0 imgs=[] labels=[] i=index*self.batch_size if self.random_shift: random.shuffle(self.video_list) while i < (len(self.video_list)): record = self.video_list[i] if not self.test_mode: segment_indices = self._sample_indices(record) if self.random_shift else self._get_val_indices(record) else: segment_indices = self._get_test_indices(record) img, label = self.get(record, segment_indices) img=np.array(img).astype('float32') label=np.array(label).astype('int64') imgs.append(img) labels.append(label) batch += 1 i+=1 if batch == self.batch_size: bimgs=np.array(imgs).reshape(-1,3,224,224) blabels=np.array(labels).reshape(-1,1) break if batch == self.batch_size: return bimgs,blabels def get(self, record, indices): images = list() for seg_ind in indices: p = int(seg_ind) for i in range(self.new_length): seg_imgs = self._load_image(record.path, p) images.extend(seg_imgs) if p < record.num_frames: p += 1 process_data = self.transform(images) return process_data, record.label def __len__(self): return len(self.video_list) if __name__ == '__main__': from transforms import * from models import * import paddle.fluid as fluid fset = TSNDataSet("", 'data/ucf101_rgb_train_t.txt', num_segments=24, new_length=1, modality='RGB', random_shift=False, test_mode=False, image_tmpl='img_'+'{:05d}.jpg' if args.modality in ["RGB", "RGBDiff"] else 'img_'+'{:05d}.jpg', transform=Compose([ GroupScale(int(224)), Stack(roll=True), ToTorchFormatTensor(div=False), IdentityTransform(), ])) def batch_generator_creator(): def __reader__(): batch =0 img=[] batch_data=[] label=[] for i in range(len(fset)): record = fset.video_list[i] if not fset.test_mode: segment_indices = fset._sample_indices(record) if fset.random_shift else fset._get_val_indices(record) else: segment_indices = fset._get_test_indices(record) print(record.path) img, label = fset.get(record, segment_indices) img=np.array(img).astype('float32') label=np.array(label).astype('int64') batch_data.append([img,label]) batch += 1 if batch == fset.batch_size: yield batch_data batch =0 img=[] batch_data=[] label=[] return __reader__ place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace() with fluid.dygraph.guard(place): t_loader= fluid.io.DataLoader.from_generator(capacity=10,return_list=True, iterable=True, drop_last=True) t_loader.set_sample_list_generator(batch_generator_creator(), places=place) #i=0 batch=len(fset)//fset.batch_size for i in range (batch): print(i) img,lab =fset.__getitem__(i) img = np.array(img).astype('float32').reshape(-1,3,224,224) lab = np.array(lab).astype('int64').reshape(-1,1) #print('\n 8888888888888888888888888') if i==1: break i=0 for image, label in t_loader(): print(i) i+=1 image=paddle.fluid.layers.reshape(image, shape=[-1,3,224,224]) label=paddle.fluid.layers.reshape(label, shape=[-1,1]) #print(i,image.shape,img.shape,label,lab) if i==2: break
[ "random.shuffle", "paddle.fluid.dygraph.guard", "paddle.fluid.io.DataLoader.from_generator", "paddle.fluid.CPUPlace", "opts.parser.parse_args", "numpy.array", "numpy.zeros", "numpy.random.randint", "paddle.fluid.CUDAPlace", "paddle.fluid.layers.reshape" ]
[((198, 217), 'opts.parser.parse_args', 'parser.parse_args', ([], {}), '()\n', (215, 217), False, 'from opts import parser\n'), ((6692, 6710), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (6707, 6710), True, 'import paddle.fluid as fluid\n'), ((6732, 6748), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (6746, 6748), True, 'import paddle.fluid as fluid\n'), ((6758, 6784), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', (['place'], {}), '(place)\n', (6777, 6784), True, 'import paddle.fluid as fluid\n'), ((6804, 6905), 'paddle.fluid.io.DataLoader.from_generator', 'fluid.io.DataLoader.from_generator', ([], {'capacity': '(10)', 'return_list': '(True)', 'iterable': '(True)', 'drop_last': '(True)'}), '(capacity=10, return_list=True, iterable=\n True, drop_last=True)\n', (6838, 6905), True, 'import paddle.fluid as fluid\n'), ((2958, 2988), 'numpy.zeros', 'np.zeros', (['(self.num_segments,)'], {}), '((self.num_segments,))\n', (2966, 2988), True, 'import numpy as np\n'), ((3478, 3509), 'random.shuffle', 'random.shuffle', (['self.video_list'], {}), '(self.video_list)\n', (3492, 3509), False, 'import random\n'), ((7489, 7548), 'paddle.fluid.layers.reshape', 'paddle.fluid.layers.reshape', (['image'], {'shape': '[-1, 3, 224, 224]'}), '(image, shape=[-1, 3, 224, 224])\n', (7516, 7548), False, 'import paddle\n'), ((7564, 7613), 'paddle.fluid.layers.reshape', 'paddle.fluid.layers.reshape', (['label'], {'shape': '[-1, 1]'}), '(label, shape=[-1, 1])\n', (7591, 7613), False, 'import paddle\n'), ((2249, 2298), 'numpy.random.randint', 'randint', (['average_duration'], {'size': 'self.num_segments'}), '(average_duration, size=self.num_segments)\n', (2256, 2298), False, 'from numpy.random import randint\n'), ((2491, 2521), 'numpy.zeros', 'np.zeros', (['(self.num_segments,)'], {}), '((self.num_segments,))\n', (2499, 2521), True, 'import numpy as np\n'), ((2381, 2453), 'numpy.random.randint', 'randint', (['(record.num_frames - self.new_length + 1)'], {'size': 'self.num_segments'}), '(record.num_frames - self.new_length + 1, size=self.num_segments)\n', (2388, 2453), False, 'from numpy.random import randint\n'), ((3919, 3932), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (3927, 3932), True, 'import numpy as np\n'), ((3969, 3984), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (3977, 3984), True, 'import numpy as np\n'), ((4181, 4195), 'numpy.array', 'np.array', (['imgs'], {}), '(imgs)\n', (4189, 4195), True, 'import numpy as np\n'), ((4242, 4258), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (4250, 4258), True, 'import numpy as np\n'), ((6257, 6270), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (6265, 6270), True, 'import numpy as np\n'), ((6315, 6330), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (6323, 6330), True, 'import numpy as np\n'), ((7171, 7184), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (7179, 7184), True, 'import numpy as np\n'), ((7243, 7256), 'numpy.array', 'np.array', (['lab'], {}), '(lab)\n', (7251, 7256), True, 'import numpy as np\n')]
# This code performes a dimension reduction on the dataset, # Using a DenseNet121 pretrained model. import tensorflow as tf from scipy.io import loadmat, savemat import numpy as np # Load saved preprocessed images. FV = loadmat('images.mat') data = FV['data'] labels = FV['labels'] labels = labels.transpose() labels = labels.ravel() # Create the model. inputs = tf.keras.Input(shape=(224, 224, 3)) # Here different models were tested, # TODO : add all the models in parallel with the best model. model = tf.keras.applications.DenseNet121(include_top=False, weights='imagenet', input_shape=(224,224,3)) # Possibly try other models here. model_outputs = model(inputs) outputs = tf.keras.layers.GlobalAveragePooling2D(name='ga')(model_outputs) feature_extractor = tf.keras.models.Model(inputs=inputs, outputs=outputs) # Get features in a memory friendly way. X = [] samples = data.shape[0] for i in range(samples): X.append(feature_extractor(np.array([data[i]]))) X = np.array(X) # Replace old images with features. data = X.reshape(746, 1024) del X # Save the Exctracted Features. savemat('features.mat', {'data': data, 'labels': labels})
[ "tensorflow.keras.applications.DenseNet121", "scipy.io.savemat", "scipy.io.loadmat", "numpy.array", "tensorflow.keras.Input", "tensorflow.keras.models.Model", "tensorflow.keras.layers.GlobalAveragePooling2D" ]
[((222, 243), 'scipy.io.loadmat', 'loadmat', (['"""images.mat"""'], {}), "('images.mat')\n", (229, 243), False, 'from scipy.io import loadmat, savemat\n'), ((366, 401), 'tensorflow.keras.Input', 'tf.keras.Input', ([], {'shape': '(224, 224, 3)'}), '(shape=(224, 224, 3))\n', (380, 401), True, 'import tensorflow as tf\n'), ((509, 612), 'tensorflow.keras.applications.DenseNet121', 'tf.keras.applications.DenseNet121', ([], {'include_top': '(False)', 'weights': '"""imagenet"""', 'input_shape': '(224, 224, 3)'}), "(include_top=False, weights='imagenet',\n input_shape=(224, 224, 3))\n", (542, 612), True, 'import tensorflow as tf\n'), ((808, 861), 'tensorflow.keras.models.Model', 'tf.keras.models.Model', ([], {'inputs': 'inputs', 'outputs': 'outputs'}), '(inputs=inputs, outputs=outputs)\n', (829, 861), True, 'import tensorflow as tf\n'), ((1015, 1026), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (1023, 1026), True, 'import numpy as np\n'), ((1130, 1187), 'scipy.io.savemat', 'savemat', (['"""features.mat"""', "{'data': data, 'labels': labels}"], {}), "('features.mat', {'data': data, 'labels': labels})\n", (1137, 1187), False, 'from scipy.io import loadmat, savemat\n'), ((723, 772), 'tensorflow.keras.layers.GlobalAveragePooling2D', 'tf.keras.layers.GlobalAveragePooling2D', ([], {'name': '"""ga"""'}), "(name='ga')\n", (761, 772), True, 'import tensorflow as tf\n'), ((989, 1008), 'numpy.array', 'np.array', (['[data[i]]'], {}), '([data[i]])\n', (997, 1008), True, 'import numpy as np\n')]
#!/usr/bin/python from sympy import * from pylab import * import matplotlib.pyplot as plt import numpy as np # Load in data file data = np.loadtxt("data.txt") ga = data[:,0] exact = data[:,2] corrCCD = data[:,8] corr3 = data[:,6] corr4 = data[:,7] plt.axis([-1,1,-0.5,0.08]) plt.xlabel(r'Interaction strength, $g$', fontsize=16) plt.ylabel(r'Correlation energy', fontsize=16) exact = plt.plot(ga, exact,'b-*',linewidth = 2.0, label = 'Exact') mbpt3 = plt.plot(ga, corr3,'r:.', linewidth = 2.0, label = 'MBPT3') mbpt4 = plt.plot(ga, corr4,'g:.', linewidth = 2.0, label = 'MBPT4') ccd = plt.plot(ga, corrCCD, 'm:v',linewidth = 2.0, label = 'CCD') plt.legend() plt.savefig('CCDMBPT4theory.pdf', format='pdf') plt.show()
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.axis", "numpy.loadtxt", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((136, 158), 'numpy.loadtxt', 'np.loadtxt', (['"""data.txt"""'], {}), "('data.txt')\n", (146, 158), True, 'import numpy as np\n'), ((250, 279), 'matplotlib.pyplot.axis', 'plt.axis', (['[-1, 1, -0.5, 0.08]'], {}), '([-1, 1, -0.5, 0.08])\n', (258, 279), True, 'import matplotlib.pyplot as plt\n'), ((277, 329), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Interaction strength, $g$"""'], {'fontsize': '(16)'}), "('Interaction strength, $g$', fontsize=16)\n", (287, 329), True, 'import matplotlib.pyplot as plt\n'), ((331, 376), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Correlation energy"""'], {'fontsize': '(16)'}), "('Correlation energy', fontsize=16)\n", (341, 376), True, 'import matplotlib.pyplot as plt\n'), ((386, 442), 'matplotlib.pyplot.plot', 'plt.plot', (['ga', 'exact', '"""b-*"""'], {'linewidth': '(2.0)', 'label': '"""Exact"""'}), "(ga, exact, 'b-*', linewidth=2.0, label='Exact')\n", (394, 442), True, 'import matplotlib.pyplot as plt\n'), ((453, 509), 'matplotlib.pyplot.plot', 'plt.plot', (['ga', 'corr3', '"""r:."""'], {'linewidth': '(2.0)', 'label': '"""MBPT3"""'}), "(ga, corr3, 'r:.', linewidth=2.0, label='MBPT3')\n", (461, 509), True, 'import matplotlib.pyplot as plt\n'), ((521, 577), 'matplotlib.pyplot.plot', 'plt.plot', (['ga', 'corr4', '"""g:."""'], {'linewidth': '(2.0)', 'label': '"""MBPT4"""'}), "(ga, corr4, 'g:.', linewidth=2.0, label='MBPT4')\n", (529, 577), True, 'import matplotlib.pyplot as plt\n'), ((587, 643), 'matplotlib.pyplot.plot', 'plt.plot', (['ga', 'corrCCD', '"""m:v"""'], {'linewidth': '(2.0)', 'label': '"""CCD"""'}), "(ga, corrCCD, 'm:v', linewidth=2.0, label='CCD')\n", (595, 643), True, 'import matplotlib.pyplot as plt\n'), ((647, 659), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (657, 659), True, 'import matplotlib.pyplot as plt\n'), ((660, 707), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""CCDMBPT4theory.pdf"""'], {'format': '"""pdf"""'}), "('CCDMBPT4theory.pdf', format='pdf')\n", (671, 707), True, 'import matplotlib.pyplot as plt\n'), ((708, 718), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (716, 718), True, 'import matplotlib.pyplot as plt\n')]
import logging from typing import Callable, Dict, Mapping, Optional, Union import numpy as np from tqdm.auto import tqdm from meerkat.provenance import capture_provenance logger = logging.getLogger(__name__) class MappableMixin: def __init__(self, *args, **kwargs): super(MappableMixin, self).__init__(*args, **kwargs) @capture_provenance() def map( self, function: Optional[Callable] = None, with_indices: bool = False, is_batched_fn: bool = False, batch_size: Optional[int] = 1, drop_last_batch: bool = False, num_workers: Optional[int] = 0, output_type: Union[type, Dict[str, type]] = None, materialize: bool = True, pbar: bool = False, mmap: bool = False, mmap_path: str = None, flush_size: int = None, **kwargs, ): # TODO (sabri): add materialize? from meerkat.columns.abstract import AbstractColumn from meerkat.datapanel import DataPanel """Map a function over the elements of the column.""" # Return if `self` has no examples if not len(self): logger.info("Dataset empty, returning None.") return None if not is_batched_fn: # Convert to a batch function function = self._convert_to_batch_fn( function, with_indices=with_indices, materialize=materialize, **kwargs ) is_batched_fn = True logger.info(f"Converting `function` {function} to a batched function.") # Run the map logger.info("Running `map`, the dataset will be left unchanged.") for i, batch in tqdm( enumerate( self.batch( batch_size=batch_size, drop_last_batch=drop_last_batch, num_workers=num_workers, materialize=materialize # TODO: collate=batched was commented out in list_column ) ), total=(len(self) // batch_size) + int(not drop_last_batch and len(self) % batch_size != 0), disable=not pbar, ): # Calculate the start and end indexes for the batch start_index = i * batch_size end_index = min(len(self), (i + 1) * batch_size) # Use the first batch for setup if i == 0: # Get some information about the function function_properties = self._inspect_function( function, with_indices, is_batched_fn, batch, range(start_index, end_index), materialize=materialize, **kwargs, ) # Pull out information output = function_properties.output dtype = function_properties.output_dtype is_mapping = isinstance(output, Mapping) is_type_mapping = isinstance(output_type, Mapping) if not is_mapping and is_type_mapping: raise ValueError( "output_type is a mapping but function output is not a mapping" ) writers = {} for key, curr_output in ( output.items() if is_mapping else [("0", output)] ): curr_output_type = ( type(AbstractColumn.from_data(curr_output)) if output_type is None or (is_type_mapping and key not in output_type.keys()) else output_type[key] if is_type_mapping else output_type ) writer = curr_output_type.get_writer( mmap=mmap, template=( curr_output.copy() if isinstance(curr_output, AbstractColumn) else None ), ) # Setup for writing to a certain output column # TODO: support optionally memmapping only some columns if mmap: if not hasattr(curr_output, "shape"): curr_output = np.array(curr_output) # Assumes first dimension of output is the batch dimension. shape = (len(self), *curr_output.shape[1:]) # Construct the mmap file path if mmap_path is None: mmap_path = self.logdir / f"{hash(function)}" / key # Open the output writer writer.open(str(mmap_path), dtype, shape=shape) else: # Create an empty dict or list for the outputs writer.open() writers[key] = writer else: # Run `function` on the batch output = ( function( batch, range(i * batch_size, min(len(self), (i + 1) * batch_size)), **kwargs, ) if with_indices else function(batch, **kwargs) ) # Append the output if output is not None: if isinstance(output, Mapping): if set(output.keys()) != set(writers.keys()): raise ValueError( "Map function must return same keys for each batch." ) for k, writer in writers.items(): writer.write(output[k]) else: writers["0"].write(output) # intermittently flush if flush_size is not None and ((i + 1) % flush_size == 0): for writer in writers.values(): writer.flush() # Check if we are returning a special output type outputs = {key: writer.finalize() for key, writer in writers.items()} if not is_mapping: outputs = outputs["0"] else: # TODO (arjundd): This is duck type. We should probably make this # class signature explicit. outputs = ( self._clone(data=outputs) if isinstance(self, DataPanel) else DataPanel.from_batch(outputs) ) outputs._visible_columns = None return outputs
[ "logging.getLogger", "meerkat.datapanel.DataPanel.from_batch", "numpy.array", "meerkat.columns.abstract.AbstractColumn.from_data", "meerkat.provenance.capture_provenance" ]
[((183, 210), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (200, 210), False, 'import logging\n'), ((342, 362), 'meerkat.provenance.capture_provenance', 'capture_provenance', ([], {}), '()\n', (360, 362), False, 'from meerkat.provenance import capture_provenance\n'), ((6669, 6698), 'meerkat.datapanel.DataPanel.from_batch', 'DataPanel.from_batch', (['outputs'], {}), '(outputs)\n', (6689, 6698), False, 'from meerkat.datapanel import DataPanel\n'), ((3529, 3566), 'meerkat.columns.abstract.AbstractColumn.from_data', 'AbstractColumn.from_data', (['curr_output'], {}), '(curr_output)\n', (3553, 3566), False, 'from meerkat.columns.abstract import AbstractColumn\n'), ((4457, 4478), 'numpy.array', 'np.array', (['curr_output'], {}), '(curr_output)\n', (4465, 4478), True, 'import numpy as np\n')]
# test arena objects used in tracking. import os import unittest import matplotlib.pyplot as plt import motmot.FlyMovieFormat.FlyMovieFormat as FMF import numpy as np from context import trk_arena class TestArena(unittest.TestCase): """Tests common Arena functions.""" def setUp(self): """Opens a video for use in test-cases.""" self.video = FMF.FlyMovie('D:/test_data/test_01.fmf') def test_arena_init(self): """Assures we can initialize an arena using a test video.""" arena = trk_arena.CircularArena(self.video) self.assertEqual(arena.height, 480) self.assertEqual(arena.width, 640) self.assertEqual(arena.n_frames, 14399) def test_calculate_background(self): """Assures we can calculate a background image from an Arena.""" arena = trk_arena.CircularArena(self.video) arena.calculate_background() np.testing.assert_array_equal( arena.background_image.shape, (arena.height, arena.width)) class TestCircularArena(unittest.TestCase): """Tests CircularArena functions.""" def setUp(self): """Opens a video for use in test-cases.""" self.video = FMF.FlyMovie('D:/test_data/test_01.fmf') self.arena = trk_arena.CircularArena(self.video) self.arena.calculate_background() # set estimated arena center/radius self.arena.center = (self.arena.height / 2, self.arena.width / 2) self.arena.radius = (self.arena.height / 2) def test_draw_arena(self): """Makes sure that we can draw the outline of a CircularArena.""" img = self.arena.draw_arena(color=(255, 0, 0), thickness=2) fig, ax = plt.subplots() ax.imshow(img) fig.savefig('figures/test_draw_arena.png') def test_get_arena_mask(self): """Assures we can generate a mask image of a CircularArena.""" mask_img = self.arena.get_arena_mask() fig, ax = plt.subplots() ax.imshow(mask_img) fig.savefig('figures/test_arena_mask.png') np.testing.assert_array_equal( mask_img.shape, self.arena.background_image.shape) if __name__ == '__main__': unittest.main(verbosity=2)
[ "context.trk_arena.CircularArena", "unittest.main", "motmot.FlyMovieFormat.FlyMovieFormat.FlyMovie", "matplotlib.pyplot.subplots", "numpy.testing.assert_array_equal" ]
[((2201, 2227), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (2214, 2227), False, 'import unittest\n'), ((371, 411), 'motmot.FlyMovieFormat.FlyMovieFormat.FlyMovie', 'FMF.FlyMovie', (['"""D:/test_data/test_01.fmf"""'], {}), "('D:/test_data/test_01.fmf')\n", (383, 411), True, 'import motmot.FlyMovieFormat.FlyMovieFormat as FMF\n'), ((529, 564), 'context.trk_arena.CircularArena', 'trk_arena.CircularArena', (['self.video'], {}), '(self.video)\n', (552, 564), False, 'from context import trk_arena\n'), ((831, 866), 'context.trk_arena.CircularArena', 'trk_arena.CircularArena', (['self.video'], {}), '(self.video)\n', (854, 866), False, 'from context import trk_arena\n'), ((913, 1005), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['arena.background_image.shape', '(arena.height, arena.width)'], {}), '(arena.background_image.shape, (arena.height,\n arena.width))\n', (942, 1005), True, 'import numpy as np\n'), ((1195, 1235), 'motmot.FlyMovieFormat.FlyMovieFormat.FlyMovie', 'FMF.FlyMovie', (['"""D:/test_data/test_01.fmf"""'], {}), "('D:/test_data/test_01.fmf')\n", (1207, 1235), True, 'import motmot.FlyMovieFormat.FlyMovieFormat as FMF\n'), ((1257, 1292), 'context.trk_arena.CircularArena', 'trk_arena.CircularArena', (['self.video'], {}), '(self.video)\n', (1280, 1292), False, 'from context import trk_arena\n'), ((1698, 1712), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1710, 1712), True, 'import matplotlib.pyplot as plt\n'), ((1959, 1973), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1971, 1973), True, 'import matplotlib.pyplot as plt\n'), ((2062, 2147), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['mask_img.shape', 'self.arena.background_image.shape'], {}), '(mask_img.shape, self.arena.background_image.shape\n )\n', (2091, 2147), True, 'import numpy as np\n')]
""" Created on 07/05/2015 @author: user """ import numpy from optparse import OptionParser from prody.measure.measure import calcPsi, calcPhi, calcOmega from prody.proteins.pdbfile import parsePDB def get_dihedrals_for_conformation(conformation): """ Gets the dihedrals we need for the coarse grain model we are using (prolines count as only one unit). """ dihedral_angles = [] for residue in conformation.iterResidues(): if residue.getResname() != "PRO": try: dihedral_angles.append(calcPhi(residue, radian=True)) except ValueError: dihedral_angles.append(0) try: dihedral_angles.append(calcPsi(residue, radian=True)) except ValueError: dihedral_angles.append(0) return numpy.array(dihedral_angles[1:-1]) def get_omegas_for_conformation(conformation): """ Calculates all omega angles. """ omega_angles = [] for residue in conformation.iterResidues(): try: omega_angles.append((residue.getResname(),calcOmega(residue, radian=True))) except ValueError: omega_angles.append(("--",0)) return numpy.array(omega_angles) if __name__ == '__main__': parser = OptionParser() parser.add_option("-i", dest="input") parser.add_option("-o", dest="output") parser.add_option("-w", action= "store_true", dest="omega") (options, args) = parser.parse_args() pdb = parsePDB(options.input) if not options.omega: angles = get_dihedrals_for_conformation(pdb) numpy.savetxt(options.output, angles, delimiter = "\n") else: angles = get_omegas_for_conformation(pdb) open(options.output,"w").write("\n".join([str(omega) for omega in angles])) # #open = numpy.loadtxt("5XHK_helix.dih") #closed = numpy.loadtxt("9WVG_helix.dih") #numpy.savetxt("diff.dih", open-closed)
[ "prody.proteins.pdbfile.parsePDB", "prody.measure.measure.calcOmega", "prody.measure.measure.calcPhi", "optparse.OptionParser", "prody.measure.measure.calcPsi", "numpy.array", "numpy.savetxt" ]
[((806, 840), 'numpy.array', 'numpy.array', (['dihedral_angles[1:-1]'], {}), '(dihedral_angles[1:-1])\n', (817, 840), False, 'import numpy\n'), ((1189, 1214), 'numpy.array', 'numpy.array', (['omega_angles'], {}), '(omega_angles)\n', (1200, 1214), False, 'import numpy\n'), ((1256, 1270), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (1268, 1270), False, 'from optparse import OptionParser\n'), ((1477, 1500), 'prody.proteins.pdbfile.parsePDB', 'parsePDB', (['options.input'], {}), '(options.input)\n', (1485, 1500), False, 'from prody.proteins.pdbfile import parsePDB\n'), ((1593, 1646), 'numpy.savetxt', 'numpy.savetxt', (['options.output', 'angles'], {'delimiter': '"""\n"""'}), "(options.output, angles, delimiter='\\n')\n", (1606, 1646), False, 'import numpy\n'), ((699, 728), 'prody.measure.measure.calcPsi', 'calcPsi', (['residue'], {'radian': '(True)'}), '(residue, radian=True)\n', (706, 728), False, 'from prody.measure.measure import calcPsi, calcPhi, calcOmega\n'), ((547, 576), 'prody.measure.measure.calcPhi', 'calcPhi', (['residue'], {'radian': '(True)'}), '(residue, radian=True)\n', (554, 576), False, 'from prody.measure.measure import calcPsi, calcPhi, calcOmega\n'), ((1075, 1106), 'prody.measure.measure.calcOmega', 'calcOmega', (['residue'], {'radian': '(True)'}), '(residue, radian=True)\n', (1084, 1106), False, 'from prody.measure.measure import calcPsi, calcPhi, calcOmega\n')]
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # To determine the classification of Game results using Decision trees & Random Forests import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline df = pd.read_csv('../../data/processed/LOLOracleData_ChampStats.csv') df.head() print(df.columns) req_cols = ['BTop','BJng','BMid','BAdc','BSup','RTop','RJng','RMid','RAdc','RSup','BTopWr','BJngWr','BMidWr','BAdcWr','BSupWr','RTopWr','RJngWr','RMidWr','RAdcWr','RSupWr','BToptags','BJngtags','BMidtags','BAdctags','BSuptags','RToptags','RJngtags','RMidtags','RAdctags','RSuptags','Winner'] columns = list(df.columns) for i in range(len(req_cols)): columns.remove(req_cols[i]) columns df.drop(columns,axis=1,inplace=True) df df2 = pd.read_csv('../../data/processed/LOLOracleDatawithSynscores.csv') df2.head() df2.columns df2.drop(['BTop', 'BJng', 'BMid', 'BAdc', 'BSup', 'RTop', 'RJng', 'RMid', 'RAdc', 'RSup', 'Winner'],axis=1,inplace=True) df = pd.concat([df,df2],axis=1) df.head(50) df.head() df.drop(['BTop', 'BJng', 'BMid', 'BAdc', 'BSup', 'RTop', 'RJng', 'RMid', 'RAdc', 'RSup'],axis=1,inplace=True) df.head() df.columns taglist = list(df['BToptags'].unique()) taglist len(taglist) taglistencode = np.arange(0,13) taglist2encode = zip(taglist,taglistencode) taglist2encode = dict(taglist2encode) taglist2encode tagcols = ['BToptags','BJngtags','BMidtags','BAdctags','BSuptags','RToptags','RJngtags','RMidtags','RAdctags','RSuptags'] for j in tagcols: df[j].replace(taglist2encode,inplace=True) df df.columns # ### Lets perform Decision Trees and Random Forests X = df.drop('Winner',axis=1) y = df['Winner'] from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=101) from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier() dtc.fit(X_train,y_train) predict_dtc = dtc.predict(X_test) from sklearn.metrics import classification_report,confusion_matrix print (confusion_matrix(y_test,predict_dtc)) print('\n') print(classification_report(y_test,predict_dtc)) from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier(n_estimators=200) rfc.fit(X_train,y_train) predict_rfc = rfc.predict(X_test) print (confusion_matrix(y_test,predict_rfc)) print('\n') print(classification_report(y_test,predict_rfc))
[ "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.metrics.classification_report", "sklearn.tree.DecisionTreeClassifier", "sklearn.ensemble.RandomForestClassifier", "pandas.concat", "numpy.arange", "sklearn.metrics.confusion_matrix" ]
[((531, 595), 'pandas.read_csv', 'pd.read_csv', (['"""../../data/processed/LOLOracleData_ChampStats.csv"""'], {}), "('../../data/processed/LOLOracleData_ChampStats.csv')\n", (542, 595), True, 'import pandas as pd\n'), ((1069, 1135), 'pandas.read_csv', 'pd.read_csv', (['"""../../data/processed/LOLOracleDatawithSynscores.csv"""'], {}), "('../../data/processed/LOLOracleDatawithSynscores.csv')\n", (1080, 1135), True, 'import pandas as pd\n'), ((1296, 1324), 'pandas.concat', 'pd.concat', (['[df, df2]'], {'axis': '(1)'}), '([df, df2], axis=1)\n', (1305, 1324), True, 'import pandas as pd\n'), ((1569, 1585), 'numpy.arange', 'np.arange', (['(0)', '(13)'], {}), '(0, 13)\n', (1578, 1585), True, 'import numpy as np\n'), ((2089, 2144), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)', 'random_state': '(101)'}), '(X, y, test_size=0.3, random_state=101)\n', (2105, 2144), False, 'from sklearn.model_selection import train_test_split\n'), ((2198, 2222), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (2220, 2222), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((2520, 2560), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(200)'}), '(n_estimators=200)\n', (2542, 2560), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2361, 2398), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_test', 'predict_dtc'], {}), '(y_test, predict_dtc)\n', (2377, 2398), False, 'from sklearn.metrics import classification_report, confusion_matrix\n'), ((2417, 2459), 'sklearn.metrics.classification_report', 'classification_report', (['y_test', 'predict_dtc'], {}), '(y_test, predict_dtc)\n', (2438, 2459), False, 'from sklearn.metrics import classification_report, confusion_matrix\n'), ((2631, 2668), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_test', 'predict_rfc'], {}), '(y_test, predict_rfc)\n', (2647, 2668), False, 'from sklearn.metrics import classification_report, confusion_matrix\n'), ((2687, 2729), 'sklearn.metrics.classification_report', 'classification_report', (['y_test', 'predict_rfc'], {}), '(y_test, predict_rfc)\n', (2708, 2729), False, 'from sklearn.metrics import classification_report, confusion_matrix\n')]
import os import numpy as np from sklearn.feature_extraction.text import TfidfTransformer from tqdm import tqdm from utils.file import loadJson, dumpJson ############################################## # 根据序列数据集(ngram,api),先统计元素的样本内频率, # 然后计算各个特征的TF-IDF值 ############################################## def calTFIDF(dataset_path, dict_map_path, # 将序列元素转化为一个实值的映射的路径,通常为wordMap.json is_class_dir=True, level='item', # 在样本层次上上统计TFIDF还是类层次上 tfidf_dump_path=None, top_k=2000): # 取tf-idf值最高的k个api value_map = loadJson(dict_map_path) value_min = min(value_map.values()) value_max = max(value_map.values()) value_size = value_max - value_min + 1 item_frq_mat = None class_frq_mat = None N = None for i,folder in enumerate(tqdm(os.listdir(dataset_path))): # if i==1000: # return None class_cache = None if is_class_dir: items = os.listdir(dataset_path + folder + '/') else: items = [folder+'.json'] for item in items: data = loadJson(dataset_path + folder + '/' + item) seqs = data['apis'] if len(seqs) < 10: continue # 映射token为实值 seqs = [value_map[s] for s in seqs] hist, bins_sep = np.histogram(seqs, range=(value_min-0.5,value_max+0.5), # 这样划分使得每一个int值都处于一个单独的bin中 bins=value_size, normed=True) # if frq_mat is None: # frq_mat = np.expand_dims(hist, axis=0) # else: # frq_mat = np.concatenate((frq_mat,np.expand_dims(hist, axis=0)), axis=0) if item_frq_mat is None: item_frq_mat = np.expand_dims(hist, axis=0) else: item_frq_mat = np.concatenate((item_frq_mat,np.expand_dims(hist,axis=0)), axis=0) if class_cache is None: class_cache = np.expand_dims(hist, axis=0) else: class_cache = np.concatenate((item_frq_mat,np.expand_dims(hist,axis=0)), axis=0) class_val = class_cache.sum(axis=0) if class_frq_mat is None: class_frq_mat = np.expand_dims(class_val, axis=0) else: class_frq_mat = np.concatenate((class_frq_mat, np.expand_dims(class_val, axis=0)), axis=1) # 如果要计算类级别的tfidf,则把类内样本的元素频率相加作为整个类的频率向量, # 然后在类的级别上计算tf和idf if level == 'class': frq_mat = class_frq_mat else: frq_mat = item_frq_mat transformer = TfidfTransformer() transformer.fit(frq_mat) tf = np.mean(frq_mat, axis=0) tfidf = tf*transformer.idf_ # 取tf-idf最大的k个api的下标 top_k_idxes = tfidf.argsort()[::-1][:top_k] api_list = list(value_map.keys()) top_k_apis = [api_list[i] for i in top_k_idxes] if tfidf_dump_path is not None: api_tfidf = {api:val for api,val in zip(api_list,tfidf)} dumpJson(api_tfidf, tfidf_dump_path) print("- Done -") return top_k_apis # return tfidf, transformer if __name__ == '__main__': calTFIDF(dataset_path='/home/asichurter/datasets/JSONs/virushare-10-3gram/all/', dict_map_path='/home/asichurter/datasets/JSONs/virushare-10-3gram/data/wordMap.json', is_class_dir=True, level='item')
[ "sklearn.feature_extraction.text.TfidfTransformer", "numpy.mean", "os.listdir", "utils.file.dumpJson", "numpy.histogram", "utils.file.loadJson", "numpy.expand_dims" ]
[((580, 603), 'utils.file.loadJson', 'loadJson', (['dict_map_path'], {}), '(dict_map_path)\n', (588, 603), False, 'from utils.file import loadJson, dumpJson\n'), ((2663, 2681), 'sklearn.feature_extraction.text.TfidfTransformer', 'TfidfTransformer', ([], {}), '()\n', (2679, 2681), False, 'from sklearn.feature_extraction.text import TfidfTransformer\n'), ((2721, 2745), 'numpy.mean', 'np.mean', (['frq_mat'], {'axis': '(0)'}), '(frq_mat, axis=0)\n', (2728, 2745), True, 'import numpy as np\n'), ((3053, 3089), 'utils.file.dumpJson', 'dumpJson', (['api_tfidf', 'tfidf_dump_path'], {}), '(api_tfidf, tfidf_dump_path)\n', (3061, 3089), False, 'from utils.file import loadJson, dumpJson\n'), ((826, 850), 'os.listdir', 'os.listdir', (['dataset_path'], {}), '(dataset_path)\n', (836, 850), False, 'import os\n'), ((976, 1015), 'os.listdir', 'os.listdir', (["(dataset_path + folder + '/')"], {}), "(dataset_path + folder + '/')\n", (986, 1015), False, 'import os\n'), ((1115, 1159), 'utils.file.loadJson', 'loadJson', (["(dataset_path + folder + '/' + item)"], {}), "(dataset_path + folder + '/' + item)\n", (1123, 1159), False, 'from utils.file import loadJson, dumpJson\n'), ((1353, 1448), 'numpy.histogram', 'np.histogram', (['seqs'], {'range': '(value_min - 0.5, value_max + 0.5)', 'bins': 'value_size', 'normed': '(True)'}), '(seqs, range=(value_min - 0.5, value_max + 0.5), bins=\n value_size, normed=True)\n', (1365, 1448), True, 'import numpy as np\n'), ((2324, 2357), 'numpy.expand_dims', 'np.expand_dims', (['class_val'], {'axis': '(0)'}), '(class_val, axis=0)\n', (2338, 2357), True, 'import numpy as np\n'), ((1860, 1888), 'numpy.expand_dims', 'np.expand_dims', (['hist'], {'axis': '(0)'}), '(hist, axis=0)\n', (1874, 1888), True, 'import numpy as np\n'), ((2072, 2100), 'numpy.expand_dims', 'np.expand_dims', (['hist'], {'axis': '(0)'}), '(hist, axis=0)\n', (2086, 2100), True, 'import numpy as np\n'), ((2431, 2464), 'numpy.expand_dims', 'np.expand_dims', (['class_val'], {'axis': '(0)'}), '(class_val, axis=0)\n', (2445, 2464), True, 'import numpy as np\n'), ((1967, 1995), 'numpy.expand_dims', 'np.expand_dims', (['hist'], {'axis': '(0)'}), '(hist, axis=0)\n', (1981, 1995), True, 'import numpy as np\n'), ((2178, 2206), 'numpy.expand_dims', 'np.expand_dims', (['hist'], {'axis': '(0)'}), '(hist, axis=0)\n', (2192, 2206), True, 'import numpy as np\n')]
from model import DGCNN import config from tokenizer import sent2id,tokenize from utils import alignWord2Char,focal_loss,binary_confusion_matrix_evaluate import torch import numpy as np import torch.optim as optim from log import logger from copy import deepcopy from tabulate import tabulate class Model(object): def __init__(self): self.device = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu') self.model = DGCNN(256,char_file = config.char_embedding_path,\ word_file = config.word_embedding_path).to(self.device) self.epoches = 150 self.lr = 1e-4 self.print_step = 15 self.optimizer = optim.Adam(filter(lambda p: p.requires_grad, self.model.parameters()),\ lr=self.lr) self.best_model = DGCNN(256,char_file=config.char_embedding_path,\ word_file = config.word_embedding_path).to(self.device) self._val_loss = 1e12 #Debug def train(self,train_data,dev_data,threshold=0.1): for epoch in range(self.epoches): self.model.train() for i,item in enumerate(train_data): self.optimizer.zero_grad() Qc,Qw,q_mask,Ec,Ew,e_mask,As,Ae = [i.to(self.device) for i in item] As_, Ae_ = self.model([Qc,Qw,q_mask,Ec,Ew,e_mask]) As_loss=focal_loss(As,As_,self.device) Ae_loss=focal_loss(Ae,Ae_,self.device) # batch_size, max_seq_len_e mask=e_mask==1 loss=(As_loss.masked_select(mask).sum()+Ae_loss.masked_select(mask).sum()) / e_mask.sum() loss.backward() self.optimizer.step() if (i+1)%self.print_step==0 or i==len(train_data)-1: logger.info("In Training : Epoch : {} \t Step / All Step : {} / {} \t Loss of every char : {}"\ .format(epoch+1, i+1,len(train_data),loss.item()*100)) #debug # if i==2000: # break self.model.eval() with torch.no_grad(): self.validate(dev_data) def test(self,test_data,threshold=0.1): self.best_model.eval() self.best_model.to(self.device) with torch.no_grad(): sl,el,sl_,el_=[],[],[],[] for i, item in enumerate(test_data): Qc,Qw,q_mask,Ec,Ew,e_mask,As,Ae = [i.to(self.device) for i in item] mask=e_mask==1 As_,Ae_ = self.model([Qc,Qw,q_mask,Ec,Ew,e_mask]) As_,Ae_,As,Ae = [ i.masked_select(mask).cpu().numpy() for i in [As_,Ae_,As,Ae]] As_,Ae_ = np.where(As_>threshold,1,0), np.where(Ae_>threshold,1,0) As,Ae = As.astype(int),Ae.astype(int) sl.append(As) el.append(Ae) sl_.append(As_) el.append(el_) a=binary_confusion_matrix_evaluate(np.concatenate(sl),np.concatenate(sl_)) b=binary_confusion_matrix_evaluate(np.concatenate(el),np.concatenate(el_)) logger.info('In Test DataSet: START EVALUATION:\t Acc : {}\t Prec : {}\t Recall : {}\t F1-score : {}'\ .format(a[0],a[1],a[2],a[3])) logger.info('In Test DataSet: START EVALUATION:\t Acc : {}\t Prec : {}\t Recall : {}\t F1-score : {}'\ .format(b[0],b[1],b[2],b[3])) def validate(self,dev_data,threshold=0.1): val_loss=[] # import pdb; pdb.set_trace() for i, item in enumerate(dev_data): Qc,Qw,q_mask,Ec,Ew,e_mask,As,Ae = [i.to(self.device) for i in item] As_, Ae_ = self.model([Qc,Qw,q_mask,Ec,Ew,e_mask]) #cal loss As_loss,Ae_loss=focal_loss(As,As_,self.device) ,focal_loss(Ae,Ae_,self.device) mask=e_mask==1 loss=(As_loss.masked_select(mask).sum() + Ae_loss.masked_select(mask).sum()) / e_mask.sum() if (i+1)%self.print_step==0 or i==len(dev_data)-1: logger.info("In Validation: Step / All Step : {} / {} \t Loss of every char : {}"\ .format(i+1,len(dev_data),loss.item()*100)) val_loss.append(loss.item()) As_,Ae_,As,Ae = [ i.masked_select(mask).cpu().numpy() for i in [As_,Ae_,As,Ae]] As_,Ae_ = np.where(As_>threshold,1,0), np.where(Ae_>threshold,1,0) As,Ae = As.astype(int),Ae.astype(int) acc,prec,recall,f1=binary_confusion_matrix_evaluate(As,As_) logger.info('START EVALUATION :\t Acc : {}\t Prec : {}\t Recall : {}\t F1-score : {}'\ .format(acc,prec,recall,f1)) acc,prec,recall,f1=binary_confusion_matrix_evaluate(Ae,Ae_) logger.info('END EVALUATION :\t Acc : {}\t Prec : {}\t Recall : {}\t F1-score : {}'\ .format(acc,prec,recall,f1)) # [ , seq_len] l=sum(val_loss)/len(val_loss) logger.info('In Validation, Average Loss : {}'.format(l*100)) if l<self._val_loss: logger.info('Update best Model in Valiation Dataset') self._val_loss=l self.best_model=deepcopy(self.model) def load_model(self,PATH): self.best_model.load_state_dict(torch.load(PATH)) self.best_model.eval() def save_model(self,PATH): torch.save(self.best_model.state_dict(),PATH) logger.info('save best model successfully') ''' 这里的Data是指含有原始文本的数据List[ dict ] - test_data | - { 'question', 'evidences', 'answer'} ''' def get_test_answer(self,test_data,word2id,char2id): all_item = len(test_data) t1=0. t3=0. t5=0. self.best_model.eval() with torch.no_grad(): for item in test_data: q_text = item['question'] e_texts = item['evidences'] a = item['answer'] a_ = extract_answer(q_text,e_texts,word2id,char2id) # a_ list of [ answer , possibility] n=len(a_) a_1 = {i[0] for i in a_[:1]} a_3 = {i[0] for i in a_[:3]} a_5 = {i[0] for i in a_[:5]} if a[0] == 'no_answer' and n==0: t1+=1 t3+=1 t5+=1 if [i for i in a if i in a_1]: t1+=1 if [i for i in a if i in a_3]: t3+=1 if [i for i in a if i in a_5]: t5+=1 logger.info('In Test Raw File') logger.info('Top One Answer : Acc : {}'.format(t1/all_item)) logger.info('Top Three Answer : Acc : {}'.format(t3/all_item)) logger.info('Top Five Answer : Acc : {}'.format(t5/all_item)) def extract_answer(self,q_text,e_texts,word2id,char2id,maxlen=10,threshold=0.1): Qc,Qw,Ec,Ew= [],[],[],[] qc = list(q_text) Qc,q_mask=sent2id([qc],char2id) qw = alignWord2Char(tokenize(q_text)) Qw,q_mask_=sent2id([qw],word2id) assert torch.all(q_mask == q_mask_) tmp = [(list(e),alignWord2Char(tokenize(e))) for e in e_texts] ec,ew = zip(*tmp) Ec,e_mask=sent2id(list(ec),char2id) Ew,e_mask_=sent2id(list(ew),word2id) assert torch.all(e_mask == e_mask_) totensor=lambda x: torch.from_numpy(np.array(x)).long() L=[Qc,Qw,q_mask,Ec,Ew,e_mask] L=[totensor(x) for x in L] As_ , Ae_ = self.best_model(L) R={} for as_ ,ae_ , e in zip(As_,Ae_,e_texts): as_ ,ae_ = as_[:len(e)].numpy() , ae_[:len(e)].numpy() sidx = torch.where(as_>threshold)[0] eidx = torch.where(ae_>threshold)[0] result = { } for i in sidx: cond = (eidx >= i) & (eidx < i+maxlen) for j in eidx[cond]: key=e[i:j+1] result[key]=max(result.get(key,0),as_[i] * ae_[j]) if result: for k,v in result.items(): if k not in R: R[k]=[] R[k].append(v) # sort all answer R= [ [k,((np.array(v)**2).sum()/(sum(v)+1))] for k , v in R.items() ] R.sort(key=lambda x: x[1], reversed=True) # R 降序排列的 (answer, possibility) return R if __name__ == '__main__': pass
[ "utils.focal_loss", "numpy.where", "model.DGCNN", "torch.load", "log.logger.info", "tokenizer.sent2id", "tokenizer.tokenize", "torch.cuda.is_available", "numpy.array", "numpy.concatenate", "copy.deepcopy", "torch.no_grad", "utils.binary_confusion_matrix_evaluate", "torch.all", "torch.whe...
[((5502, 5545), 'log.logger.info', 'logger.info', (['"""save best model successfully"""'], {}), "('save best model successfully')\n", (5513, 5545), False, 'from log import logger\n'), ((6675, 6706), 'log.logger.info', 'logger.info', (['"""In Test Raw File"""'], {}), "('In Test Raw File')\n", (6686, 6706), False, 'from log import logger\n'), ((7088, 7110), 'tokenizer.sent2id', 'sent2id', (['[qc]', 'char2id'], {}), '([qc], char2id)\n', (7095, 7110), False, 'from tokenizer import sent2id, tokenize\n'), ((7176, 7198), 'tokenizer.sent2id', 'sent2id', (['[qw]', 'word2id'], {}), '([qw], word2id)\n', (7183, 7198), False, 'from tokenizer import sent2id, tokenize\n'), ((7214, 7242), 'torch.all', 'torch.all', (['(q_mask == q_mask_)'], {}), '(q_mask == q_mask_)\n', (7223, 7242), False, 'import torch\n'), ((7446, 7474), 'torch.all', 'torch.all', (['(e_mask == e_mask_)'], {}), '(e_mask == e_mask_)\n', (7455, 7474), False, 'import torch\n'), ((2315, 2330), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2328, 2330), False, 'import torch\n'), ((4566, 4607), 'utils.binary_confusion_matrix_evaluate', 'binary_confusion_matrix_evaluate', (['As', 'As_'], {}), '(As, As_)\n', (4598, 4607), False, 'from utils import alignWord2Char, focal_loss, binary_confusion_matrix_evaluate\n'), ((4795, 4836), 'utils.binary_confusion_matrix_evaluate', 'binary_confusion_matrix_evaluate', (['Ae', 'Ae_'], {}), '(Ae, Ae_)\n', (4827, 4836), False, 'from utils import alignWord2Char, focal_loss, binary_confusion_matrix_evaluate\n'), ((5154, 5207), 'log.logger.info', 'logger.info', (['"""Update best Model in Valiation Dataset"""'], {}), "('Update best Model in Valiation Dataset')\n", (5165, 5207), False, 'from log import logger\n'), ((5265, 5285), 'copy.deepcopy', 'deepcopy', (['self.model'], {}), '(self.model)\n', (5273, 5285), False, 'from copy import deepcopy\n'), ((5359, 5375), 'torch.load', 'torch.load', (['PATH'], {}), '(PATH)\n', (5369, 5375), False, 'import torch\n'), ((5837, 5852), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5850, 5852), False, 'import torch\n'), ((7139, 7155), 'tokenizer.tokenize', 'tokenize', (['q_text'], {}), '(q_text)\n', (7147, 7155), False, 'from tokenizer import sent2id, tokenize\n'), ((388, 413), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (411, 413), False, 'import torch\n'), ((448, 539), 'model.DGCNN', 'DGCNN', (['(256)'], {'char_file': 'config.char_embedding_path', 'word_file': 'config.word_embedding_path'}), '(256, char_file=config.char_embedding_path, word_file=config.\n word_embedding_path)\n', (453, 539), False, 'from model import DGCNN\n'), ((795, 886), 'model.DGCNN', 'DGCNN', (['(256)'], {'char_file': 'config.char_embedding_path', 'word_file': 'config.word_embedding_path'}), '(256, char_file=config.char_embedding_path, word_file=config.\n word_embedding_path)\n', (800, 886), False, 'from model import DGCNN\n'), ((1355, 1387), 'utils.focal_loss', 'focal_loss', (['As', 'As_', 'self.device'], {}), '(As, As_, self.device)\n', (1365, 1387), False, 'from utils import alignWord2Char, focal_loss, binary_confusion_matrix_evaluate\n'), ((1410, 1442), 'utils.focal_loss', 'focal_loss', (['Ae', 'Ae_', 'self.device'], {}), '(Ae, Ae_, self.device)\n', (1420, 1442), False, 'from utils import alignWord2Char, focal_loss, binary_confusion_matrix_evaluate\n'), ((2117, 2132), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2130, 2132), False, 'import torch\n'), ((3003, 3021), 'numpy.concatenate', 'np.concatenate', (['sl'], {}), '(sl)\n', (3017, 3021), True, 'import numpy as np\n'), ((3022, 3041), 'numpy.concatenate', 'np.concatenate', (['sl_'], {}), '(sl_)\n', (3036, 3041), True, 'import numpy as np\n'), ((3090, 3108), 'numpy.concatenate', 'np.concatenate', (['el'], {}), '(el)\n', (3104, 3108), True, 'import numpy as np\n'), ((3109, 3128), 'numpy.concatenate', 'np.concatenate', (['el_'], {}), '(el_)\n', (3123, 3128), True, 'import numpy as np\n'), ((3813, 3845), 'utils.focal_loss', 'focal_loss', (['As', 'As_', 'self.device'], {}), '(As, As_, self.device)\n', (3823, 3845), False, 'from utils import alignWord2Char, focal_loss, binary_confusion_matrix_evaluate\n'), ((3845, 3877), 'utils.focal_loss', 'focal_loss', (['Ae', 'Ae_', 'self.device'], {}), '(Ae, Ae_, self.device)\n', (3855, 3877), False, 'from utils import alignWord2Char, focal_loss, binary_confusion_matrix_evaluate\n'), ((4415, 4446), 'numpy.where', 'np.where', (['(As_ > threshold)', '(1)', '(0)'], {}), '(As_ > threshold, 1, 0)\n', (4423, 4446), True, 'import numpy as np\n'), ((4444, 4475), 'numpy.where', 'np.where', (['(Ae_ > threshold)', '(1)', '(0)'], {}), '(Ae_ > threshold, 1, 0)\n', (4452, 4475), True, 'import numpy as np\n'), ((7804, 7832), 'torch.where', 'torch.where', (['(as_ > threshold)'], {}), '(as_ > threshold)\n', (7815, 7832), False, 'import torch\n'), ((7853, 7881), 'torch.where', 'torch.where', (['(ae_ > threshold)'], {}), '(ae_ > threshold)\n', (7864, 7881), False, 'import torch\n'), ((2722, 2753), 'numpy.where', 'np.where', (['(As_ > threshold)', '(1)', '(0)'], {}), '(As_ > threshold, 1, 0)\n', (2730, 2753), True, 'import numpy as np\n'), ((2751, 2782), 'numpy.where', 'np.where', (['(Ae_ > threshold)', '(1)', '(0)'], {}), '(Ae_ > threshold, 1, 0)\n', (2759, 2782), True, 'import numpy as np\n'), ((7283, 7294), 'tokenizer.tokenize', 'tokenize', (['e'], {}), '(e)\n', (7291, 7294), False, 'from tokenizer import sent2id, tokenize\n'), ((7520, 7531), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (7528, 7531), True, 'import numpy as np\n'), ((8363, 8374), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (8371, 8374), True, 'import numpy as np\n')]
''' Copyright 2013 <NAME> and <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the 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. ''' # Based on the Python impl of IRLB by <NAME> (https://github.com/bwlewis/irlbpy), # but with support for sparse centering / scaling import numpy as np import scipy.sparse as sp import warnings # Matrix-vector product wrapper # A is a numpy 2d array or matrix, or a scipy matrix or sparse matrix. # x is a numpy vector only. # Compute A.dot(x) if t is False, A.transpose().dot(x) otherwise. def mult(A, x, t=False): assert x.ndim == 1 if(sp.issparse(A)): if(t): return(sp.csr_matrix(x).dot(A).transpose().todense().A[:, 0]) return(A.dot(sp.csr_matrix(x).transpose()).todense().A[:, 0]) if(t): return np.asarray(A.transpose().dot(x)).ravel() return np.asarray(A.dot(x)).ravel() def orthog(Y, X): """Orthogonalize a vector or matrix Y against the columns of the matrix X. This function requires that the column dimension of Y is less than X and that Y and X have the same number of rows. """ dotY = Y.dot(X) return (Y - mult(X, dotY)) # Simple utility function used to check linear dependencies during computation: def invcheck(x): eps2 = 2 * np.finfo(np.float).eps if(x > eps2): return 1.0 / x else: warnings.warn( "Ill-conditioning encountered, result accuracy may be poor") return 0.0 def irlb(A, n, tol=0.0001, maxit=50, center=None, scale=None, random_state=0): """Estimate a few of the largest singular values and corresponding singular vectors of matrix using the implicitly restarted Lanczos bidiagonalization method of Baglama and Reichel, see: Augmented Implicitly Restarted Lanczos Bidiagonalization Methods, <NAME> and <NAME>, SIAM J. Sci. Comput. 2005 Keyword arguments: tol -- An estimation tolerance. Smaller means more accurate estimates. maxit -- Maximum number of Lanczos iterations allowed. Given an input matrix A of dimension j * k, and an input desired number of singular values n, the function returns a tuple X with five entries: X[0] A j * nu matrix of estimated left singular vectors. X[1] A vector of length nu of estimated singular values. X[2] A k * nu matrix of estimated right singular vectors. X[3] The number of Lanczos iterations run. X[4] The number of matrix-vector products run. The algorithm estimates the truncated singular value decomposition: A.dot(X[2]) = X[0]*X[1]. """ np.random.seed(random_state) # Numpy routines do undesirable things if these come in as N x 1 matrices instead of size N arrays if center is not None and not isinstance(center, np.ndarray): raise TypeError("center must be a numpy.ndarray") if scale is not None and not isinstance(scale, np.ndarray): raise TypeError("scale must be a numpy.ndarray") nu = n m = A.shape[0] n = A.shape[1] if(min(m, n) < 2): raise Exception("The input matrix must be at least 2x2.") # TODO: More efficient to have a path that performs a standard SVD # if over half the eigenvectors are requested m_b = min((nu + 20, 3 * nu, min(A.shape))) # Working dimension size # m_b = nu + 7 # uncomment this line to check for similar results with R package mprod = 0 it = 0 j = 0 k = nu smax = 1 V = np.zeros((n, m_b)) # Approximate right vectors W = np.zeros((m, m_b)) # Approximate left vectors F = np.zeros((n, 1)) # Residual vector B = np.zeros((m_b, m_b)) #Bidiagonal approximation V[:, 0] = np.random.randn(n) # Initial vector V[:, 0] = V[:, 0] / np.linalg.norm(V) while(it < maxit): if(it > 0): j = k VJ = V[:, j] # apply scaling if scale is not None: VJ = VJ / scale W[:, j] = mult(A, VJ) mprod += 1 # apply centering # R code: W[, j_w] <- W[, j_w] - ds * drop(cross(dv, VJ)) * du if center is not None: W[:, j] = W[:, j] - np.dot(center, VJ) if(it > 0): # NB W[:,0:j] selects columns 0,1,...,j-1 W[:, j] = orthog(W[:, j], W[:, 0:j]) s = np.linalg.norm(W[:, j]) sinv = invcheck(s) W[:, j] = sinv * W[:, j] # Lanczos process while(j < m_b): F = mult(A, W[:, j], t=True) mprod += 1 # apply scaling if scale is not None: F = F / scale # apply centering, note for cases where center is the column # mean, this correction is often equivalent to a no-op as # np.sum(W[:, j]) is often close to zero if center is not None: F = F - np.sum(W[:, j]) * center F = F - s * V[:, j] F = orthog(F, V[:, 0:(j + 1)]) fn = np.linalg.norm(F) fninv = invcheck(fn) F = fninv * F if(j < m_b - 1): V[:, j + 1] = F B[j, j] = s B[j, j + 1] = fn VJp1 = V[:, j + 1] # apply scaling if scale is not None: VJp1 = VJp1 / scale W[:, j + 1] = mult(A, VJp1) mprod += 1 # apply centering # R code: W[, jp1_w] <- W[, jp1_w] - ds * drop(cross(dv, VJP1)) * du if center is not None: W[:, j + 1] = W[:, j + 1] - np.dot(center, VJp1) # One step of classical Gram-Schmidt... W[:, j + 1] = W[:, j + 1] - fn * W[:, j] # ...with full reorthogonalization W[:, j + 1] = orthog(W[:, j + 1], W[:, 0:(j + 1)]) s = np.linalg.norm(W[:, j + 1]) sinv = invcheck(s) W[:, j + 1] = sinv * W[:, j + 1] else: B[j, j] = s j += 1 # End of Lanczos process S = np.linalg.svd(B) R = fn * S[0][m_b - 1, :] # Residuals if(it < 1): smax = S[1][0] # Largest Ritz value else: smax = max((S[1][0], smax)) conv = sum(np.abs(R[0:nu]) < tol * smax) if(conv < nu): # Not coverged yet k = max(conv + nu, k) k = min(k, m_b - 3) else: break # Update the Ritz vectors V[:, 0:k] = V[:, 0:m_b].dot(S[2].transpose()[:, 0:k]) V[:, k] = F B = np.zeros((m_b, m_b)) # Improve this! There must be better way to assign diagonal... for l in xrange(0, k): B[l, l] = S[1][l] B[0:k, k] = R[0:k] # Update the left approximate singular vectors W[:, 0:k] = W[:, 0:m_b].dot(S[0][:, 0:k]) it += 1 U = W[:, 0:m_b].dot(S[0][:, 0:nu]) V = V[:, 0:m_b].dot(S[2].transpose()[:, 0:nu]) return((U, S[1][0:nu], V, it, mprod))
[ "numpy.abs", "scipy.sparse.issparse", "numpy.linalg.svd", "numpy.sum", "numpy.zeros", "numpy.dot", "numpy.random.seed", "numpy.linalg.norm", "warnings.warn", "numpy.finfo", "scipy.sparse.csr_matrix", "numpy.random.randn" ]
[((1015, 1029), 'scipy.sparse.issparse', 'sp.issparse', (['A'], {}), '(A)\n', (1026, 1029), True, 'import scipy.sparse as sp\n'), ((2990, 3018), 'numpy.random.seed', 'np.random.seed', (['random_state'], {}), '(random_state)\n', (3004, 3018), True, 'import numpy as np\n'), ((3854, 3872), 'numpy.zeros', 'np.zeros', (['(n, m_b)'], {}), '((n, m_b))\n', (3862, 3872), True, 'import numpy as np\n'), ((3909, 3927), 'numpy.zeros', 'np.zeros', (['(m, m_b)'], {}), '((m, m_b))\n', (3917, 3927), True, 'import numpy as np\n'), ((3963, 3979), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (3971, 3979), True, 'import numpy as np\n'), ((4006, 4026), 'numpy.zeros', 'np.zeros', (['(m_b, m_b)'], {}), '((m_b, m_b))\n', (4014, 4026), True, 'import numpy as np\n'), ((4068, 4086), 'numpy.random.randn', 'np.random.randn', (['n'], {}), '(n)\n', (4083, 4086), True, 'import numpy as np\n'), ((1774, 1848), 'warnings.warn', 'warnings.warn', (['"""Ill-conditioning encountered, result accuracy may be poor"""'], {}), "('Ill-conditioning encountered, result accuracy may be poor')\n", (1787, 1848), False, 'import warnings\n'), ((4129, 4146), 'numpy.linalg.norm', 'np.linalg.norm', (['V'], {}), '(V)\n', (4143, 4146), True, 'import numpy as np\n'), ((4680, 4703), 'numpy.linalg.norm', 'np.linalg.norm', (['W[:, j]'], {}), '(W[:, j])\n', (4694, 4703), True, 'import numpy as np\n'), ((6463, 6479), 'numpy.linalg.svd', 'np.linalg.svd', (['B'], {}), '(B)\n', (6476, 6479), True, 'import numpy as np\n'), ((6969, 6989), 'numpy.zeros', 'np.zeros', (['(m_b, m_b)'], {}), '((m_b, m_b))\n', (6977, 6989), True, 'import numpy as np\n'), ((1692, 1710), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (1700, 1710), True, 'import numpy as np\n'), ((5344, 5361), 'numpy.linalg.norm', 'np.linalg.norm', (['F'], {}), '(F)\n', (5358, 5361), True, 'import numpy as np\n'), ((4525, 4543), 'numpy.dot', 'np.dot', (['center', 'VJ'], {}), '(center, VJ)\n', (4531, 4543), True, 'import numpy as np\n'), ((6241, 6268), 'numpy.linalg.norm', 'np.linalg.norm', (['W[:, j + 1]'], {}), '(W[:, j + 1])\n', (6255, 6268), True, 'import numpy as np\n'), ((6670, 6685), 'numpy.abs', 'np.abs', (['R[0:nu]'], {}), '(R[0:nu])\n', (6676, 6685), True, 'import numpy as np\n'), ((5227, 5242), 'numpy.sum', 'np.sum', (['W[:, j]'], {}), '(W[:, j])\n', (5233, 5242), True, 'import numpy as np\n'), ((5968, 5988), 'numpy.dot', 'np.dot', (['center', 'VJp1'], {}), '(center, VJp1)\n', (5974, 5988), True, 'import numpy as np\n'), ((1142, 1158), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['x'], {}), '(x)\n', (1155, 1158), True, 'import scipy.sparse as sp\n'), ((1066, 1082), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['x'], {}), '(x)\n', (1079, 1082), True, 'import scipy.sparse as sp\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt # set path path = '../data/data_sub.xlsx' dataFrame = pd.read_excel(path, header=2, sheet_name='trials_noTime') headers = dataFrame.columns trials = 5 fields = 11 subjects = 4 vasSubjectNeck1 = [] vasSubjectNeck2 = [] vasSubjectNeck3 = [] vasSubjectNeck4 = [] vasSubjectNeck5 = [] vasSubjectNeck6 = [] meanNeck = [] vasSpeed = [3, 10, 30, 50, 100, 200] for t in range(0, subjects): for u in range(0, len(dataFrame)): if dataFrame[headers[(t * fields) + 2]][u] == 3: vasSubjectNeck1.append(dataFrame[headers[t * fields]][u]) if len(vasSubjectNeck1) == trials: meanNeck.append([np.mean(vasSubjectNeck1), 3]) # print(meanNeck) vasSubjectNeck1 = [] if dataFrame[headers[(t * fields) + 2]][u] == 10: vasSubjectNeck2.append(dataFrame[headers[t * fields]][u]) if len(vasSubjectNeck2) == trials: meanNeck.append([np.mean(vasSubjectNeck2), 10]) vasSubjectNeck2 = [] if dataFrame[headers[(t * fields) + 2]][u] == 30: vasSubjectNeck3.append(dataFrame[headers[t * fields]][u]) if len(vasSubjectNeck3) == trials: meanNeck.append([np.mean(vasSubjectNeck3), 30]) vasSubjectNeck3 = [] if dataFrame[headers[(t * fields) + 2]][u] == 50: vasSubjectNeck4.append(dataFrame[headers[t * fields]][u]) if len(vasSubjectNeck4) == trials: meanNeck.append([np.mean(vasSubjectNeck4), 50]) vasSubjectNeck4 = [] if dataFrame[headers[(t * fields) + 2]][u] == 100: vasSubjectNeck5.append(dataFrame[headers[t * fields]][u]) if len(vasSubjectNeck5) == trials: meanNeck.append([np.mean(vasSubjectNeck5), 100]) vasSubjectNeck5 = [] if dataFrame[headers[(t * fields) + 2]][u] == 200: vasSubjectNeck6.append(dataFrame[headers[t * fields]][u]) if len(vasSubjectNeck6) == trials: meanNeck.append([np.mean(vasSubjectNeck6), 200]) vasSubjectNeck6 = [] if len(meanNeck) == 6: plot1 = pd.DataFrame({'stimulation velocity': vasSpeed, 'VAS score': [meanNeck[0][0], meanNeck[1][0], meanNeck[2][0], meanNeck[3][0], meanNeck[4][0], meanNeck[5][0]]}) plt.plot(vasSpeed, [meanNeck[0][0], meanNeck[1][0], meanNeck[2][0], meanNeck[3][0], meanNeck[4][0], meanNeck[5][0]]) plt.yticks((-10, -5, 0, 5, 10)) #plt.xticks((3, 10, 30, 50, 100, 200)) meanNeck = [] #print(meanNeck) #print(meanNeck[0][0])
[ "numpy.mean", "matplotlib.pyplot.plot", "matplotlib.pyplot.yticks", "pandas.read_excel", "pandas.DataFrame" ]
[((126, 183), 'pandas.read_excel', 'pd.read_excel', (['path'], {'header': '(2)', 'sheet_name': '"""trials_noTime"""'}), "(path, header=2, sheet_name='trials_noTime')\n", (139, 183), True, 'import pandas as pd\n'), ((2241, 2409), 'pandas.DataFrame', 'pd.DataFrame', (["{'stimulation velocity': vasSpeed, 'VAS score': [meanNeck[0][0], meanNeck[1\n ][0], meanNeck[2][0], meanNeck[3][0], meanNeck[4][0], meanNeck[5][0]]}"], {}), "({'stimulation velocity': vasSpeed, 'VAS score': [meanNeck[0][0\n ], meanNeck[1][0], meanNeck[2][0], meanNeck[3][0], meanNeck[4][0],\n meanNeck[5][0]]})\n", (2253, 2409), True, 'import pandas as pd\n'), ((2413, 2533), 'matplotlib.pyplot.plot', 'plt.plot', (['vasSpeed', '[meanNeck[0][0], meanNeck[1][0], meanNeck[2][0], meanNeck[3][0], meanNeck[4\n ][0], meanNeck[5][0]]'], {}), '(vasSpeed, [meanNeck[0][0], meanNeck[1][0], meanNeck[2][0],\n meanNeck[3][0], meanNeck[4][0], meanNeck[5][0]])\n', (2421, 2533), True, 'import matplotlib.pyplot as plt\n'), ((2559, 2590), 'matplotlib.pyplot.yticks', 'plt.yticks', (['(-10, -5, 0, 5, 10)'], {}), '((-10, -5, 0, 5, 10))\n', (2569, 2590), True, 'import matplotlib.pyplot as plt\n'), ((705, 729), 'numpy.mean', 'np.mean', (['vasSubjectNeck1'], {}), '(vasSubjectNeck1)\n', (712, 729), True, 'import numpy as np\n'), ((1014, 1038), 'numpy.mean', 'np.mean', (['vasSubjectNeck2'], {}), '(vasSubjectNeck2)\n', (1021, 1038), True, 'import numpy as np\n'), ((1290, 1314), 'numpy.mean', 'np.mean', (['vasSubjectNeck3'], {}), '(vasSubjectNeck3)\n', (1297, 1314), True, 'import numpy as np\n'), ((1566, 1590), 'numpy.mean', 'np.mean', (['vasSubjectNeck4'], {}), '(vasSubjectNeck4)\n', (1573, 1590), True, 'import numpy as np\n'), ((1843, 1867), 'numpy.mean', 'np.mean', (['vasSubjectNeck5'], {}), '(vasSubjectNeck5)\n', (1850, 1867), True, 'import numpy as np\n'), ((2121, 2145), 'numpy.mean', 'np.mean', (['vasSubjectNeck6'], {}), '(vasSubjectNeck6)\n', (2128, 2145), True, 'import numpy as np\n')]
import os import numpy as np import stk import itertools as it from collections import Counter from os.path import join import rdkit.Chem.AllChem as rdkit if not os.path.exists('building_block_tests_output'): os.mkdir('building_block_tests_output') def test_init_rdkit(): rdkit_mol = rdkit.AddHs(rdkit.MolFromSmiles('NCCCN')) rdkit.EmbedMolecule(rdkit_mol, rdkit.ETKDGv2()) mol0 = stk.BuildingBlock.init_from_rdkit_mol(rdkit_mol, ['amine']) # Test that all values are initialized correctly. assert len(mol0.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol0.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol0.atoms) == 15 assert len(mol0.bonds) == 14 atom_count = { (stk.H, 0): 10, (stk.N, 0): 2, (stk.C, 0): 3 } assert atom_count == Counter( (a.__class__, a.charge) for a in mol0.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol0.bonds ) # Test that caching is working properly. mol1 = stk.BuildingBlock.init_from_rdkit_mol(rdkit_mol, ['amine']) assert mol0 is not mol1 mol2 = stk.BuildingBlock.init_from_rdkit_mol( mol=rdkit_mol, functional_groups=['amine'], use_cache=True ) mol3 = stk.BuildingBlock.init_from_rdkit_mol( mol=rdkit_mol, functional_groups=['amine'], use_cache=True ) assert mol0 is not mol2 and mol1 is not mol2 assert mol2 is mol3 mol4 = stk.BuildingBlock.init_from_rdkit_mol( mol=rdkit_mol, functional_groups=['aldehyde'], use_cache=True ) assert mol3 is not mol4 # Make sure that charged molecules are handled correctly. negative_carbon = rdkit.AddHs(rdkit.MolFromSmiles('NC[C-]CN')) rdkit.EmbedMolecule(negative_carbon, rdkit.ETKDGv2()) mol5 = stk.BuildingBlock.init_from_rdkit_mol( mol=negative_carbon, functional_groups=['amine'], use_cache=True ) assert mol5 is not mol0 # Test that all values are initialized correctly. assert len(mol5.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol5.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol5.atoms) == 13 assert len(mol5.bonds) == 12 atom_count = { (stk.C, 0): 2, (stk.C, -1): 1, (stk.N, 0): 2, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol5.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 4 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol5.bonds ) negative_nitrogen = rdkit.AddHs(rdkit.MolFromSmiles('[N-]CCCN')) rdkit.EmbedMolecule(negative_nitrogen, rdkit.ETKDGv2()) mol6 = stk.BuildingBlock.init_from_rdkit_mol( mol=negative_nitrogen, functional_groups=['amine'], use_cache=True ) assert mol6 is not mol5 and mol6 is not mol0 # Test that all values are initialized correctly. assert len(mol6.func_groups) == 1 fg_types = stk.dedupe(fg.fg_type.name for fg in mol6.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol6.atoms) == 13 assert len(mol6.bonds) == 12 atom_count = { (stk.C, 0): 3, (stk.N, 0): 1, (stk.N, -1): 1, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol6.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 2, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol6.bonds ) def test_init_mol(bb_dir): mol0 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.mol'), functional_groups=['amine'] ) # Test that all values are initialized correctly. assert len(mol0.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol0.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol0.atoms) == 15 assert len(mol0.bonds) == 14 atom_count = { (stk.H, 0): 10, (stk.N, 0): 2, (stk.C, 0): 3 } assert atom_count == Counter( (a.__class__, a.charge) for a in mol0.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol0.bonds ) # Test that caching is working properly. mol1 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.mol'), functional_groups=['amine'] ) assert mol0 is not mol1 mol2 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.mol'), functional_groups=['amine'], use_cache=True ) mol3 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.mol'), functional_groups=['amine'], use_cache=True ) assert mol0 is not mol2 and mol1 is not mol2 assert mol2 is mol3 mol4 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.mol'), functional_groups=['aldehyde'], use_cache=True ) assert mol3 is not mol4 # Make sure that charged molecules are handled correctly. mol5 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'negative_carbon.mol'), functional_groups=['amine'], use_cache=True ) assert mol5 is not mol0 # Test that all values are initialized correctly. assert len(mol5.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol5.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol5.atoms) == 13 assert len(mol5.bonds) == 12 atom_count = { (stk.C, 0): 2, (stk.C, -1): 1, (stk.N, 0): 2, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol5.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 4 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol5.bonds ) mol6 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'negative_nitrogen.mol'), functional_groups=['amine'], use_cache=True ) assert mol6 is not mol5 and mol6 is not mol0 # Test that all values are initialized correctly. assert len(mol6.func_groups) == 1 fg_types = stk.dedupe(fg.fg_type.name for fg in mol6.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol6.atoms) == 13 assert len(mol6.bonds) == 12 atom_count = { (stk.C, 0): 3, (stk.N, 0): 1, (stk.N, -1): 1, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol6.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 2, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol6.bonds ) def test_init_pdb(bb_dir): mol0 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.pdb'), functional_groups=['amine'] ) # Test that all values are initialized correctly. assert len(mol0.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol0.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol0.atoms) == 15 assert len(mol0.bonds) == 14 atom_count = { (stk.H, 0): 10, (stk.N, 0): 2, (stk.C, 0): 3 } assert atom_count == Counter( (a.__class__, a.charge) for a in mol0.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol0.bonds ) # Test that caching is working properly. mol1 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.pdb'), functional_groups=['amine'] ) assert mol0 is not mol1 mol2 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.pdb'), functional_groups=['amine'], use_cache=True ) mol3 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.pdb'), functional_groups=['amine'], use_cache=True ) assert mol0 is not mol2 and mol1 is not mol2 assert mol2 is mol3 mol4 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'neutral.pdb'), functional_groups=['aldehyde'], use_cache=True ) assert mol3 is not mol4 # Make sure that charged molecules are handled correctly. mol5 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'negative_carbon.pdb'), functional_groups=['amine'], use_cache=True ) assert mol5 is not mol0 # Test that all values are initialized correctly. assert len(mol5.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol5.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol5.atoms) == 13 assert len(mol5.bonds) == 12 atom_count = { (stk.C, 0): 2, (stk.C, -1): 1, (stk.N, 0): 2, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol5.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 4 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol5.bonds ) mol6 = stk.BuildingBlock.init_from_file( path=join(bb_dir, 'negative_nitrogen.pdb'), functional_groups=['amine'], use_cache=True ) assert mol6 is not mol5 and mol6 is not mol0 # Test that all values are initialized correctly. assert len(mol6.func_groups) == 1 fg_types = stk.dedupe(fg.fg_type.name for fg in mol6.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol6.atoms) == 13 assert len(mol6.bonds) == 12 atom_count = { (stk.C, 0): 3, (stk.N, 0): 1, (stk.N, -1): 1, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol6.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 2, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol6.bonds ) def test_init_from_random_file(bb_dir): mol0 = stk.BuildingBlock.init_from_random_file( file_glob=join(bb_dir, 'neutral.mol'), functional_groups=['amine'] ) # Test that all values are initialized correctly. assert len(mol0.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol0.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol0.atoms) == 15 assert len(mol0.bonds) == 14 atom_count = { (stk.H, 0): 10, (stk.N, 0): 2, (stk.C, 0): 3 } assert atom_count == Counter( (a.__class__, a.charge) for a in mol0.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol0.bonds ) # Test that caching is working properly. mol1 = stk.BuildingBlock.init_from_random_file( file_glob=join(bb_dir, 'neutral.mol'), functional_groups=['amine'] ) assert mol0 is not mol1 mol2 = stk.BuildingBlock.init_from_random_file( file_glob=join(bb_dir, 'neutral.mol'), functional_groups=['amine'], use_cache=True ) mol3 = stk.BuildingBlock.init_from_random_file( file_glob=join(bb_dir, 'neutral.mol'), functional_groups=['amine'], use_cache=True ) assert mol0 is not mol2 and mol1 is not mol2 assert mol2 is mol3 mol4 = stk.BuildingBlock.init_from_random_file( file_glob=join(bb_dir, 'neutral.mol'), functional_groups=['aldehyde'], use_cache=True ) assert mol3 is not mol4 # Make sure that charged molecules are handled correctly. mol5 = stk.BuildingBlock.init_from_random_file( file_glob=join(bb_dir, 'negative_carbon.mol'), functional_groups=['amine'], use_cache=True ) assert mol5 is not mol0 # Test that all values are initialized correctly. assert len(mol5.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol5.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol5.atoms) == 13 assert len(mol5.bonds) == 12 atom_count = { (stk.C, 0): 2, (stk.C, -1): 1, (stk.N, 0): 2, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol5.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 4 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol5.bonds ) mol6 = stk.BuildingBlock.init_from_random_file( file_glob=join(bb_dir, 'negative_nitrogen.mol'), functional_groups=['amine'], use_cache=True ) assert mol6 is not mol5 and mol6 is not mol0 # Test that all values are initialized correctly. assert len(mol6.func_groups) == 1 fg_types = stk.dedupe(fg.fg_type.name for fg in mol6.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol6.atoms) == 13 assert len(mol6.bonds) == 12 atom_count = { (stk.C, 0): 3, (stk.N, 0): 1, (stk.N, -1): 1, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol6.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 2, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol6.bonds ) def test_init_from_smiles(): mol0 = stk.BuildingBlock('NCCCN', ['amine']) # Test that all values are initialized correctly. assert len(mol0.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol0.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol0.atoms) == 15 assert len(mol0.bonds) == 14 atom_count = { (stk.H, 0): 10, (stk.N, 0): 2, (stk.C, 0): 3 } assert atom_count == Counter( (a.__class__, a.charge) for a in mol0.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol0.bonds ) # Test that caching is working properly. mol1 = stk.BuildingBlock('NCCCN', ['amine']) assert mol0 is not mol1 mol2 = stk.BuildingBlock( smiles='NCCCN', functional_groups=['amine'], use_cache=True ) mol3 = stk.BuildingBlock( smiles='NCCCN', functional_groups=['amine'], use_cache=True ) assert mol0 is not mol2 and mol1 is not mol2 assert mol2 is mol3 mol4 = stk.BuildingBlock( smiles='NCCCN', functional_groups=['aldehyde'], use_cache=True ) assert mol3 is not mol4 # Make sure that charged molecules are handled correctly. mol5 = stk.BuildingBlock( smiles='NC[C-]CN', functional_groups=['amine'], use_cache=True ) assert mol5 is not mol0 # Test that all values are initialized correctly. assert len(mol5.func_groups) == 2 fg_types = stk.dedupe(fg.fg_type.name for fg in mol5.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol5.atoms) == 13 assert len(mol5.bonds) == 12 atom_count = { (stk.C, 0): 2, (stk.C, -1): 1, (stk.N, 0): 2, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol5.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 4, frozenset({stk.H, stk.C}): 4, } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol5.bonds ) mol6 = stk.BuildingBlock( smiles='[N-]CCCN', functional_groups=['amine'], use_cache=True ) assert mol6 is not mol5 and mol6 is not mol0 # Test that all values are initialized correctly. assert len(mol6.func_groups) == 1 fg_types = stk.dedupe(fg.fg_type.name for fg in mol6.func_groups) assert sum(1 for _ in fg_types) == 1 assert len(mol6.atoms) == 13 assert len(mol6.bonds) == 12 atom_count = { (stk.C, 0): 3, (stk.N, 0): 1, (stk.N, -1): 1, (stk.H, 0): 8, } assert atom_count == Counter( (a.__class__, a.charge) for a in mol6.atoms ) expected_bonds = { frozenset({stk.N, stk.C}): 2, frozenset({stk.C}): 2, frozenset({stk.H, stk.N}): 2, frozenset({stk.H, stk.C}): 6 } assert expected_bonds == Counter( frozenset({b.atom1.__class__, b.atom2.__class__}) for b in mol6.bonds ) def test_get_bonder_ids(aldehyde3): # Make sure that by default all bonder ids are yielded. all_ids = [] for func_group in aldehyde3.func_groups: all_ids.extend(func_group.get_bonder_ids()) all_ids.sort() default_ids = sorted(aldehyde3.get_bonder_ids()) assert default_ids == all_ids # Make sure that providing all fg ids explicitly is the same # as default behaviour. fg_ids = range(len(aldehyde3.func_groups)) explicit_ids = sorted(aldehyde3.get_bonder_ids(fg_ids=fg_ids)) assert default_ids == explicit_ids # Make sure when providing a subset of fg ids, only those are # returned. subset_ids = [] fgs = [aldehyde3.func_groups[0], aldehyde3.func_groups[2]] for func_group in fgs: subset_ids.extend(func_group.get_bonder_ids()) subset_ids.sort() returned_subset_ids = sorted( aldehyde3.get_bonder_ids(fg_ids=[0, 2]) ) assert returned_subset_ids == subset_ids def test_get_bonder_centroids(tmp_aldehyde3): # Set the position of all bonder atoms to (0, 0, 0). bonder_ids = list(tmp_aldehyde3.get_bonder_ids()) coords = tmp_aldehyde3.get_position_matrix() coords[bonder_ids, :] = np.zeros((len(bonder_ids), 3)) tmp_aldehyde3.set_position_matrix(coords) # Check that the bonder centroids are all at (0, 0, 0). for i, centroid in enumerate(tmp_aldehyde3.get_bonder_centroids()): assert np.allclose(centroid, [0, 0, 0], 1e-6) assert i == 2 # Set the position of the bonder atoms in functional groups 1 and 2 # to (1, 1, 1). fg_ids = [1, 2] bonder_ids = list(tmp_aldehyde3.get_bonder_ids(fg_ids=fg_ids)) coords[bonder_ids, :] = np.ones((len(bonder_ids), 3)) tmp_aldehyde3.set_position_matrix(coords) # Check that the bonder centroids of functional groups 1 and 2 are # at (1, 1, 1). centroids = tmp_aldehyde3.get_bonder_centroids(fg_ids=[1, 2]) for i, centroid in enumerate(centroids): assert np.allclose(centroid, [1, 1, 1], 1e-6) assert i == 1 # Check that the bonder centroid of functional group 0 is still at # (0, 0, 0). centroids = tmp_aldehyde3.get_bonder_centroids(fg_ids=[0]) for i, centroid in enumerate(centroids): assert np.allclose(centroid, [0, 0, 0], 1e-6) assert i == 0 def test_get_bonder_plane(tmp_amine4): # First check that when 3 fgs are used, the bonder centroids all # sit on the plane. for fg_ids in it.combinations(range(4), 3): a, b, c, d = tmp_amine4.get_bonder_plane(fg_ids=fg_ids) for x, y, z in tmp_amine4.get_bonder_centroids(fg_ids=fg_ids): product = a*x + b*y + c*z assert abs(product-d) < 1e-6 # When 4 are used make sure that a best fit plane is produced. # Ensure that centroids are placed such that the plane of best fit # Goes through two of the centroids and is equidistant from the # other two. bonder_ids = list(tmp_amine4.get_bonder_ids()) coords = tmp_amine4.get_position_matrix() coords[bonder_ids[0]] = [1, 1, 0] coords[bonder_ids[1]] = [0, 0, 0.5] coords[bonder_ids[2]] = [0, 0, -0.5] coords[bonder_ids[3]] = [1, -1, 0] tmp_amine4.set_position_matrix(coords) a, b, c, d = tmp_amine4.get_bonder_plane() for x, y, z in tmp_amine4.get_bonder_centroids(fg_ids=[0, 3]): product = a*x + b*y + c*z assert abs(product-d) < 1e-6 for x, y, z in tmp_amine4.get_bonder_centroids(fg_ids=[1, 2]): product = a*x + b*y + c*z assert abs(0.5 - abs(product-d)) < 1e-6 def test_get_bonder_plane_normal(tmp_amine4): bonder_ids = list(tmp_amine4.get_bonder_ids()) other_ids = [ id_ for id_ in range(len(tmp_amine4.atoms)) if id_ not in bonder_ids ] coords = tmp_amine4.get_position_matrix() coords[bonder_ids[0]] = [1, 1, 0] coords[bonder_ids[1]] = [0, 0, 0.5] coords[bonder_ids[2]] = [0, 0, -0.5] coords[bonder_ids[3]] = [1, -1, 0] # Set the centroid of the molecule so that the plane normal # has a positive direction. coords[other_ids, 2] = 10 tmp_amine4.set_position_matrix(coords) assert np.allclose( a=tmp_amine4.get_bonder_plane_normal(), b=[0, 0, 1], atol=1e-6 ) def test_get_bonder_distances(tmp_amine4): # Place all bonders on a line. coords = tmp_amine4.get_position_matrix() for bonder_id in tmp_amine4.get_bonder_ids(): coords[bonder_id] = [bonder_id, 0, 0] tmp_amine4.set_position_matrix(coords) # Test default behaviour. distances = tmp_amine4.get_bonder_distances() for i, (fg1, fg2, distance) in enumerate(distances): coord1 = tmp_amine4.func_groups[fg1].bonders[0].id coord2 = tmp_amine4.func_groups[fg2].bonders[0].id assert abs(distance - abs(coord1 - coord2)) < 1e-6 assert i == 5 # Test explicilty setting fg_ids. distances = tmp_amine4.get_bonder_distances(fg_ids=[0, 2, 3]) for i, (fg1, fg2, distance) in enumerate(distances): coord1 = tmp_amine4.func_groups[fg1].bonders[0].id coord2 = tmp_amine4.func_groups[fg2].bonders[0].id assert abs(distance - abs(coord1 - coord2)) < 1e-6 assert i == 2 def test_get_bonder_direction_vectors(tmp_amine4): pos_mat = tmp_amine4.get_position_matrix() # Set the coordinate of each bonder to the id of the fg. for fg_id, fg in enumerate(tmp_amine4.func_groups): for bonder in fg.get_bonder_ids(): pos_mat[bonder] = [fg_id, fg_id, fg_id] tmp_amine4.set_position_matrix(pos_mat) dir_vectors = tmp_amine4.get_bonder_direction_vectors() for i, (id1, id2, v) in enumerate(dir_vectors): # Calculate the expected direction vector based on ids. d = stk.normalize_vector(np.array([id2]*3) - np.array([id1]*3)) assert np.allclose(d, stk.normalize_vector(v), atol=1e-8) assert i == 5 # Test explicitly setting fg_ids. dir_vectors = tmp_amine4.get_bonder_direction_vectors( fg_ids=[0, 3] ) for i, (id1, id2, v) in enumerate(dir_vectors): # Calculate the expected direction vector based on ids. d = stk.normalize_vector(np.array([id2]*3) - np.array([id1]*3)) assert np.allclose(d, stk.normalize_vector(v), atol=1e-8) assert i == 0 def test_get_centroid_centroid_direction_vector(tmp_amine4): bonder_ids = list(tmp_amine4.get_bonder_ids()) other_ids = [ id_ for id_ in range(len(tmp_amine4.atoms)) if id_ not in bonder_ids ] coords = tmp_amine4.get_position_matrix() for bonder_id in bonder_ids: coords[bonder_id] = [10, 0, 0] coords[other_ids] = np.zeros((len(other_ids), 3)) tmp_amine4.set_position_matrix(coords) dir_vector = tmp_amine4.get_centroid_centroid_direction_vector() assert np.allclose( a=stk.normalize_vector(dir_vector), b=[-1, 0, 0], atol=1e-8 ) # Test explicitly setting the fg_ids. fg_ids = [0, 2] for bonder_id in tmp_amine4.get_bonder_ids(fg_ids=fg_ids): coords[bonder_id] = [-100, 0, 0] tmp_amine4.set_position_matrix(coords) dir_vector = tmp_amine4.get_centroid_centroid_direction_vector( fg_ids=fg_ids ) assert np.allclose( a=stk.normalize_vector(dir_vector), b=[1, 0, 0], atol=1e-8 ) def test_get_identity_key(amine2, amine2_conf1, amine2_alt1): assert amine2.get_identity_key() == amine2_conf1.get_identity_key() assert amine2.get_identity_key() != amine2_alt1.get_identity_key() def test_dump_and_load(tmp_amine2): path = os.path.join('building_block_tests_output', 'mol.dump') tmp_amine2.test_attr1 = 'something' tmp_amine2.test_attr2 = 12 tmp_amine2.test_attr3 = ['12', 'something', 21] tmp_amine2.test_attr4 = 'skip' include_attrs = ['test_attr1', 'test_attr2', 'test_attr3'] # Add some custom atom properties. tmp_amine2.atoms[0].some_prop = 'custom atom prop' tmp_amine2.dump(path, include_attrs) mol2 = stk.Molecule.load(path) assert tmp_amine2 is not mol2 fgs = it.zip_longest(mol2.func_groups, tmp_amine2.func_groups) for fg1, fg2 in fgs: atoms = it.zip_longest(fg1.atoms, fg2.atoms) bonders = it.zip_longest(fg1.bonders, fg2.bonders) deleters = it.zip_longest(fg1.deleters, fg2.deleters) for a1, a2 in it.chain(atoms, bonders, deleters): assert a1.__class__ is a2.__class__ assert a1.id == a2.id assert tmp_amine2.test_attr1 == mol2.test_attr1 assert tmp_amine2.test_attr2 == mol2.test_attr2 assert tmp_amine2.test_attr3 == mol2.test_attr3 assert not hasattr(mol2, 'test_attr4') for a1, a2 in zip(tmp_amine2.atoms, mol2.atoms): assert vars(a1) == vars(a2) mol3 = stk.Molecule.load(path, use_cache=True) assert mol3 is not mol2 mol4 = stk.Molecule.load(path, use_cache=True) assert mol3 is mol4
[ "itertools.chain", "os.path.exists", "numpy.allclose", "rdkit.Chem.AllChem.MolFromSmiles", "stk.Molecule.load", "os.path.join", "itertools.zip_longest", "collections.Counter", "stk.BuildingBlock", "numpy.array", "os.mkdir", "stk.normalize_vector", "stk.dedupe", "stk.BuildingBlock.init_from...
[((164, 209), 'os.path.exists', 'os.path.exists', (['"""building_block_tests_output"""'], {}), "('building_block_tests_output')\n", (178, 209), False, 'import os\n'), ((215, 254), 'os.mkdir', 'os.mkdir', (['"""building_block_tests_output"""'], {}), "('building_block_tests_output')\n", (223, 254), False, 'import os\n'), ((402, 461), 'stk.BuildingBlock.init_from_rdkit_mol', 'stk.BuildingBlock.init_from_rdkit_mol', (['rdkit_mol', "['amine']"], {}), "(rdkit_mol, ['amine'])\n", (439, 461), False, 'import stk\n'), ((569, 623), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol0.func_groups)'], {}), '(fg.fg_type.name for fg in mol0.func_groups)\n', (579, 623), False, 'import stk\n'), ((1279, 1338), 'stk.BuildingBlock.init_from_rdkit_mol', 'stk.BuildingBlock.init_from_rdkit_mol', (['rdkit_mol', "['amine']"], {}), "(rdkit_mol, ['amine'])\n", (1316, 1338), False, 'import stk\n'), ((1379, 1481), 'stk.BuildingBlock.init_from_rdkit_mol', 'stk.BuildingBlock.init_from_rdkit_mol', ([], {'mol': 'rdkit_mol', 'functional_groups': "['amine']", 'use_cache': '(True)'}), "(mol=rdkit_mol, functional_groups=[\n 'amine'], use_cache=True)\n", (1416, 1481), False, 'import stk\n'), ((1518, 1620), 'stk.BuildingBlock.init_from_rdkit_mol', 'stk.BuildingBlock.init_from_rdkit_mol', ([], {'mol': 'rdkit_mol', 'functional_groups': "['amine']", 'use_cache': '(True)'}), "(mol=rdkit_mol, functional_groups=[\n 'amine'], use_cache=True)\n", (1555, 1620), False, 'import stk\n'), ((1731, 1836), 'stk.BuildingBlock.init_from_rdkit_mol', 'stk.BuildingBlock.init_from_rdkit_mol', ([], {'mol': 'rdkit_mol', 'functional_groups': "['aldehyde']", 'use_cache': '(True)'}), "(mol=rdkit_mol, functional_groups=[\n 'aldehyde'], use_cache=True)\n", (1768, 1836), False, 'import stk\n'), ((2090, 2197), 'stk.BuildingBlock.init_from_rdkit_mol', 'stk.BuildingBlock.init_from_rdkit_mol', ([], {'mol': 'negative_carbon', 'functional_groups': "['amine']", 'use_cache': '(True)'}), "(mol=negative_carbon,\n functional_groups=['amine'], use_cache=True)\n", (2127, 2197), False, 'import stk\n'), ((2359, 2413), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol5.func_groups)'], {}), '(fg.fg_type.name for fg in mol5.func_groups)\n', (2369, 2413), False, 'import stk\n'), ((3178, 3287), 'stk.BuildingBlock.init_from_rdkit_mol', 'stk.BuildingBlock.init_from_rdkit_mol', ([], {'mol': 'negative_nitrogen', 'functional_groups': "['amine']", 'use_cache': '(True)'}), "(mol=negative_nitrogen,\n functional_groups=['amine'], use_cache=True)\n", (3215, 3287), False, 'import stk\n'), ((3470, 3524), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol6.func_groups)'], {}), '(fg.fg_type.name for fg in mol6.func_groups)\n', (3480, 3524), False, 'import stk\n'), ((4412, 4466), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol0.func_groups)'], {}), '(fg.fg_type.name for fg in mol0.func_groups)\n', (4422, 4466), False, 'import stk\n'), ((6192, 6246), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol5.func_groups)'], {}), '(fg.fg_type.name for fg in mol5.func_groups)\n', (6202, 6246), False, 'import stk\n'), ((7189, 7243), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol6.func_groups)'], {}), '(fg.fg_type.name for fg in mol6.func_groups)\n', (7199, 7243), False, 'import stk\n'), ((8131, 8185), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol0.func_groups)'], {}), '(fg.fg_type.name for fg in mol0.func_groups)\n', (8141, 8185), False, 'import stk\n'), ((9911, 9965), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol5.func_groups)'], {}), '(fg.fg_type.name for fg in mol5.func_groups)\n', (9921, 9965), False, 'import stk\n'), ((10908, 10962), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol6.func_groups)'], {}), '(fg.fg_type.name for fg in mol6.func_groups)\n', (10918, 10962), False, 'import stk\n'), ((11875, 11929), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol0.func_groups)'], {}), '(fg.fg_type.name for fg in mol0.func_groups)\n', (11885, 11929), False, 'import stk\n'), ((13715, 13769), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol5.func_groups)'], {}), '(fg.fg_type.name for fg in mol5.func_groups)\n', (13725, 13769), False, 'import stk\n'), ((14724, 14778), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol6.func_groups)'], {}), '(fg.fg_type.name for fg in mol6.func_groups)\n', (14734, 14778), False, 'import stk\n'), ((15443, 15480), 'stk.BuildingBlock', 'stk.BuildingBlock', (['"""NCCCN"""', "['amine']"], {}), "('NCCCN', ['amine'])\n", (15460, 15480), False, 'import stk\n'), ((15588, 15642), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol0.func_groups)'], {}), '(fg.fg_type.name for fg in mol0.func_groups)\n', (15598, 15642), False, 'import stk\n'), ((16298, 16335), 'stk.BuildingBlock', 'stk.BuildingBlock', (['"""NCCCN"""', "['amine']"], {}), "('NCCCN', ['amine'])\n", (16315, 16335), False, 'import stk\n'), ((16376, 16454), 'stk.BuildingBlock', 'stk.BuildingBlock', ([], {'smiles': '"""NCCCN"""', 'functional_groups': "['amine']", 'use_cache': '(True)'}), "(smiles='NCCCN', functional_groups=['amine'], use_cache=True)\n", (16393, 16454), False, 'import stk\n'), ((16496, 16574), 'stk.BuildingBlock', 'stk.BuildingBlock', ([], {'smiles': '"""NCCCN"""', 'functional_groups': "['amine']", 'use_cache': '(True)'}), "(smiles='NCCCN', functional_groups=['amine'], use_cache=True)\n", (16513, 16574), False, 'import stk\n'), ((16690, 16776), 'stk.BuildingBlock', 'stk.BuildingBlock', ([], {'smiles': '"""NCCCN"""', 'functional_groups': "['aldehyde']", 'use_cache': '(True)'}), "(smiles='NCCCN', functional_groups=['aldehyde'], use_cache\n =True)\n", (16707, 16776), False, 'import stk\n'), ((16904, 16990), 'stk.BuildingBlock', 'stk.BuildingBlock', ([], {'smiles': '"""NC[C-]CN"""', 'functional_groups': "['amine']", 'use_cache': '(True)'}), "(smiles='NC[C-]CN', functional_groups=['amine'], use_cache\n =True)\n", (16921, 16990), False, 'import stk\n'), ((17151, 17205), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol5.func_groups)'], {}), '(fg.fg_type.name for fg in mol5.func_groups)\n', (17161, 17205), False, 'import stk\n'), ((17841, 17927), 'stk.BuildingBlock', 'stk.BuildingBlock', ([], {'smiles': '"""[N-]CCCN"""', 'functional_groups': "['amine']", 'use_cache': '(True)'}), "(smiles='[N-]CCCN', functional_groups=['amine'], use_cache\n =True)\n", (17858, 17927), False, 'import stk\n'), ((18109, 18163), 'stk.dedupe', 'stk.dedupe', (['(fg.fg_type.name for fg in mol6.func_groups)'], {}), '(fg.fg_type.name for fg in mol6.func_groups)\n', (18119, 18163), False, 'import stk\n'), ((26391, 26446), 'os.path.join', 'os.path.join', (['"""building_block_tests_output"""', '"""mol.dump"""'], {}), "('building_block_tests_output', 'mol.dump')\n", (26403, 26446), False, 'import os\n'), ((26817, 26840), 'stk.Molecule.load', 'stk.Molecule.load', (['path'], {}), '(path)\n', (26834, 26840), False, 'import stk\n'), ((26887, 26943), 'itertools.zip_longest', 'it.zip_longest', (['mol2.func_groups', 'tmp_amine2.func_groups'], {}), '(mol2.func_groups, tmp_amine2.func_groups)\n', (26901, 26943), True, 'import itertools as it\n'), ((27584, 27623), 'stk.Molecule.load', 'stk.Molecule.load', (['path'], {'use_cache': '(True)'}), '(path, use_cache=True)\n', (27601, 27623), False, 'import stk\n'), ((27663, 27702), 'stk.Molecule.load', 'stk.Molecule.load', (['path'], {'use_cache': '(True)'}), '(path, use_cache=True)\n', (27680, 27702), False, 'import stk\n'), ((308, 336), 'rdkit.Chem.AllChem.MolFromSmiles', 'rdkit.MolFromSmiles', (['"""NCCCN"""'], {}), "('NCCCN')\n", (327, 336), True, 'import rdkit.Chem.AllChem as rdkit\n'), ((373, 388), 'rdkit.Chem.AllChem.ETKDGv2', 'rdkit.ETKDGv2', ([], {}), '()\n', (386, 388), True, 'import rdkit.Chem.AllChem as rdkit\n'), ((851, 903), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol0.atoms)'], {}), '((a.__class__, a.charge) for a in mol0.atoms)\n', (858, 903), False, 'from collections import Counter\n'), ((1987, 2018), 'rdkit.Chem.AllChem.MolFromSmiles', 'rdkit.MolFromSmiles', (['"""NC[C-]CN"""'], {}), "('NC[C-]CN')\n", (2006, 2018), True, 'import rdkit.Chem.AllChem as rdkit\n'), ((2061, 2076), 'rdkit.Chem.AllChem.ETKDGv2', 'rdkit.ETKDGv2', ([], {}), '()\n', (2074, 2076), True, 'import rdkit.Chem.AllChem as rdkit\n'), ((2665, 2717), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol5.atoms)'], {}), '((a.__class__, a.charge) for a in mol5.atoms)\n', (2672, 2717), False, 'from collections import Counter\n'), ((3073, 3104), 'rdkit.Chem.AllChem.MolFromSmiles', 'rdkit.MolFromSmiles', (['"""[N-]CCCN"""'], {}), "('[N-]CCCN')\n", (3092, 3104), True, 'import rdkit.Chem.AllChem as rdkit\n'), ((3149, 3164), 'rdkit.Chem.AllChem.ETKDGv2', 'rdkit.ETKDGv2', ([], {}), '()\n', (3162, 3164), True, 'import rdkit.Chem.AllChem as rdkit\n'), ((3776, 3828), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol6.atoms)'], {}), '((a.__class__, a.charge) for a in mol6.atoms)\n', (3783, 3828), False, 'from collections import Counter\n'), ((4694, 4746), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol0.atoms)'], {}), '((a.__class__, a.charge) for a in mol0.atoms)\n', (4701, 4746), False, 'from collections import Counter\n'), ((6498, 6550), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol5.atoms)'], {}), '((a.__class__, a.charge) for a in mol5.atoms)\n', (6505, 6550), False, 'from collections import Counter\n'), ((7495, 7547), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol6.atoms)'], {}), '((a.__class__, a.charge) for a in mol6.atoms)\n', (7502, 7547), False, 'from collections import Counter\n'), ((8413, 8465), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol0.atoms)'], {}), '((a.__class__, a.charge) for a in mol0.atoms)\n', (8420, 8465), False, 'from collections import Counter\n'), ((10217, 10269), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol5.atoms)'], {}), '((a.__class__, a.charge) for a in mol5.atoms)\n', (10224, 10269), False, 'from collections import Counter\n'), ((11214, 11266), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol6.atoms)'], {}), '((a.__class__, a.charge) for a in mol6.atoms)\n', (11221, 11266), False, 'from collections import Counter\n'), ((12157, 12209), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol0.atoms)'], {}), '((a.__class__, a.charge) for a in mol0.atoms)\n', (12164, 12209), False, 'from collections import Counter\n'), ((14021, 14073), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol5.atoms)'], {}), '((a.__class__, a.charge) for a in mol5.atoms)\n', (14028, 14073), False, 'from collections import Counter\n'), ((15030, 15082), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol6.atoms)'], {}), '((a.__class__, a.charge) for a in mol6.atoms)\n', (15037, 15082), False, 'from collections import Counter\n'), ((15870, 15922), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol0.atoms)'], {}), '((a.__class__, a.charge) for a in mol0.atoms)\n', (15877, 15922), False, 'from collections import Counter\n'), ((17457, 17509), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol5.atoms)'], {}), '((a.__class__, a.charge) for a in mol5.atoms)\n', (17464, 17509), False, 'from collections import Counter\n'), ((18415, 18467), 'collections.Counter', 'Counter', (['((a.__class__, a.charge) for a in mol6.atoms)'], {}), '((a.__class__, a.charge) for a in mol6.atoms)\n', (18422, 18467), False, 'from collections import Counter\n'), ((20215, 20254), 'numpy.allclose', 'np.allclose', (['centroid', '[0, 0, 0]', '(1e-06)'], {}), '(centroid, [0, 0, 0], 1e-06)\n', (20226, 20254), True, 'import numpy as np\n'), ((20773, 20812), 'numpy.allclose', 'np.allclose', (['centroid', '[1, 1, 1]', '(1e-06)'], {}), '(centroid, [1, 1, 1], 1e-06)\n', (20784, 20812), True, 'import numpy as np\n'), ((21041, 21080), 'numpy.allclose', 'np.allclose', (['centroid', '[0, 0, 0]', '(1e-06)'], {}), '(centroid, [0, 0, 0], 1e-06)\n', (21052, 21080), True, 'import numpy as np\n'), ((26985, 27021), 'itertools.zip_longest', 'it.zip_longest', (['fg1.atoms', 'fg2.atoms'], {}), '(fg1.atoms, fg2.atoms)\n', (26999, 27021), True, 'import itertools as it\n'), ((27040, 27080), 'itertools.zip_longest', 'it.zip_longest', (['fg1.bonders', 'fg2.bonders'], {}), '(fg1.bonders, fg2.bonders)\n', (27054, 27080), True, 'import itertools as it\n'), ((27100, 27142), 'itertools.zip_longest', 'it.zip_longest', (['fg1.deleters', 'fg2.deleters'], {}), '(fg1.deleters, fg2.deleters)\n', (27114, 27142), True, 'import itertools as it\n'), ((27165, 27199), 'itertools.chain', 'it.chain', (['atoms', 'bonders', 'deleters'], {}), '(atoms, bonders, deleters)\n', (27173, 27199), True, 'import itertools as it\n'), ((4234, 4261), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (4238, 4261), False, 'from os.path import join\n'), ((5169, 5196), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (5173, 5196), False, 'from os.path import join\n'), ((5327, 5354), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (5331, 5354), False, 'from os.path import join\n'), ((5480, 5507), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (5484, 5507), False, 'from os.path import join\n'), ((5707, 5734), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (5711, 5734), False, 'from os.path import join\n'), ((5954, 5989), 'os.path.join', 'join', (['bb_dir', '"""negative_carbon.mol"""'], {}), "(bb_dir, 'negative_carbon.mol')\n", (5958, 5989), False, 'from os.path import join\n'), ((6928, 6965), 'os.path.join', 'join', (['bb_dir', '"""negative_nitrogen.mol"""'], {}), "(bb_dir, 'negative_nitrogen.mol')\n", (6932, 6965), False, 'from os.path import join\n'), ((7953, 7980), 'os.path.join', 'join', (['bb_dir', '"""neutral.pdb"""'], {}), "(bb_dir, 'neutral.pdb')\n", (7957, 7980), False, 'from os.path import join\n'), ((8888, 8915), 'os.path.join', 'join', (['bb_dir', '"""neutral.pdb"""'], {}), "(bb_dir, 'neutral.pdb')\n", (8892, 8915), False, 'from os.path import join\n'), ((9046, 9073), 'os.path.join', 'join', (['bb_dir', '"""neutral.pdb"""'], {}), "(bb_dir, 'neutral.pdb')\n", (9050, 9073), False, 'from os.path import join\n'), ((9199, 9226), 'os.path.join', 'join', (['bb_dir', '"""neutral.pdb"""'], {}), "(bb_dir, 'neutral.pdb')\n", (9203, 9226), False, 'from os.path import join\n'), ((9426, 9453), 'os.path.join', 'join', (['bb_dir', '"""neutral.pdb"""'], {}), "(bb_dir, 'neutral.pdb')\n", (9430, 9453), False, 'from os.path import join\n'), ((9673, 9708), 'os.path.join', 'join', (['bb_dir', '"""negative_carbon.pdb"""'], {}), "(bb_dir, 'negative_carbon.pdb')\n", (9677, 9708), False, 'from os.path import join\n'), ((10647, 10684), 'os.path.join', 'join', (['bb_dir', '"""negative_nitrogen.pdb"""'], {}), "(bb_dir, 'negative_nitrogen.pdb')\n", (10651, 10684), False, 'from os.path import join\n'), ((11697, 11724), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (11701, 11724), False, 'from os.path import join\n'), ((12644, 12671), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (12648, 12671), False, 'from os.path import join\n'), ((12814, 12841), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (12818, 12841), False, 'from os.path import join\n'), ((12979, 13006), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (12983, 13006), False, 'from os.path import join\n'), ((13218, 13245), 'os.path.join', 'join', (['bb_dir', '"""neutral.mol"""'], {}), "(bb_dir, 'neutral.mol')\n", (13222, 13245), False, 'from os.path import join\n'), ((13477, 13512), 'os.path.join', 'join', (['bb_dir', '"""negative_carbon.mol"""'], {}), "(bb_dir, 'negative_carbon.mol')\n", (13481, 13512), False, 'from os.path import join\n'), ((14463, 14500), 'os.path.join', 'join', (['bb_dir', '"""negative_nitrogen.mol"""'], {}), "(bb_dir, 'negative_nitrogen.mol')\n", (14467, 14500), False, 'from os.path import join\n'), ((24640, 24663), 'stk.normalize_vector', 'stk.normalize_vector', (['v'], {}), '(v)\n', (24660, 24663), False, 'import stk\n'), ((25038, 25061), 'stk.normalize_vector', 'stk.normalize_vector', (['v'], {}), '(v)\n', (25058, 25061), False, 'import stk\n'), ((25635, 25667), 'stk.normalize_vector', 'stk.normalize_vector', (['dir_vector'], {}), '(dir_vector)\n', (25655, 25667), False, 'import stk\n'), ((26056, 26088), 'stk.normalize_vector', 'stk.normalize_vector', (['dir_vector'], {}), '(dir_vector)\n', (26076, 26088), False, 'import stk\n'), ((24571, 24590), 'numpy.array', 'np.array', (['([id2] * 3)'], {}), '([id2] * 3)\n', (24579, 24590), True, 'import numpy as np\n'), ((24591, 24610), 'numpy.array', 'np.array', (['([id1] * 3)'], {}), '([id1] * 3)\n', (24599, 24610), True, 'import numpy as np\n'), ((24969, 24988), 'numpy.array', 'np.array', (['([id2] * 3)'], {}), '([id2] * 3)\n', (24977, 24988), True, 'import numpy as np\n'), ((24989, 25008), 'numpy.array', 'np.array', (['([id1] * 3)'], {}), '([id1] * 3)\n', (24997, 25008), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import os import copy # BEGIN THREAD SETTINGS this sets the number of threads used by numpy in the program (should be set to 1 for Parts 1 and 3) implicit_num_threads = 2 os.environ["OMP_NUM_THREADS"] = str(implicit_num_threads) os.environ["MKL_NUM_THREADS"] = str(implicit_num_threads) os.environ["OPENBLAS_NUM_THREADS"] = str(implicit_num_threads) # END THREAD SETTINGS import pickle import numpy as np import numpy from numpy import random import scipy import matplotlib import mnist import pickle matplotlib.use('agg') from matplotlib import pyplot as plt import threading import time from scipy.special import softmax from tqdm import tqdm mnist_data_directory = os.path.join(os.path.dirname(__file__), "data") # TODO add any additional imports and global variables # SOME UTILITY FUNCTIONS that you may find to be useful, from my PA3 implementation # feel free to use your own implementation instead if you prefer def multinomial_logreg_error(Xs, Ys, W): predictions = numpy.argmax(numpy.dot(W, Xs), axis=0) error = numpy.mean(predictions != numpy.argmax(Ys, axis=0)) return error def multinomial_logreg_grad_i(Xs, Ys, ii, gamma, W, dtype=np.float64): WdotX = numpy.dot(W, Xs[:,ii]) expWdotX = numpy.exp(WdotX - numpy.amax(WdotX, axis=0), dtype=dtype) softmaxWdotX = expWdotX / numpy.sum(expWdotX, axis=0, dtype=dtype) return numpy.dot(softmaxWdotX - Ys[:,ii], Xs[:,ii].transpose()) / len(ii) + gamma * W # END UTILITY FUNCTIONS def load_MNIST_dataset(): PICKLE_FILE = os.path.join(mnist_data_directory, "MNIST.pickle") try: dataset = pickle.load(open(PICKLE_FILE, 'rb')) except: # load the MNIST dataset mnist_data = mnist.MNIST(mnist_data_directory, return_type="numpy", gz=True) Xs_tr, Lbls_tr = mnist_data.load_training(); Xs_tr = Xs_tr.transpose() / 255.0 Ys_tr = numpy.zeros((10, 60000)) for i in range(60000): Ys_tr[Lbls_tr[i], i] = 1.0 # one-hot encode each label # shuffle the training data numpy.random.seed(4787) perm = numpy.random.permutation(60000) Xs_tr = numpy.ascontiguousarray(Xs_tr[:,perm]) Ys_tr = numpy.ascontiguousarray(Ys_tr[:,perm]) Xs_te, Lbls_te = mnist_data.load_testing(); Xs_te = Xs_te.transpose() / 255.0 Ys_te = numpy.zeros((10, 10000)) for i in range(10000): Ys_te[Lbls_te[i], i] = 1.0 # one-hot encode each label Xs_te = numpy.ascontiguousarray(Xs_te) Ys_te = numpy.ascontiguousarray(Ys_te) dataset = (Xs_tr, Ys_tr, Xs_te, Ys_te) pickle.dump(dataset, open(PICKLE_FILE, 'wb')) return dataset # SGD + Momentum (adapt from Programming Assignment 3) # # Xs training examples (d * n) # Ys training labels (c * n) # gamma L2 regularization constant # W0 the initial value of the parameters (c * d) # alpha step size/learning rate # beta momentum hyperparameter # B minibatch size # num_epochs number of epochs (passes through the training set) to run # # returns the final model arrived at at the end of training def sgd_mss_with_momentum(Xs, Ys, gamma, W0, alpha, beta, B, num_epochs): # TODO students should use their implementation from programming assignment 3 # or adapt this version, which is from my own solution to programming assignment 3 models = [] (d, n) = Xs.shape V = numpy.zeros(W0.shape) W = W0 # print("Running minibatch sequential-scan SGD with momentum") for it in tqdm(range(num_epochs)): for ibatch in range(int(n/B)): ii = range(ibatch*B, (ibatch+1)*B) V = beta * V - alpha * multinomial_logreg_grad_i(Xs, Ys, ii, gamma, W) W = W + V # if ((ibatch+1) % monitor_period == 0): # models.append(W) return models # SGD + Momentum (No Allocation) => all operations in the inner loop should be a # call to a numpy.____ function with the "out=" argument explicitly specified # so that no extra allocations occur # # Xs training examples (d * n) # Ys training labels (c * n) # gamma L2 regularization constant # W0 the initial value of the parameters (c * d) # alpha step size/learning rate # beta momentum hyperparameter # B minibatch size # num_epochs number of epochs (passes through the training set) to run # monitor_period how frequently, in terms of batches (not epochs) to output the parameter vector # # returns the final model arrived at at the end of training def sgd_mss_with_momentum_noalloc(Xs, Ys, gamma, W0, alpha, beta, B, num_epochs): (d, n) = Xs.shape (c, d) = W0.shape # TODO students should initialize the parameter vector W and pre-allocate any needed arrays here Y_temp = np.zeros((c,B)) W_temp = np.zeros(W0.shape) amax_temp = np.zeros(B) softmax_temp = np.zeros((c,B)) V = np.zeros(W0.shape) g = np.zeros(W0.shape) X_batch = [] Y_batch = [] for i in range(n // B): ii = [(i*B + j) for j in range(B)] X_batch.append(np.ascontiguousarray(Xs[:,ii])) Y_batch.append(np.ascontiguousarray(Ys[:,ii])) # print("Running minibatch sequential-scan SGD with momentum (no allocation)") for it in tqdm(range(num_epochs)): for i in range(int(n/B)): # ii = range(ibatch*B, (ibatch+1)*B) # TODO this section of code should only use numpy operations with the "out=" argument specified (students should implement this) np.matmul(W0, X_batch[i], out=Y_temp) # WdotX = numpy.dot(W0, Xs[:,ii]) # expWdotX = numpy.exp(WdotX - numpy.amax(WdotX, axis=0), dtype=dtype) # softmaxWdotX = expWdotX / numpy.sum(expWdotX, axis=0, dtype=dtype) np.amax(Y_temp, axis=0, out=amax_temp) np.subtract(Y_temp, amax_temp, out=softmax_temp) np.exp(softmax_temp, out=softmax_temp) np.sum(softmax_temp, axis=0, out=amax_temp) np.divide(softmax_temp, amax_temp, out=softmax_temp) # numpy.dot(softmaxWdotX - Ys[:,ii], Xs[:,ii].transpose()) / len(ii) + gamma * W np.subtract(softmax_temp, Y_batch[i], out=Y_temp) # Y_temp = softmax(Y_temp, axis=0) - Y_batch[i] np.matmul(Y_temp, X_batch[i].T, out=W_temp) np.divide(W_temp, B, out=W_temp) np.multiply(gamma, W0, out=g) np.add(W_temp, g, out=g) # g = W_temp / B + gamma * W0 np.multiply(V, beta, out=V) np.multiply(g, alpha, out=g) # V = (beta * V) - (alpha * g) np.subtract(V, g, out=V) np.add(V, W0, out=W0) # W0 = W0 + V return W0 # SGD + Momentum (threaded) # # Xs training examples (d * n) # Ys training labels (c * n) # gamma L2 regularization constant # W0 the initial value of the parameters (c * d) # alpha step size/learning rate # beta momentum hyperparameter # B minibatch size # num_epochs number of epochs (passes through the training set) to run # monitor_period how frequently, in terms of batches (not epochs) to output the parameter vector # num_threads how many threads to use # # returns the final model arrived at at the end of training def sgd_mss_with_momentum_threaded(Xs, Ys, gamma, W0, alpha, beta, B, num_epochs, num_threads): (d, n) = Xs.shape (c, d) = W0.shape # TODO perform any global setup/initialization/allocation (students should implement this) g = [W0 for i in range(num_threads)] Bt = B//num_threads W_temp1 = np.zeros(W0.shape) # construct the barrier object iter_barrier = threading.Barrier(num_threads + 1) # a function for each thread to run def thread_main(ithread): # TODO perform any per-thread allocations for it in range(num_epochs): W_temp = np.zeros(W0.shape) amax_temp = np.zeros(Bt) softmax_temp = np.zeros((c,Bt)) for ibatch in range(int(n/B)): # TODO work done by thread in each iteration; this section of code should primarily use numpy operations with the "out=" argument specified (students should implement this) ii = range(ibatch*B + ithread*Bt, ibatch*B + (ithread+1)*Bt) iter_barrier.wait() np.dot(g[ithread], Xs[:,ii], out=softmax_temp) np.amax(softmax_temp, axis=0, out=amax_temp) np.subtract(softmax_temp, amax_temp, out=softmax_temp) np.exp(softmax_temp, out=softmax_temp) np.sum(softmax_temp, axis=0, out=amax_temp) np.divide(softmax_temp, amax_temp, out=softmax_temp) np.subtract(softmax_temp, Ys[:,ii], out=softmax_temp) np.matmul(softmax_temp, Xs[:,ii].T, out=W_temp) np.divide(W_temp, B, out=W_temp) np.multiply(gamma, g[ithread], out=g[ithread]) np.add(W_temp, g[ithread], out=g[ithread]) # g[ithread] = multinomial_logreg_grad_i(Xs, Ys, ii, gamma, W0) iter_barrier.wait() worker_threads = [threading.Thread(target=thread_main, args=(it,)) for it in range(num_threads)] for t in worker_threads: print("running thread ", t) t.start() print("Running minibatch sequential-scan SGD with momentum (%d threads)" % num_threads) for it in tqdm(range(num_epochs)): for ibatch in range(int(n/B)): iter_barrier.wait() # TODO work done on a single thread at each iteration; this section of code should primarily use numpy operations with the "out=" argument specified (students should implement this) # W0 = W0 - alpha * (1/B) * np.sum(g) np.sum(g, axis=0, out=W_temp1) np.multiply(W_temp1, alpha/B, out=W_temp1) np.subtract(W0, W_temp1, out=W0) iter_barrier.wait() for t in worker_threads: t.join() # return the learned model return W0 # SGD + Momentum (No Allocation) in 32-bits => all operations in the inner loop should be a # call to a numpy.____ function with the "out=" argument explicitly specified # so that no extra allocations occur # # Xs training examples (d * n) # Ys training labels (c * n) # gamma L2 regularization constant # W0 the initial value of the parameters (c * d) # alpha step size/learning rate # beta momentum hyperparameter # B minibatch size # num_epochs number of epochs (passes through the training set) to run # monitor_period how frequently, in terms of batches (not epochs) to output the parameter vector # # returns the final model arrived at at the end of training def sgd_mss_with_momentum_noalloc_float32(Xs, Ys, gamma, W0, alpha, beta, B, num_epochs): Xs = Xs.astype(np.float32) Ys = Ys.astype(np.float32) W0 = W0.astype(np.float32) alpha = np.float32(alpha) gamma = np.float32(gamma) (d, n) = Xs.shape (c, d) = W0.shape # TODO students should initialize the parameter vector W and pre-allocate any needed arrays here Y_temp = np.zeros((c,B), dtype=np.float32) W_temp = np.zeros(W0.shape, dtype=np.float32) amax_temp = np.zeros((B,), dtype=np.float32) softmax_temp = np.zeros((c,B), dtype=np.float32) V = np.zeros(W0.shape, dtype=np.float32) g = np.zeros(W0.shape, dtype=np.float32) X_batch = [] Y_batch = [] for i in range(n // B): ii = [(i*B + j) for j in range(B)] X_batch.append(np.ascontiguousarray(Xs[:,ii], dtype=np.float32)) Y_batch.append(np.ascontiguousarray(Ys[:,ii], dtype=np.float32)) print("Running minibatch sequential-scan SGD with momentum (no allocation)") for it in tqdm(range(num_epochs)): for i in range(int(n/B)): # ii = range(ibatch*B, (ibatch+1)*B) # TODO this section of code should only use numpy operations with the "out=" argument specified (students should implement this) np.matmul(W0, X_batch[i], out=Y_temp).astype(numpy.float32) np.amax(Y_temp, axis=0, out=amax_temp).astype(numpy.float32) np.subtract(Y_temp, amax_temp, out=softmax_temp, dtype=np.float32) np.exp(softmax_temp, out=softmax_temp, dtype=np.float32) np.sum(softmax_temp, axis=0, out=amax_temp, dtype=np.float32) np.divide(softmax_temp, amax_temp, out=softmax_temp, dtype=np.float32) np.subtract(softmax_temp, Y_batch[i], out=Y_temp, dtype=np.float32) np.matmul(Y_temp, X_batch[i].T, out=W_temp, dtype=np.float32) np.divide(W_temp, B, out=W_temp, dtype=np.float32) np.multiply(gamma, W0, out=g, dtype=np.float32) np.add(W_temp, g, out=g, dtype=np.float32) np.multiply(V, beta, out=V, dtype=np.float32) np.multiply(g, alpha, out=g, dtype=np.float32) np.subtract(V, g, out=V, dtype=np.float32) np.add(V, W0, out=W0, dtype=np.float32) return W0 # SGD + Momentum (threaded, float32) # # Xs training examples (d * n) # Ys training labels (c * n) # gamma L2 regularization constant # W0 the initial value of the parameters (c * d) # alpha step size/learning rate # beta momentum hyperparameter # B minibatch size # num_epochs number of epochs (passes through the training set) to run # monitor_period how frequently, in terms of batches (not epochs) to output the parameter vector # num_threads how many threads to use # # returns the final model arrived at at the end of training def sgd_mss_with_momentum_threaded_float32(Xs, Ys, gamma, W0, alpha, beta, B, num_epochs, num_threads): Xs = Xs.astype(np.float32) Ys = Ys.astype(np.float32) W0 = W0.astype(np.float32) alpha = np.float32(alpha) gamma = np.float32(gamma) (d, n) = Xs.shape (c, d) = W0.shape # TODO perform any global setup/initialization/allocation (students should implement this) g = [W0 for i in range(num_threads)] Bt = B//num_threads W_temp1 = np.zeros(W0.shape).astype(np.float32) # amax_temp = np.zeros(Bt) # softmax_temp = np.zeros((c,Bt)) # construct the barrier object iter_barrier = threading.Barrier(num_threads + 1) # a function for each thread to run def thread_main(ithread): W_temp = np.zeros(W0.shape, dtype=np.float32) amax_temp = np.zeros((Bt,), dtype=np.float32) softmax_temp = np.zeros((c,Bt), dtype=np.float32) # TODO perform any per-thread allocations for it in range(num_epochs): for ibatch in range(int(n/B)): # TODO work done by thread in each iteration; this section of code should primarily use numpy operations with the "out=" argument specified (students should implement this) ii = range(ibatch*B + ithread*Bt, ibatch*B + (ithread+1)*Bt) iter_barrier.wait() np.dot(g[ithread], Xs[:,ii], out=softmax_temp).astype(np.float32) np.amax(softmax_temp, axis=0, out=amax_temp).astype(np.float32) np.subtract(softmax_temp, amax_temp, out=softmax_temp, dtype=np.float32) np.exp(softmax_temp, out=softmax_temp, dtype=np.float32) np.sum(softmax_temp, axis=0, out=amax_temp, dtype=np.float32) np.divide(softmax_temp, amax_temp, out=softmax_temp, dtype=np.float32) np.subtract(softmax_temp, Ys[:,ii], out=softmax_temp, dtype=np.float32) np.matmul(softmax_temp, Xs[:,ii].T, out=W_temp, dtype=np.float32) np.divide(W_temp, B, out=W_temp, dtype=np.float32) np.multiply(gamma, g[ithread], out=g[ithread], dtype=np.float32) np.add(W_temp, g[ithread], out=g[ithread], dtype=np.float32) iter_barrier.wait() worker_threads = [threading.Thread(target=thread_main, args=(it,)) for it in range(num_threads)] for t in worker_threads: print("running thread ", t) t.start() print("Running minibatch sequential-scan SGD with momentum (%d threads)" % num_threads) for it in tqdm(range(num_epochs)): for ibatch in range(int(n/B)): iter_barrier.wait() # TODO work done on a single thread at each iteration; this section of code should primarily use numpy operations with the "out=" argument specified (students should implement this) # W0 = W0 - alpha * (1/B) * np.sum(g) np.sum(g, axis=0, out=W_temp1, dtype=np.float32) np.multiply(W_temp1, alpha/B, out=W_temp1, dtype=np.float32) np.subtract(W0, W_temp1, out=W0, dtype=np.float32) iter_barrier.wait() for t in worker_threads: t.join() # return the learned model return W0 def run_algo(algorithm_identifier, algo_args): algorithms = { "sgd_momen": (sgd_mss_with_momentum, "SGD with Momentum"), "sgd_momen_no_alloc": (sgd_mss_with_momentum_noalloc, "SGD with Momentum (no alloc)"), "sgd_momen_threaded": (sgd_mss_with_momentum_threaded, "SGD with Momentum (Threaded)"), "sgd_momen_no_alloc_fl32": (sgd_mss_with_momentum_noalloc_float32, "SGD with Momentum (no alloc, float 32)"), "sgd_momen_threaded_fl32": (sgd_mss_with_momentum_threaded_float32, "SGD with Momentum (Threaded, float 32)"), } algo_fn = algorithms[algorithm_identifier][0] print(f"\nRunning Algorithm {algorithm_identifier} ...") print_config(algo_args) d, n = algo_args["Xs"].shape c, n = algo_args["Ys"].shape W0 = np.zeros((c, d)) algo_args["W0"] = W0 start = time.time() model = algo_fn(**algo_args) end = time.time() time_taken = end - start print(f"Algorithm {algorithm_identifier} complete. Time taken: {time_taken}") return time_taken, W0 def generatePlot(listOfElements, nameOfElements, batchSizes, batchNames): figures_dir = "Figures/" if not os.path.isdir(figures_dir): print("Figures folder does not exist. Creating ...") os.makedirs(figures_dir) print(f"Created {figures_dir}.") for n, element in enumerate(listOfElements): print((element)) print() print((batchSizes)) print() print(nameOfElements[n]) print() print() plt.loglog(batchNames, (element), label=nameOfElements[n]) # plt.xticks(batchSizes, batchNames) plt.xlabel("Batch Sizes") plt.ylabel("Time Taken") plt.legend(loc="upper right") plt.savefig(figures_dir + "Result" + ".png") return plt def print_config(config): print("Current Configuration:") print("~" * 15) for k in config: if k != "Xs" and k != "Ys" and k!= "W0": print(f"{k}: {config[k]}") print("~" * 15) if __name__ == "__main__": (Xs_tr, Ys_tr, Xs_te, Ys_te) = load_MNIST_dataset() # TODO: NEXT LINE IS ONLY FOR DEBUGGING, REMOVE ON SUBMISSION Xs_tr, Ys_tr = Xs_tr[:50], Ys_tr[:50] sgd_args = { "Xs": Xs_tr, "Ys": Ys_tr, "alpha": 0.1, "num_epochs": 20, "beta": 0.9, "gamma": 10 ** -4, } DIVIDER = "#" * 20 # Comments from the documenttion # TODO FOR sgd_mss_with_momentum_noalloc # To validate your implementation, you should check that the output of this new function is close to the output of your original sgd_mss_with_momentum function. def checkSimilarity(original, altered, atol=10**-6): isSimilar = np.allclose(original, altered, rtol=1, atol=atol) print(f"Similarity of the two matrices : {isSimilar}") return isSimilar # TODO For threaded # In order to make sure that your cores are not overloaded, you should set the number of cores used implicitly by numpy back to 1 (allowing the cores to be used explicitly by your implementation). listOfElements = [] batch_sizes = [8, 16, 30, 60, 200, 600, 3000] if not os.path.exists("part134(1).pickle") and implicit_num_threads==1: # ----- PART-1 sgd_momen, sgd_momen_noalloc = [], [] for batch_size in batch_sizes: sgd_args["B"] = batch_size time_alloc, W_alloc = run_algo("sgd_momen", sgd_args) sgd_momen += [time_alloc] time_no_alloc, W_no_alloc = run_algo("sgd_momen_no_alloc", sgd_args) sgd_momen_noalloc += [time_no_alloc] checkSimilarity(W_alloc, W_no_alloc) # ----- PART-3 # TODO: Reset implicit numpy multithreading # e_threaded = explicitly_threaded e_threaded = [] threaded_args = copy.copy(sgd_args) threaded_args["num_threads"] = 2 for batch_size in batch_sizes: threaded_args["B"] = batch_size time_threaded, Ws = run_algo("sgd_momen_threaded", threaded_args) e_threaded += [time_threaded] # ----- PART-4 (1) # fl32_noalloc_e is for explicit threading fl32_noalloc_e, fl32_threaded = [], [] for batch_size in batch_sizes: sgd_args["B"] = batch_size time_noalloc, W_no_alloc = run_algo("sgd_momen_no_alloc_fl32", sgd_args) fl32_noalloc_e += [time_noalloc] threaded_args["B"] = batch_size time_threaded, W_threaded = run_algo("sgd_momen_threaded_fl32", threaded_args) fl32_threaded += [time_threaded] checkSimilarity(W_threaded, W_no_alloc) listA = [sgd_momen, sgd_momen_noalloc, e_threaded, fl32_noalloc_e, fl32_threaded] pickle.dump(listA, open("part134(1).pickle", "wb")) elif os.path.exists("part134(1).pickle"): f1 = open("part134(1).pickle", "rb") listOfElements134_1 = pickle.load(f1) # listofList = [sgd_momen, sgd_momen_noalloc, e_threaded, fl32_noalloc_e, fl32_threaded] sgd_momen = listOfElements134_1[0] sgd_momen_noalloc = listOfElements134_1[1] e_threaded = listOfElements134_1[2] fl32_noalloc_e = listOfElements134_1[3] fl32_threaded = listOfElements134_1[4] if not os.path.exists("part24(2).pickle") and implicit_num_threads==2: # ----- PART-2 # TODO: Change the environ variables here # i_threaded = implicitly_threaded i_threaded, noalloc_i_threaded = [], [] for batch_size in batch_sizes: sgd_args["B"] = batch_size time_alloc, W_alloc = run_algo("sgd_momen", sgd_args) i_threaded += [time_alloc] time_no_alloc, W_no_alloc = run_algo("sgd_momen_no_alloc", sgd_args) noalloc_i_threaded += [time_no_alloc] checkSimilarity(W_alloc, W_no_alloc) # ----- PART-4 (2) # TODO: Change the environ variables here to use implicit therading # fl32_noalloc_i is for implicit threading fl32_noalloc_i = [] for batch_size in batch_sizes: sgd_args["B"] = batch_size time_fl32_noalloc_i, W = run_algo("sgd_momen_no_alloc_fl32", sgd_args) fl32_noalloc_i += [time_fl32_noalloc_i] listA = [i_threaded, noalloc_i_threaded, fl32_noalloc_i] pickle.dump(listA, open("part24(2).pickle", "wb")) elif os.path.exists("part24(2).pickle"): f2 = open("part24(2).pickle", "rb") listOfElements24_2 = pickle.load(f2) # listofList = [i_threaded, noalloc_i_threaded, fl32_noalloc_i] i_threaded = listOfElements24_2[0] noalloc_i_threaded = listOfElements24_2[1] fl32_noalloc_i = listOfElements24_2[2] listOfElements = [sgd_momen, sgd_momen_noalloc, fl32_noalloc_e, i_threaded, noalloc_i_threaded, fl32_noalloc_i, e_threaded, fl32_threaded] nameOfElements = ["Baseline-64 Exp", "NMA-64 Exp", "NMA-32 Exp", "Baseline-64 Imp", "NMA-64 Imp", "NMA-32 Imp", "Multithreaded-64 Exp", "Multithreaded-32 Exp"] generatePlot(listOfElements, nameOfElements, range(len(batch_sizes)), batch_sizes)
[ "mnist.MNIST", "matplotlib.pyplot.ylabel", "numpy.ascontiguousarray", "copy.copy", "numpy.divide", "os.path.exists", "numpy.multiply", "matplotlib.pyplot.loglog", "matplotlib.pyplot.xlabel", "numpy.subtract", "numpy.exp", "numpy.dot", "os.path.isdir", "numpy.matmul", "numpy.random.seed",...
[((525, 546), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (539, 546), False, 'import matplotlib\n'), ((706, 731), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (721, 731), False, 'import os\n'), ((1211, 1234), 'numpy.dot', 'numpy.dot', (['W', 'Xs[:, ii]'], {}), '(W, Xs[:, ii])\n', (1220, 1234), False, 'import numpy\n'), ((1538, 1588), 'os.path.join', 'os.path.join', (['mnist_data_directory', '"""MNIST.pickle"""'], {}), "(mnist_data_directory, 'MNIST.pickle')\n", (1550, 1588), False, 'import os\n'), ((3498, 3519), 'numpy.zeros', 'numpy.zeros', (['W0.shape'], {}), '(W0.shape)\n', (3509, 3519), False, 'import numpy\n'), ((4934, 4950), 'numpy.zeros', 'np.zeros', (['(c, B)'], {}), '((c, B))\n', (4942, 4950), True, 'import numpy as np\n'), ((4963, 4981), 'numpy.zeros', 'np.zeros', (['W0.shape'], {}), '(W0.shape)\n', (4971, 4981), True, 'import numpy as np\n'), ((4998, 5009), 'numpy.zeros', 'np.zeros', (['B'], {}), '(B)\n', (5006, 5009), True, 'import numpy as np\n'), ((5029, 5045), 'numpy.zeros', 'np.zeros', (['(c, B)'], {}), '((c, B))\n', (5037, 5045), True, 'import numpy as np\n'), ((5053, 5071), 'numpy.zeros', 'np.zeros', (['W0.shape'], {}), '(W0.shape)\n', (5061, 5071), True, 'import numpy as np\n'), ((5080, 5098), 'numpy.zeros', 'np.zeros', (['W0.shape'], {}), '(W0.shape)\n', (5088, 5098), True, 'import numpy as np\n'), ((7825, 7843), 'numpy.zeros', 'np.zeros', (['W0.shape'], {}), '(W0.shape)\n', (7833, 7843), True, 'import numpy as np\n'), ((7898, 7932), 'threading.Barrier', 'threading.Barrier', (['(num_threads + 1)'], {}), '(num_threads + 1)\n', (7915, 7932), False, 'import threading\n'), ((11228, 11245), 'numpy.float32', 'np.float32', (['alpha'], {}), '(alpha)\n', (11238, 11245), True, 'import numpy as np\n'), ((11258, 11275), 'numpy.float32', 'np.float32', (['gamma'], {}), '(gamma)\n', (11268, 11275), True, 'import numpy as np\n'), ((11435, 11469), 'numpy.zeros', 'np.zeros', (['(c, B)'], {'dtype': 'np.float32'}), '((c, B), dtype=np.float32)\n', (11443, 11469), True, 'import numpy as np\n'), ((11482, 11518), 'numpy.zeros', 'np.zeros', (['W0.shape'], {'dtype': 'np.float32'}), '(W0.shape, dtype=np.float32)\n', (11490, 11518), True, 'import numpy as np\n'), ((11535, 11567), 'numpy.zeros', 'np.zeros', (['(B,)'], {'dtype': 'np.float32'}), '((B,), dtype=np.float32)\n', (11543, 11567), True, 'import numpy as np\n'), ((11587, 11621), 'numpy.zeros', 'np.zeros', (['(c, B)'], {'dtype': 'np.float32'}), '((c, B), dtype=np.float32)\n', (11595, 11621), True, 'import numpy as np\n'), ((11629, 11665), 'numpy.zeros', 'np.zeros', (['W0.shape'], {'dtype': 'np.float32'}), '(W0.shape, dtype=np.float32)\n', (11637, 11665), True, 'import numpy as np\n'), ((11674, 11710), 'numpy.zeros', 'np.zeros', (['W0.shape'], {'dtype': 'np.float32'}), '(W0.shape, dtype=np.float32)\n', (11682, 11710), True, 'import numpy as np\n'), ((14174, 14191), 'numpy.float32', 'np.float32', (['alpha'], {}), '(alpha)\n', (14184, 14191), True, 'import numpy as np\n'), ((14204, 14221), 'numpy.float32', 'np.float32', (['gamma'], {}), '(gamma)\n', (14214, 14221), True, 'import numpy as np\n'), ((14603, 14637), 'threading.Barrier', 'threading.Barrier', (['(num_threads + 1)'], {}), '(num_threads + 1)\n', (14620, 14637), False, 'import threading\n'), ((17970, 17986), 'numpy.zeros', 'np.zeros', (['(c, d)'], {}), '((c, d))\n', (17978, 17986), True, 'import numpy as np\n'), ((18024, 18035), 'time.time', 'time.time', ([], {}), '()\n', (18033, 18035), False, 'import time\n'), ((18079, 18090), 'time.time', 'time.time', ([], {}), '()\n', (18088, 18090), False, 'import time\n'), ((18823, 18848), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Batch Sizes"""'], {}), "('Batch Sizes')\n", (18833, 18848), True, 'from matplotlib import pyplot as plt\n'), ((18853, 18877), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time Taken"""'], {}), "('Time Taken')\n", (18863, 18877), True, 'from matplotlib import pyplot as plt\n'), ((18882, 18911), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (18892, 18911), True, 'from matplotlib import pyplot as plt\n'), ((18917, 18961), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(figures_dir + 'Result' + '.png')"], {}), "(figures_dir + 'Result' + '.png')\n", (18928, 18961), True, 'from matplotlib import pyplot as plt\n'), ((1020, 1036), 'numpy.dot', 'numpy.dot', (['W', 'Xs'], {}), '(W, Xs)\n', (1029, 1036), False, 'import numpy\n'), ((1337, 1377), 'numpy.sum', 'numpy.sum', (['expWdotX'], {'axis': '(0)', 'dtype': 'dtype'}), '(expWdotX, axis=0, dtype=dtype)\n', (1346, 1377), False, 'import numpy\n'), ((9383, 9431), 'threading.Thread', 'threading.Thread', ([], {'target': 'thread_main', 'args': '(it,)'}), '(target=thread_main, args=(it,))\n', (9399, 9431), False, 'import threading\n'), ((14726, 14762), 'numpy.zeros', 'np.zeros', (['W0.shape'], {'dtype': 'np.float32'}), '(W0.shape, dtype=np.float32)\n', (14734, 14762), True, 'import numpy as np\n'), ((14783, 14816), 'numpy.zeros', 'np.zeros', (['(Bt,)'], {'dtype': 'np.float32'}), '((Bt,), dtype=np.float32)\n', (14791, 14816), True, 'import numpy as np\n'), ((14840, 14875), 'numpy.zeros', 'np.zeros', (['(c, Bt)'], {'dtype': 'np.float32'}), '((c, Bt), dtype=np.float32)\n', (14848, 14875), True, 'import numpy as np\n'), ((16255, 16303), 'threading.Thread', 'threading.Thread', ([], {'target': 'thread_main', 'args': '(it,)'}), '(target=thread_main, args=(it,))\n', (16271, 16303), False, 'import threading\n'), ((18344, 18370), 'os.path.isdir', 'os.path.isdir', (['figures_dir'], {}), '(figures_dir)\n', (18357, 18370), False, 'import os\n'), ((18441, 18465), 'os.makedirs', 'os.makedirs', (['figures_dir'], {}), '(figures_dir)\n', (18452, 18465), False, 'import os\n'), ((18715, 18771), 'matplotlib.pyplot.loglog', 'plt.loglog', (['batchNames', 'element'], {'label': 'nameOfElements[n]'}), '(batchNames, element, label=nameOfElements[n])\n', (18725, 18771), True, 'from matplotlib import pyplot as plt\n'), ((19890, 19939), 'numpy.allclose', 'np.allclose', (['original', 'altered'], {'rtol': '(1)', 'atol': 'atol'}), '(original, altered, rtol=1, atol=atol)\n', (19901, 19939), True, 'import numpy as np\n'), ((21002, 21021), 'copy.copy', 'copy.copy', (['sgd_args'], {}), '(sgd_args)\n', (21011, 21021), False, 'import copy\n'), ((21993, 22028), 'os.path.exists', 'os.path.exists', (['"""part134(1).pickle"""'], {}), "('part134(1).pickle')\n", (22007, 22028), False, 'import os\n'), ((23586, 23620), 'os.path.exists', 'os.path.exists', (['"""part24(2).pickle"""'], {}), "('part24(2).pickle')\n", (23600, 23620), False, 'import os\n'), ((1084, 1108), 'numpy.argmax', 'numpy.argmax', (['Ys'], {'axis': '(0)'}), '(Ys, axis=0)\n', (1096, 1108), False, 'import numpy\n'), ((1267, 1292), 'numpy.amax', 'numpy.amax', (['WdotX'], {'axis': '(0)'}), '(WdotX, axis=0)\n', (1277, 1292), False, 'import numpy\n'), ((1719, 1782), 'mnist.MNIST', 'mnist.MNIST', (['mnist_data_directory'], {'return_type': '"""numpy"""', 'gz': '(True)'}), "(mnist_data_directory, return_type='numpy', gz=True)\n", (1730, 1782), False, 'import mnist\n'), ((1894, 1918), 'numpy.zeros', 'numpy.zeros', (['(10, 60000)'], {}), '((10, 60000))\n', (1905, 1918), False, 'import numpy\n'), ((2062, 2085), 'numpy.random.seed', 'numpy.random.seed', (['(4787)'], {}), '(4787)\n', (2079, 2085), False, 'import numpy\n'), ((2101, 2132), 'numpy.random.permutation', 'numpy.random.permutation', (['(60000)'], {}), '(60000)\n', (2125, 2132), False, 'import numpy\n'), ((2149, 2188), 'numpy.ascontiguousarray', 'numpy.ascontiguousarray', (['Xs_tr[:, perm]'], {}), '(Xs_tr[:, perm])\n', (2172, 2188), False, 'import numpy\n'), ((2204, 2243), 'numpy.ascontiguousarray', 'numpy.ascontiguousarray', (['Ys_tr[:, perm]'], {}), '(Ys_tr[:, perm])\n', (2227, 2243), False, 'import numpy\n'), ((2353, 2377), 'numpy.zeros', 'numpy.zeros', (['(10, 10000)'], {}), '((10, 10000))\n', (2364, 2377), False, 'import numpy\n'), ((2493, 2523), 'numpy.ascontiguousarray', 'numpy.ascontiguousarray', (['Xs_te'], {}), '(Xs_te)\n', (2516, 2523), False, 'import numpy\n'), ((2540, 2570), 'numpy.ascontiguousarray', 'numpy.ascontiguousarray', (['Ys_te'], {}), '(Ys_te)\n', (2563, 2570), False, 'import numpy\n'), ((5227, 5258), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['Xs[:, ii]'], {}), '(Xs[:, ii])\n', (5247, 5258), True, 'import numpy as np\n'), ((5282, 5313), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['Ys[:, ii]'], {}), '(Ys[:, ii])\n', (5302, 5313), True, 'import numpy as np\n'), ((5672, 5709), 'numpy.matmul', 'np.matmul', (['W0', 'X_batch[i]'], {'out': 'Y_temp'}), '(W0, X_batch[i], out=Y_temp)\n', (5681, 5709), True, 'import numpy as np\n'), ((5933, 5971), 'numpy.amax', 'np.amax', (['Y_temp'], {'axis': '(0)', 'out': 'amax_temp'}), '(Y_temp, axis=0, out=amax_temp)\n', (5940, 5971), True, 'import numpy as np\n'), ((5984, 6032), 'numpy.subtract', 'np.subtract', (['Y_temp', 'amax_temp'], {'out': 'softmax_temp'}), '(Y_temp, amax_temp, out=softmax_temp)\n', (5995, 6032), True, 'import numpy as np\n'), ((6045, 6083), 'numpy.exp', 'np.exp', (['softmax_temp'], {'out': 'softmax_temp'}), '(softmax_temp, out=softmax_temp)\n', (6051, 6083), True, 'import numpy as np\n'), ((6096, 6139), 'numpy.sum', 'np.sum', (['softmax_temp'], {'axis': '(0)', 'out': 'amax_temp'}), '(softmax_temp, axis=0, out=amax_temp)\n', (6102, 6139), True, 'import numpy as np\n'), ((6152, 6204), 'numpy.divide', 'np.divide', (['softmax_temp', 'amax_temp'], {'out': 'softmax_temp'}), '(softmax_temp, amax_temp, out=softmax_temp)\n', (6161, 6204), True, 'import numpy as np\n'), ((6311, 6360), 'numpy.subtract', 'np.subtract', (['softmax_temp', 'Y_batch[i]'], {'out': 'Y_temp'}), '(softmax_temp, Y_batch[i], out=Y_temp)\n', (6322, 6360), True, 'import numpy as np\n'), ((6434, 6477), 'numpy.matmul', 'np.matmul', (['Y_temp', 'X_batch[i].T'], {'out': 'W_temp'}), '(Y_temp, X_batch[i].T, out=W_temp)\n', (6443, 6477), True, 'import numpy as np\n'), ((6490, 6522), 'numpy.divide', 'np.divide', (['W_temp', 'B'], {'out': 'W_temp'}), '(W_temp, B, out=W_temp)\n', (6499, 6522), True, 'import numpy as np\n'), ((6535, 6564), 'numpy.multiply', 'np.multiply', (['gamma', 'W0'], {'out': 'g'}), '(gamma, W0, out=g)\n', (6546, 6564), True, 'import numpy as np\n'), ((6577, 6601), 'numpy.add', 'np.add', (['W_temp', 'g'], {'out': 'g'}), '(W_temp, g, out=g)\n', (6583, 6601), True, 'import numpy as np\n'), ((6657, 6684), 'numpy.multiply', 'np.multiply', (['V', 'beta'], {'out': 'V'}), '(V, beta, out=V)\n', (6668, 6684), True, 'import numpy as np\n'), ((6697, 6725), 'numpy.multiply', 'np.multiply', (['g', 'alpha'], {'out': 'g'}), '(g, alpha, out=g)\n', (6708, 6725), True, 'import numpy as np\n'), ((6781, 6805), 'numpy.subtract', 'np.subtract', (['V', 'g'], {'out': 'V'}), '(V, g, out=V)\n', (6792, 6805), True, 'import numpy as np\n'), ((6818, 6839), 'numpy.add', 'np.add', (['V', 'W0'], {'out': 'W0'}), '(V, W0, out=W0)\n', (6824, 6839), True, 'import numpy as np\n'), ((8112, 8130), 'numpy.zeros', 'np.zeros', (['W0.shape'], {}), '(W0.shape)\n', (8120, 8130), True, 'import numpy as np\n'), ((8155, 8167), 'numpy.zeros', 'np.zeros', (['Bt'], {}), '(Bt)\n', (8163, 8167), True, 'import numpy as np\n'), ((8195, 8212), 'numpy.zeros', 'np.zeros', (['(c, Bt)'], {}), '((c, Bt))\n', (8203, 8212), True, 'import numpy as np\n'), ((10005, 10035), 'numpy.sum', 'np.sum', (['g'], {'axis': '(0)', 'out': 'W_temp1'}), '(g, axis=0, out=W_temp1)\n', (10011, 10035), True, 'import numpy as np\n'), ((10048, 10092), 'numpy.multiply', 'np.multiply', (['W_temp1', '(alpha / B)'], {'out': 'W_temp1'}), '(W_temp1, alpha / B, out=W_temp1)\n', (10059, 10092), True, 'import numpy as np\n'), ((10103, 10135), 'numpy.subtract', 'np.subtract', (['W0', 'W_temp1'], {'out': 'W0'}), '(W0, W_temp1, out=W0)\n', (10114, 10135), True, 'import numpy as np\n'), ((11839, 11888), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['Xs[:, ii]'], {'dtype': 'np.float32'}), '(Xs[:, ii], dtype=np.float32)\n', (11859, 11888), True, 'import numpy as np\n'), ((11912, 11961), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['Ys[:, ii]'], {'dtype': 'np.float32'}), '(Ys[:, ii], dtype=np.float32)\n', (11932, 11961), True, 'import numpy as np\n'), ((12463, 12529), 'numpy.subtract', 'np.subtract', (['Y_temp', 'amax_temp'], {'out': 'softmax_temp', 'dtype': 'np.float32'}), '(Y_temp, amax_temp, out=softmax_temp, dtype=np.float32)\n', (12474, 12529), True, 'import numpy as np\n'), ((12542, 12598), 'numpy.exp', 'np.exp', (['softmax_temp'], {'out': 'softmax_temp', 'dtype': 'np.float32'}), '(softmax_temp, out=softmax_temp, dtype=np.float32)\n', (12548, 12598), True, 'import numpy as np\n'), ((12611, 12672), 'numpy.sum', 'np.sum', (['softmax_temp'], {'axis': '(0)', 'out': 'amax_temp', 'dtype': 'np.float32'}), '(softmax_temp, axis=0, out=amax_temp, dtype=np.float32)\n', (12617, 12672), True, 'import numpy as np\n'), ((12685, 12755), 'numpy.divide', 'np.divide', (['softmax_temp', 'amax_temp'], {'out': 'softmax_temp', 'dtype': 'np.float32'}), '(softmax_temp, amax_temp, out=softmax_temp, dtype=np.float32)\n', (12694, 12755), True, 'import numpy as np\n'), ((12768, 12835), 'numpy.subtract', 'np.subtract', (['softmax_temp', 'Y_batch[i]'], {'out': 'Y_temp', 'dtype': 'np.float32'}), '(softmax_temp, Y_batch[i], out=Y_temp, dtype=np.float32)\n', (12779, 12835), True, 'import numpy as np\n'), ((12848, 12909), 'numpy.matmul', 'np.matmul', (['Y_temp', 'X_batch[i].T'], {'out': 'W_temp', 'dtype': 'np.float32'}), '(Y_temp, X_batch[i].T, out=W_temp, dtype=np.float32)\n', (12857, 12909), True, 'import numpy as np\n'), ((12922, 12972), 'numpy.divide', 'np.divide', (['W_temp', 'B'], {'out': 'W_temp', 'dtype': 'np.float32'}), '(W_temp, B, out=W_temp, dtype=np.float32)\n', (12931, 12972), True, 'import numpy as np\n'), ((12985, 13032), 'numpy.multiply', 'np.multiply', (['gamma', 'W0'], {'out': 'g', 'dtype': 'np.float32'}), '(gamma, W0, out=g, dtype=np.float32)\n', (12996, 13032), True, 'import numpy as np\n'), ((13045, 13087), 'numpy.add', 'np.add', (['W_temp', 'g'], {'out': 'g', 'dtype': 'np.float32'}), '(W_temp, g, out=g, dtype=np.float32)\n', (13051, 13087), True, 'import numpy as np\n'), ((13100, 13145), 'numpy.multiply', 'np.multiply', (['V', 'beta'], {'out': 'V', 'dtype': 'np.float32'}), '(V, beta, out=V, dtype=np.float32)\n', (13111, 13145), True, 'import numpy as np\n'), ((13158, 13204), 'numpy.multiply', 'np.multiply', (['g', 'alpha'], {'out': 'g', 'dtype': 'np.float32'}), '(g, alpha, out=g, dtype=np.float32)\n', (13169, 13204), True, 'import numpy as np\n'), ((13217, 13259), 'numpy.subtract', 'np.subtract', (['V', 'g'], {'out': 'V', 'dtype': 'np.float32'}), '(V, g, out=V, dtype=np.float32)\n', (13228, 13259), True, 'import numpy as np\n'), ((13272, 13311), 'numpy.add', 'np.add', (['V', 'W0'], {'out': 'W0', 'dtype': 'np.float32'}), '(V, W0, out=W0, dtype=np.float32)\n', (13278, 13311), True, 'import numpy as np\n'), ((14442, 14460), 'numpy.zeros', 'np.zeros', (['W0.shape'], {}), '(W0.shape)\n', (14450, 14460), True, 'import numpy as np\n'), ((16877, 16925), 'numpy.sum', 'np.sum', (['g'], {'axis': '(0)', 'out': 'W_temp1', 'dtype': 'np.float32'}), '(g, axis=0, out=W_temp1, dtype=np.float32)\n', (16883, 16925), True, 'import numpy as np\n'), ((16938, 17000), 'numpy.multiply', 'np.multiply', (['W_temp1', '(alpha / B)'], {'out': 'W_temp1', 'dtype': 'np.float32'}), '(W_temp1, alpha / B, out=W_temp1, dtype=np.float32)\n', (16949, 17000), True, 'import numpy as np\n'), ((17011, 17061), 'numpy.subtract', 'np.subtract', (['W0', 'W_temp1'], {'out': 'W0', 'dtype': 'np.float32'}), '(W0, W_temp1, out=W0, dtype=np.float32)\n', (17022, 17061), True, 'import numpy as np\n'), ((20340, 20375), 'os.path.exists', 'os.path.exists', (['"""part134(1).pickle"""'], {}), "('part134(1).pickle')\n", (20354, 20375), False, 'import os\n'), ((22106, 22121), 'pickle.load', 'pickle.load', (['f1'], {}), '(f1)\n', (22117, 22121), False, 'import pickle\n'), ((22464, 22498), 'os.path.exists', 'os.path.exists', (['"""part24(2).pickle"""'], {}), "('part24(2).pickle')\n", (22478, 22498), False, 'import os\n'), ((23696, 23711), 'pickle.load', 'pickle.load', (['f2'], {}), '(f2)\n', (23707, 23711), False, 'import pickle\n'), ((8573, 8620), 'numpy.dot', 'np.dot', (['g[ithread]', 'Xs[:, ii]'], {'out': 'softmax_temp'}), '(g[ithread], Xs[:, ii], out=softmax_temp)\n', (8579, 8620), True, 'import numpy as np\n'), ((8636, 8680), 'numpy.amax', 'np.amax', (['softmax_temp'], {'axis': '(0)', 'out': 'amax_temp'}), '(softmax_temp, axis=0, out=amax_temp)\n', (8643, 8680), True, 'import numpy as np\n'), ((8697, 8751), 'numpy.subtract', 'np.subtract', (['softmax_temp', 'amax_temp'], {'out': 'softmax_temp'}), '(softmax_temp, amax_temp, out=softmax_temp)\n', (8708, 8751), True, 'import numpy as np\n'), ((8768, 8806), 'numpy.exp', 'np.exp', (['softmax_temp'], {'out': 'softmax_temp'}), '(softmax_temp, out=softmax_temp)\n', (8774, 8806), True, 'import numpy as np\n'), ((8823, 8866), 'numpy.sum', 'np.sum', (['softmax_temp'], {'axis': '(0)', 'out': 'amax_temp'}), '(softmax_temp, axis=0, out=amax_temp)\n', (8829, 8866), True, 'import numpy as np\n'), ((8883, 8935), 'numpy.divide', 'np.divide', (['softmax_temp', 'amax_temp'], {'out': 'softmax_temp'}), '(softmax_temp, amax_temp, out=softmax_temp)\n', (8892, 8935), True, 'import numpy as np\n'), ((8952, 9006), 'numpy.subtract', 'np.subtract', (['softmax_temp', 'Ys[:, ii]'], {'out': 'softmax_temp'}), '(softmax_temp, Ys[:, ii], out=softmax_temp)\n', (8963, 9006), True, 'import numpy as np\n'), ((9023, 9071), 'numpy.matmul', 'np.matmul', (['softmax_temp', 'Xs[:, ii].T'], {'out': 'W_temp'}), '(softmax_temp, Xs[:, ii].T, out=W_temp)\n', (9032, 9071), True, 'import numpy as np\n'), ((9088, 9120), 'numpy.divide', 'np.divide', (['W_temp', 'B'], {'out': 'W_temp'}), '(W_temp, B, out=W_temp)\n', (9097, 9120), True, 'import numpy as np\n'), ((9137, 9183), 'numpy.multiply', 'np.multiply', (['gamma', 'g[ithread]'], {'out': 'g[ithread]'}), '(gamma, g[ithread], out=g[ithread])\n', (9148, 9183), True, 'import numpy as np\n'), ((9201, 9243), 'numpy.add', 'np.add', (['W_temp', 'g[ithread]'], {'out': 'g[ithread]'}), '(W_temp, g[ithread], out=g[ithread])\n', (9207, 9243), True, 'import numpy as np\n'), ((15486, 15558), 'numpy.subtract', 'np.subtract', (['softmax_temp', 'amax_temp'], {'out': 'softmax_temp', 'dtype': 'np.float32'}), '(softmax_temp, amax_temp, out=softmax_temp, dtype=np.float32)\n', (15497, 15558), True, 'import numpy as np\n'), ((15575, 15631), 'numpy.exp', 'np.exp', (['softmax_temp'], {'out': 'softmax_temp', 'dtype': 'np.float32'}), '(softmax_temp, out=softmax_temp, dtype=np.float32)\n', (15581, 15631), True, 'import numpy as np\n'), ((15648, 15709), 'numpy.sum', 'np.sum', (['softmax_temp'], {'axis': '(0)', 'out': 'amax_temp', 'dtype': 'np.float32'}), '(softmax_temp, axis=0, out=amax_temp, dtype=np.float32)\n', (15654, 15709), True, 'import numpy as np\n'), ((15726, 15796), 'numpy.divide', 'np.divide', (['softmax_temp', 'amax_temp'], {'out': 'softmax_temp', 'dtype': 'np.float32'}), '(softmax_temp, amax_temp, out=softmax_temp, dtype=np.float32)\n', (15735, 15796), True, 'import numpy as np\n'), ((15813, 15885), 'numpy.subtract', 'np.subtract', (['softmax_temp', 'Ys[:, ii]'], {'out': 'softmax_temp', 'dtype': 'np.float32'}), '(softmax_temp, Ys[:, ii], out=softmax_temp, dtype=np.float32)\n', (15824, 15885), True, 'import numpy as np\n'), ((15902, 15968), 'numpy.matmul', 'np.matmul', (['softmax_temp', 'Xs[:, ii].T'], {'out': 'W_temp', 'dtype': 'np.float32'}), '(softmax_temp, Xs[:, ii].T, out=W_temp, dtype=np.float32)\n', (15911, 15968), True, 'import numpy as np\n'), ((15985, 16035), 'numpy.divide', 'np.divide', (['W_temp', 'B'], {'out': 'W_temp', 'dtype': 'np.float32'}), '(W_temp, B, out=W_temp, dtype=np.float32)\n', (15994, 16035), True, 'import numpy as np\n'), ((16052, 16116), 'numpy.multiply', 'np.multiply', (['gamma', 'g[ithread]'], {'out': 'g[ithread]', 'dtype': 'np.float32'}), '(gamma, g[ithread], out=g[ithread], dtype=np.float32)\n', (16063, 16116), True, 'import numpy as np\n'), ((16134, 16194), 'numpy.add', 'np.add', (['W_temp', 'g[ithread]'], {'out': 'g[ithread]', 'dtype': 'np.float32'}), '(W_temp, g[ithread], out=g[ithread], dtype=np.float32)\n', (16140, 16194), True, 'import numpy as np\n'), ((12318, 12355), 'numpy.matmul', 'np.matmul', (['W0', 'X_batch[i]'], {'out': 'Y_temp'}), '(W0, X_batch[i], out=Y_temp)\n', (12327, 12355), True, 'import numpy as np\n'), ((12390, 12428), 'numpy.amax', 'np.amax', (['Y_temp'], {'axis': '(0)', 'out': 'amax_temp'}), '(Y_temp, axis=0, out=amax_temp)\n', (12397, 12428), True, 'import numpy as np\n'), ((15324, 15371), 'numpy.dot', 'np.dot', (['g[ithread]', 'Xs[:, ii]'], {'out': 'softmax_temp'}), '(g[ithread], Xs[:, ii], out=softmax_temp)\n', (15330, 15371), True, 'import numpy as np\n'), ((15406, 15450), 'numpy.amax', 'np.amax', (['softmax_temp'], {'axis': '(0)', 'out': 'amax_temp'}), '(softmax_temp, axis=0, out=amax_temp)\n', (15413, 15450), True, 'import numpy as np\n')]
import ndjson as json import matplotlib matplotlib.use('qt5agg') import pylab import seaborn as sns sns.set_style("whitegrid") import pandas import numpy as np import scipy #https://ipip.ori.org/New_IPIP-50-item-scale.htm def get_confusion_matrix(scores, images): def shrink(name): return "$" + name[0] + name[-1] + "$" traits = ["Openness", "Conscientiousness", "Extraversion", "Agreeableness", "Neuroticism"] traits_plus = [x + "+" for x in traits] traits_neg = [x + "-" for x in traits] traits_pn = [traits_plus[i // 2] if i %2 == 0 else traits_neg[i // 2] for i in range(2*len(traits))] ret = np.zeros((len(traits_pn), len(traits_pn)), dtype=float) ret = pandas.DataFrame(ret, index=list(map(shrink, traits_pn))[:], columns=list(map(shrink, traits_pn))) mask = np.ones((len(traits_pn), len(traits_pn)), dtype=bool) for i in range(len(traits_pn)): for j in range(len(traits_pn)): if abs(i - j) <= 1 and not(i != j and (i + j + 1) % 4 == 0): mask[i, j] = False for trait_i in traits: score = scores[trait_i].values for sign_i in ["+", "-"]: if sign_i == "+": score_mask = (score >= score.mean()) else: score_mask = (score < score.mean()) for trait_j in traits: image = images[trait_j].values for sign_j in ["+", "-"]: if sign_j == "+": image_mask = (image >= image.mean()) else: image_mask = (image < image.mean()) #ret.loc[shrink(trait_i + sign_i)][shrink(trait_j + sign_j)] = (score_mask * image_mask).sum() print("AAA") #ret.loc[shrink(trait_i + sign_i)][shrink(trait_j + sign_j)] = scipy.stats.spearmanr(score_mask, image_mask)[0] ret.loc[shrink(trait_i + sign_i)][shrink(trait_j + sign_j)] = (score_mask * image_mask).sum() / (image_mask.sum()) print(ret) sns.heatmap(ret, annot=True, cmap="Blues", fmt='.2f', mask=mask) pylab.gca().set_yticklabels(ret.index.values, rotation=0) # pylab.tight_layout(h_pad=1000) pylab.suptitle("Precision") pylab.xlabel("Trait") pylab.ylabel("Trait") pylab.gca().xaxis.tick_top() pylab.savefig("plots/precisionmat.eps") pylab.show() ret.to_csv("confusion.csv") def get_confusion_matrix_join(scores, images): def shrink(name): return name[0] traits = ["Openness", "Conscientiousness", "Extraversion", "Agreeableness", "Neuroticism"] ret = np.zeros((len(traits), len(traits)), dtype=float) ret = pandas.DataFrame(ret, index=list(map(shrink, traits)), columns=list(map(shrink, traits))) mask = np.zeros((len(traits), len(traits)), dtype=bool) for i in range(len(traits)): for j in range(len(traits)): if j > i : mask[i,j] = True for i, trait_i in enumerate(traits): score = scores[traits[i]].values # score = score > score.mean() for j, trait_j in enumerate(traits): if j <= i or True: image = images[traits[j]].values image = image > image.mean() #ret.loc[shrink(trait_i)][shrink(trait_j)] = (score * image).sum() ret.loc[shrink(traits[i])][shrink(traits[j])] = scipy.stats.pearsonr(score, image)[0] # ret.loc[shrink(traits[j])][shrink(traits[i])] = scipy.stats.pearsonr(score, image)[0] #ret.loc[shrink(trait_i + sign_i)][shrink(trait_j + sign_j)] = (score_mask * image_mask).sum() / (image_mask.sum()) print(ret) sns.heatmap(ret, annot=True, cmap="Blues", fmt='.3f', mask=mask) pylab.gca().xaxis.tick_top() pylab.gca().set_yticklabels(ret.index.values, rotation=0) pylab.tight_layout(pad=2) # pylab.show() pylab.suptitle("Pearson $\\rho$") pylab.xlabel("Trait") pylab.ylabel("Trait") pylab.savefig('plots/ocean_pearson.eps') ret.to_csv("confusion.csv") def get_pearson_matrix(scores, images, confidence_interval=0): traits = list(scores.columns) ret = np.zeros((len(traits), len(traits))) for i, trait_i in enumerate(traits): s = scores[trait_i].as_matrix() for j, trait_j in enumerate(traits): mask = np.ones_like(s, dtype=bool) im = images[trait_j].as_matrix() ret[i, j] += np.corrcoef(s[mask], im[mask])[0,1] if i != j: ret[j,i] = 0 # ret[j, i] += np.corrcoef(scores[trait_i].as_matrix(), images[trait_j].as_matrix())[0,1] / 2. pylab.title(trait_i) pylab.bar(range(5), height=ret[i, :]) pylab.xticks(range(5), traits, rotation='30') pylab.tight_layout() pylab.show() return pandas.DataFrame(ret, columns=[traits], index=[traits]) def welch_matrix(scores, images): traits = list(scores.columns) traits = ["Openness", "Conscientiousness", "Extraversion", "Agreeableness", "Neuroticism"] ret = np.zeros((len(traits), len(traits))) for i, trait_i in enumerate(traits): arr_i = scores[trait_i].as_matrix() arr_i = (arr_i > np.median(arr_i)).astype(float) * 200 - 100 for j, trait_j in enumerate(traits): arr_j = images[trait_j].values ret[i, j] = scipy.stats.kendalltau(arr_i, arr_j)[0] if i != j: ret[j,i] = 0 with sns.plotting_context("notebook", font_scale=1.5): pylab.clf() cmap = sns.cubehelix_palette(100, start=0, rot=-0.25, reverse=False) v = ret[i, :].max() - ret[i, :].min() color = (99 * (ret[i, :] - ret[i, :].min()) / v).astype(int) for idx in range(5): pylab.bar(idx, height=ret[i, idx], color=cmap[color[idx]]) pylab.text(idx, ret[i, idx] + v * (0.025 if ret[i,idx] > 0 else -0.04), traits[idx], horizontalalignment="center", fontsize=12) pylab.ylabel("Spearman $\\rho$") pylab.tight_layout() pylab.gca().set_xticks([]) pylab.show() return pandas.DataFrame(ret, columns=[traits], index=[traits]) def binarization(scores, images, trait): ret = [] scr = scores[trait].as_matrix() x = [] for threshold in range(10, 100, 5): scrt = (scr > threshold).astype(float) ret.append(np.corrcoef(scrt, images[trait].values)[0, 1]) x.append(threshold) return np.array(x), np.array(ret) def save_histograms(pscores): with sns.plotting_context("notebook", font_scale=2.5): for column in pscores.columns: pylab.figure() pylab.title(str(column)) data = pscores[column].values data = data - data.mean() data = data / data.max() pylab.hist(data) pylab.xlabel('score') pylab.ylabel('count') pylab.tight_layout(pad=0) pylab.xlim(-1, 1) pylab.savefig("plots/%s_histogram.eps" %(str(column))) pylab.close() if __name__ == "__main__": with open("backup/personality_local.json", 'r') as infile: local = json.load(infile) with open("backup/personality_new.json", 'r') as infile: remote = json.load(infile) merged = local + remote scores = [] images = [] for datum in merged: scores.append(datum["scores"]) images.append(datum["images"]) pscores = pandas.DataFrame.from_records(scores) #save_histograms(pscores) #pscores.hist() pimages = pandas.DataFrame.from_records(images) * -100 #get_confusion_matrix(pscores, pimages) get_confusion_matrix_join(pscores, pimages) # pimages.hist() # pylab.figure() # pylab.title("Thresholding") # rets = [] # for i, trait in enumerate(list(pscores.columns)): # pylab.subplot(3,2, i+1) # x, ret = binarization(pscores, pimages, trait) # rets.append(ret.copy()) # pylab.plot(x, ret) # pylab.xlabel("threshold") # pylab.ylabel("correlation") # pylab.title(trait) # pylab.subplot(3, 2, 6) # pylab.plot(x, np.nanmean(rets, 0)) # pylab.title("mean") # pylab.show() # with pandas.option_context('display.max_rows', None, 'display.max_columns', None): #print(get_pearson_matrix(pscores, pimages)) # print(welch_matrix(pscores, pimages))
[ "pylab.title", "seaborn.cubehelix_palette", "pylab.savefig", "ndjson.load", "pylab.xlabel", "seaborn.set_style", "numpy.array", "scipy.stats.pearsonr", "pylab.bar", "pylab.gca", "pylab.ylabel", "pylab.xlim", "pandas.DataFrame", "pylab.suptitle", "scipy.stats.kendalltau", "pylab.tight_l...
[((40, 64), 'matplotlib.use', 'matplotlib.use', (['"""qt5agg"""'], {}), "('qt5agg')\n", (54, 64), False, 'import matplotlib\n'), ((100, 126), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (113, 126), True, 'import seaborn as sns\n'), ((2042, 2106), 'seaborn.heatmap', 'sns.heatmap', (['ret'], {'annot': '(True)', 'cmap': '"""Blues"""', 'fmt': '""".2f"""', 'mask': 'mask'}), "(ret, annot=True, cmap='Blues', fmt='.2f', mask=mask)\n", (2053, 2106), True, 'import seaborn as sns\n'), ((2211, 2238), 'pylab.suptitle', 'pylab.suptitle', (['"""Precision"""'], {}), "('Precision')\n", (2225, 2238), False, 'import pylab\n'), ((2243, 2264), 'pylab.xlabel', 'pylab.xlabel', (['"""Trait"""'], {}), "('Trait')\n", (2255, 2264), False, 'import pylab\n'), ((2269, 2290), 'pylab.ylabel', 'pylab.ylabel', (['"""Trait"""'], {}), "('Trait')\n", (2281, 2290), False, 'import pylab\n'), ((2328, 2367), 'pylab.savefig', 'pylab.savefig', (['"""plots/precisionmat.eps"""'], {}), "('plots/precisionmat.eps')\n", (2341, 2367), False, 'import pylab\n'), ((2372, 2384), 'pylab.show', 'pylab.show', ([], {}), '()\n', (2382, 2384), False, 'import pylab\n'), ((3687, 3751), 'seaborn.heatmap', 'sns.heatmap', (['ret'], {'annot': '(True)', 'cmap': '"""Blues"""', 'fmt': '""".3f"""', 'mask': 'mask'}), "(ret, annot=True, cmap='Blues', fmt='.3f', mask=mask)\n", (3698, 3751), True, 'import seaborn as sns\n'), ((3851, 3876), 'pylab.tight_layout', 'pylab.tight_layout', ([], {'pad': '(2)'}), '(pad=2)\n', (3869, 3876), False, 'import pylab\n'), ((3900, 3933), 'pylab.suptitle', 'pylab.suptitle', (['"""Pearson $\\\\rho$"""'], {}), "('Pearson $\\\\rho$')\n", (3914, 3933), False, 'import pylab\n'), ((3938, 3959), 'pylab.xlabel', 'pylab.xlabel', (['"""Trait"""'], {}), "('Trait')\n", (3950, 3959), False, 'import pylab\n'), ((3964, 3985), 'pylab.ylabel', 'pylab.ylabel', (['"""Trait"""'], {}), "('Trait')\n", (3976, 3985), False, 'import pylab\n'), ((3990, 4030), 'pylab.savefig', 'pylab.savefig', (['"""plots/ocean_pearson.eps"""'], {}), "('plots/ocean_pearson.eps')\n", (4003, 4030), False, 'import pylab\n'), ((4840, 4895), 'pandas.DataFrame', 'pandas.DataFrame', (['ret'], {'columns': '[traits]', 'index': '[traits]'}), '(ret, columns=[traits], index=[traits])\n', (4856, 4895), False, 'import pandas\n'), ((6161, 6216), 'pandas.DataFrame', 'pandas.DataFrame', (['ret'], {'columns': '[traits]', 'index': '[traits]'}), '(ret, columns=[traits], index=[traits])\n', (6177, 6216), False, 'import pandas\n'), ((7507, 7544), 'pandas.DataFrame.from_records', 'pandas.DataFrame.from_records', (['scores'], {}), '(scores)\n', (7536, 7544), False, 'import pandas\n'), ((4657, 4677), 'pylab.title', 'pylab.title', (['trait_i'], {}), '(trait_i)\n', (4668, 4677), False, 'import pylab\n'), ((4786, 4806), 'pylab.tight_layout', 'pylab.tight_layout', ([], {}), '()\n', (4804, 4806), False, 'import pylab\n'), ((4815, 4827), 'pylab.show', 'pylab.show', ([], {}), '()\n', (4825, 4827), False, 'import pylab\n'), ((6511, 6522), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (6519, 6522), True, 'import numpy as np\n'), ((6524, 6537), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (6532, 6537), True, 'import numpy as np\n'), ((6578, 6626), 'seaborn.plotting_context', 'sns.plotting_context', (['"""notebook"""'], {'font_scale': '(2.5)'}), "('notebook', font_scale=2.5)\n", (6598, 6626), True, 'import seaborn as sns\n'), ((7213, 7230), 'ndjson.load', 'json.load', (['infile'], {}), '(infile)\n', (7222, 7230), True, 'import ndjson as json\n'), ((7309, 7326), 'ndjson.load', 'json.load', (['infile'], {}), '(infile)\n', (7318, 7326), True, 'import ndjson as json\n'), ((7609, 7646), 'pandas.DataFrame.from_records', 'pandas.DataFrame.from_records', (['images'], {}), '(images)\n', (7638, 7646), False, 'import pandas\n'), ((2112, 2123), 'pylab.gca', 'pylab.gca', ([], {}), '()\n', (2121, 2123), False, 'import pylab\n'), ((3789, 3800), 'pylab.gca', 'pylab.gca', ([], {}), '()\n', (3798, 3800), False, 'import pylab\n'), ((4356, 4383), 'numpy.ones_like', 'np.ones_like', (['s'], {'dtype': 'bool'}), '(s, dtype=bool)\n', (4368, 4383), True, 'import numpy as np\n'), ((5478, 5526), 'seaborn.plotting_context', 'sns.plotting_context', (['"""notebook"""'], {'font_scale': '(1.5)'}), "('notebook', font_scale=1.5)\n", (5498, 5526), True, 'import seaborn as sns\n'), ((5540, 5551), 'pylab.clf', 'pylab.clf', ([], {}), '()\n', (5549, 5551), False, 'import pylab\n'), ((5571, 5632), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', (['(100)'], {'start': '(0)', 'rot': '(-0.25)', 'reverse': '(False)'}), '(100, start=0, rot=-0.25, reverse=False)\n', (5592, 5632), True, 'import seaborn as sns\n'), ((6020, 6052), 'pylab.ylabel', 'pylab.ylabel', (['"""Spearman $\\\\rho$"""'], {}), "('Spearman $\\\\rho$')\n", (6032, 6052), False, 'import pylab\n'), ((6065, 6085), 'pylab.tight_layout', 'pylab.tight_layout', ([], {}), '()\n', (6083, 6085), False, 'import pylab\n'), ((6137, 6149), 'pylab.show', 'pylab.show', ([], {}), '()\n', (6147, 6149), False, 'import pylab\n'), ((6679, 6693), 'pylab.figure', 'pylab.figure', ([], {}), '()\n', (6691, 6693), False, 'import pylab\n'), ((6860, 6876), 'pylab.hist', 'pylab.hist', (['data'], {}), '(data)\n', (6870, 6876), False, 'import pylab\n'), ((6889, 6910), 'pylab.xlabel', 'pylab.xlabel', (['"""score"""'], {}), "('score')\n", (6901, 6910), False, 'import pylab\n'), ((6923, 6944), 'pylab.ylabel', 'pylab.ylabel', (['"""count"""'], {}), "('count')\n", (6935, 6944), False, 'import pylab\n'), ((6957, 6982), 'pylab.tight_layout', 'pylab.tight_layout', ([], {'pad': '(0)'}), '(pad=0)\n', (6975, 6982), False, 'import pylab\n'), ((6995, 7012), 'pylab.xlim', 'pylab.xlim', (['(-1)', '(1)'], {}), '(-1, 1)\n', (7005, 7012), False, 'import pylab\n'), ((7092, 7105), 'pylab.close', 'pylab.close', ([], {}), '()\n', (7103, 7105), False, 'import pylab\n'), ((2295, 2306), 'pylab.gca', 'pylab.gca', ([], {}), '()\n', (2304, 2306), False, 'import pylab\n'), ((3756, 3767), 'pylab.gca', 'pylab.gca', ([], {}), '()\n', (3765, 3767), False, 'import pylab\n'), ((4454, 4484), 'numpy.corrcoef', 'np.corrcoef', (['s[mask]', 'im[mask]'], {}), '(s[mask], im[mask])\n', (4465, 4484), True, 'import numpy as np\n'), ((5373, 5409), 'scipy.stats.kendalltau', 'scipy.stats.kendalltau', (['arr_i', 'arr_j'], {}), '(arr_i, arr_j)\n', (5395, 5409), False, 'import scipy\n'), ((5805, 5863), 'pylab.bar', 'pylab.bar', (['idx'], {'height': 'ret[i, idx]', 'color': 'cmap[color[idx]]'}), '(idx, height=ret[i, idx], color=cmap[color[idx]])\n', (5814, 5863), False, 'import pylab\n'), ((5880, 6012), 'pylab.text', 'pylab.text', (['idx', '(ret[i, idx] + v * (0.025 if ret[i, idx] > 0 else -0.04))', 'traits[idx]'], {'horizontalalignment': '"""center"""', 'fontsize': '(12)'}), "(idx, ret[i, idx] + v * (0.025 if ret[i, idx] > 0 else -0.04),\n traits[idx], horizontalalignment='center', fontsize=12)\n", (5890, 6012), False, 'import pylab\n'), ((6425, 6464), 'numpy.corrcoef', 'np.corrcoef', (['scrt', 'images[trait].values'], {}), '(scrt, images[trait].values)\n', (6436, 6464), True, 'import numpy as np\n'), ((3393, 3427), 'scipy.stats.pearsonr', 'scipy.stats.pearsonr', (['score', 'image'], {}), '(score, image)\n', (3413, 3427), False, 'import scipy\n'), ((6098, 6109), 'pylab.gca', 'pylab.gca', ([], {}), '()\n', (6107, 6109), False, 'import pylab\n'), ((5217, 5233), 'numpy.median', 'np.median', (['arr_i'], {}), '(arr_i)\n', (5226, 5233), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np from PIL import Image import flowpy flow = flowpy.flow_read("static/kitti_occ_000010_10.png") first_image = np.asarray(Image.open("static/kitti_000010_10.png")) second_image = np.asarray(Image.open("static/kitti_000010_11.png")) flow[np.isnan(flow)] = 0 warped_second_image = flowpy.forward_warp(first_image, flow) fig, ax = plt.subplots() ax.imshow(warped_second_image) ax.set_title( "First image warped to the second") ax.set_axis_off() plt.show()
[ "PIL.Image.open", "matplotlib.pyplot.show", "flowpy.flow_read", "numpy.isnan", "matplotlib.pyplot.subplots", "flowpy.forward_warp" ]
[((97, 147), 'flowpy.flow_read', 'flowpy.flow_read', (['"""static/kitti_occ_000010_10.png"""'], {}), "('static/kitti_occ_000010_10.png')\n", (113, 147), False, 'import flowpy\n'), ((331, 369), 'flowpy.forward_warp', 'flowpy.forward_warp', (['first_image', 'flow'], {}), '(first_image, flow)\n', (350, 369), False, 'import flowpy\n'), ((381, 395), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (393, 395), True, 'import matplotlib.pyplot as plt\n'), ((497, 507), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (505, 507), True, 'import matplotlib.pyplot as plt\n'), ((173, 213), 'PIL.Image.open', 'Image.open', (['"""static/kitti_000010_10.png"""'], {}), "('static/kitti_000010_10.png')\n", (183, 213), False, 'from PIL import Image\n'), ((241, 281), 'PIL.Image.open', 'Image.open', (['"""static/kitti_000010_11.png"""'], {}), "('static/kitti_000010_11.png')\n", (251, 281), False, 'from PIL import Image\n'), ((289, 303), 'numpy.isnan', 'np.isnan', (['flow'], {}), '(flow)\n', (297, 303), True, 'import numpy as np\n')]
from adlib27.optimize import optimize from adlib27.elem_function import exp, sin, cos, tan, arcsin, arccos, arctan, sinh, cosh, tanh, logistic, log, log2, log10, logb, sqrt from adlib27.autodiff import AutoDiff as AD import numpy as np #initialize the program and ask for variables def getvars(): yeslist = ["y", "Yes", "Y", "yes"] more = True variables = [] if input("Welcome to AdLib27. Does your function contain any variables? [y/n]: ") in yeslist: while more == True: #if there are variables, must enter a variable that is composed of letters a = input("Please enter your variable: ") if a.isalpha() == True and a not in variables: variables.append(a) #if variable already exists or is not a letter, retry else: print("Invalid or duplicate variable name. Please retry.") #ask if user wants to enter another function, then execute loop again if true. if input("Would you like to enter another variable? [y/n]: ") in yeslist: more = True else: more = False #return collected variables print("Your variables are: ", variables) return variables #function to get the function that will be evaulated def getfunc(variables): #ask for a formatted function (using the formatting in out documentation, and standard to python) func = input("Enter a Python-formatted function for evaluation: ") dummyfunc = func x=1 #check if function contains all variables for var in variables: if not var in dummyfunc: print("This function is invalid or does not contain all variables, please retry.") return False else: dummyfunc = dummyfunc.replace(var,"x") try: #check if function is executable, using a dummy variable x exec(dummyfunc) except: #if not valid, retry entry print("This is not a valid function, please retry.") return False else: return func #function to get the mode: evaluating at a given point, or optimizing over a range def getmode(): mode = input("Would you like to \n(a) evaluate at a point, or \n(b) optimize over a range? [a/b] ") if mode.lower() == 'a': return 0 elif mode.lower() == 'b': return 1 else: return 2 #function to get values for optimization def getoptvals(variables): #ask for some step size that must be a float step = input("What step size would you like to take while finding values? Please enter a float. Note that small step sizes will increase program runtime. ") try: step = abs(float(step)) except: #if not a float, retry print("Not a valid step size") return False #ask for start of range that must be float start = input("At what value would you like to start searching? ") try: start = float(start) except: print("Not a valid start point") return False #ask for end of range that must be floats end = input("At what value would you like to stop searching? ") try: end = float(end) assert end > start except: print("Not a valid end point") return False #create list of values to test using numpy linspace optval = list(np.linspace(start, end, ((end-start)/step)+1)) return optval #for point evaluation mode, find number of points being evaluated def getpointnum(): x = input("How many points would you like to evaluate at? ") try: x = abs(int(x)) except: print("This is not a valid number of evaluation points, please retry") return False else: return x #for point evaluation mode, ask for places to evaluate for each variables def getvalues(variables, pointnum): i = 0 values =[] j = 0 while i < len(variables): print("Enter an evaluation value for the variable '", variables[i], "' as a python-formatted list of length", pointnum, "of floats or integers:") values.append(input().strip('][').split(', ')) i += 1 #map to floats, must be valid while j < len(values): try: values[j] = list(map(float, values[j])) j += 1 except: print("Not all evaluation values are valid, please re-start entries.") return False return values #use ADlist to evaluate value and derivative for a function def getresult(values,variables,func): funcdict = {"exp": exp, "sin": sin, "cos": cos, "tan": tan, "arcsin": arcsin, "arccos": arccos, "arctan": arctan, "sinh": sinh, "cosh": cosh, "tanh": tanh, "logistic": logistic, "log": log, "log2": log2, "log10": log10, "logb": logb, "sqrt": sqrt} i = 0 ADlist = [] vardict = {} while i < len(variables): ADlist.append(AD(values[i],i,len(variables))) vardict[variables[i]] = ADlist[i] i += 1 return eval(func,funcdict,vardict) #represent result for point evaluation mode def reprresult(values, variables, result, pointnum, func): #represent values after evaluation def reprvals(values, variables, pointnum): valrep = [] a = 0 while a < pointnum: b = 0 pointsrep = [] while b < len(variables): pointrep = [] pointrep.append(str(variables[b])) pointrep.append(" = ") pointrep.append("{:.5f}".format(values[b][a])) pointsrep.append(''.join(pointrep)) b += 1 valrep.append(', '.join(pointsrep)) a += 1 return valrep #represent derivatives after evaluation def reprders(result, variables, pointnum): derrep = [] a = 0 while a < pointnum: b = 0 drep = [] while b < len(variables): ddrep = [] ddrep.append("df/d") ddrep.append(str(variables[b])) ddrep.append(" = ") ddrep.append("{:.5f}".format(result.der[b][a])) drep.append(''.join(ddrep)) b += 1 derrep.append(', '.join(drep)) a += 1 return derrep vals = reprvals(values, variables, pointnum) ders = reprders(result, variables, pointnum) c = 0 reslist = [] #put all together into string for output, for each point while c < pointnum: resmini = [] resmini.append("For evaluation values (") resmini.append(vals[c]) resmini.append("), the value of the function f=") resmini.append(str(func)) resmini.append(" is: ") resmini.append("{:.5f}".format(result.val[c])) resmini.append(" and the the derivatives are: ") resmini.append(ders[c]) reslist.append(''.join(resmini)) c += 1 return '\n\n'.join(reslist) #represent results for optimization def repropt(optimized, vals, variables, func): #within a domain, represent local min and max for function optout = [] optout.append("\nIn the domain ") optout.append("{:.5f}".format(vals[0])) optout.append(" to ") optout.append("{:.5f}".format(vals[-1])) optout.append(", the extrema for ") optout.append(str(func)) optout.append(" represented as ") optout.append(str(variables)) optout.append(" are:") optout.append("\nThe local minimum is the ") optout.append((str(optimized.get("global minimum").get("inflection type")))) optout.append(" located in the range ") optout.append(str(optimized.get("global minimum").get("input range"))) optout.append(" valued near ") optout.append(str(optimized.get("global minimum").get("value range"))) optout.append("\nThe local maximum is the ") optout.append((str(optimized.get("global maximum").get("inflection type")))) optout.append(" located in the range ") optout.append(str(optimized.get("global maximum").get("input range"))) optout.append(" valued near ") optout.append(str(optimized.get("global maximum").get("value range"))) return ''.join(optout) #ask if cotinued optimizing after output def contopt(): yeslist = ["y", "Yes", "Y", "yes"] if input("Would you like to continue optimizing this function? [y/n] ") in yeslist: return True else: return False def main(): gv = getvars() gf = getfunc(gv) while gf == False: gf = getfunc(gv) gm = getmode() while gm == 2: gm = getmode() if gm == 0: gp= getpointnum() while gp == False: gp = getpointnum() gx = getvalues(gv, gp) while gx == False: gx = getvalues(gv, gp) print(reprresult(gx,gv,getresult(gx,gv,gf),gp,gf)) else: searching = True while searching == True: go = getoptvals(gv) while go == False: go = getoptvals(gv) print(repropt(optimize(go,gv,gf), go, gv, gf)) searching = contopt() if __name__ == '__main__': main()
[ "numpy.linspace", "adlib27.optimize.optimize" ]
[((3389, 3438), 'numpy.linspace', 'np.linspace', (['start', 'end', '((end - start) / step + 1)'], {}), '(start, end, (end - start) / step + 1)\n', (3400, 3438), True, 'import numpy as np\n'), ((9032, 9052), 'adlib27.optimize.optimize', 'optimize', (['go', 'gv', 'gf'], {}), '(go, gv, gf)\n', (9040, 9052), False, 'from adlib27.optimize import optimize\n')]
import numpy as np from sklearn import linear_model X = np.random.randn(10, 5) y = np.random.randn(10) X y #clf = linear_model.SGDRegressor( penalty = 'l2' , max_iter=1000, tol=1e-3 , loss = 'huber') clf = linear_model.SGDRegressor( penalty = 'l2' , max_iter=1000, tol=1e-3 , loss = 'squared_loss') #clf = linear_model.SGDRegressor( penalty = 'l1' , max_iter=1000, tol=1e-3 , loss = 'huber') #clf = linear_model.SGDRegressor( penalty = 'l1' , max_iter=1000, tol=1e-3 , loss = 'squared_loss') clf.fit(X, y) clf.score(X,y) z = np.random.randn(5) print('Predict for ',z , ' is ' , clf.predict(z.reshape(1,-1)))
[ "numpy.random.randn", "sklearn.linear_model.SGDRegressor" ]
[((56, 78), 'numpy.random.randn', 'np.random.randn', (['(10)', '(5)'], {}), '(10, 5)\n', (71, 78), True, 'import numpy as np\n'), ((83, 102), 'numpy.random.randn', 'np.random.randn', (['(10)'], {}), '(10)\n', (98, 102), True, 'import numpy as np\n'), ((207, 298), 'sklearn.linear_model.SGDRegressor', 'linear_model.SGDRegressor', ([], {'penalty': '"""l2"""', 'max_iter': '(1000)', 'tol': '(0.001)', 'loss': '"""squared_loss"""'}), "(penalty='l2', max_iter=1000, tol=0.001, loss=\n 'squared_loss')\n", (232, 298), False, 'from sklearn import linear_model\n'), ((529, 547), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (544, 547), True, 'import numpy as np\n')]
#!/usr/bin/env python #-*- coding: utf-8 -*- import meep_utils, meep_materials import numpy as np from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab """ """ class dielbar_model(meep_utils.AbstractMeepModel): #{{{ """ Array of dielectric bars or blocks #{{{ FD 2013-07-13 |PMLPMLPML| ^ +---------+ <-- monitor plane 2 | | | z | | <-- Bloch-periodic boundaries on X, Y faces | +---+ | | |XXX| |<------- bar of TiO2 | +---+ | | | | | y +---------+ <-- monitor plane 1 --> +=========+ <-- source |PMLPMLPML| #}}} """ def cell_centers(self):#{{{ """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) ## alternatively: add surrounding two cells to compare the propagation _inside_ a metamaterial #return np.arange(-self.monzd*(self.cells+1)/2, self.monzd*(self.cells+1)/2+1e-12, self.monzd)#}}} def __init__(self, comment="", simtime=100e-12, resolution=6e-6, cells=1, monzc=0e-6, Kx=0, Ky=0, xs=55e-6, ys=95e-6, zs=25e-6, xyspacing=150e-6, monzd=100e-6, padding=0e-6, metalspacing=0e-6): meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "DielectricBar" ## self.register_locals(locals()) ## Remember the parameters ## Initialization of materials used #self.materials = [meep_materials.material_TiO2_THz(where = self.where_TiO2)] #self.materials = [meep_materials.material_dielectric(where = self.where_TiO2, eps=4.)] self.materials = [ meep_materials.material_dielectric(where = self.where_TiO2, eps=12.), #meep_materials.material_STO(where = self.where_TiO2), #meep_materials.material_STO_THz(where = self.where_TiO2), #meep_materials.material_STO_hiloss(where = self.where_TiO2), #meep_materials.material_Metal_THz(where = self.where_metal) ] ## Dimension constants for the simulation #self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 400e-6+cells*self.monzd self.size_x = resolution/1.8 if (xs==np.inf) else xyspacing self.size_y = resolution/.9 if (ys==np.inf) else xyspacing self.size_z = 300e-6+cells*self.monzd ## constants for the simulation self.pml_thickness = 30e-6 (self.monitor_z1, self.monitor_z2) = (-(monzd*cells)/2+monzc, (monzd*cells)/2+monzc) self.simtime = simtime # [s] self.srcWidth = 2000e9 self.srcFreq = 1000e9 #self.srcFreq = 4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.interesting_frequencies = (0., 3000e9) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback #meep_utils.plot_eps(self.materials, freq_range=(1e10, 1e14)) def where_TiO2(self, r): for cellz in self.cell_centers(): zz = in_zslab(r, cz=cellz, d=self.zs) yy = in_yslab(r, cy=0, d=self.ys) xx = in_xslab(r, cx=0, d=self.xs) if (zz and yy and xx): return self.return_value return 0 def where_metal(self, r): ## XXX for cellz in self.cell_centers(): zz = in_zslab(r, cz=cellz+self.zs/2+10e-6/2 + self.metalspacing, d=10e-6) xx = in_xslab(r, cx=0, d=self.xyspacing-10e-6) yy = in_yslab(r, cy=0, d=self.xyspacing-10e-6) if (zz and yy and xx): return self.return_value return 0 #}}} class XCylWire_model(meep_utils.AbstractMeepModel): #{{{ """ Array of circular metallic wires along electric field FD 2013-07-13 """ def cell_centers(self): """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) ## alternatively: add surrounding two cells to compare the propagation _inside_ a metamaterial #return np.arange(-self.monzd*(self.cells+1)/2, self.monzd*(self.cells+1)/2+1e-12, self.monzd) def __init__(self, comment="", simtime=100e-12, resolution=6e-6, cells=1, monzc=0e-6, Kx=0, Ky=0, padding=50e-6, radius=10e-6, yspacing=100e-6, monzd=100e-6, epsilon=100): meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "XCylWire" ## self.register_locals(locals()) ## Remember the parameters ## Initialization of materials used if 'TiO2' in comment: self.materials = [meep_materials.material_TiO2_THz(where = self.where_wire)] elif 'STO' in comment: self.materials = [meep_materials.material_STO_THz(where = self.where_wire)] elif 'DielLossless' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0.0)] elif 'DielLoLoss' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0.005)] elif 'Diel' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0.05)] else: self.materials = [meep_materials.material_Metal_THz(where = self.where_wire)] ## Dimension constants for the simulation #self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 400e-6+cells*self.monzd self.pml_thickness = 20e-6 self.size_x = resolution/1.8 self.size_x = yspacing #XXX self.size_y = yspacing self.size_z = 200e-6+cells*self.monzd + 2*self.padding + 2*self.pml_thickness ## constants for the simulation (self.monitor_z1, self.monitor_z2) = (-(monzd*cells)/2+monzc - padding, (monzd*cells)/2+monzc + padding) self.simtime = simtime # [s] self.srcWidth = 5000e9 self.srcFreq = 4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.interesting_frequencies = (0., 2000e9) #meep_utils.plot_eps(self.materials, freq_range=(1e10, 1e14), plot_conductivity=True) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback def where_wire(self, r): for cellz in self.cell_centers(): if (in_xcyl(r, cy=self.resolution/4, cz=cellz, rad=self.radius)): return self.return_value #if (in_zslab(r, cz=cellz, d=self.radius)): # and in_yslab(r, cy=.7e-6, d=60e-6-self.radius)): # XXX #return self.return_value #if abs(cellz)>self.yspacing*1.5: #if (in_zslab(r, cz=cellz, d=self.radius)): # and in_yslab(r, cy=.7e-6, d=60e-6-self.radius)): # XXX #return self.return_value #else: #if (in_zslab(r, cz=cellz, d=self.radius*2)): # and in_yslab(r, cy=.7e-6, d=60e-6-self.radius)): # XXX #return self.return_value return 0 #}}} class YCylWire_model(meep_utils.AbstractMeepModel): #{{{ """ Array of circular metallic wires along electric field FD 2013-07-13 """ def cell_centers(self): """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) ## alternatively: add surrounding two cells to compare the propagation _inside_ a metamaterial #return np.arange(-self.monzd*(self.cells+1)/2, self.monzd*(self.cells+1)/2+1e-12, self.monzd) def __init__(self, comment="", simtime=100e-12, resolution=6e-6, cells=1, monzc=0e-6, Kx=0, Ky=0, padding=50e-6, radius=20e-6, xspacing=100e-6, monzd=100e-6, epsilon=600): meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "YCylWire" ## self.register_locals(locals()) ## Remember the parameters ## Initialization of materials used if 'TiO2' in comment: self.materials = [meep_materials.material_TiO2_THz(where = self.where_wire)] elif 'STO' in comment: self.materials = [meep_materials.material_STO_THz(where = self.where_wire)] elif 'Diel' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0.001)] else: self.materials = [meep_materials.material_Metal_THz(where = self.where_wire)] ## Dimension constants for the simulation #self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 400e-6+cells*self.monzd self.pml_thickness = 20e-6 self.size_x = xspacing self.size_y = resolution/1.8 self.size_z = 200e-6+cells*self.monzd + 2*self.padding + 2*self.pml_thickness ## constants for the simulation self.monitor_z1 =-(monzd*cells)/2+self.monzc - self.padding self.monitor_z2 = (monzd*cells)/2+self.monzc + self.padding self.simtime = simtime # [s] self.srcWidth = 3000e9 self.srcFreq = 1e12 #4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.interesting_frequencies = (0., 3000e9) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback def where_wire(self, r): for cellz in self.cell_centers(): if (in_ycyl(r, cx=self.resolution/4, cz=cellz, rad=self.radius)): return self.return_value #if (in_zslab(r, cz=cellz, d=self.radius) and in_yslab(r, cy=.7e-6, d=60e-6-self.radius)): # XXX #return self.return_value return 0 #}}} class XRectWire_model(meep_utils.AbstractMeepModel): #{{{ """ Array of circular metallic wires along electric field FD 2013-07-13 """ def cell_centers(self): """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) ## alternatively: add surrounding two cells to compare the propagation _inside_ a metamaterial #return np.arange(-self.monzd*(self.cells+1)/2, self.monzd*(self.cells+1)/2+1e-12, self.monzd) def __init__(self, comment="STO", simtime=100e-12, resolution=2e-6, cells=1, Kx=0, Ky=0, width=64e-6, thick=26e-6, yspacing=96e-6, monzd=96e-6, epsilon=600, padding=50e-6): ## XXX padding=100e-6 ## XXX meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "XRectWire" ## self.monzc=0e-6 self.register_locals(locals()) ## Remember the parameters self.padding=50e-6 self.monzc=0e-6 ## Initialization of materials used if 'TiO2' in comment: self.materials = [meep_materials.material_TiO2_THz(where = self.where_wire)] elif 'STO' in comment: self.materials = [meep_materials.material_STO_THz(where = self.where_wire)] elif 'DielLossless' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0)] elif 'DielLoloss' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0.01)] elif 'Diel' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=.1)] else: self.materials = [meep_materials.material_Metal_THz(where = self.where_wire)] ## Dimension constants for the simulation #self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 400e-6+cells*self.monzd self.pml_thickness = 20e-6 self.size_x = resolution/1.8 self.size_y = yspacing self.size_z = 200e-6+cells*self.monzd + 2*self.padding + 2*self.pml_thickness ## constants for the simulation self.monitor_z1 =-(monzd*cells)/2+self.monzc - self.padding self.monitor_z2 = (monzd*cells)/2+self.monzc + self.padding self.simtime = simtime # [s] self.srcWidth = 3000e9 #self.srcFreq = 4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.srcFreq = 1e12 self.interesting_frequencies = (0., 1000e9) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback def where_wire(self, r): for cellz in self.cell_centers(): #if (in_xcyl(r, cy=self.resolution/4, cz=cellz+self.resolution/4, rad=self.radius)): #return self.return_value if (in_zslab(r, cz=cellz, d=self.thick) and in_yslab(r, cy=.7e-6, d=self.width)): # XXX return self.return_value return 0 #}}} class XRectWireMet_model(meep_utils.AbstractMeepModel): #{{{ """ FD 2013-07-13 """ def cell_centers(self): """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) ## alternatively: add surrounding two cells to compare the propagation _inside_ a metamaterial #return np.arange(-self.monzd*(self.cells+1)/2, self.monzd*(self.cells+1)/2+1e-12, self.monzd) def __init__(self, comment="", simtime=100e-12, resolution=2e-6, cells=1, Kx=0, Ky=0, width=64e-6, thick=26e-6, yspacing=96e-6, monzd=96e-6, epsilon=100, padding=50e-6): meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "XRectWire" ## self.monzc=0e-6 self.register_locals(locals()) ## Remember the parameters self.padding=50e-6 self.monzc=0e-6 ## Initialization of materials used self.materials = [ meep_materials.material_dielectric(where = self.where_slab, eps=epsilon, loss=0.01), meep_materials.material_Metal_THz(where = self.where_met)] ## Dimension constants for the simulation #self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 400e-6+cells*self.monzd self.pml_thickness = 20e-6 self.size_x = resolution/1.8 self.size_y = yspacing self.size_z = 120e-6+cells*self.monzd + 2*self.padding + 2*self.pml_thickness ## constants for the simulation self.monitor_z1 =-(monzd*cells)/2+self.monzc - self.padding self.monitor_z2 = (monzd*cells)/2+self.monzc + self.padding self.simtime = simtime # [s] self.srcWidth = 3000e9 #self.srcFreq = 4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.srcFreq = 1e12 self.interesting_frequencies = (0., 1000e9) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback def where_slab(self, r): for cellz in self.cell_centers(): if (in_zslab(r, cz=cellz, d=self.thick) and in_yslab(r, cy=0e-6, d=self.width)): # XXX return self.return_value return 0 def where_met(self, r): for cellz in self.cell_centers(): #if (in_xcyl(r, cy=self.resolution/4, cz=cellz+self.resolution/4, rad=self.radius)): #return self.return_value ## Metallisation along Z #if ((in_zslab(r, cz=cellz, d=self.thick+4*self.resolution) and not in_zslab(r, cz=cellz, d=self.thick)) \ #and in_yslab(r, cy=.7e-6, d=2*self.width)): # XXX #return self.return_value if (in_zslab(r, cz=cellz, d=self.thick)) \ and (in_yslab(r, cy=0e-6, d=self.width+max(3e-6,2*self.resolution)) and not in_yslab(r, cy=0e-6, d=self.width)): # XXX return self.return_value return 0 #}}} class PKCutSheet_model_test(meep_utils.AbstractMeepModel): #{{{ """ Thin high-permittivity dielectric sheet along E,k vectors FD 2013-06-04 |PMLPMLPML| <------ Absorbing boundaries on X, Y faces ^ | | | +mmmmmmmmm+ <-- monitor plane 2 z | | <------ Bloch-periodic boundaries on X, Y faces | | |XXXXXXXXX| <---sheet of micromachined STO | | | | | +mmmmmmmmm+ <-- monitor plane 1 x | | --> +sssssssss+ <-- source |PMLPMLPML| The purpose of computing is insight, not numbers. -- <NAME> """ def cell_centers(self): """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) def __init__(self, comment="", simtime=1000e-12, resolution=5e-6, cells=1, monzc=0e-6, Kx=0, Ky=0, xs=50e-6, ys=50e-6, zs=50e-6, xyspacing=100e-6, monzd=100e-6): meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "PKCTest" ## self.register_locals(locals()) ## Remember the parameters ## Definition of materials used self.materials = [meep_materials.material_TiO2_THz(where = self.where_TiO2), ] ## Dimension constants for the simulation self.monzd = monzd self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 400e-6 + cells*self.monzd ## constants for the simulation self.pml_thickness = 100e-6 self.monitor_z1 =-(monzd*cells)/2+self.monzc - self.padding self.monitor_z2 = (monzd*cells)/2+self.monzc + self.padding self.simtime = simtime # [s] self.srcWidth = 1000e9 self.srcFreq = 4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.interesting_frequencies = (0., 1000e9) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback #def where_metal(self, r): #for cellz in self.cell_centers(): #if (in_xslab(r, cx=0e-6, d=self.wtth) or in_yslab(r, cy=0e-6, d=self.wtth)) and \ #in_zslab(r, cz=self.wzofs+cellz, d=self.wlth): #return self.return_value #return 0 def where_TiO2(self, r): for cellz in self.cell_centers(): zz = in_zslab(r, cz=cellz, d=self.zs) yy = in_yslab(r, cy=0, d=self.ys) xx = in_xslab(r, cx=0, d=self.xs) if (zz and yy and xx): return self.return_value return 0 #}}} class Fishnet_model(meep_utils.AbstractMeepModel): #{{{ """ FD 2013-09-20 """ def cell_centers(self): """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) def __init__(self, comment="", simtime=100e-12, resolution=7e-6, cells=1, monzc=0e-6, Kx=0, Ky=0, xs=50e-6, ys=50e-6, zs=12e-6, xyspacing=100e-6, monzd=100e-6, padding=50e-6): meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "PKCTest" ## self.register_locals(locals()) ## Remember the parameters ## Definition of materials used self.materials = [meep_materials.material_Metal_THz(where = self.where_metal), ] ## Dimension constants for the simulation self.monzd = monzd self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 200e-6 + cells*self.monzd ## constants for the simulation self.pml_thickness = 30e-6 self.monitor_z1 =-(monzd*cells)/2+self.monzc - self.padding self.monitor_z2 = (monzd*cells)/2+self.monzc + self.padding self.simtime = simtime # [s] self.srcWidth = 4000e9 self.srcFreq = 4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.interesting_frequencies = (0., 5000e9) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback #def where_metal(self, r): #for cellz in self.cell_centers(): #if (in_xslab(r, cx=0e-6, d=self.wtth) or in_yslab(r, cy=0e-6, d=self.wtth)) and \ #in_zslab(r, cz=self.wzofs+cellz, d=self.wlth): #return self.return_value #return 0 def where_metal(self, r): for cellz in self.cell_centers(): zz = in_zslab(r, cz=cellz, d=self.zs) yy = not in_yslab(r, cy=self.resolution/2, d=self.ys) xx = not in_xslab(r, cx=self.resolution/2, d=self.xs) if (zz and (yy or xx)): return self.return_value return 0 #}}} class XCylWire_model_test(meep_utils.AbstractMeepModel): #{{{ """ Array of metallic wires along electric field FD 2013-07-13 """ def cell_centers(self): """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) ## alternatively: add surrounding two cells to compare the propagation _inside_ a metamaterial #return np.arange(-self.monzd*(self.cells+1)/2, self.monzd*(self.cells+1)/2+1e-12, self.monzd) def __init__(self, comment="", simtime=100e-12, resolution=2e-6, cells=1, monzc=0e-6, Kx=0, Ky=0, padding=100e-6, radius=4e-6, spacing=100e-6, monzd=100e-6, epsilon=600, xlen=50e-6): meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "XCylWire" ## self.register_locals(locals()) ## Remember the parameters ## Initialization of materials used self.materials = [ meep_materials.material_Metal_THz(where = self.where_particle), #meep_materials.material_TiO2_THz(where = self.where_particle), meep_materials.material_dielectric(where = self.where_filling, eps=epsilon)] ## Dimension constants for the simulation #self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 400e-6+cells*self.monzd self.pml_thickness = 100e-6 self.size_x = spacing self.size_y = spacing self.size_z = 400e-6+cells*self.monzd + 2*self.padding + 2*self.pml_thickness ## constants for the simulation (self.monitor_z1, self.monitor_z2) = (-(monzd*cells)/2+monzc - padding , (monzd*cells)/2+monzc + padding) self.simtime = simtime # [s] self.srcWidth = 3000e9 self.srcFreq = 4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.interesting_frequencies = (0., 1000e9) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback def where_particle(self, r): for cellz in self.cell_centers(): if (in_xcyl(r, cy=self.resolution/4, cz=cellz+self.resolution/4, rad=self.radius) and in_xslab(r, cx=self.resolution/4, d=self.xlen)) : return self.return_value return 0 def where_filling(self, r): for cellz in self.cell_centers(): if (in_xcyl(r, cy=self.resolution/4, cz=cellz+self.resolution/4, rad=self.radius) and not in_xslab(r, cx=self.resolution/4, d=self.xlen)) : return self.return_value return 0 #}}} class Wedge_model(meep_utils.AbstractMeepModel): #{{{ """ Array of circular metallic wires along electric field FD 2013-07-13 """ def cell_centers(self): """ Helper function for stacked multilayered metamaterials """ return np.arange(-self.monzd*(self.cells-1)/2, self.monzd*(self.cells-1)/2+1e-12, self.monzd) ## alternatively: add surrounding two cells to compare the propagation _inside_ a metamaterial #return np.arange(-self.monzd*(self.cells+1)/2, self.monzd*(self.cells+1)/2+1e-12, self.monzd) def __init__(self, comment="TiO2", simtime=10e-12, resolution=3e-6, cells=1, monzc=0e-6, Kx=0, Ky=0, padding=50e-6, radius=10e-6, yspacing=100e-6, zspacing=100e-6, monzd=200e-6, epsilon=100): meep_utils.AbstractMeepModel.__init__(self) ## Base class initialisation self.simulation_name = "Wedge" ## self.register_locals(locals()) ## Remember the parameters ## Initialization of materials used if 'TiO2' in comment: self.materials = [meep_materials.material_TiO2_THz(where = self.where_wire)] elif 'STO' in comment: self.materials = [meep_materials.material_STO_THz(where = self.where_wire)] elif 'DielLossless' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0.0)] elif 'DielLoLoss' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0.005)] elif 'Diel' in comment: self.materials = [meep_materials.material_dielectric(where = self.where_wire, eps=epsilon, loss=0.05)] else: self.materials = [meep_materials.material_Metal_THz(where = self.where_wire)] ## Dimension constants for the simulation #self.size_x, self.size_y, self.size_z = xyspacing, xyspacing, 400e-6+cells*self.monzd self.pml_thickness = 20e-6 self.size_x = resolution/1.8 self.size_y = 2200e-6 self.size_z = 2000e-6+cells*self.monzd + 2*self.padding + 2*self.pml_thickness ## constants for the simulation (self.monitor_z1, self.monitor_z2) = (-(monzd*cells)/2+monzc - padding, (monzd*cells)/2+monzc + padding) self.simtime = simtime # [s] self.srcWidth = 3000e9 self.srcFreq = 4e9 + self.srcWidth/2 + (Ky**2+Kx**2)**.5 / (2*np.pi/3e8) ## cutoff for oblique incidence self.interesting_frequencies = (0., 2000e9) #meep_utils.plot_eps(self.materials, freq_range=(1e10, 1e14), plot_conductivity=True) self.TestMaterials() ## catches (most) errors in structure syntax, before they crash the callback def where_wire(self, r): y,z = r.y(), r.z() if z < self.size_z*(-.3) or z+y/2>0: return 0 yy,zz = np.arccos(np.cos(y/self.yspacing*np.pi*2))*self.yspacing/(np.pi*2), np.arccos(np.cos(z/self.zspacing*np.pi*2))*self.zspacing/(np.pi*2) if (yy**2+zz**2)**.5 < self.radius: return self.return_value return 0 #}}}
[ "meep_materials.material_dielectric", "meep_utils.AbstractMeepModel.__init__", "meep_materials.material_TiO2_THz", "meep_materials.material_STO_THz", "meep_utils.in_xcyl", "meep_utils.in_ycyl", "numpy.cos", "meep_utils.in_zslab", "meep_utils.in_xslab", "meep_utils.in_yslab", "meep_materials.mate...
[((848, 952), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (857, 952), True, 'import numpy as np\n'), ((1363, 1406), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (1400, 1406), False, 'import meep_utils, meep_materials\n'), ((4183, 4287), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (4192, 4287), True, 'import numpy as np\n'), ((4672, 4715), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (4709, 4715), False, 'import meep_utils, meep_materials\n'), ((7720, 7824), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (7729, 7824), True, 'import numpy as np\n'), ((8209, 8252), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (8246, 8252), False, 'import meep_utils, meep_materials\n'), ((10448, 10552), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (10457, 10552), True, 'import numpy as np\n'), ((10993, 11036), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (11030, 11036), False, 'import meep_utils, meep_materials\n'), ((13630, 13734), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (13639, 13734), True, 'import numpy as np\n'), ((14117, 14160), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (14154, 14160), False, 'import meep_utils, meep_materials\n'), ((17318, 17422), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (17327, 17422), True, 'import numpy as np\n'), ((17591, 17634), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (17628, 17634), False, 'import meep_utils, meep_materials\n'), ((19525, 19629), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (19534, 19629), True, 'import numpy as np\n'), ((19812, 19855), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (19849, 19855), False, 'import meep_utils, meep_materials\n'), ((21825, 21929), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (21834, 21929), True, 'import numpy as np\n'), ((22325, 22368), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (22362, 22368), False, 'import meep_utils, meep_materials\n'), ((24556, 24660), 'numpy.arange', 'np.arange', (['(-self.monzd * (self.cells - 1) / 2)', '(self.monzd * (self.cells - 1) / 2 + 1e-12)', 'self.monzd'], {}), '(-self.monzd * (self.cells - 1) / 2, self.monzd * (self.cells - 1) /\n 2 + 1e-12, self.monzd)\n', (24565, 24660), True, 'import numpy as np\n'), ((25065, 25108), 'meep_utils.AbstractMeepModel.__init__', 'meep_utils.AbstractMeepModel.__init__', (['self'], {}), '(self)\n', (25102, 25108), False, 'import meep_utils, meep_materials\n'), ((1842, 1909), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_TiO2', 'eps': '(12.0)'}), '(where=self.where_TiO2, eps=12.0)\n', (1876, 1909), False, 'import meep_utils, meep_materials\n'), ((3282, 3314), 'meep_utils.in_zslab', 'in_zslab', (['r'], {'cz': 'cellz', 'd': 'self.zs'}), '(r, cz=cellz, d=self.zs)\n', (3290, 3314), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((3337, 3365), 'meep_utils.in_yslab', 'in_yslab', (['r'], {'cy': '(0)', 'd': 'self.ys'}), '(r, cy=0, d=self.ys)\n', (3345, 3365), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((3392, 3420), 'meep_utils.in_xslab', 'in_xslab', (['r'], {'cx': '(0)', 'd': 'self.xs'}), '(r, cx=0, d=self.xs)\n', (3400, 3420), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((3620, 3696), 'meep_utils.in_zslab', 'in_zslab', (['r'], {'cz': '(cellz + self.zs / 2 + 1e-05 / 2 + self.metalspacing)', 'd': '(1e-05)'}), '(r, cz=cellz + self.zs / 2 + 1e-05 / 2 + self.metalspacing, d=1e-05)\n', (3628, 3696), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((3708, 3751), 'meep_utils.in_xslab', 'in_xslab', (['r'], {'cx': '(0)', 'd': '(self.xyspacing - 1e-05)'}), '(r, cx=0, d=self.xyspacing - 1e-05)\n', (3716, 3751), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((3772, 3815), 'meep_utils.in_yslab', 'in_yslab', (['r'], {'cy': '(0)', 'd': '(self.xyspacing - 1e-05)'}), '(r, cy=0, d=self.xyspacing - 1e-05)\n', (3780, 3815), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((6782, 6843), 'meep_utils.in_xcyl', 'in_xcyl', (['r'], {'cy': '(self.resolution / 4)', 'cz': 'cellz', 'rad': 'self.radius'}), '(r, cy=self.resolution / 4, cz=cellz, rad=self.radius)\n', (6789, 6843), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((9909, 9970), 'meep_utils.in_ycyl', 'in_ycyl', (['r'], {'cx': '(self.resolution / 4)', 'cz': 'cellz', 'rad': 'self.radius'}), '(r, cx=self.resolution / 4, cz=cellz, rad=self.radius)\n', (9916, 9970), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((14471, 14557), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_slab', 'eps': 'epsilon', 'loss': '(0.01)'}), '(where=self.where_slab, eps=epsilon, loss\n =0.01)\n', (14505, 14557), False, 'import meep_utils, meep_materials\n'), ((14572, 14627), 'meep_materials.material_Metal_THz', 'meep_materials.material_Metal_THz', ([], {'where': 'self.where_met'}), '(where=self.where_met)\n', (14605, 14627), False, 'import meep_utils, meep_materials\n'), ((17862, 17917), 'meep_materials.material_TiO2_THz', 'meep_materials.material_TiO2_THz', ([], {'where': 'self.where_TiO2'}), '(where=self.where_TiO2)\n', (17894, 17917), False, 'import meep_utils, meep_materials\n'), ((19069, 19101), 'meep_utils.in_zslab', 'in_zslab', (['r'], {'cz': 'cellz', 'd': 'self.zs'}), '(r, cz=cellz, d=self.zs)\n', (19077, 19101), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((19124, 19152), 'meep_utils.in_yslab', 'in_yslab', (['r'], {'cy': '(0)', 'd': 'self.ys'}), '(r, cy=0, d=self.ys)\n', (19132, 19152), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((19179, 19207), 'meep_utils.in_xslab', 'in_xslab', (['r'], {'cx': '(0)', 'd': 'self.xs'}), '(r, cx=0, d=self.xs)\n', (19187, 19207), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((20083, 20140), 'meep_materials.material_Metal_THz', 'meep_materials.material_Metal_THz', ([], {'where': 'self.where_metal'}), '(where=self.where_metal)\n', (20116, 20140), False, 'import meep_utils, meep_materials\n'), ((21293, 21325), 'meep_utils.in_zslab', 'in_zslab', (['r'], {'cz': 'cellz', 'd': 'self.zs'}), '(r, cz=cellz, d=self.zs)\n', (21301, 21325), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((22617, 22677), 'meep_materials.material_Metal_THz', 'meep_materials.material_Metal_THz', ([], {'where': 'self.where_particle'}), '(where=self.where_particle)\n', (22650, 22677), False, 'import meep_utils, meep_materials\n'), ((22777, 22850), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_filling', 'eps': 'epsilon'}), '(where=self.where_filling, eps=epsilon)\n', (22811, 22850), False, 'import meep_utils, meep_materials\n'), ((4983, 5038), 'meep_materials.material_TiO2_THz', 'meep_materials.material_TiO2_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (5015, 5038), False, 'import meep_utils, meep_materials\n'), ((8518, 8573), 'meep_materials.material_TiO2_THz', 'meep_materials.material_TiO2_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (8550, 8573), False, 'import meep_utils, meep_materials\n'), ((11380, 11435), 'meep_materials.material_TiO2_THz', 'meep_materials.material_TiO2_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (11412, 11435), False, 'import meep_utils, meep_materials\n'), ((13271, 13306), 'meep_utils.in_zslab', 'in_zslab', (['r'], {'cz': 'cellz', 'd': 'self.thick'}), '(r, cz=cellz, d=self.thick)\n', (13279, 13306), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((13311, 13346), 'meep_utils.in_yslab', 'in_yslab', (['r'], {'cy': '(7e-07)', 'd': 'self.width'}), '(r, cy=7e-07, d=self.width)\n', (13319, 13346), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((15650, 15685), 'meep_utils.in_zslab', 'in_zslab', (['r'], {'cz': 'cellz', 'd': 'self.thick'}), '(r, cz=cellz, d=self.thick)\n', (15658, 15685), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((15690, 15723), 'meep_utils.in_yslab', 'in_yslab', (['r'], {'cy': '(0.0)', 'd': 'self.width'}), '(r, cy=0.0, d=self.width)\n', (15698, 15723), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((16289, 16324), 'meep_utils.in_zslab', 'in_zslab', (['r'], {'cz': 'cellz', 'd': 'self.thick'}), '(r, cz=cellz, d=self.thick)\n', (16297, 16324), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((21352, 21398), 'meep_utils.in_yslab', 'in_yslab', (['r'], {'cy': '(self.resolution / 2)', 'd': 'self.ys'}), '(r, cy=self.resolution / 2, d=self.ys)\n', (21360, 21398), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((21420, 21466), 'meep_utils.in_xslab', 'in_xslab', (['r'], {'cx': '(self.resolution / 2)', 'd': 'self.xs'}), '(r, cx=self.resolution / 2, d=self.xs)\n', (21428, 21466), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((23783, 23871), 'meep_utils.in_xcyl', 'in_xcyl', (['r'], {'cy': '(self.resolution / 4)', 'cz': '(cellz + self.resolution / 4)', 'rad': 'self.radius'}), '(r, cy=self.resolution / 4, cz=cellz + self.resolution / 4, rad=self\n .radius)\n', (23790, 23871), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((23882, 23930), 'meep_utils.in_xslab', 'in_xslab', (['r'], {'cx': '(self.resolution / 4)', 'd': 'self.xlen'}), '(r, cx=self.resolution / 4, d=self.xlen)\n', (23890, 23930), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((24081, 24169), 'meep_utils.in_xcyl', 'in_xcyl', (['r'], {'cy': '(self.resolution / 4)', 'cz': '(cellz + self.resolution / 4)', 'rad': 'self.radius'}), '(r, cy=self.resolution / 4, cz=cellz + self.resolution / 4, rad=self\n .radius)\n', (24088, 24169), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((25371, 25426), 'meep_materials.material_TiO2_THz', 'meep_materials.material_TiO2_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (25403, 25426), False, 'import meep_utils, meep_materials\n'), ((5103, 5157), 'meep_materials.material_STO_THz', 'meep_materials.material_STO_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (5134, 5157), False, 'import meep_utils, meep_materials\n'), ((8638, 8692), 'meep_materials.material_STO_THz', 'meep_materials.material_STO_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (8669, 8692), False, 'import meep_utils, meep_materials\n'), ((11500, 11554), 'meep_materials.material_STO_THz', 'meep_materials.material_STO_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (11531, 11554), False, 'import meep_utils, meep_materials\n'), ((24184, 24232), 'meep_utils.in_xslab', 'in_xslab', (['r'], {'cx': '(self.resolution / 4)', 'd': 'self.xlen'}), '(r, cx=self.resolution / 4, d=self.xlen)\n', (24192, 24232), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((25491, 25545), 'meep_materials.material_STO_THz', 'meep_materials.material_STO_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (25522, 25545), False, 'import meep_utils, meep_materials\n'), ((5231, 5316), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.0)'}), '(where=self.where_wire, eps=epsilon, loss=0.0\n )\n', (5265, 5316), False, 'import meep_utils, meep_materials\n'), ((8758, 8845), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.001)'}), '(where=self.where_wire, eps=epsilon, loss\n =0.001)\n', (8792, 8845), False, 'import meep_utils, meep_materials\n'), ((8888, 8944), 'meep_materials.material_Metal_THz', 'meep_materials.material_Metal_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (8921, 8944), False, 'import meep_utils, meep_materials\n'), ((11628, 11706), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0)'}), '(where=self.where_wire, eps=epsilon, loss=0)\n', (11662, 11706), False, 'import meep_utils, meep_materials\n'), ((16424, 16457), 'meep_utils.in_yslab', 'in_yslab', (['r'], {'cy': '(0.0)', 'd': 'self.width'}), '(r, cy=0.0, d=self.width)\n', (16432, 16457), False, 'from meep_utils import in_sphere, in_xcyl, in_ycyl, in_zcyl, in_xslab, in_yslab, in_zslab\n'), ((25619, 25704), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.0)'}), '(where=self.where_wire, eps=epsilon, loss=0.0\n )\n', (25653, 25704), False, 'import meep_utils, meep_materials\n'), ((27196, 27233), 'numpy.cos', 'np.cos', (['(y / self.yspacing * np.pi * 2)'], {}), '(y / self.yspacing * np.pi * 2)\n', (27202, 27233), True, 'import numpy as np\n'), ((27264, 27301), 'numpy.cos', 'np.cos', (['(z / self.zspacing * np.pi * 2)'], {}), '(z / self.zspacing * np.pi * 2)\n', (27270, 27301), True, 'import numpy as np\n'), ((5383, 5470), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.005)'}), '(where=self.where_wire, eps=epsilon, loss\n =0.005)\n', (5417, 5470), False, 'import meep_utils, meep_materials\n'), ((11778, 11864), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.01)'}), '(where=self.where_wire, eps=epsilon, loss\n =0.01)\n', (11812, 11864), False, 'import meep_utils, meep_materials\n'), ((25771, 25858), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.005)'}), '(where=self.where_wire, eps=epsilon, loss\n =0.005)\n', (25805, 25858), False, 'import meep_utils, meep_materials\n'), ((5531, 5617), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.05)'}), '(where=self.where_wire, eps=epsilon, loss\n =0.05)\n', (5565, 5617), False, 'import meep_utils, meep_materials\n'), ((5660, 5716), 'meep_materials.material_Metal_THz', 'meep_materials.material_Metal_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (5693, 5716), False, 'import meep_utils, meep_materials\n'), ((11925, 12010), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.1)'}), '(where=self.where_wire, eps=epsilon, loss=0.1\n )\n', (11959, 12010), False, 'import meep_utils, meep_materials\n'), ((12052, 12108), 'meep_materials.material_Metal_THz', 'meep_materials.material_Metal_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (12085, 12108), False, 'import meep_utils, meep_materials\n'), ((25919, 26005), 'meep_materials.material_dielectric', 'meep_materials.material_dielectric', ([], {'where': 'self.where_wire', 'eps': 'epsilon', 'loss': '(0.05)'}), '(where=self.where_wire, eps=epsilon, loss\n =0.05)\n', (25953, 26005), False, 'import meep_utils, meep_materials\n'), ((26048, 26104), 'meep_materials.material_Metal_THz', 'meep_materials.material_Metal_THz', ([], {'where': 'self.where_wire'}), '(where=self.where_wire)\n', (26081, 26104), False, 'import meep_utils, meep_materials\n')]
import numpy as np class LossFunction: ''' Loss function base class. Usage: >>> Inherited by other loss functions. >>> LossFunction__call__(y, y_hat) -> float ''' def __call__(self, y_hat: np.ndarray, y: np.ndarray) -> float: ''' Loss function. Parameters: y: np.ndarray y_hat: np.ndarray Returns: float ''' raise NotImplementedError def deriv(self, y_hat: np.ndarray, y: np.ndarray) -> float: ''' Derivative of loss function. Parameters: y: np.ndarray y_hat: np.ndarray Returns: float ''' raise NotImplementedError class CategoricalCrossentropy(LossFunction): def __call__(self, y_hat, y): sample_losses = self.forward(y_hat, y) data_loss = np.mean(sample_losses) return data_loss def forward(self, y_pred, y_true): samples = len(y_pred) y_pred_clipped = np.clip(y_pred, 1e-7, 1 - 1e-7) if len(y_true.shape) == 1: correct_confidences = y_pred_clipped[range(samples), y_true] elif len(y_true.shape) == 2: correct_confidences = np.sum(y_pred_clipped*y_true, axis=1) negative_log_likelihoods = -np.log(correct_confidences) return negative_log_likelihoods # This is 'backward' from Activation_Softmax_Loss_CategoricalCrossentropy in book.py def deriv(self, dvalues, y_true): samples = len(dvalues) if len(y_true.shape) == 2: y_true = np.argmax(y_true, axis=1) self.dinputs = dvalues.copy() self.dinputs[range(samples), y_true] -= 1 self.dinputs = self.dinputs / samples return self.dinputs # This is backward from Loss_CategoricalCrossentropy in book.py '''def deriv(self, dvalues, y_true): samples = len(dvalues) labels = len(dvalues[0]) if len(y_true.shape) == 1: y_true = np.eye(labels)[y_true] self.dinputs = -y_true / dvalues self.dinputs = self.dinputs / samples return self.dinputs'''
[ "numpy.clip", "numpy.mean", "numpy.log", "numpy.argmax", "numpy.sum" ]
[((874, 896), 'numpy.mean', 'np.mean', (['sample_losses'], {}), '(sample_losses)\n', (881, 896), True, 'import numpy as np\n'), ((1018, 1051), 'numpy.clip', 'np.clip', (['y_pred', '(1e-07)', '(1 - 1e-07)'], {}), '(y_pred, 1e-07, 1 - 1e-07)\n', (1025, 1051), True, 'import numpy as np\n'), ((1303, 1330), 'numpy.log', 'np.log', (['correct_confidences'], {}), '(correct_confidences)\n', (1309, 1330), True, 'import numpy as np\n'), ((1586, 1611), 'numpy.argmax', 'np.argmax', (['y_true'], {'axis': '(1)'}), '(y_true, axis=1)\n', (1595, 1611), True, 'import numpy as np\n'), ((1229, 1268), 'numpy.sum', 'np.sum', (['(y_pred_clipped * y_true)'], {'axis': '(1)'}), '(y_pred_clipped * y_true, axis=1)\n', (1235, 1268), True, 'import numpy as np\n')]
import cv2 import numpy as np class ImageProcessing: @staticmethod def __contour_is_bad(c): epsilon = 5.0 approx = cv2.approxPolyDP(c, epsilon, True) return len(approx) <= 3 @staticmethod def findContours(img, sort = True): im_copy = img.copy() gray = cv2.cvtColor(im_copy, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), cv2.BORDER_DEFAULT) _, th = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) contours, _ = cv2.findContours(th, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) contours = [c for c in contours if not ImageProcessing.__contour_is_bad(c)] if sort: contours = ImageProcessing.sortContours(contours) return contours @staticmethod def sortContours(contours, method="left-to-right"): # initialize the reverse flag and sort index reverse = False i = 0 # handle if we need to sort in reverse if method == "right-to-left" or method == "bottom-to-top": reverse = True # handle if we are sorting against the y-coordinate rather than # the x-coordinate of the bounding box if method == "top-to-bottom" or method == "bottom-to-top": i = 1 boxes = [cv2.boundingRect(c) for c in contours] contours, _ = zip(*sorted(zip(contours, boxes), key=lambda b: b[1][i], reverse=reverse)) return contours @staticmethod def boundingRectContour(c): poly = cv2.approxPolyDP(c, 3, True) return cv2.boundingRect(poly) @staticmethod def extremumContour(c): left = tuple(c[c[:, :, 0].argmin()][0]) right = tuple(c[c[:, :, 0].argmax()][0]) top = tuple(c[c[:, :, 1].argmin()][0]) bot = tuple(c[c[:, :, 1].argmax()][0]) return left, right, top, bot if __name__ == '__main__': image = cv2.imread('sample_fly.JPG') h, w = image.shape[:2] contours = ImageProcessing.findContours(image) blank = np.zeros((h, w, 1), dtype=np.uint8) mask = cv2.fillPoly(blank, contours, (255, 255, 255)) image = cv2.bitwise_and(image, image, mask=mask) # image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.imwrite("processing_sample_fly.JPG", image)
[ "cv2.fillPoly", "cv2.imwrite", "cv2.threshold", "cv2.bitwise_and", "numpy.zeros", "cv2.approxPolyDP", "cv2.cvtColor", "cv2.findContours", "cv2.GaussianBlur", "cv2.imread", "cv2.boundingRect" ]
[((1969, 1997), 'cv2.imread', 'cv2.imread', (['"""sample_fly.JPG"""'], {}), "('sample_fly.JPG')\n", (1979, 1997), False, 'import cv2\n'), ((2088, 2123), 'numpy.zeros', 'np.zeros', (['(h, w, 1)'], {'dtype': 'np.uint8'}), '((h, w, 1), dtype=np.uint8)\n', (2096, 2123), True, 'import numpy as np\n'), ((2135, 2181), 'cv2.fillPoly', 'cv2.fillPoly', (['blank', 'contours', '(255, 255, 255)'], {}), '(blank, contours, (255, 255, 255))\n', (2147, 2181), False, 'import cv2\n'), ((2194, 2234), 'cv2.bitwise_and', 'cv2.bitwise_and', (['image', 'image'], {'mask': 'mask'}), '(image, image, mask=mask)\n', (2209, 2234), False, 'import cv2\n'), ((2296, 2343), 'cv2.imwrite', 'cv2.imwrite', (['"""processing_sample_fly.JPG"""', 'image'], {}), "('processing_sample_fly.JPG', image)\n", (2307, 2343), False, 'import cv2\n'), ((141, 175), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['c', 'epsilon', '(True)'], {}), '(c, epsilon, True)\n', (157, 175), False, 'import cv2\n'), ((311, 352), 'cv2.cvtColor', 'cv2.cvtColor', (['im_copy', 'cv2.COLOR_BGR2GRAY'], {}), '(im_copy, cv2.COLOR_BGR2GRAY)\n', (323, 352), False, 'import cv2\n'), ((368, 418), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['gray', '(5, 5)', 'cv2.BORDER_DEFAULT'], {}), '(gray, (5, 5), cv2.BORDER_DEFAULT)\n', (384, 418), False, 'import cv2\n'), ((435, 499), 'cv2.threshold', 'cv2.threshold', (['blur', '(0)', '(255)', '(cv2.THRESH_BINARY | cv2.THRESH_OTSU)'], {}), '(blur, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n', (448, 499), False, 'import cv2\n'), ((552, 610), 'cv2.findContours', 'cv2.findContours', (['th', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_NONE'], {}), '(th, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n', (568, 610), False, 'import cv2\n'), ((1586, 1614), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['c', '(3)', '(True)'], {}), '(c, 3, True)\n', (1602, 1614), False, 'import cv2\n'), ((1630, 1652), 'cv2.boundingRect', 'cv2.boundingRect', (['poly'], {}), '(poly)\n', (1646, 1652), False, 'import cv2\n'), ((1326, 1345), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (1342, 1345), False, 'import cv2\n')]
import poppy from astropy import units as u import numpy as np import matplotlib.pyplot as plt from astropy.io import fits def test_kolmo(niter=3, r0_at_500=0.2, dz=1, wl=0.5e-6): telescope_radius = 19.5 * u.m r0 = r0_at_500 * (wl / 0.5e-6)**(6 / 5) for i in range(niter): ss = poppy.OpticalSystem(pupil_diameter=2 * telescope_radius) ss.add_pupil(poppy.KolmogorovWFE( r0=r0, dz=dz, outer_scale=40, inner_scale=0.05, kind='von Karman')) ss.add_pupil(poppy.CircularAperture(radius=telescope_radius, name='Entrance Pupil')) ss.add_detector(pixelscale=0.20, fov_arcsec=2.0) hdu = ss.calc_psf(wavelength=wl)[0] if i == 0: psfs = np.zeros((niter, hdu.shape[0], hdu.shape[1])) psfs[i] = hdu.data hdu.data = psfs.sum(axis=0) hdulist = fits.HDUList(hdu) print("0.98*l/r0 = %g - FWHM %g " % ( 0.98 * wl / r0 / 4.848e-6, poppy.utils.measure_fwhm_radprof(hdulist))) plt.figure() poppy.utils.display_profiles(hdulist) plt.figure() poppy.utils.display_psf(hdulist) return psfs, hdulist, ss
[ "poppy.OpticalSystem", "astropy.io.fits.HDUList", "poppy.utils.measure_fwhm_radprof", "poppy.utils.display_psf", "poppy.utils.display_profiles", "matplotlib.pyplot.figure", "numpy.zeros", "poppy.CircularAperture", "poppy.KolmogorovWFE" ]
[((875, 892), 'astropy.io.fits.HDUList', 'fits.HDUList', (['hdu'], {}), '(hdu)\n', (887, 892), False, 'from astropy.io import fits\n'), ((1019, 1031), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1029, 1031), True, 'import matplotlib.pyplot as plt\n'), ((1036, 1073), 'poppy.utils.display_profiles', 'poppy.utils.display_profiles', (['hdulist'], {}), '(hdulist)\n', (1064, 1073), False, 'import poppy\n'), ((1078, 1090), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1088, 1090), True, 'import matplotlib.pyplot as plt\n'), ((1095, 1127), 'poppy.utils.display_psf', 'poppy.utils.display_psf', (['hdulist'], {}), '(hdulist)\n', (1118, 1127), False, 'import poppy\n'), ((300, 356), 'poppy.OpticalSystem', 'poppy.OpticalSystem', ([], {'pupil_diameter': '(2 * telescope_radius)'}), '(pupil_diameter=2 * telescope_radius)\n', (319, 356), False, 'import poppy\n'), ((378, 469), 'poppy.KolmogorovWFE', 'poppy.KolmogorovWFE', ([], {'r0': 'r0', 'dz': 'dz', 'outer_scale': '(40)', 'inner_scale': '(0.05)', 'kind': '"""von Karman"""'}), "(r0=r0, dz=dz, outer_scale=40, inner_scale=0.05, kind=\n 'von Karman')\n", (397, 469), False, 'import poppy\n'), ((500, 570), 'poppy.CircularAperture', 'poppy.CircularAperture', ([], {'radius': 'telescope_radius', 'name': '"""Entrance Pupil"""'}), "(radius=telescope_radius, name='Entrance Pupil')\n", (522, 570), False, 'import poppy\n'), ((756, 801), 'numpy.zeros', 'np.zeros', (['(niter, hdu.shape[0], hdu.shape[1])'], {}), '((niter, hdu.shape[0], hdu.shape[1]))\n', (764, 801), True, 'import numpy as np\n'), ((971, 1012), 'poppy.utils.measure_fwhm_radprof', 'poppy.utils.measure_fwhm_radprof', (['hdulist'], {}), '(hdulist)\n', (1003, 1012), False, 'import poppy\n')]
import logging from matplotlib.patches import Ellipse import numpy as np import typing import autoarray as aa logging.basicConfig() logger = logging.getLogger(__name__) class AbstractShearField: @property def ellipticities(self) -> aa.ValuesIrregular: """ If we treat this vector field as a set of weak lensing shear measurements, the galaxy ellipticity each vector corresponds too. """ return aa.ValuesIrregular( values=np.sqrt(self.slim[:, 0] ** 2 + self.slim[:, 1] ** 2.0) ) @property def semi_major_axes(self) -> aa.ValuesIrregular: """ If we treat this vector field as a set of weak lensing shear measurements, the semi-major axis of each galaxy ellipticity that each vector corresponds too. """ return aa.ValuesIrregular(values=3 * (1 + self.ellipticities)) @property def semi_minor_axes(self) -> aa.ValuesIrregular: """ If we treat this vector field as a set of weak lensing shear measurements, the semi-minor axis of each galaxy ellipticity that each vector corresponds too. """ return aa.ValuesIrregular(values=3 * (1 - self.ellipticities)) @property def phis(self) -> aa.ValuesIrregular: """ If we treat this vector field as a set of weak lensing shear measurements, the position angle defined counter clockwise from the positive x-axis of each galaxy ellipticity that each vector corresponds too. """ return aa.ValuesIrregular( values=np.arctan2(self.slim[:, 0], self.slim[:, 1]) * 180.0 / np.pi / 2.0 ) @property def elliptical_patches(self) -> typing.List[Ellipse]: """ If we treat this vector field as a set of weak lensing shear measurements, the elliptical patch representing each galaxy ellipticity. This patch is used for visualizing an ellipse of each galaxy in an image. """ return [ Ellipse( xy=(x, y), width=semi_major_axis, height=semi_minor_axis, angle=angle ) for x, y, semi_major_axis, semi_minor_axis, angle in zip( self.grid.slim[:, 1], self.grid.slim[:, 0], self.semi_major_axes, self.semi_minor_axes, self.phis, ) ] class ShearYX2D(aa.VectorYX2D, AbstractShearField): """ A regular shear field, which is collection of (y,x) vectors which are located on a uniform grid of (y,x) coordinates. The structure of this data structure is described in `autoarray.structures.vectors.uniform.VectorYX2D` This class extends `VectorYX2D` to include methods that are specific to a shear field, typically used for weak lensing calculations. Parameters ---------- vectors The 2D (y,x) vectors on an irregular grid that represent the vector-field. grid The irregular grid of (y,x) coordinates where each vector is located. """ class ShearYX2DIrregular(aa.VectorYX2DIrregular, AbstractShearField): """ An irregular shear field, which is collection of (y,x) vectors which are located on an irregular grid of (y,x) coordinates. The structure of this data structure is described in `autoarray.structures.vectors.irregular.VectorYX2DIrregular` This class extends `VectorYX2DIrregular` to include methods that are specific to a shear field, typically used for weak lensing calculations. Parameters ---------- vectors The 2D (y,x) vectors on an irregular grid that represent the vector-field. grid The irregular grid of (y,x) coordinates where each vector is located. """
[ "logging.basicConfig", "logging.getLogger", "numpy.sqrt", "autoarray.ValuesIrregular", "numpy.arctan2", "matplotlib.patches.Ellipse" ]
[((119, 140), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (138, 140), False, 'import logging\n'), ((151, 178), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (168, 178), False, 'import logging\n'), ((857, 912), 'autoarray.ValuesIrregular', 'aa.ValuesIrregular', ([], {'values': '(3 * (1 + self.ellipticities))'}), '(values=3 * (1 + self.ellipticities))\n', (875, 912), True, 'import autoarray as aa\n'), ((1200, 1255), 'autoarray.ValuesIrregular', 'aa.ValuesIrregular', ([], {'values': '(3 * (1 - self.ellipticities))'}), '(values=3 * (1 - self.ellipticities))\n', (1218, 1255), True, 'import autoarray as aa\n'), ((2061, 2139), 'matplotlib.patches.Ellipse', 'Ellipse', ([], {'xy': '(x, y)', 'width': 'semi_major_axis', 'height': 'semi_minor_axis', 'angle': 'angle'}), '(xy=(x, y), width=semi_major_axis, height=semi_minor_axis, angle=angle)\n', (2068, 2139), False, 'from matplotlib.patches import Ellipse\n'), ((504, 558), 'numpy.sqrt', 'np.sqrt', (['(self.slim[:, 0] ** 2 + self.slim[:, 1] ** 2.0)'], {}), '(self.slim[:, 0] ** 2 + self.slim[:, 1] ** 2.0)\n', (511, 558), True, 'import numpy as np\n'), ((1622, 1666), 'numpy.arctan2', 'np.arctan2', (['self.slim[:, 0]', 'self.slim[:, 1]'], {}), '(self.slim[:, 0], self.slim[:, 1])\n', (1632, 1666), True, 'import numpy as np\n')]
from datetime import date, timedelta from math import sqrt from yahoofinancials import YahooFinancials import numpy as np from Stock import Stock NUM_EXCHANGE_DAYS = 252 RISK_FREE_RATE_10YR_US = 1.71 class PortfolioService: """Service to management Portfolio""" @staticmethod def _print_ending(): print('\n') print('-' * 50) print('\n') @staticmethod def _get_and_print_time_period(): today = date.today() three_years_ago = today - timedelta(days=(3 * 365)) print('\nTime period: {0} / {1}'.format(three_years_ago, today)) return {'start_date': three_years_ago, 'end_date': today} @staticmethod def _get_historical_price_data(ticker, start_date, end_date): s = YahooFinancials(ticker) historical_data = s.get_historical_price_data(start_date, end_date, "daily") return historical_data[ticker.upper()]['prices'] @staticmethod def get_financial_values_by_ticker(ticker): print('Finding ticker in Yahoo Finance...') s = YahooFinancials(ticker) financial_values = {'beta': round(s.get_beta(), 2), 'current_price': round(s.get_current_price(), 2), 'prev_close_price': round(s.get_prev_close_price(), 2)} return financial_values @staticmethod def calculate_portfolio_beta(portfolio_data): percentage_by_beta = list(map(lambda x: (x.percentage / 100) * x.beta, portfolio_data)) return round(sum(percentage_by_beta), 2) @staticmethod def _merge_prices(ticker_prices): merge_prices = dict() for key in ticker_prices: for k, v in [(k, v) for x in ticker_prices[key] for (k, v) in x.items()]: merge_prices.setdefault(k, []).append(v) return merge_prices @staticmethod def _calculate_daily_return(merge_prices, stocks_weight, stock_list): portfolio_daily_return = list() first_key = list(merge_prices.keys())[0] prev_price = merge_prices[first_key] daily_return_by_ticker = dict() for price_key in merge_prices: current_price = merge_prices[price_key] if first_key == price_key: continue total_daily_return = 0 for i in range(len(current_price)): for j in range(len(prev_price)): if i == j: stock_daily_return = ((current_price[i]/prev_price[j]) - 1) * 100 if stock_list[j].ticker in daily_return_by_ticker: daily_return_by_ticker.update({stock_list[j].ticker: daily_return_by_ticker[stock_list[j] .ticker] + stock_daily_return}) else: daily_return_by_ticker[stock_list[j].ticker] = stock_daily_return total_daily_return += stock_daily_return * stocks_weight[j] portfolio_daily_return.append(total_daily_return/100) prev_price = current_price deviation = np.std(portfolio_daily_return) annualized_deviation = deviation * sqrt(NUM_EXCHANGE_DAYS) return deviation, annualized_deviation, daily_return_by_ticker, len(merge_prices), stocks_weight @staticmethod def calculate_annual_standard_deviation(portfolio_data): print('\nCalculating annualized standard deviation...') total_portfolio = sum(list(map(lambda x: x.number_of_actions * x.price, portfolio_data))) stocks_weight = list() ticker_prices = dict() time_period = PortfolioService._get_and_print_time_period() print('\nStocks weight') for stock in portfolio_data: weight = ((stock.number_of_actions * stock.price) * 100) / total_portfolio print('{0}: {1}'.format(stock.ticker.upper(), round(weight, 2))) stocks_weight.append(round(weight, 2)) prices_by_ticker = PortfolioService._get_historical_price_data(stock.ticker, str(time_period['start_date']), str(time_period['end_date'])) ticker_prices[stock.ticker] = list(map(lambda x: {x['formatted_date']: round(x['close'], 2)}, prices_by_ticker)) merge_prices = PortfolioService._merge_prices(ticker_prices) return PortfolioService._calculate_daily_return(merge_prices, stocks_weight, portfolio_data) @staticmethod def calculate_sharpe_ratio(deviation_tuple): i = 0 portfolio_expected_return = 0 for key in deviation_tuple[2]: avg = (deviation_tuple[2][key] / deviation_tuple[3]) / 100 expected_return_by_ticker = (pow((1 + avg), NUM_EXCHANGE_DAYS) - 1) * 100 portfolio_expected_return += expected_return_by_ticker * deviation_tuple[4][i] i += 1 portfolio_expected_return = round(portfolio_expected_return / 100, 2) print('Portfolio expected return: {0}%'.format(portfolio_expected_return)) sharpe_ratio = ((portfolio_expected_return - RISK_FREE_RATE_10YR_US) / deviation_tuple[1]) * 100 return round(sharpe_ratio, 2) @staticmethod def create_stock(ticker, percentage, number_of_actions, beta, price): stock = Stock(ticker, percentage, number_of_actions, beta, price) PortfolioService._print_ending() return stock
[ "math.sqrt", "datetime.date.today", "yahoofinancials.YahooFinancials", "Stock.Stock", "numpy.std", "datetime.timedelta" ]
[((452, 464), 'datetime.date.today', 'date.today', ([], {}), '()\n', (462, 464), False, 'from datetime import date, timedelta\n'), ((761, 784), 'yahoofinancials.YahooFinancials', 'YahooFinancials', (['ticker'], {}), '(ticker)\n', (776, 784), False, 'from yahoofinancials import YahooFinancials\n'), ((1058, 1081), 'yahoofinancials.YahooFinancials', 'YahooFinancials', (['ticker'], {}), '(ticker)\n', (1073, 1081), False, 'from yahoofinancials import YahooFinancials\n'), ((3105, 3135), 'numpy.std', 'np.std', (['portfolio_daily_return'], {}), '(portfolio_daily_return)\n', (3111, 3135), True, 'import numpy as np\n'), ((5376, 5433), 'Stock.Stock', 'Stock', (['ticker', 'percentage', 'number_of_actions', 'beta', 'price'], {}), '(ticker, percentage, number_of_actions, beta, price)\n', (5381, 5433), False, 'from Stock import Stock\n'), ((499, 522), 'datetime.timedelta', 'timedelta', ([], {'days': '(3 * 365)'}), '(days=3 * 365)\n', (508, 522), False, 'from datetime import date, timedelta\n'), ((3179, 3202), 'math.sqrt', 'sqrt', (['NUM_EXCHANGE_DAYS'], {}), '(NUM_EXCHANGE_DAYS)\n', (3183, 3202), False, 'from math import sqrt\n')]
import numpy as np import matplotlib.pyplot as plt def replaceInfNaN(x, value): ''' replace Inf and NaN with a default value Args: ----- x: arr of values that might be Inf or NaN value: default value to replace Inf or Nan with Returns: -------- x: same as input x, but with Inf or Nan raplaced by value ''' x[np.isfinite( x ) == False] = value return x # ----------------------------------------------------------------- def apply_calojet_cuts(df): ''' Apply recommended cuts for Akt4EMTopoJets ''' cuts = (abs(df['jet_eta']) < 2.5) & \ (df['jet_pt'] > 10e3) & \ (df['jet_aliveAfterOR'] == 1) & \ (df['jet_aliveAfterORmu'] == 1) & \ (df['jet_nConst'] > 1) df = df[cuts].reset_index(drop=True) return df # ----------------------------------------------------------------- def reweight_to_b(X, y, pt_col, eta_col): ''' Definition: ----------- Reweight to b-distribution in eta and pt ''' pt_bins = [10, 50, 100, 150, 200, 300, 500, 99999] eta_bins = np.linspace(0, 2.5, 6) b_bins = plt.hist2d(X[y == 5, pt_col] / 1000, X[y == 5, eta_col], bins=[pt_bins, eta_bins]) c_bins = plt.hist2d(X[y == 4, pt_col] / 1000, X[y == 4, eta_col], bins=[pt_bins, eta_bins]) l_bins = plt.hist2d(X[y == 0, pt_col] / 1000, X[y == 0, eta_col], bins=[pt_bins, eta_bins]) wb= np.ones(X[y == 5].shape[0]) wc = [(b_bins[0] / c_bins[0])[arg] for arg in zip( np.digitize(X[y == 4, pt_col] / 1000, b_bins[1]) - 1, np.digitize(X[y == 4, eta_col], b_bins[2]) - 1 )] wl = [(b_bins[0] / l_bins[0])[arg] for arg in zip( np.digitize(X[y == 0, pt_col] / 1000, b_bins[1]) - 1, np.digitize(X[y == 0, eta_col], b_bins[2]) - 1 )] # -- hardcoded, standard flavor fractions C_FRAC = 0.07 L_FRAC = 0.61 n_light = wl.sum() n_charm = (n_light * C_FRAC) / L_FRAC n_bottom = (n_light * (1 - L_FRAC - C_FRAC)) / L_FRAC w = np.zeros(len(y)) w[y == 5] = wb w[y == 4] = wc w[y == 0] = wl return w # ----------------------------------------------------------------- def reweight_to_l(X, y, pt_col, eta_col): ''' Definition: ----------- Reweight to light-distribution in eta and pt ''' pt_bins = [10, 50, 100, 150, 200, 300, 500, 99999] eta_bins = np.linspace(0, 2.5, 6) b_bins = plt.hist2d(X[y == 5, pt_col] / 1000, X[y == 5, eta_col], bins=[pt_bins, eta_bins]) c_bins = plt.hist2d(X[y == 4, pt_col] / 1000, X[y == 4, eta_col], bins=[pt_bins, eta_bins]) l_bins = plt.hist2d(X[y == 0, pt_col] / 1000, X[y == 0, eta_col], bins=[pt_bins, eta_bins]) wl= np.ones(X[y == 0].shape[0]) wc = [(l_bins[0] / c_bins[0])[arg] for arg in zip( np.digitize(X[y == 4, pt_col] / 1000, l_bins[1]) - 1, np.digitize(X[y == 4, eta_col], l_bins[2]) - 1 )] wb = [(l_bins[0] / b_bins[0])[arg] for arg in zip( np.digitize(X[y == 5, pt_col] / 1000, l_bins[1]) - 1, np.digitize(X[y == 5, eta_col], l_bins[2]) - 1 )] # -- hardcoded, standard flavor fractions C_FRAC = 0.07 L_FRAC = 0.61 n_light = wl.sum() n_charm = (n_light * C_FRAC) / L_FRAC n_bottom = (n_light * (1 - L_FRAC - C_FRAC)) / L_FRAC w = np.zeros(len(y)) w[y == 5] = wb w[y == 4] = wc w[y == 0] = wl return w # -----------------------------------------------------------------
[ "numpy.ones", "matplotlib.pyplot.hist2d", "numpy.digitize", "numpy.linspace", "numpy.isfinite" ]
[((1126, 1148), 'numpy.linspace', 'np.linspace', (['(0)', '(2.5)', '(6)'], {}), '(0, 2.5, 6)\n', (1137, 1148), True, 'import numpy as np\n'), ((1163, 1249), 'matplotlib.pyplot.hist2d', 'plt.hist2d', (['(X[y == 5, pt_col] / 1000)', 'X[y == 5, eta_col]'], {'bins': '[pt_bins, eta_bins]'}), '(X[y == 5, pt_col] / 1000, X[y == 5, eta_col], bins=[pt_bins,\n eta_bins])\n', (1173, 1249), True, 'import matplotlib.pyplot as plt\n'), ((1259, 1345), 'matplotlib.pyplot.hist2d', 'plt.hist2d', (['(X[y == 4, pt_col] / 1000)', 'X[y == 4, eta_col]'], {'bins': '[pt_bins, eta_bins]'}), '(X[y == 4, pt_col] / 1000, X[y == 4, eta_col], bins=[pt_bins,\n eta_bins])\n', (1269, 1345), True, 'import matplotlib.pyplot as plt\n'), ((1355, 1441), 'matplotlib.pyplot.hist2d', 'plt.hist2d', (['(X[y == 0, pt_col] / 1000)', 'X[y == 0, eta_col]'], {'bins': '[pt_bins, eta_bins]'}), '(X[y == 0, pt_col] / 1000, X[y == 0, eta_col], bins=[pt_bins,\n eta_bins])\n', (1365, 1441), True, 'import matplotlib.pyplot as plt\n'), ((1447, 1474), 'numpy.ones', 'np.ones', (['X[y == 5].shape[0]'], {}), '(X[y == 5].shape[0])\n', (1454, 1474), True, 'import numpy as np\n'), ((2424, 2446), 'numpy.linspace', 'np.linspace', (['(0)', '(2.5)', '(6)'], {}), '(0, 2.5, 6)\n', (2435, 2446), True, 'import numpy as np\n'), ((2461, 2547), 'matplotlib.pyplot.hist2d', 'plt.hist2d', (['(X[y == 5, pt_col] / 1000)', 'X[y == 5, eta_col]'], {'bins': '[pt_bins, eta_bins]'}), '(X[y == 5, pt_col] / 1000, X[y == 5, eta_col], bins=[pt_bins,\n eta_bins])\n', (2471, 2547), True, 'import matplotlib.pyplot as plt\n'), ((2557, 2643), 'matplotlib.pyplot.hist2d', 'plt.hist2d', (['(X[y == 4, pt_col] / 1000)', 'X[y == 4, eta_col]'], {'bins': '[pt_bins, eta_bins]'}), '(X[y == 4, pt_col] / 1000, X[y == 4, eta_col], bins=[pt_bins,\n eta_bins])\n', (2567, 2643), True, 'import matplotlib.pyplot as plt\n'), ((2653, 2739), 'matplotlib.pyplot.hist2d', 'plt.hist2d', (['(X[y == 0, pt_col] / 1000)', 'X[y == 0, eta_col]'], {'bins': '[pt_bins, eta_bins]'}), '(X[y == 0, pt_col] / 1000, X[y == 0, eta_col], bins=[pt_bins,\n eta_bins])\n', (2663, 2739), True, 'import matplotlib.pyplot as plt\n'), ((2745, 2772), 'numpy.ones', 'np.ones', (['X[y == 0].shape[0]'], {}), '(X[y == 0].shape[0])\n', (2752, 2772), True, 'import numpy as np\n'), ((375, 389), 'numpy.isfinite', 'np.isfinite', (['x'], {}), '(x)\n', (386, 389), True, 'import numpy as np\n'), ((1539, 1587), 'numpy.digitize', 'np.digitize', (['(X[y == 4, pt_col] / 1000)', 'b_bins[1]'], {}), '(X[y == 4, pt_col] / 1000, b_bins[1])\n', (1550, 1587), True, 'import numpy as np\n'), ((1602, 1644), 'numpy.digitize', 'np.digitize', (['X[y == 4, eta_col]', 'b_bins[2]'], {}), '(X[y == 4, eta_col], b_bins[2])\n', (1613, 1644), True, 'import numpy as np\n'), ((1720, 1768), 'numpy.digitize', 'np.digitize', (['(X[y == 0, pt_col] / 1000)', 'b_bins[1]'], {}), '(X[y == 0, pt_col] / 1000, b_bins[1])\n', (1731, 1768), True, 'import numpy as np\n'), ((1783, 1825), 'numpy.digitize', 'np.digitize', (['X[y == 0, eta_col]', 'b_bins[2]'], {}), '(X[y == 0, eta_col], b_bins[2])\n', (1794, 1825), True, 'import numpy as np\n'), ((2837, 2885), 'numpy.digitize', 'np.digitize', (['(X[y == 4, pt_col] / 1000)', 'l_bins[1]'], {}), '(X[y == 4, pt_col] / 1000, l_bins[1])\n', (2848, 2885), True, 'import numpy as np\n'), ((2900, 2942), 'numpy.digitize', 'np.digitize', (['X[y == 4, eta_col]', 'l_bins[2]'], {}), '(X[y == 4, eta_col], l_bins[2])\n', (2911, 2942), True, 'import numpy as np\n'), ((3018, 3066), 'numpy.digitize', 'np.digitize', (['(X[y == 5, pt_col] / 1000)', 'l_bins[1]'], {}), '(X[y == 5, pt_col] / 1000, l_bins[1])\n', (3029, 3066), True, 'import numpy as np\n'), ((3081, 3123), 'numpy.digitize', 'np.digitize', (['X[y == 5, eta_col]', 'l_bins[2]'], {}), '(X[y == 5, eta_col], l_bins[2])\n', (3092, 3123), True, 'import numpy as np\n')]
# -*- coding=UTF-8 -*- # pyright: strict from __future__ import annotations import traceback from concurrent import futures from typing import Callable, Iterator, Optional, Tuple import cast_unknown as cast import cv2 import numpy as np from PIL.Image import Image from PIL.Image import fromarray as image_from_array from ... import action, app, imagetools, mathtools, ocr, template, templates from ...single_mode import Context, Training, training from ...single_mode.training import Partner from ..scene import Scene, SceneHolder from .command import CommandScene _TRAINING_CONFIRM = template.Specification( templates.SINGLE_MODE_TRAINING_CONFIRM, threshold=0.8 ) def _gradient(colors: Tuple[Tuple[Tuple[int, int, int], int], ...]) -> np.ndarray: ret = np.linspace((0, 0, 0), colors[0][0], colors[0][1]) for index, i in enumerate(colors[1:], 1): color, stop = i prev_color, prev_stop = colors[index - 1] g = np.linspace(prev_color, color, stop - prev_stop + 1) ret = np.concatenate((ret, g[1:])) return ret def _recognize_base_effect(img: Image) -> int: cv_img = imagetools.cv_image(imagetools.resize(img, height=32)) sharpened_img = imagetools.sharpen(cv_img) sharpened_img = imagetools.mix(sharpened_img, cv_img, 0.4) white_outline_img = imagetools.constant_color_key( sharpened_img, (255, 255, 255), ) white_outline_img_dilated = cv2.morphologyEx( white_outline_img, cv2.MORPH_DILATE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)), ) white_outline_img_dilated = cv2.morphologyEx( white_outline_img_dilated, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 7)), ) bg_mask_img = ( imagetools.bg_mask_by_outline(white_outline_img_dilated) + white_outline_img ) masked_img = cv2.copyTo(cv_img, 255 - bg_mask_img) brown_img = imagetools.constant_color_key( cv_img, (29, 62, 194), (24, 113, 218), (30, 109, 216), (69, 104, 197), (119, 139, 224), (103, 147, 223), (59, 142, 226), threshold=0.85, ) _, non_brown_img = cv2.threshold(brown_img, 120, 255, cv2.THRESH_BINARY_INV) border_brown_img = imagetools.border_flood_fill(non_brown_img) brown_outline_img = cv2.copyTo(brown_img, 255 - border_brown_img) bg_mask_img = imagetools.bg_mask_by_outline(brown_outline_img) masked_img = cv2.copyTo(masked_img, 255 - bg_mask_img) fill_gradient = _gradient( ( ((140, 236, 255), 0), ((140, 236, 255), round(cv_img.shape[0] * 0.25)), ((114, 229, 255), round(cv_img.shape[0] * 0.35)), ((113, 198, 255), round(cv_img.shape[0] * 0.55)), ((95, 179, 255), round(cv_img.shape[0] * 0.63)), ((74, 157, 255), round(cv_img.shape[0] * 0.70)), ((74, 117, 255), round(cv_img.shape[0] * 0.83)), ((74, 117, 255), cv_img.shape[0]), ) ).astype(np.uint8) fill_img = np.repeat(np.expand_dims(fill_gradient, 1), cv_img.shape[1], axis=1) assert fill_img.shape == cv_img.shape text_img = imagetools.color_key(masked_img, fill_img) text_img_extra = imagetools.constant_color_key( masked_img, (175, 214, 255), threshold=0.95, ) text_img = np.array(np.maximum(text_img, text_img_extra)) imagetools.fill_area(text_img, (0,), size_lt=48) app.log.image( "base effect", img, level=app.DEBUG, layers={ "sharpened": sharpened_img, "white_outline": white_outline_img, "white_outline_dilated": white_outline_img_dilated, "brown": brown_img, "non_brown": non_brown_img, "border_brown": border_brown_img, "brown_outline": brown_outline_img, "bg_mask": bg_mask_img, "masked": masked_img, "text_extra": text_img_extra, "text": text_img, }, ) if cv2.countNonZero(text_img) < 100: # ignore skin match result return 0 # +100 has different color hash100 = "000000000000006600ee00ff00ff00ff004e0000000000000000000000000000" if ( imagetools.compare_hash( imagetools.image_hash(imagetools.pil_image(text_img)), hash100, ) > 0.9 ): return 100 text = ocr.text(image_from_array(text_img)) if not text: return 0 return int(text.lstrip("+")) def _recognize_red_effect(img: Image) -> int: cv_img = imagetools.cv_image( imagetools.resize( imagetools.resize(img, height=24), height=48, ) ) sharpened_img = cv2.filter2D( cv_img, 8, np.array( ( (0, -1, 0), (-1, 5, -1), (0, -1, 0), ) ), ) sharpened_img = imagetools.mix(sharpened_img, cv_img, 0.5) white_outline_img = imagetools.constant_color_key( sharpened_img, (255, 255, 255), (222, 220, 237), (252, 254, 202), (236, 249, 105), (243, 220, 160), ) masked_img = imagetools.inside_outline(cv_img, white_outline_img) red_outline_img = imagetools.constant_color_key( cv_img, (15, 18, 216), (34, 42, 234), (56, 72, 218), (20, 18, 181), (27, 35, 202), ) red_outline_img = cv2.morphologyEx( red_outline_img, cv2.MORPH_CLOSE, np.ones((3, 3)), ) masked_img = imagetools.inside_outline(masked_img, red_outline_img) height = cv_img.shape[0] fill_gradient = _gradient( ( ((129, 211, 255), 0), ((126, 188, 255), round(height * 0.5)), ((82, 134, 255), round(height * 0.75)), ((36, 62, 211), height), ) ).astype(np.uint8) fill_img = np.repeat(np.expand_dims(fill_gradient, 1), cv_img.shape[1], axis=1) assert fill_img.shape == cv_img.shape text_img_base = imagetools.color_key(masked_img, fill_img) imagetools.fill_area(text_img_base, (0,), size_lt=8) text_img_extra = imagetools.constant_color_key( masked_img, (128, 196, 253), (136, 200, 255), (144, 214, 255), (58, 116, 255), (64, 111, 238), (114, 174, 251), (89, 140, 240), (92, 145, 244), (91, 143, 238), (140, 228, 254), threshold=0.95, ) text_img = np.array(np.maximum(text_img_base, text_img_extra)) h = cv_img.shape[0] imagetools.fill_area(text_img, (0,), size_lt=round(h * 0.2**2)) app.log.image( "red effect", cv_img, level=app.DEBUG, layers={ "sharppend": sharpened_img, "white_outline": white_outline_img, "red_outline": red_outline_img, "masked": masked_img, "fill": fill_img, "text_base": text_img_base, "text_extra": text_img_extra, "text": text_img, }, ) text = ocr.text(image_from_array(text_img)) if not text: return 0 return int(text.lstrip("+")) def _recognize_level(rgb_color: Tuple[int, ...]) -> int: if imagetools.compare_color((49, 178, 22), rgb_color) > 0.9: return 1 if imagetools.compare_color((46, 139, 244), rgb_color) > 0.9: return 2 if imagetools.compare_color((255, 134, 0), rgb_color) > 0.9: return 3 if imagetools.compare_color((244, 69, 132), rgb_color) > 0.9: return 4 if imagetools.compare_color((165, 78, 255), rgb_color) > 0.9: return 5 raise ValueError("_recognize_level: unknown level color: %s" % (rgb_color,)) def _recognize_failure_rate( rp: mathtools.ResizeProxy, trn: Training, img: Image ) -> float: x, y = trn.confirm_position bbox = ( x + rp.vector(15, 540), y + rp.vector(-155, 540), x + rp.vector(75, 540), y + rp.vector(-120, 540), ) rate_img = imagetools.cv_image(imagetools.resize(img.crop(bbox), height=48)) outline_img = imagetools.constant_color_key( rate_img, (252, 150, 14), (255, 183, 89), (0, 150, 255), (0, 69, 255), ) fg_img = imagetools.inside_outline(rate_img, outline_img) text_img = imagetools.constant_color_key( fg_img, (255, 255, 255), (18, 218, 255), ) app.log.image( "failure rate", rate_img, level=app.DEBUG, layers={ "outline": outline_img, "fg": fg_img, "text": text_img, }, ) text = ocr.text(imagetools.pil_image(text_img)) return int(text.strip("%")) / 100 def _estimate_vitality(ctx: Context, trn: Training) -> float: # https://gamewith.jp/uma-musume/article/show/257432 vit_data = { trn.TYPE_SPEED: (-21, -22, -23, -25, -27), trn.TYPE_STAMINA: (-19, -20, -21, -23, -25), trn.TYPE_POWER: (-20, -21, -22, -24, -26), trn.TYPE_GUTS: (-22, -23, -24, -26, -28), trn.TYPE_WISDOM: (5, 5, 5, 5, 5), } if trn.type not in vit_data: return 0 return vit_data[trn.type][trn.level - 1] / ctx.max_vitality def _iter_training_images(static: bool): rp = action.resize_proxy() radius = rp.vector(30, 540) _, first_confirm_pos = action.wait_image(_TRAINING_CONFIRM) yield template.screenshot() if static: return seen_confirm_pos = { first_confirm_pos, } for pos in ( rp.vector2((78, 850), 540), rp.vector2((171, 850), 540), rp.vector2((268, 850), 540), rp.vector2((367, 850), 540), rp.vector2((461, 850), 540), ): if mathtools.distance(first_confirm_pos, pos) < radius: continue action.tap(pos) _, pos = action.wait_image(_TRAINING_CONFIRM) if pos not in seen_confirm_pos: yield template.screenshot() seen_confirm_pos.add(pos) def _recognize_type_color(rp: mathtools.ResizeProxy, icon_img: Image) -> int: type_pos = rp.vector2((7, 18), 540) type_colors = ( ((36, 170, 255), Partner.TYPE_SPEED), ((255, 106, 86), Partner.TYPE_STAMINA), ((255, 151, 27), Partner.TYPE_POWER), ((255, 96, 156), Partner.TYPE_GUTS), ((3, 191, 126), Partner.TYPE_WISDOM), ((255, 179, 22), Partner.TYPE_FRIEND), ) for color, v in type_colors: if ( imagetools.compare_color_near( imagetools.cv_image(icon_img), type_pos, color[::-1] ) > 0.9 ): return v return Partner.TYPE_OTHER def _recognize_has_hint(rp: mathtools.ResizeProxy, icon_img: Image) -> bool: bbox = rp.vector4((50, 0, 58, 8), 540) hint_mark_color = (127, 67, 255) hint_mark_img = icon_img.crop(bbox) hint_mask = imagetools.constant_color_key( imagetools.cv_image(hint_mark_img), hint_mark_color ) return np.average(hint_mask) > 200 def _recognize_has_training( ctx: Context, rp: mathtools.ResizeProxy, icon_img: Image ) -> bool: if ctx.scenario != ctx.SCENARIO_AOHARU: return False bbox = rp.vector4((52, 0, 65, 8), 540) mark_img = icon_img.crop(bbox) mask = imagetools.constant_color_key( imagetools.cv_image(mark_img), (67, 131, 255), (82, 171, 255), threshold=0.9, ) mask_avg = np.average(mask) ret = mask_avg > 80 app.log.image( "has training: %s mask_avg=%0.2f" % (ret, mask_avg), icon_img, layers={ "mark": mask, }, ) return ret def _recognize_has_soul_burst( ctx: Context, rp: mathtools.ResizeProxy, icon_img: Image ) -> bool: if ctx.scenario != ctx.SCENARIO_AOHARU: return False bbox = rp.vector4((52, 0, 65, 8), 540) mark_img = imagetools.cv_image(icon_img.crop(bbox)) mask = imagetools.constant_color_key( mark_img, (198, 255, 255), threshold=0.9, ) mask_avg = np.average(mask) ret = mask_avg > 80 app.log.image( "has soul burst: %s mask_avg=%s" % (ret, mask_avg), icon_img, level=app.DEBUG, layers={ "mark": mark_img, "mark_mask": mask, }, ) return ret def _recognize_partner_level(rp: mathtools.ResizeProxy, icon_img: Image) -> int: pos = ( rp.vector2((10, 65), 540), # level 1 rp.vector2((20, 65), 540), # level 2 rp.vector2((33, 65), 540), # level 3 rp.vector2((43, 65), 540), # level 4 rp.vector2((55, 65), 540), # level 5 ) colors = ( (109, 108, 119), # empty (42, 192, 255), # level 1 (42, 192, 255), # level 2 (162, 230, 30), # level 3 (255, 173, 30), # level 4 (255, 235, 120), # level 5 ) spec: Tuple[Tuple[Tuple[Tuple[int, int], Tuple[int, int, int]], ...], ...] = ( # level 0 ( (pos[0], colors[0]), (pos[1], colors[0]), (pos[2], colors[0]), (pos[3], colors[0]), (pos[4], colors[0]), ), # level 1 ( (pos[0], colors[1]), (pos[1], colors[0]), (pos[2], colors[0]), (pos[3], colors[0]), (pos[4], colors[0]), ), # level 2 ( (pos[0], colors[2]), (pos[1], colors[2]), (pos[3], colors[0]), (pos[4], colors[0]), ), # level 3 ( (pos[0], colors[3]), (pos[1], colors[3]), (pos[2], colors[3]), (pos[4], colors[0]), ), # level 4 ( (pos[0], colors[4]), (pos[1], colors[4]), (pos[2], colors[4]), (pos[3], colors[4]), ), # level 5 ( (pos[0], colors[5]), (pos[4], colors[5]), ), ) for level, s in enumerate(spec): if all( imagetools.compare_color_near( imagetools.cv_image(icon_img), pos, color[::-1], ) > 0.95 for pos, color in s ): return level return -1 def _recognize_soul( rp: mathtools.ResizeProxy, screenshot: Image, icon_bbox: Tuple[int, int, int, int] ) -> float: right_bottom_icon_bbox = ( icon_bbox[0] + rp.vector(49, 540), icon_bbox[1] + rp.vector(32, 540), icon_bbox[0] + rp.vector(74, 540), icon_bbox[1] + rp.vector(58, 540), ) right_bottom_icon_img = screenshot.crop(right_bottom_icon_bbox) is_full = any( template.match(right_bottom_icon_img, templates.SINGLE_MODE_AOHARU_SOUL_FULL) ) if is_full: return 1 soul_bbox = ( icon_bbox[0] - rp.vector(35, 540), icon_bbox[1] + rp.vector(33, 540), icon_bbox[0] + rp.vector(2, 540), icon_bbox[3] - rp.vector(0, 540), ) img = screenshot.crop(soul_bbox) img = imagetools.resize(img, height=40) cv_img = imagetools.cv_image(img) blue_outline_img = imagetools.constant_color_key( cv_img, (251, 109, 0), (255, 178, 99), threshold=0.6, ) bg_mask1 = imagetools.border_flood_fill(blue_outline_img) fg_mask1 = 255 - bg_mask1 masked_img = cv2.copyTo(cv_img, fg_mask1) shapened_img = imagetools.mix(imagetools.sharpen(masked_img, 1), masked_img, 0.5) white_outline_img = imagetools.constant_color_key( shapened_img, (255, 255, 255), (252, 251, 251), (248, 227, 159), (254, 245, 238), (253, 233, 218), threshold=0.9, ) bg_mask2 = imagetools.border_flood_fill(white_outline_img) fg_mask2 = 255 - bg_mask2 imagetools.fill_area(fg_mask2, (0,), size_lt=100) fg_img = cv2.copyTo(masked_img, fg_mask2) empty_mask = imagetools.constant_color_key(fg_img, (126, 121, 121)) app.log.image( "soul", img, level=app.DEBUG, layers={ "sharpened": shapened_img, "right_bottom_icon": right_bottom_icon_img, "blue_outline": blue_outline_img, "white_outline": white_outline_img, "fg_mask1": fg_mask1, "fg_mask2": fg_mask2, "empty_mask": empty_mask, }, ) fg_avg = np.average(fg_mask2) if fg_avg < 100: return -1 empty_avg = np.average(empty_mask) outline_avg = 45 return max(0, min(1, 1 - (empty_avg / (fg_avg - outline_avg)))) def _recognize_partner_icon( ctx: Context, img: Image, bbox: Tuple[int, int, int, int] ) -> Optional[training.Partner]: rp = mathtools.ResizeProxy(img.width) icon_img = img.crop(bbox) app.log.image("partner icon", icon_img, level=app.DEBUG) level = _recognize_partner_level(rp, icon_img) soul = -1 has_training = False has_soul_burst = False if ctx.scenario == ctx.SCENARIO_AOHARU: has_soul_burst = _recognize_has_soul_burst(ctx, rp, icon_img) if has_soul_burst: has_training = True soul = 1 else: has_training = _recognize_has_training(ctx, rp, icon_img) soul = _recognize_soul(rp, img, bbox) if level < 0 and soul < 0: return None self = Partner.new() self.icon_bbox = bbox self.level = level self.soul = soul self.has_hint = _recognize_has_hint(rp, icon_img) self.has_training = has_training self.has_soul_burst = has_soul_burst if self.has_soul_burst: self.has_training = True self.soul = 1 self.type = _recognize_type_color(rp, icon_img) if soul >= 0 and self.type == Partner.TYPE_OTHER: self.type = Partner.TYPE_TEAMMATE app.log.text("partner: %s" % self, level=app.DEBUG) return self def _recognize_partners(ctx: Context, img: Image) -> Iterator[training.Partner]: rp = mathtools.ResizeProxy(img.width) icon_bbox, icon_y_offset = { ctx.SCENARIO_URA: ( rp.vector4((448, 146, 516, 220), 540), rp.vector(90, 540), ), ctx.SCENARIO_AOHARU: ( rp.vector4((448, 147, 516, 220), 540), rp.vector(86, 540), ), ctx.SCENARIO_CLIMAX: ( rp.vector4((448, 147, 516, 220), 540), rp.vector(90, 540), ), }[ctx.scenario] icons_bottom = rp.vector(578, 540) while icon_bbox[2] < icons_bottom: v = _recognize_partner_icon(ctx, img, icon_bbox) if not v: break yield v icon_bbox = ( icon_bbox[0], icon_bbox[1] + icon_y_offset, icon_bbox[2], icon_bbox[3] + icon_y_offset, ) _Vector4 = Tuple[int, int, int, int] def _effect_recognitions( ctx: Context, rp: mathtools.ResizeProxy ) -> Iterator[ Tuple[ Tuple[_Vector4, _Vector4, _Vector4, _Vector4, _Vector4, _Vector4], Callable[[Image], int], ] ]: def _bbox_groups(t: int, b: int): return ( rp.vector4((18, t, 104, b), 540), rp.vector4((104, t, 190, b), 540), rp.vector4((190, t, 273, b), 540), rp.vector4((273, t, 358, b), 540), rp.vector4((358, t, 441, b), 540), rp.vector4((448, t, 521, b), 540), ) if ctx.scenario == ctx.SCENARIO_URA: yield _bbox_groups(582, 616), _recognize_base_effect elif ctx.scenario == ctx.SCENARIO_AOHARU: yield _bbox_groups(597, 625), _recognize_base_effect yield _bbox_groups(570, 595), _recognize_red_effect elif ctx.scenario == ctx.SCENARIO_CLIMAX: yield _bbox_groups(595, 623), _recognize_base_effect yield _bbox_groups(568, 593), _recognize_red_effect else: raise NotImplementedError(ctx.scenario) def _recognize_training(ctx: Context, img: Image) -> Training: try: rp = mathtools.ResizeProxy(img.width) self = Training.new() self.confirm_position = next( template.match( img, template.Specification( templates.SINGLE_MODE_TRAINING_CONFIRM, threshold=0.8 ), ) )[1] radius = rp.vector(30, 540) for t, center in zip( Training.ALL_TYPES, ( rp.vector2((78, 850), 540), rp.vector2((171, 850), 540), rp.vector2((268, 850), 540), rp.vector2((367, 850), 540), rp.vector2((461, 850), 540), ), ): if mathtools.distance(self.confirm_position, center) < radius: self.type = t break else: raise ValueError( "unknown type for confirm position: %s" % self.confirm_position ) self.level = _recognize_level( tuple(cast.list_(img.getpixel(rp.vector2((10, 200), 540)), int)) ) for bbox_group, recognize in _effect_recognitions(ctx, rp): self.speed += recognize(img.crop(bbox_group[0])) self.stamina += recognize(img.crop(bbox_group[1])) self.power += recognize(img.crop(bbox_group[2])) self.guts += recognize(img.crop(bbox_group[3])) self.wisdom += recognize(img.crop(bbox_group[4])) self.skill += recognize(img.crop(bbox_group[5])) # TODO: recognize vitality # plugin hook self._use_estimate_vitality = True # type: ignore self.vitality = _estimate_vitality(ctx, self) self.failure_rate = _recognize_failure_rate(rp, self, img) self.partners = tuple(_recognize_partners(ctx, img)) app.log.image("%s" % self, img, level=app.DEBUG) except: app.log.image( ("training recognition failed: %s" % traceback.format_exc()), img, level=app.ERROR, ) raise return self class TrainingScene(Scene): @classmethod def name(cls): return "single-mode-training" @classmethod def _enter(cls, ctx: SceneHolder) -> Scene: CommandScene.enter(ctx) action.wait_tap_image(templates.SINGLE_MODE_COMMAND_TRAINING) action.wait_image(_TRAINING_CONFIRM) return cls() def __init__(self): self.trainings: Tuple[Training, ...] = () def recognize(self) -> None: # TODO: remove old api at next major version import warnings warnings.warn( "use recognize_v2 instead", DeprecationWarning, ) ctx = Context() ctx.scenario = ctx.SCENARIO_URA return self.recognize_v2(ctx) def recognize_v2(self, ctx: Context, static: bool = False) -> None: with futures.ThreadPoolExecutor() as pool: self.trainings = tuple( i.result() for i in [ pool.submit(_recognize_training, ctx, j) for j in _iter_training_images(static) ] ) assert len(set(i.type for i in self.trainings)) == len( self.trainings ), "duplicated trainings" ctx.trainings = self.trainings if not ctx.is_summer_camp: ctx.training_levels = {i.type: i.level for i in self.trainings}
[ "traceback.format_exc", "PIL.Image.fromarray", "cv2.countNonZero", "numpy.ones", "numpy.average", "cv2.threshold", "concurrent.futures.ThreadPoolExecutor", "cv2.copyTo", "numpy.linspace", "numpy.array", "numpy.concatenate", "numpy.expand_dims", "warnings.warn", "numpy.maximum", "cv2.getS...
[((770, 820), 'numpy.linspace', 'np.linspace', (['(0, 0, 0)', 'colors[0][0]', 'colors[0][1]'], {}), '((0, 0, 0), colors[0][0], colors[0][1])\n', (781, 820), True, 'import numpy as np\n'), ((1879, 1916), 'cv2.copyTo', 'cv2.copyTo', (['cv_img', '(255 - bg_mask_img)'], {}), '(cv_img, 255 - bg_mask_img)\n', (1889, 1916), False, 'import cv2\n'), ((2203, 2260), 'cv2.threshold', 'cv2.threshold', (['brown_img', '(120)', '(255)', 'cv2.THRESH_BINARY_INV'], {}), '(brown_img, 120, 255, cv2.THRESH_BINARY_INV)\n', (2216, 2260), False, 'import cv2\n'), ((2352, 2397), 'cv2.copyTo', 'cv2.copyTo', (['brown_img', '(255 - border_brown_img)'], {}), '(brown_img, 255 - border_brown_img)\n', (2362, 2397), False, 'import cv2\n'), ((2483, 2524), 'cv2.copyTo', 'cv2.copyTo', (['masked_img', '(255 - bg_mask_img)'], {}), '(masked_img, 255 - bg_mask_img)\n', (2493, 2524), False, 'import cv2\n'), ((11557, 11573), 'numpy.average', 'np.average', (['mask'], {}), '(mask)\n', (11567, 11573), True, 'import numpy as np\n'), ((12170, 12186), 'numpy.average', 'np.average', (['mask'], {}), '(mask)\n', (12180, 12186), True, 'import numpy as np\n'), ((15542, 15570), 'cv2.copyTo', 'cv2.copyTo', (['cv_img', 'fg_mask1'], {}), '(cv_img, fg_mask1)\n', (15552, 15570), False, 'import cv2\n'), ((16048, 16080), 'cv2.copyTo', 'cv2.copyTo', (['masked_img', 'fg_mask2'], {}), '(masked_img, fg_mask2)\n', (16058, 16080), False, 'import cv2\n'), ((16569, 16589), 'numpy.average', 'np.average', (['fg_mask2'], {}), '(fg_mask2)\n', (16579, 16589), True, 'import numpy as np\n'), ((16645, 16667), 'numpy.average', 'np.average', (['empty_mask'], {}), '(empty_mask)\n', (16655, 16667), True, 'import numpy as np\n'), ((953, 1005), 'numpy.linspace', 'np.linspace', (['prev_color', 'color', '(stop - prev_stop + 1)'], {}), '(prev_color, color, stop - prev_stop + 1)\n', (964, 1005), True, 'import numpy as np\n'), ((1020, 1048), 'numpy.concatenate', 'np.concatenate', (['(ret, g[1:])'], {}), '((ret, g[1:]))\n', (1034, 1048), True, 'import numpy as np\n'), ((1512, 1564), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(5, 5)'], {}), '(cv2.MORPH_ELLIPSE, (5, 5))\n', (1537, 1564), False, 'import cv2\n'), ((1690, 1742), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(3, 7)'], {}), '(cv2.MORPH_ELLIPSE, (3, 7))\n', (1715, 1742), False, 'import cv2\n'), ((3075, 3107), 'numpy.expand_dims', 'np.expand_dims', (['fill_gradient', '(1)'], {}), '(fill_gradient, 1)\n', (3089, 3107), True, 'import numpy as np\n'), ((3387, 3423), 'numpy.maximum', 'np.maximum', (['text_img', 'text_img_extra'], {}), '(text_img, text_img_extra)\n', (3397, 3423), True, 'import numpy as np\n'), ((4061, 4087), 'cv2.countNonZero', 'cv2.countNonZero', (['text_img'], {}), '(text_img)\n', (4077, 4087), False, 'import cv2\n'), ((4460, 4486), 'PIL.Image.fromarray', 'image_from_array', (['text_img'], {}), '(text_img)\n', (4476, 4486), True, 'from PIL.Image import fromarray as image_from_array\n'), ((4819, 4866), 'numpy.array', 'np.array', (['((0, -1, 0), (-1, 5, -1), (0, -1, 0))'], {}), '(((0, -1, 0), (-1, 5, -1), (0, -1, 0)))\n', (4827, 4866), True, 'import numpy as np\n'), ((5592, 5607), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (5599, 5607), True, 'import numpy as np\n'), ((5992, 6024), 'numpy.expand_dims', 'np.expand_dims', (['fill_gradient', '(1)'], {}), '(fill_gradient, 1)\n', (6006, 6024), True, 'import numpy as np\n'), ((6586, 6627), 'numpy.maximum', 'np.maximum', (['text_img_base', 'text_img_extra'], {}), '(text_img_base, text_img_extra)\n', (6596, 6627), True, 'import numpy as np\n'), ((7166, 7192), 'PIL.Image.fromarray', 'image_from_array', (['text_img'], {}), '(text_img)\n', (7182, 7192), True, 'from PIL.Image import fromarray as image_from_array\n'), ((11109, 11130), 'numpy.average', 'np.average', (['hint_mask'], {}), '(hint_mask)\n', (11119, 11130), True, 'import numpy as np\n'), ((22717, 22778), 'warnings.warn', 'warnings.warn', (['"""use recognize_v2 instead"""', 'DeprecationWarning'], {}), "('use recognize_v2 instead', DeprecationWarning)\n", (22730, 22778), False, 'import warnings\n'), ((23002, 23030), 'concurrent.futures.ThreadPoolExecutor', 'futures.ThreadPoolExecutor', ([], {}), '()\n', (23028, 23030), False, 'from concurrent import futures\n'), ((22073, 22095), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (22093, 22095), False, 'import traceback\n')]
import random import numpy as np from abc import ABC, abstractmethod class Param(ABC): @abstractmethod def __init__(self, space=None, projection_fn=None, name="Param"): self.space = space if projection_fn is not None: self.projection_fn = projection_fn else: self.projection_fn = lambda x: x self.name = name def sample(self): return self.transform_raw_sample(self.raw_sample()) @abstractmethod def transform_raw_sample(self, raw_sample): pass @abstractmethod def raw_sample(self): pass @abstractmethod def create_generator(self): pass class Integer(Param): def __init__(self, space=None, projection_fn=None, name="IntegerParam"): if space is None: space = [0, 1] super(Integer, self).__init__(space, projection_fn, name) def transform_raw_sample(self, raw_sample): return self.projection_fn(self.space[int(raw_sample)]) def raw_sample(self): rand_item = random.randint(0, len(self.space) - 1) return rand_item def create_generator(self): def generator(): for i in self.space: yield self.projection_fn(i) return generator class Real(Param): def __init__(self, space=None, projection_fn=None, name="RealParam", n_points_to_sample=50): if space is None: space = [0, 1] if len(space) != 2: raise Exception("RealParam expects list of length two with: [lower_bound_inclusive, upper_bound_inclusive]") self.lower_bound = space[0] self.upper_bound = space[1] self.n_points_to_sample = n_points_to_sample super(Real, self).__init__(space, projection_fn, name) def transform_raw_sample(self, raw_sample): return self.projection_fn(raw_sample) def raw_sample(self): random_sample = random.uniform(self.lower_bound, self.upper_bound) return random_sample def create_generator(self): def generator(): sampled_xs = np.linspace(self.lower_bound, self.upper_bound, self.n_points_to_sample) for i in sampled_xs: yield self.projection_fn(i) return generator class Bool(Integer): def __init__(self, space=None, projection_fn=None, name="BoolParam"): if space is None: space = [0, 1] if space != [0, 1]: raise Exception('For Bool no structured_space or structured_space of [0, 1] must be given') super(Bool, self).__init__(space, projection_fn, name) class Choice(Param): def __init__(self, space=None, projection_fn=None, name="ChoiceParam"): if space is None: space = [0, 1] super(Choice, self).__init__(space, projection_fn, name) def transform_raw_sample(self, raw_sample): return self.projection_fn(self.space[int(raw_sample)]) def raw_sample(self): rand_item = random.randint(0, len(self.space) - 1) return rand_item def create_generator(self): def generator(): for i in self.space: yield self.projection_fn(i) return generator
[ "random.uniform", "numpy.linspace" ]
[((1923, 1973), 'random.uniform', 'random.uniform', (['self.lower_bound', 'self.upper_bound'], {}), '(self.lower_bound, self.upper_bound)\n', (1937, 1973), False, 'import random\n'), ((2086, 2158), 'numpy.linspace', 'np.linspace', (['self.lower_bound', 'self.upper_bound', 'self.n_points_to_sample'], {}), '(self.lower_bound, self.upper_bound, self.n_points_to_sample)\n', (2097, 2158), True, 'import numpy as np\n')]
import torch from torch.utils.data import Dataset import numpy as np import pandas as pd class GenevaStrokeOutcomeDataset(Dataset): """Geneva Clinical Stroke Outcome Dataset.""" def __init__(self, imaging_dataset_path, outcome_file_path, channels, outcome, transform=None, preload_data=True): """ """ self.imaging_dataset_path = imaging_dataset_path self.params = np.load(imaging_dataset_path, allow_pickle=True)['params'] self.channels = channels self.ids = np.load(imaging_dataset_path, allow_pickle=True)['ids'] outcomes_df = pd.read_excel(outcome_file_path) raw_labels = [outcomes_df.loc[outcomes_df['anonymised_id'] == subj_id, outcome].iloc[0] for subj_id in self.ids] self.raw_labels = torch.tensor(raw_labels).long() try: print('Using channels:', [self.params.item()['ct_sequences'][channel] for channel in channels]) except: print('Geneva Stroke Dataset (perfusion CT maps) parameters: ', self.params) # data augmentation self.transform = transform # data load into the ram memory self.preload_data = preload_data if self.preload_data: print('Preloading the dataset ...') # select only from data available for this split self.raw_images = np.load(imaging_dataset_path, allow_pickle=True)['ct_inputs'][..., self.channels] self.raw_masks = np.load(imaging_dataset_path, allow_pickle=True)['brain_masks'] self.raw_masks = np.expand_dims(self.raw_masks, axis=-1) if self.raw_images.ndim < 5: self.raw_images = np.expand_dims(self.raw_images, axis=-1) # Apply masks self.raw_images = self.raw_images * self.raw_masks assert len(self.raw_images) == len(self.raw_labels) print('Loading is done\n') def get_ids(self, indices): return [self.ids[index] for index in indices] def __getitem__(self, index): ''' Return sample at index :param index: int :return: sample (c, x, y, z) ''' # load the images if not self.preload_data: input = np.load(self.imaging_dataset_path, allow_pickle=True)['ct_inputs'][index, ..., self.channels] mask = np.load(self.imaging_dataset_path, allow_pickle=True)['brain_masks'][index] # Make sure there is a channel dimension mask = np.expand_dims(mask, axis=-1) if input.ndim < 5: input = np.expand_dims(input, axis=-1) # Apply masks input = input * mask # Remove first dimension input = np.squeeze(input, axis=0) else: # With preload, it is already only the images from a certain split that are loaded input = self.raw_images[index] target = self.raw_labels[index] id = self.ids[index] # input = torch.from_numpy(input).permute(3, 0, 1, 2).to(torch.float32) input = np.transpose(input, (3, 0, 1, 2)) # apply transformations if self.transform: # transiently transform into dictionary to use DKFZ augmentation data_dict = {'data': input} input = self.transform(**data_dict)['data'] input = torch.from_numpy(input).to(torch.float32) return input, target, id def __len__(self): return len(self.ids)
[ "numpy.transpose", "torch.from_numpy", "numpy.squeeze", "torch.tensor", "numpy.expand_dims", "pandas.read_excel", "numpy.load" ]
[((598, 630), 'pandas.read_excel', 'pd.read_excel', (['outcome_file_path'], {}), '(outcome_file_path)\n', (611, 630), True, 'import pandas as pd\n'), ((3095, 3128), 'numpy.transpose', 'np.transpose', (['input', '(3, 0, 1, 2)'], {}), '(input, (3, 0, 1, 2))\n', (3107, 3128), True, 'import numpy as np\n'), ((408, 456), 'numpy.load', 'np.load', (['imaging_dataset_path'], {'allow_pickle': '(True)'}), '(imaging_dataset_path, allow_pickle=True)\n', (415, 456), True, 'import numpy as np\n'), ((519, 567), 'numpy.load', 'np.load', (['imaging_dataset_path'], {'allow_pickle': '(True)'}), '(imaging_dataset_path, allow_pickle=True)\n', (526, 567), True, 'import numpy as np\n'), ((1581, 1620), 'numpy.expand_dims', 'np.expand_dims', (['self.raw_masks'], {'axis': '(-1)'}), '(self.raw_masks, axis=-1)\n', (1595, 1620), True, 'import numpy as np\n'), ((2515, 2544), 'numpy.expand_dims', 'np.expand_dims', (['mask'], {'axis': '(-1)'}), '(mask, axis=-1)\n', (2529, 2544), True, 'import numpy as np\n'), ((2748, 2773), 'numpy.squeeze', 'np.squeeze', (['input'], {'axis': '(0)'}), '(input, axis=0)\n', (2758, 2773), True, 'import numpy as np\n'), ((800, 824), 'torch.tensor', 'torch.tensor', (['raw_labels'], {}), '(raw_labels)\n', (812, 824), False, 'import torch\n'), ((1487, 1535), 'numpy.load', 'np.load', (['imaging_dataset_path'], {'allow_pickle': '(True)'}), '(imaging_dataset_path, allow_pickle=True)\n', (1494, 1535), True, 'import numpy as np\n'), ((1696, 1736), 'numpy.expand_dims', 'np.expand_dims', (['self.raw_images'], {'axis': '(-1)'}), '(self.raw_images, axis=-1)\n', (1710, 1736), True, 'import numpy as np\n'), ((2600, 2630), 'numpy.expand_dims', 'np.expand_dims', (['input'], {'axis': '(-1)'}), '(input, axis=-1)\n', (2614, 2630), True, 'import numpy as np\n'), ((1376, 1424), 'numpy.load', 'np.load', (['imaging_dataset_path'], {'allow_pickle': '(True)'}), '(imaging_dataset_path, allow_pickle=True)\n', (1383, 1424), True, 'import numpy as np\n'), ((2252, 2305), 'numpy.load', 'np.load', (['self.imaging_dataset_path'], {'allow_pickle': '(True)'}), '(self.imaging_dataset_path, allow_pickle=True)\n', (2259, 2305), True, 'import numpy as np\n'), ((2366, 2419), 'numpy.load', 'np.load', (['self.imaging_dataset_path'], {'allow_pickle': '(True)'}), '(self.imaging_dataset_path, allow_pickle=True)\n', (2373, 2419), True, 'import numpy as np\n'), ((3382, 3405), 'torch.from_numpy', 'torch.from_numpy', (['input'], {}), '(input)\n', (3398, 3405), False, 'import torch\n')]
import matplotlib.pyplot as plt from scipy.io import wavfile import os from pydub import AudioSegment import pandas as pd import numpy as np import pickle from scipy.signal import spectrogram from python_speech_features import mfcc from mpl_toolkits.axes_grid1 import make_axes_locatable from src import char_map # import pydevd # pydevd.settrace('localhost', port=51234, stdoutToServer=True, stderrToServer=True) # sampling time AUDIO_DURATION = 10000 # The number of time steps input to the model from the spectrogram Tx = 999 # Number of frequencies input to the model at each time step of the spectrogram n_freq = 26 # duration of activation time ACTIVE_DURATION = 20 # dataset ratio TRAIN_RATIO = 0.95 VALIDATE_RATIO = 0.05 # Calculate and plot spectrogram for a wav audio file def graph_spectrogram(wav_file): rate, data = get_wav_info(wav_file) nfft = 200 # Length of each window segment fs = 8000 # Sampling frequencies noverlap = 120 # Overlap between windows nchannels = data.ndim if nchannels == 1: pxx, freqs, bins, im = plt.specgram(data, nfft, fs, noverlap=noverlap) elif nchannels == 2: pxx, freqs, bins, im = plt.specgram(data[:, 0], nfft, fs, noverlap=noverlap) else: raise RuntimeError(f"invalid channels. file={wav_file}") return pxx # Calculate spectrogram for a wav audio file def create_spectrogram(wav_file): rate, data = get_wav_info(wav_file) nfft = 200 # Length of each window segment fs = 8000 # Sampling frequencies noverlap = 120 # Overlap between windows nchannels = data.ndim if nchannels == 1: freqs, bins, pxx = spectrogram(data, fs, nperseg=nfft, noverlap=noverlap) elif nchannels == 2: freqs, bins, pxx = spectrogram(data[:, 0], fs, nperseg=nfft, noverlap=noverlap) else: raise RuntimeError(f"invalid channels. file={wav_file}") return pxx def plot_mfcc_feature(vis_mfcc_feature): # plot the MFCC feature fig = plt.figure(figsize=(12,5)) ax = fig.add_subplot(111) im = ax.imshow(vis_mfcc_feature, cmap=plt.cm.jet, aspect='auto') plt.title('Normalized MFCC') plt.ylabel('Time') plt.xlabel('MFCC Coefficient') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) ax.set_xticks(np.arange(0, 13, 2), minor=False) plt.show() # Calculate mfcc for a wav audio file def create_mfcc(wav_file): rate, data = get_wav_info(wav_file) mfcc_dim = n_freq nchannels = data.ndim if nchannels == 1: features = mfcc(data, rate, numcep=mfcc_dim) elif nchannels == 2: features = mfcc(data[:, 0], rate, numcep=mfcc_dim) else: raise RuntimeError(f"invalid channels. file={wav_file}") return features # Load a wav file def get_wav_info(wav_file): rate, data = wavfile.read(wav_file) return rate, data # Used to standardize volume of audio clip def match_target_amplitude(sound, target_dBFS): change_in_dBFS = target_dBFS - sound.dBFS return sound.apply_gain(change_in_dBFS) # Load raw audio files for speech synthesis def load_raw_audio(): audio_dir_path = "./train/audio/" keywords = {} backgrounds = [] for keyword in os.listdir(audio_dir_path): if keyword.startswith("_"): continue if keyword not in keywords: keywords[keyword] = [] for filename in os.listdir(audio_dir_path + keyword): if not filename.endswith("wav"): continue audio = AudioSegment.from_wav(audio_dir_path + keyword + "/" + filename) keywords[keyword].append({'audio': audio, 'filename': filename}) for filename in os.listdir(audio_dir_path + "_background_noise_/"): if not filename.endswith("wav"): continue audio = AudioSegment.from_wav(audio_dir_path + "_background_noise_/" + filename) backgrounds.append({'audio': audio, 'filename': filename}) return keywords, backgrounds def get_random_time_segment(segment_ms): """ Gets a random time segment of duration segment_ms in a 10,000 ms audio clip. Arguments: segment_ms -- the duration of the audio clip in ms ("ms" stands for "milliseconds") Returns: segment_time -- a tuple of (segment_start, segment_end) in ms """ # Make sure segment doesn't run past the AUDIO_DURATION sec background segment_start = np.random.randint(low=0, high=AUDIO_DURATION-segment_ms) segment_end = segment_start + segment_ms - 1 return segment_start, segment_end def get_random_time_segment_bg(background): """ Gets background file positions Arguments: background -- background AudioSegment Returns: segment_time -- a tuple of (segment_start, segment_end) in ms """ bg_duration = len(background) # Make sure segment doesn't run past the 10sec background segment_start = np.random.randint(low=0, high=bg_duration - AUDIO_DURATION) segment_end = segment_start + AUDIO_DURATION return segment_start, segment_end def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples of (segment_start, segment_end) for the existing segments Returns: True if the time segment overlaps with any of the existing segments, False otherwise """ segment_start, segment_end = segment_time ### START CODE HERE ### (≈ 4 line) # Step 1: Initialize overlap as a "False" flag. (≈ 1 line) overlap = False # Step 2: loop over the previous_segments start and end times. # Compare start/end times and set the flag to True if there is an overlap (≈ 3 lines) for previous_start, previous_end in previous_segments: if previous_start <= segment_start <= previous_end + ACTIVE_DURATION or \ previous_start <= segment_end <= previous_end + ACTIVE_DURATION: overlap = True ### END CODE HERE ### return overlap def insert_audio_clip(background, audio_clip, previous_segments): """ Insert a new audio segment over the background noise at a random time step, ensuring that the audio segment does not overlap with existing segments. Arguments: background -- a 10 second background audio recording. audio_clip -- the audio clip to be inserted/overlaid. previous_segments -- times where audio segments have already been placed Returns: new_background -- the updated background audio """ # Get the duration of the audio clip in ms segment_ms = len(audio_clip) # Step 1: Use one of the helper functions to pick a random time segment onto which to insert # the new audio clip. (≈ 1 line) segment_time = get_random_time_segment(segment_ms) # Step 2: Check if the new segment_time overlaps with one of the previous_segments. If so, keep # picking new segment_time at random until it doesn't overlap. (≈ 2 lines) while is_overlapping(segment_time, previous_segments): segment_time = get_random_time_segment(segment_ms) # Step 3: Add the new segment_time to the list of previous_segments (≈ 1 line) previous_segments.append(segment_time) # Step 4: Superpose audio segment and background new_background = background.overlay(audio_clip, position=segment_time[0]) return new_background, segment_time def create_training_sample(background, keywords, filename='sample.wav', feature_type='mfcc', is_train=True): """ Creates a training example with a given background, activates, and negatives. Arguments: background -- a 10 second background audio recording keywords -- a list of audio segments of each word Returns: x -- the spectrogram of the training example y -- the label at each time step of the spectrogram """ # Make background quieter output = background - 20 y_words = {} # Step 2: Initialize segment times as empty list (≈ 1 line) previous_segments = [] # Select 0-4 random "activate" audio clips from the entire list of "activates" recordings # number_of_keywords = np.random.randint(0, 5) number_of_keywords = np.random.choice([0, 1, 1, 2, 2, 3, 3, 3, 4, 4]) random_keyword_indices = np.random.randint(len(keywords), size=number_of_keywords) random_keywords = [(i, keywords[list(keywords.keys())[i]]) for i in random_keyword_indices] # print(f"num:{number_of_keywords}") # Step 3: Loop over randomly selected "activate" clips and insert in background for idx, random_keyword_list in random_keywords: # print(f"idx:{idx}") sample_num = len(random_keyword_list) train_num = int(sample_num * TRAIN_RATIO) if is_train: random_index = np.random.randint(train_num) else: validate_num = int(sample_num * VALIDATE_RATIO) random_index = train_num + np.random.randint(validate_num) random_keyword = random_keyword_list[random_index] audio_data = random_keyword['audio'] audio_filename = random_keyword['filename'] # Insert the audio clip on the background output, segment_time = insert_audio_clip(output, audio_data, previous_segments) # Retrieve segment_start and segment_end from segment_time segment_start, segment_end = segment_time # Insert labels in "y" with increment keyword = list(keywords.keys())[idx] # print(f"keyword:{keyword} start:{segment_start} end:{segment_end} audio_file:{audio_filename}") # print(f"create_training_sample1 y:{y[701:]}") if keyword in KEYWORDS.keys(): y_words[segment_start] = keyword # print(f"create_training_sample2 y:{y[701:]}") # Standardize the volume of the audio clip output = match_target_amplitude(output, -20.0) # Export new training example file_handle = output.export(filename, format="wav") # print(f"File ({filename}) was saved in your directory.") # Get features of the new recording (background with superposition of positive and negatives) x = create_features(filename, feature_type) keyword_times = sorted(list(y_words.keys())) if len(y_words.keys()) == 0: y_sequence = " " elif keyword_times[0] < ACTIVE_DURATION // 2: y_sequence = "" else: y_sequence = " " for segment in keyword_times: y_sequence += y_words[segment] + " " y = [] for char in y_sequence: y.append(char_map.CHAR_MAP[char]) # print(f"y_words:{y_words} y_seq:'{y_sequence}' y:{y} decoded_y:'{int_sequence_to_text(y)}'") return x, y def normalize(features, mean, std, eps=1e-14): """ Center a feature using the mean and std Params: feature (numpy.ndarray): Feature to normalize """ # return (feature - np.mean(feature, axis=0)) / (np.std(feature, axis=0) + eps) return (features - mean) / (std + eps) def normalize_dataset(features_list): flatten = np.vstack([features for features in features_list]) # print(f"originshape:{features_list.shape} flattenshape:{flatten.shape}") mean = np.mean(flatten, axis=0) std = np.std(flatten, axis=0) for i, features in enumerate(features_list): features_list[i] = normalize(features, mean, std) def create_dataset(backgrounds, keywords, is_train=True): # extract background background = backgrounds[np.random.randint(len(backgrounds))] background_audio_data = background['audio'] bg_segment = get_random_time_segment_bg(background_audio_data) clipped_background = background_audio_data[bg_segment[0]:bg_segment[1]] feat, label = create_training_sample(clipped_background, keywords, is_train=is_train) return feat, label def load_dataset(filename): with open(filename, 'rb') as f: # The protocol version used is detected automatically, so we do not # have to specify it. train_dataset = pickle.load(f) return train_dataset def text_to_int_sequence(text): """ Convert text to an integer sequence """ int_sequence = [] for c in text: if c == ' ': ch = char_map.CHAR_MAP['<SPACE>'] else: ch = char_map.CHAR_MAP[c] int_sequence.append(ch) return int_sequence def int_sequence_to_text(int_sequence): """ Convert an integer sequence to text """ text = [] for c in int_sequence: ch = char_map.INDEX_MAP[c] text.append(ch) return text KEYWORDS = { 'silence': 0, 'unknown': 1, # others 'up': 2, 'down': 3, 'off': 4, 'on': 5, 'yes': 6, 'no': 7, 'right': 8, 'stop': 9, 'left': 10, 'go': 11, 'tree': 12, 'zero': 13, 'one': 14, 'two': 15, 'three': 16, 'four': 17, 'five': 18, 'six': 19, 'seven': 20, 'eight': 21, 'nine': 22, 'bed': 23, 'bird': 24, 'cat': 25, 'dog': 26, 'happy': 27, 'house': 28, 'marvin': 29, 'sheila': 30, 'wow': 31, } # KEYWORDS (exclude silence) NUM_CLASSES = len(KEYWORDS) # one-hot-encoding (exclude silence) KEYWORDS_INDEX_DF = pd.get_dummies(list(range(NUM_CLASSES))) def get_keyword_index(keyword): if keyword in KEYWORDS: # target word # decrement index offset return KEYWORDS[keyword] else: # unknown return KEYWORDS['unknown']
[ "matplotlib.pyplot.ylabel", "scipy.signal.spectrogram", "matplotlib.pyplot.specgram", "numpy.arange", "numpy.mean", "os.listdir", "matplotlib.pyplot.xlabel", "numpy.vstack", "mpl_toolkits.axes_grid1.make_axes_locatable", "pydub.AudioSegment.from_wav", "numpy.random.choice", "pickle.load", "s...
[((1988, 2015), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 5)'}), '(figsize=(12, 5))\n', (1998, 2015), True, 'import matplotlib.pyplot as plt\n'), ((2118, 2146), 'matplotlib.pyplot.title', 'plt.title', (['"""Normalized MFCC"""'], {}), "('Normalized MFCC')\n", (2127, 2146), True, 'import matplotlib.pyplot as plt\n'), ((2151, 2169), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time"""'], {}), "('Time')\n", (2161, 2169), True, 'import matplotlib.pyplot as plt\n'), ((2174, 2204), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""MFCC Coefficient"""'], {}), "('MFCC Coefficient')\n", (2184, 2204), True, 'import matplotlib.pyplot as plt\n'), ((2219, 2242), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (2238, 2242), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((2307, 2332), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax'}), '(im, cax=cax)\n', (2319, 2332), True, 'import matplotlib.pyplot as plt\n'), ((2389, 2399), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2397, 2399), True, 'import matplotlib.pyplot as plt\n'), ((2876, 2898), 'scipy.io.wavfile.read', 'wavfile.read', (['wav_file'], {}), '(wav_file)\n', (2888, 2898), False, 'from scipy.io import wavfile\n'), ((3268, 3294), 'os.listdir', 'os.listdir', (['audio_dir_path'], {}), '(audio_dir_path)\n', (3278, 3294), False, 'import os\n'), ((3738, 3788), 'os.listdir', 'os.listdir', (["(audio_dir_path + '_background_noise_/')"], {}), "(audio_dir_path + '_background_noise_/')\n", (3748, 3788), False, 'import os\n'), ((4460, 4518), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(AUDIO_DURATION - segment_ms)'}), '(low=0, high=AUDIO_DURATION - segment_ms)\n', (4477, 4518), True, 'import numpy as np\n'), ((4956, 5015), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(bg_duration - AUDIO_DURATION)'}), '(low=0, high=bg_duration - AUDIO_DURATION)\n', (4973, 5015), True, 'import numpy as np\n'), ((8385, 8433), 'numpy.random.choice', 'np.random.choice', (['[0, 1, 1, 2, 2, 3, 3, 3, 4, 4]'], {}), '([0, 1, 1, 2, 2, 3, 3, 3, 4, 4])\n', (8401, 8433), True, 'import numpy as np\n'), ((11200, 11251), 'numpy.vstack', 'np.vstack', (['[features for features in features_list]'], {}), '([features for features in features_list])\n', (11209, 11251), True, 'import numpy as np\n'), ((11342, 11366), 'numpy.mean', 'np.mean', (['flatten'], {'axis': '(0)'}), '(flatten, axis=0)\n', (11349, 11366), True, 'import numpy as np\n'), ((11377, 11400), 'numpy.std', 'np.std', (['flatten'], {'axis': '(0)'}), '(flatten, axis=0)\n', (11383, 11400), True, 'import numpy as np\n'), ((1072, 1119), 'matplotlib.pyplot.specgram', 'plt.specgram', (['data', 'nfft', 'fs'], {'noverlap': 'noverlap'}), '(data, nfft, fs, noverlap=noverlap)\n', (1084, 1119), True, 'import matplotlib.pyplot as plt\n'), ((1649, 1703), 'scipy.signal.spectrogram', 'spectrogram', (['data', 'fs'], {'nperseg': 'nfft', 'noverlap': 'noverlap'}), '(data, fs, nperseg=nfft, noverlap=noverlap)\n', (1660, 1703), False, 'from scipy.signal import spectrogram\n'), ((2351, 2370), 'numpy.arange', 'np.arange', (['(0)', '(13)', '(2)'], {}), '(0, 13, 2)\n', (2360, 2370), True, 'import numpy as np\n'), ((2598, 2631), 'python_speech_features.mfcc', 'mfcc', (['data', 'rate'], {'numcep': 'mfcc_dim'}), '(data, rate, numcep=mfcc_dim)\n', (2602, 2631), False, 'from python_speech_features import mfcc\n'), ((3448, 3484), 'os.listdir', 'os.listdir', (['(audio_dir_path + keyword)'], {}), '(audio_dir_path + keyword)\n', (3458, 3484), False, 'import os\n'), ((3868, 3940), 'pydub.AudioSegment.from_wav', 'AudioSegment.from_wav', (["(audio_dir_path + '_background_noise_/' + filename)"], {}), "(audio_dir_path + '_background_noise_/' + filename)\n", (3889, 3940), False, 'from pydub import AudioSegment\n'), ((12160, 12174), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (12171, 12174), False, 'import pickle\n'), ((1176, 1229), 'matplotlib.pyplot.specgram', 'plt.specgram', (['data[:, 0]', 'nfft', 'fs'], {'noverlap': 'noverlap'}), '(data[:, 0], nfft, fs, noverlap=noverlap)\n', (1188, 1229), True, 'import matplotlib.pyplot as plt\n'), ((1756, 1816), 'scipy.signal.spectrogram', 'spectrogram', (['data[:, 0]', 'fs'], {'nperseg': 'nfft', 'noverlap': 'noverlap'}), '(data[:, 0], fs, nperseg=nfft, noverlap=noverlap)\n', (1767, 1816), False, 'from scipy.signal import spectrogram\n'), ((2676, 2715), 'python_speech_features.mfcc', 'mfcc', (['data[:, 0]', 'rate'], {'numcep': 'mfcc_dim'}), '(data[:, 0], rate, numcep=mfcc_dim)\n', (2680, 2715), False, 'from python_speech_features import mfcc\n'), ((3576, 3640), 'pydub.AudioSegment.from_wav', 'AudioSegment.from_wav', (["(audio_dir_path + keyword + '/' + filename)"], {}), "(audio_dir_path + keyword + '/' + filename)\n", (3597, 3640), False, 'from pydub import AudioSegment\n'), ((8969, 8997), 'numpy.random.randint', 'np.random.randint', (['train_num'], {}), '(train_num)\n', (8986, 8997), True, 'import numpy as np\n'), ((9111, 9142), 'numpy.random.randint', 'np.random.randint', (['validate_num'], {}), '(validate_num)\n', (9128, 9142), True, 'import numpy as np\n')]
# RLE Source: https://www.kaggle.com/rakhlin/fast-run-length-encoding-python import os import numpy as np import pandas as pd from skimage.morphology import label def rle_encoding(x): dots = np.where(x.T.flatten() == 1)[0] run_lengths = [] prev = -2 for b in dots: if (b>prev+1): run_lengths.extend((b + 1, 0)) run_lengths[-1] += 1 prev = b return run_lengths def prob_to_rles(x, cutoff): lab_img = label(x > cutoff) for i in range(1, lab_img.max() + 1): yield rle_encoding(lab_img == i) def label_to_rles(lab_img): # For each nuclei, skipping the first element(background '0' value) for i in np.unique(lab_img)[1:]: yield rle_encoding(lab_img == i) def generate_submission(test_ids, predictions, threshold, submission_file): """Generates a submission RLE CSV file based on the input predicted masks. Args: test_ids: List of all test_ids that were predicted. predictions: List of all full-size predicted masks, where each pixel is represented as a probability between 0 and 1. threshold: The threshold above which a predicted probability is considered 'True'. submission_file: The output submission file name. """ new_test_ids = [] rles = [] for n, id_ in enumerate(test_ids): rle = list(prob_to_rles(predictions[n], threshold)) rles.extend(rle) new_test_ids.extend([id_] * len(rle)) sub = pd.DataFrame() sub['ImageId'] = new_test_ids sub['EncodedPixels'] = pd.Series(rles).apply(lambda x: ' '.join(str(y) for y in x)) sub.to_csv(submission_file, index=False) def generate_submission_from_df_prediction(dfs, threshold, submission_file): """Generates a submission RLE CSV file based on the input data frame's predicted image. Args: dfs: List of all data frames that contain labeled masks to submit. threshold: The threshold above which a predicted probability is considered 'True'. submission_file: The output submission file name. """ basename, _ = os.path.split(submission_file) if not os.path.isdir(basename) and basename: os.makedirs(basename) new_test_ids = [] rles = [] for df in dfs: for img_id, prediction in zip(df.imageID, df.prediction): mask = prediction[:,:,0] rle = list(prob_to_rles(mask, threshold)) rles.extend(rle) new_test_ids.extend([img_id] * len(rle)) sub = pd.DataFrame() sub['ImageId'] = new_test_ids sub['EncodedPixels'] = pd.Series(rles).apply(lambda x: ' '.join(str(y) for y in x)) sub.to_csv(submission_file, index=False) def generate_submission_from_df(dfs, submission_file): """Generates a submission RLE CSV file based on the labeled mask in a data frame. Args: dfs: List of all data frames that contain labeled masks to submit. submission_file: The output submission file name. """ basename, _ = os.path.split(submission_file) if not os.path.isdir(basename) and basename: os.makedirs(basename) new_test_ids = [] rles = [] for df in dfs: for img_id, label in zip(df.imageID, df.label): if len(np.unique(label)) == 1: rles.extend(['']) new_test_ids.extend([img_id]) else: rle = list(label_to_rles(label)) rles.extend(rle) new_test_ids.extend([img_id] * len(rle)) sub = pd.DataFrame() sub['ImageId'] = new_test_ids sub['EncodedPixels'] = pd.Series(rles).apply(lambda x: ' '.join(str(y) for y in x)) sub.to_csv(submission_file, index=False)
[ "pandas.Series", "numpy.unique", "os.makedirs", "os.path.split", "skimage.morphology.label", "os.path.isdir", "pandas.DataFrame" ]
[((449, 466), 'skimage.morphology.label', 'label', (['(x > cutoff)'], {}), '(x > cutoff)\n', (454, 466), False, 'from skimage.morphology import label\n'), ((1467, 1481), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1479, 1481), True, 'import pandas as pd\n'), ((2080, 2110), 'os.path.split', 'os.path.split', (['submission_file'], {}), '(submission_file)\n', (2093, 2110), False, 'import os\n'), ((2498, 2512), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2510, 2512), True, 'import pandas as pd\n'), ((2992, 3022), 'os.path.split', 'os.path.split', (['submission_file'], {}), '(submission_file)\n', (3005, 3022), False, 'import os\n'), ((3506, 3520), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (3518, 3520), True, 'import pandas as pd\n'), ((664, 682), 'numpy.unique', 'np.unique', (['lab_img'], {}), '(lab_img)\n', (673, 682), True, 'import numpy as np\n'), ((2168, 2189), 'os.makedirs', 'os.makedirs', (['basename'], {}), '(basename)\n', (2179, 2189), False, 'import os\n'), ((3080, 3101), 'os.makedirs', 'os.makedirs', (['basename'], {}), '(basename)\n', (3091, 3101), False, 'import os\n'), ((1543, 1558), 'pandas.Series', 'pd.Series', (['rles'], {}), '(rles)\n', (1552, 1558), True, 'import pandas as pd\n'), ((2122, 2145), 'os.path.isdir', 'os.path.isdir', (['basename'], {}), '(basename)\n', (2135, 2145), False, 'import os\n'), ((2574, 2589), 'pandas.Series', 'pd.Series', (['rles'], {}), '(rles)\n', (2583, 2589), True, 'import pandas as pd\n'), ((3034, 3057), 'os.path.isdir', 'os.path.isdir', (['basename'], {}), '(basename)\n', (3047, 3057), False, 'import os\n'), ((3582, 3597), 'pandas.Series', 'pd.Series', (['rles'], {}), '(rles)\n', (3591, 3597), True, 'import pandas as pd\n'), ((3234, 3250), 'numpy.unique', 'np.unique', (['label'], {}), '(label)\n', (3243, 3250), True, 'import numpy as np\n')]
import pytest import numpy as np from numpy.testing import assert_allclose from .test_fixtures import * from ..standard_systems import LMT, SI from .. import meta from .. import solver_utils as su from .. import utils as u @pytest.mark.usefixtures('dm_example_72') def test_matrix_A_B_E(dm_example_72): info = meta.info(dm_example_72, [0.,0.,0.]) A, B = su.matrix_A(dm_example_72, info), su.matrix_B(dm_example_72, info) E = su.matrix_E(A, B, info) assert_allclose(A, [[3,4,5],[3,0,2],[3,2,1]]) assert_allclose(B, [[1,2],[2,4],[3,4]]) assert_allclose(E*30, [[30,0,0,0,0],[0,30,0,0,0],[-32,-48,-4,6,8],[-6,6,3,-12,9],[18,12,6,6,-12]]) @pytest.mark.usefixtures('dm_example_78') def test_row_removal_generator(dm_example_78): # 3 rows, 2/3 lin. dependent -> one row has to be removed info = meta.info(dm_example_78, [0.,0.,0.]) order = list(su.row_removal_generator(dm_example_78, info)) assert order == [(0,), (1,), (2,)] @pytest.mark.usefixtures('dm_example_72') @pytest.mark.usefixtures('dm_example_78') def test_ensure_nonsingular_A(dm_example_72, dm_example_78): info = meta.info(dm_example_72, [0.,0.,0.]) del_row, col_order = su.ensure_nonsingular_A(dm_example_72, info) assert len(del_row) == 0 assert_allclose(col_order,range(info.n_v)) info = meta.info(dm_example_78, [0.,0.,0.]) del_row, col_order = su.ensure_nonsingular_A(dm_example_78, info) assert len(del_row) == 1 assert del_row[0] in [1,2] assert_allclose(col_order,range(info.n_v)) dm = np.zeros((3,3)) dm[1,0] = 1 dm[0,1] = 1 dm[0,2] = 1 info = meta.info(dm, [0.,0.,0.]) del_row, col_order = su.ensure_nonsingular_A(dm, info) assert len(del_row) == 1 assert del_row[0] == 2 assert col_order in [ [1,0,2], [1,2,0], [2,0,1], [2,1,0]] # Test solver-options dm = np.zeros((3,3)) dm[1,0] = 1 dm[0,1] = 1 dm[0,2] = 1 info = meta.info(dm, [0.,0.,0.]) del_row, col_order = su.ensure_nonsingular_A(dm, info, remove_row_ids=[2], col_perm=[1,2,0]) assert len(del_row) == 1 assert del_row[0] == 2 assert col_order == [1,2,0] with pytest.raises(ValueError): del_row, col_order = su.ensure_nonsingular_A(dm, info, remove_row_ids=[1], col_perm=[1,2,0]) with pytest.raises(ValueError): del_row, col_order = su.ensure_nonsingular_A(dm, info, col_perm=[0,1,2]) with pytest.raises(ValueError): del_row, col_order = su.ensure_nonsingular_A(dm, info, col_perm=[1,2,1])
[ "numpy.testing.assert_allclose", "pytest.raises", "pytest.mark.usefixtures", "numpy.zeros" ]
[((226, 266), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""dm_example_72"""'], {}), "('dm_example_72')\n", (249, 266), False, 'import pytest\n'), ((662, 702), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""dm_example_78"""'], {}), "('dm_example_78')\n", (685, 702), False, 'import pytest\n'), ((965, 1005), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""dm_example_72"""'], {}), "('dm_example_72')\n", (988, 1005), False, 'import pytest\n'), ((1007, 1047), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""dm_example_78"""'], {}), "('dm_example_78')\n", (1030, 1047), False, 'import pytest\n'), ((467, 520), 'numpy.testing.assert_allclose', 'assert_allclose', (['A', '[[3, 4, 5], [3, 0, 2], [3, 2, 1]]'], {}), '(A, [[3, 4, 5], [3, 0, 2], [3, 2, 1]])\n', (482, 520), False, 'from numpy.testing import assert_allclose\n'), ((517, 561), 'numpy.testing.assert_allclose', 'assert_allclose', (['B', '[[1, 2], [2, 4], [3, 4]]'], {}), '(B, [[1, 2], [2, 4], [3, 4]])\n', (532, 561), False, 'from numpy.testing import assert_allclose\n'), ((561, 689), 'numpy.testing.assert_allclose', 'assert_allclose', (['(E * 30)', '[[30, 0, 0, 0, 0], [0, 30, 0, 0, 0], [-32, -48, -4, 6, 8], [-6, 6, 3, -12, \n 9], [18, 12, 6, 6, -12]]'], {}), '(E * 30, [[30, 0, 0, 0, 0], [0, 30, 0, 0, 0], [-32, -48, -4,\n 6, 8], [-6, 6, 3, -12, 9], [18, 12, 6, 6, -12]])\n', (576, 689), False, 'from numpy.testing import assert_allclose\n'), ((1539, 1555), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (1547, 1555), True, 'import numpy as np\n'), ((1885, 1901), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (1893, 1901), True, 'import numpy as np\n'), ((2181, 2206), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2194, 2206), False, 'import pytest\n'), ((2318, 2343), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2331, 2343), False, 'import pytest\n'), ((2435, 2460), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2448, 2460), False, 'import pytest\n')]
import numpy as np class Range(object): def __init__(self, min: float, max: float): self.min = min self.max = max def set_clamp(self, value: float): self.min = min(self.min, value) self.max = max(self.max, value) def __repr__(self): return f"Range[{self.min:0.4f} {self.max:0.4f}]" class CtrnnRanges(object): def __init__(self): self.weights = Range(-16, 16) self.biases = Range(-16, 16) self.time_constants = Range(0.5, 10) def set_weight_range(self, min=None, max=None): self.weights.min = min or self.weights.min self.weights.max = max or self.weights.max def set_bias_range(self, min=None, max=None): self.biases.min = min or self.biases.min self.biases.max = max or self.biases.max def set_time_constant_range(self, min=None, max=None): self.time_constants.min = min or self.time_constants.min self.time_constants.max = max or self.time_constants.max def get_weights(self, neurons: int = 2) -> np.ndarray: return np.random.uniform( self.weights.min, self.weights.max, size=(neurons, neurons) ) def get_biases(self, neurons: int = 2) -> np.ndarray: return np.random.uniform( self.biases.min, self.biases.max, size=neurons ) def get_time_constants(self, neurons: int = 2) -> np.ndarray: return np.random.uniform( self.time_constants.min, self.time_constants.max, size=neurons )
[ "numpy.random.uniform" ]
[((1078, 1156), 'numpy.random.uniform', 'np.random.uniform', (['self.weights.min', 'self.weights.max'], {'size': '(neurons, neurons)'}), '(self.weights.min, self.weights.max, size=(neurons, neurons))\n', (1095, 1156), True, 'import numpy as np\n'), ((1277, 1342), 'numpy.random.uniform', 'np.random.uniform', (['self.biases.min', 'self.biases.max'], {'size': 'neurons'}), '(self.biases.min, self.biases.max, size=neurons)\n', (1294, 1342), True, 'import numpy as np\n'), ((1471, 1557), 'numpy.random.uniform', 'np.random.uniform', (['self.time_constants.min', 'self.time_constants.max'], {'size': 'neurons'}), '(self.time_constants.min, self.time_constants.max, size=\n neurons)\n', (1488, 1557), True, 'import numpy as np\n')]
import os import numpy as np from arnold import SAENOPATH import subprocess # Cylindric Inclusion -------------------------------------------------------------------------------------------------- def cylindric_contraction(simulation_folder, mesh_file, d_cyl, l_cyl, r_outer, strain, material, logfile = False, iterations= 300 , step=0.3, conv_crit = 1e-11): """ Simulates an symetric contraction (with constant strain) of the cylindric inclusion inside the spherical bulk. Args: simulation_folder(str): File path to save simulation results mesh_file(str): File path to read in mesh file d_cyl(float): Diameter of the spherical inclusion in the mesh model (in µm) l_cyl(float): Length of the spherical inclusion in the mesh model (in µm) r_outer(float): Outer radius of the bulk mesh in the mesh model (in µm) strain(float): Strain as (Length_base - Length_contracted)/Length_base. Deformation is applied in x-direction and split equally to both poles, from which defomation-size decreases linearly to the center (symetric contraction with constant strain). material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X} (see materials) logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: False. iterations(float): The maximal number of iterations for the saeno simulation. Default: 300. step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3. conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11. """ # read in material parameters K_0 = material['K_0'] D_0 = material['D_0'] L_S = material['L_S'] D_S = material['D_S'] """ Apply Boundary Conditions and start Saeno Simulation """ #convert input in um------------------------------------------------------------------------------------------------ d_cyl *= 1e-6 l_cyl *= 1e-6 r_outer *= 1e-6 deformation = strain*l_cyl # create data folder if they do not exist ------------------------------------------------------------------------------------------------ if not os.path.exists(simulation_folder): os.makedirs(simulation_folder) print('+ Created output folder') # create coords.dat and tets.dat ----------------------------------------------------------------------------------- with open(mesh_file, 'r') as f: lines = f.readlines() print (simulation_folder + '/coords.dat') # coords.dat index_nodes = lines.index('$Nodes\n') number_of_nodes = int(lines[index_nodes+1]) coords = np.zeros((number_of_nodes, 3)) for i in range(number_of_nodes): coords[i] = np.array([np.float(x) for x in lines[i+index_nodes+2].split()[1:]]) np.savetxt(simulation_folder + '/coords.dat', coords) # tets.dat index_elements = lines.index('$Elements\n') number_of_elements = int(lines[index_elements+1]) tets = np.zeros((number_of_elements, 4)) for i in range(number_of_elements): tets[i] = lines[i+index_elements+2].split()[-4:] np.savetxt(simulation_folder + '/tets.dat', tets, fmt='%i') print('+ Created coords.dat and tets.dat') # create bcond.dat and iconf.dat distance = np.sqrt(np.sum(coords**2., axis=1)) x, y, z = coords.T mask_inner = ((y**2. + z**2.) <= (d_cyl/2)**2.) & (x**2. <= (l_cyl/2)**2.) mask_outer = distance > r_outer * 0.999 # include close elements to the boundary # Save Node Density at Surface/outer # Area per outer node A_node_outer = (np.pi*4*(r_outer)**2)/np.sum(mask_outer) # simply sqrt as spacing outer_spacing = np.sqrt(A_node_outer) # Area per inner node A_node_inner = (2*np.pi*(d_cyl/2)*((d_cyl/2)+(l_cyl)))/np.sum(mask_inner) # simply sqrt as spacing inner_spacing = np.sqrt(A_node_inner) print ('Outer node spacing: '+str(outer_spacing*1e6 )+'µm') print ('Inner node spacing: '+str(inner_spacing*1e6 )+'µm') #Plot selected nodes ----------------------------------------------------------------------------------------------- # fig1 = plt.figure() # ax1 = Axes3D(fig1) # ax1.set_xlabel('X') # ax1.set_ylabel('Y') # ax1.set_zlabel('Z') # ax1.scatter(coords[mask_inner][:,0], coords[mask_inner][:,1], coords[mask_inner][:,2]) # ax1.scatter(coords[mask_outer][:,0], coords[mask_outer][:,1], coords[mask_outer][:,2]) # ax1.xaxis.set_major_formatter(FormatStrFormatter('%0.0e')) # ax1.yaxis.set_major_formatter(FormatStrFormatter('%0.0e')) # ax1.zaxis.set_major_formatter(FormatStrFormatter('%0.0e')) # plt.show() #Set Boundaries----------------------------------------------------------------------------------------------------- bcond = np.zeros((len(coords), 4)) bcond[:, 3] = 1. #setdispl mode at outer boundary (fixed displacements) bcond[mask_outer, 3] = 0 #setdispl mode at surface (fixed displacements) bcond[mask_inner, 3] = 0 #fixed displacements in x direction at surface (linear decreasing in size from both poles) bcond[mask_inner, 0] = (-deformation/2) * (coords[mask_inner][:,0]/ (l_cyl/2)) #Set Displacements for volume conservation (pi r0² h0 = pi r1² h1) r1 = (d_cyl/2) * (1/np.sqrt(((l_cyl/2) + (-deformation/2))/(l_cyl/2))) dr = r1 - (d_cyl/2) bcond[mask_inner, 1] = ((coords[mask_inner][:,1])/(d_cyl/2))*dr bcond[mask_inner, 2] = ((coords[mask_inner][:,2])/(d_cyl/2))*dr #save bcond.dat np.savetxt(simulation_folder + '/bcond.dat', bcond) #create iconf iconf = np.zeros((len(coords), 3)) iconf[mask_inner, 0] = (-deformation/2) * (coords[mask_inner][:,0]/(l_cyl/2)) iconf[mask_inner, 1] = ((coords[mask_inner][:,1])/(d_cyl/2))*dr iconf[mask_inner, 2] = ((coords[mask_inner][:,2])/(d_cyl/2))*dr np.savetxt(simulation_folder + '/iconf.dat', iconf) print('+ Created bcond.dat and iconf.dat') # create config.txt ----------------------------------------------------------- config = r""" MODE = relaxation BOXMESH = 0 FIBERPATTERNMATCHING = 0 REL_CONV_CRIT = {} REL_ITERATIONS = {} REL_SOLVER_STEP = {} K_0 = {} D_0 = {} L_S = {} D_S = {} CONFIG = {}\config.txt DATAOUT = {} """.format(conv_crit, iterations, step, K_0, D_0, L_S, D_S, simulation_folder, simulation_folder) with open(simulation_folder + "/config.txt", "w") as f: f.write(config) print('+ Created config.txt') # create parameters.txt-------------------------------------------------------- parameters = r""" K_0 = {} D_0 = {} L_S = {} D_S = {} OUTER_RADIUS = {} SURFACE_NODES = {} TOTAL_NODES = {} Mesh_file = {} Output_folder = {} d_cyl = {} l_cyl = {} deformation = {} strain = {} Inner node spacing = {} Outer node spacing = {} iterations = {} step = {} conv_crit = {} """.format(K_0, D_0, L_S, D_S, str(r_outer*1e6)+' µm', np.sum(mask_inner), len(coords), mesh_file, simulation_folder, str(d_cyl*1e6)+' µm', str(l_cyl*1e6)+' µm', str(deformation*1e6)+' µm', str(strain), str(inner_spacing*1e6)+' µm', str(outer_spacing*1e6)+' µm', iterations, step, conv_crit) with open(simulation_folder + "/parameters.txt", "w") as f: f.write(parameters) print('+ Created parameters.txt') # start SAENO ---------------------------------------------------------------------------------------------------------- print ('SAENO Path: '+str(SAENOPATH)) print('+ Starting SAENO...') # Create log file if activated if logfile == True: # create log file with system output logfile = open(simulation_folder + "/saeno_log.txt", 'w') cmd = subprocess.Popen(SAENOPATH+" CONFIG {}/config.txt".format(os.path.abspath(simulation_folder)), stdout=subprocess.PIPE , universal_newlines=True, shell=False) # print and save a reduced version of saeno log for line in cmd.stdout: if not '%' in line: print (line, end='') logfile.write(str(line)) # close again to avoid loops cmd.stdout.close() # if false just show the non reduced system output else: #cmd = subprocess.call(SAENOPATH+"\saeno CONFIG {}/config.txt".format(os.path.abspath(simulation_folder))) cmd = subprocess.call(SAENOPATH+" CONFIG {}/config.txt".format(os.path.abspath(simulation_folder))) # two point forces in certain distances -------------------------------------------------------------------------- def point_forces(simulation_folder, mesh_file, r_outer, distance, strain, material, logfile = True, iterations= 300 , step=0.3, conv_crit = 1e-11): """ Simulates an symetric contraction (with constant strain) of two nodes inside the spherical bulk. Finds nodes matching best to given distance and updates strain accordingly. Args: simulation_folder(str): File path to save simulation results mesh_file(str): File path to read in mesh file distance(float): Desired distance beetween the two point forces (in µm). Closest possible points are searched and distance is updated r_outer(float): Outer radius of the bulk mesh in the mesh model (in µm) strain(float): Strain as (distance_base - dist_contracted)/dist_base. Deformation is applied on the axis between the 2 nodes split equally to both poles. material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X} (see materials) logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: False. iterations(float): The maximal number of iterations for the saeno simulation. Default: 300. step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3. conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11. """ # read in material parameters K_0 = material['K_0'] D_0 = material['D_0'] L_S = material['L_S'] D_S = material['D_S'] """ Apply Boundary Conditions and start Saeno Simulation """ #convert input in um------------------------------------------------------------------------------------------------ r_outer *= 1e-6 distance *= 1e-6 #deformation = displacement*1e-6 # create data folder if they do not exist ------------------------------------------------------------------------------------------------ if not os.path.exists(simulation_folder): os.makedirs(simulation_folder) print('+ Created output folder') # create coords.dat and tets.dat ----------------------------------------------------------------------------------- with open(mesh_file, 'r') as f: lines = f.readlines() print (simulation_folder + '/coords.dat') # coords.dat index_nodes = lines.index('$Nodes\n') number_of_nodes = int(lines[index_nodes+1]) coords = np.zeros((number_of_nodes, 3)) for i in range(number_of_nodes): coords[i] = np.array([np.float(x) for x in lines[i+index_nodes+2].split()[1:]]) np.savetxt(simulation_folder + '/coords.dat', coords) # tets.dat index_elements = lines.index('$Elements\n') number_of_elements = int(lines[index_elements+1]) # now only save tetrahedron elements from mesh file # not necessary for cylinder and spherical inclusion but for pointforces tets = [] #np.zeros((number_of_elements, 4)) for i in range(number_of_elements): if lines[i+index_elements+2].split()[1]=='4': tets.append(lines[i+index_elements+2].split()[-4:]) tets = np.array(tets, dtype='int') np.savetxt(simulation_folder + '/tets.dat', tets, fmt='%i') print('+ Created coords.dat and tets.dat') # create bcond.dat and iconf.dat distance_c = np.sqrt(np.sum(coords**2., axis=1)) x, y, z = coords.T # search for closest grid point on the x-axis for the given distances # point on positive x-side dist_p = np.sqrt((x-(distance/2))**2+(y**2)+(z**2)) min_dist_p = np.min(np.sqrt((x-(distance/2))**2+(y)**2+(z**2))) mask_p1 = (dist_p==min_dist_p) # point on negative x-side dist_n = np.sqrt((x+(distance/2))**2+(y**2)+(z**2)) min_dist_n = np.min(np.sqrt((x+(distance/2))**2+(y)**2+(z**2))) mask_p2 = (dist_n==min_dist_n) # Coordinates for first (positive) point p1_x = x [mask_p1][0] p1_y = y [mask_p1][0] p1_z = z [mask_p1][0] print ('Set point 1 at: x='+str(p1_x)+', y='+str(p1_y)+', z='+str(p1_z)) # Coordinates for second (negative) point p2_x = x [mask_p2][0] p2_y = y [mask_p2][0] p2_z = z [mask_p2][0] print ('Set point 2 at: x='+str(p2_x)+', y='+str(p2_y)+', z='+str(p2_z)) # update new distance for the found points to have the correct strain distance = np.linalg.norm(np.array([p1_x,p1_y,p1_z])-np.array([p2_x,p2_y,p2_z])) print ('Distance between found points is updated for correct strain. Distance: '+str(distance*1e6)+'µm') mask_outer = distance_c > r_outer * 0.999 # include close elements to the boundary #Set Boundaries----------------------------------------------------------------------------------------------------- bcond = np.zeros((len(coords), 4)) bcond[:, 3] = 1. #set displ mode at outer boundary (fixed displacements) bcond[mask_outer, 3] = 0 #set displ mode at both nodes (fixed displacements) bcond[mask_p1, 3] = 0 bcond[mask_p2, 3] = 0 # total deformation deformation = strain*distance # project (0,0,x_defo) on the disctance vector because points are not perfectly alligned on xaxis vec_ideal = np.array([deformation/2,0 ,0]) # ideal deformation in positive direction for negative point 2 vec_calc = np.array([p1_x,p1_y,p1_z])-np.array([p2_x,p2_y,p2_z]) #pointing in positive direction projection = vec_calc * (vec_ideal @ vec_calc) / (vec_calc @ vec_calc) # projection for p2 pointing in positive direction #fixed displacements for both points directed to center bcond[mask_p1, 0] = -projection[0] bcond[mask_p1, 1] = -projection[1] bcond[mask_p1, 2] = -projection[2] bcond[mask_p2, 0] = projection[0] bcond[mask_p2, 1] = projection[1] bcond[mask_p2, 2] = projection[2] #save bcond.dat np.savetxt(simulation_folder + '/bcond.dat', bcond) #create iconf iconf = np.zeros((len(coords), 3)) iconf[mask_p1, 0] = -deformation/2 iconf[mask_p2, 0] = +deformation/2 np.savetxt(simulation_folder + '/iconf.dat', iconf) print('+ Created bcond.dat') # create config.txt ----------------------------------------------------------- config = r""" MODE = relaxation BOXMESH = 0 FIBERPATTERNMATCHING = 0 REL_CONV_CRIT = {} REL_ITERATIONS = {} REL_SOLVER_STEP = {} K_0 = {} D_0 = {} L_S = {} D_S = {} CONFIG = {}\config.txt DATAOUT = {} """.format(conv_crit, iterations, step, K_0, D_0, L_S, D_S, simulation_folder, simulation_folder) with open(simulation_folder + "/config.txt", "w") as f: f.write(config) print('+ Created config.txt') # create parameters.txt-------------------------------------------------------- parameters = r""" K_0 = {} D_0 = {} L_S = {} D_S = {} OUTER_RADIUS = {} TOTAL_NODES = {} Mesh_file = {} Output_folder = {} distance = {} strain = {} total_deformation (half applied at each point) = {} point_1 = {} point_2 = {} iterations = {} step = {} conv_crit = {} """.format(K_0, D_0, L_S, D_S, str(r_outer*1e6)+' µm', len(coords), mesh_file, simulation_folder, str(distance*1e6)+' µm', strain, deformation, 'x='+str(p1_x)+', y='+str(p1_y)+', z='+str(p1_z) , 'x='+str(p2_x)+', y='+str(p2_y)+', z='+str(p2_z), iterations, step, conv_crit) with open(simulation_folder + "/parameters.txt", "w") as f: f.write(parameters) print('+ Created parameters.txt') # start SAENO ---------------------------------------------------------------------------------------------------------- print ('SAENO Path: '+str(SAENOPATH)) print('+ Starting SAENO...') # Create log file if activated if logfile == True: # create log file with system output logfile = open(simulation_folder + "/saeno_log.txt", 'w') cmd = subprocess.Popen(SAENOPATH+" CONFIG {}/config.txt".format(os.path.abspath(simulation_folder)), stdout=subprocess.PIPE , universal_newlines=True, shell=False) # print and save a reduced version of saeno log for line in cmd.stdout: if not '%' in line: print (line, end='') logfile.write(str(line)) # close again to avoid loops cmd.stdout.close() # if false just show the non reduced system output else: cmd = subprocess.call(SAENOPATH+" CONFIG {}/config.txt".format(os.path.abspath(simulation_folder))) def spherical_contraction(meshfile, simulation_folder, pressure, material, r_inner=100, r_outer=20000, logfile = False, half_sphere = False, iterations= 300 , step=0.3, conv_crit = 1e-11): """ Simulates an spherical contraction of the inner inclusion for a given pressure. Args: simulation_folder(str): File path to save simulation results mesh_file(str): File path to read in mesh file r_inner(float): Radius of inner inclusion r_outer(float): Outer radius of the bulk mesh in the mesh model (in µm) pressure(float): Pressure that is applied on inner inclusion saeno (str): File path to Saeno.exe material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X} (see materials) logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: False. iterations(float): The maximal number of iterations for the saeno simulation. Default: 300. step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3. conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11. half_sphere(boolean): If true all forces on spheroid a halved (to compare spheroid with half sphere) WATCH OUT: SPHEROID POSITION+SHAPE IS NOT FIXED IF TRUE """ # open mesh file with open(meshfile, 'r') as f: lines = f.readlines() # scale radii to meter r_inner *= 10**-6 r_outer *= 10**-6 # read in material parameters K_0 = material['K_0'] D_0 = material['D_0'] L_S = material['L_S'] D_S = material['D_S'] # create output folder if it does not exist, print warning otherwise if not os.path.exists(simulation_folder): os.makedirs(simulation_folder) else: print('WARNING: Output folder already exists! ({})'.format(simulation_folder)) # transform nodes and connection in SAENO format # nodes index_nodes = lines.index('$Nodes\n') n_nodes = int(lines[index_nodes + 1]) coords = np.zeros((n_nodes, 3)) for i in range(n_nodes): coords[i] = np.array([np.float(x) for x in lines[i + index_nodes + 2].split()[1:]]) np.savetxt(simulation_folder + '/coords.dat', coords) # connections index_elements = lines.index('$Elements\n') n_elements = int(lines[index_elements + 1]) tets = np.zeros((n_elements, 4)) for i in range(n_elements): tets[i] = lines[i + index_elements + 2].split()[-4:] np.savetxt(simulation_folder + '/tets.dat', tets, fmt='%i') # define boundary conditions distance = np.sqrt(np.sum(coords ** 2., axis=1)) mask_inner = distance < r_inner * 1.001 mask_outer = distance > r_outer * 0.999 # Save Node Density at inner and outer sphere # Area per inner node A_node_inner = (np.pi*4*(r_inner)**2)/np.sum(mask_inner) # simple sqrt as spacing inner_spacing = np.sqrt(A_node_inner) # Area per outer node A_node_outer = (np.pi*4*(r_outer)**2)/np.sum(mask_outer) # simple sqrt as spacing outer_spacing = np.sqrt(A_node_outer) print ('Inner node spacing: '+str(inner_spacing*1e6)+'µm') print ('Outer node spacing: '+str(outer_spacing*1e6)+'µm') bcond = np.zeros((len(coords), 4)) bcond[:, 3] = 1. # fixed displacements for outer boundary bcond[mask_outer, 3] = 0 # fixed non-zero force at spheroid surface bcond[mask_inner, :3] = coords[mask_inner, :3] bcond[mask_inner, :3] /= distance[mask_inner, None] # halven forces if half sphere True if half_sphere == True: A_inner = 4 * np.pi * r_inner ** 2. force_per_node = pressure * A_inner / np.sum(mask_inner) bcond[mask_inner, :3] *= force_per_node/2 # compute regular forces per node for a full sphere else: A_inner = 4 * np.pi * r_inner ** 2. force_per_node = pressure * A_inner / np.sum(mask_inner) bcond[mask_inner, :3] *= force_per_node np.savetxt(simulation_folder + '/bcond.dat', bcond) # define initial configuration iconf = np.zeros((len(coords), 3)) np.savetxt(simulation_folder + '/iconf.dat', iconf) # create config file for SAENO config = r"""MODE = relaxation BOXMESH = 0 FIBERPATTERNMATCHING = 0 REL_CONV_CRIT = {} REL_ITERATIONS = {} REL_SOLVER_STEP = {} K_0 = {} D_0 = {} L_S = {} D_S = {} CONFIG = {}\config.txt DATAOUT = {}""".format(conv_crit, iterations, step, K_0, D_0, L_S, D_S, os.path.abspath(simulation_folder), os.path.abspath(simulation_folder)) with open(simulation_folder + "/config.txt", "w") as f: f.write(config) # create info file with all relevant parameters of the simulation parameters = r"""K_0 = {} D_0 = {} L_S = {} D_S = {} PRESSURE = {} FORCE_PER_SURFACE_NODE = {} INNER_RADIUS = {} µm OUTER_RADIUS = {} µm INNER_NODE_SPACING = {} µm OUTER_NODE_SPACING = {} µm SURFACE_NODES = {} TOTAL_NODES = {} REL_CONV_CRIT = {} REL_ITERATIONS = {} REL_SOLVER_STEP = {} half_sphere = {}""".format(K_0, D_0, L_S, D_S, pressure, force_per_node, r_inner*1e6 , r_outer*1e6 , inner_spacing*1e6, outer_spacing*1e6, np.sum(mask_inner), len(coords), conv_crit, iterations, step, half_sphere) with open(simulation_folder + "/parameters.txt", "w") as f: f.write(parameters) # Create log file if activated if logfile == True: # create log file with system output logfile = open(simulation_folder + "/saeno_log.txt", 'w') cmd = subprocess.Popen(SAENOPATH+" CONFIG {}/config.txt".format(os.path.abspath(simulation_folder)), stdout=subprocess.PIPE , universal_newlines=True, shell=False) # print and save a reduced version of saeno log for line in cmd.stdout: if not '%' in line: print (line, end='') logfile.write(str(line)) # close again to avoid loops cmd.stdout.close() # if false just show the non reduced system output else: cmd = subprocess.call(SAENOPATH+" CONFIG {}/config.txt".format(os.path.abspath(simulation_folder))) def spherical_contraction_strain(meshfile, simulation_folder, strain, material, r_inner=100, r_outer=20000, logfile = False, iterations= 300 , step=0.3, conv_crit = 1e-11): """ Simulates an spherical contraction of the inner inclusion for a given pressure. Args: simulation_folder(str): File path to save simulation results mesh_file(str): File path to read in mesh file r_inner(float): Radius of inner inclusion r_outer(float): Outer radius of the bulk mesh in the mesh model (in µm) strain(float): Strain that is applied on inner inclusion saeno (str): File path to Saeno.exe material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X} (see materials) logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: False. iterations(float): The maximal number of iterations for the saeno simulation. Default: 300. step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3. conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11. """ # open mesh file with open(meshfile, 'r') as f: lines = f.readlines() # scale radii to meter r_inner *= 10**-6 r_outer *= 10**-6 # read in material parameters K_0 = material['K_0'] D_0 = material['D_0'] L_S = material['L_S'] D_S = material['D_S'] # create output folder if it does not exist, print warning otherwise if not os.path.exists(simulation_folder): os.makedirs(simulation_folder) else: print('WARNING: Output folder already exists! ({})'.format(simulation_folder)) # transform nodes and connection in SAENO format # nodes index_nodes = lines.index('$Nodes\n') n_nodes = int(lines[index_nodes + 1]) coords = np.zeros((n_nodes, 3)) for i in range(n_nodes): coords[i] = np.array([np.float(x) for x in lines[i + index_nodes + 2].split()[1:]]) np.savetxt(simulation_folder + '/coords.dat', coords) # connections index_elements = lines.index('$Elements\n') n_elements = int(lines[index_elements + 1]) tets = np.zeros((n_elements, 4)) for i in range(n_elements): tets[i] = lines[i + index_elements + 2].split()[-4:] np.savetxt(simulation_folder + '/tets.dat', tets, fmt='%i') # define boundary conditions distance = np.sqrt(np.sum(coords ** 2., axis=1)) mask_inner = distance < r_inner * 1.001 mask_outer = distance > r_outer * 0.999 # Save Node Density at inner and outer sphere # Area per inner node A_node_inner = (np.pi*4*(r_inner)**2)/np.sum(mask_inner) # simple sqrt as spacing inner_spacing = np.sqrt(A_node_inner) # Area per outer node A_node_outer = (np.pi*4*(r_outer)**2)/np.sum(mask_outer) # simple sqrt as spacing outer_spacing = np.sqrt(A_node_outer) print ('Inner node spacing: '+str(inner_spacing*1e6)+'µm') print ('Outer node spacing: '+str(outer_spacing*1e6)+'µm') bcond = np.zeros((len(coords), 4)) bcond[:, 3] = 1. # fixed displacements for outer boundary bcond[mask_outer, 3] = 0 # fixed displacements at spheroid surface bcond[mask_inner, 3] = 0 # displacement mode bcond[mask_inner, :3] = coords[mask_inner, :3] bcond[mask_inner, :3] /= distance[mask_inner, None] # unit vectors deformation = strain * r_inner bcond[mask_inner, :3] *= -deformation np.savetxt(simulation_folder + '/bcond.dat', bcond) # define initial configuration, same as bconds iconf = np.zeros((len(coords), 3)) iconf[mask_inner, :3] = coords[mask_inner, :3] iconf[mask_inner, :3] /= distance[mask_inner, None] # unit vectors iconf[mask_inner, :3] *= -deformation np.savetxt(simulation_folder + '/iconf.dat', iconf) # create config file for SAENO config = r"""MODE = relaxation BOXMESH = 0 FIBERPATTERNMATCHING = 0 REL_CONV_CRIT = {} REL_ITERATIONS = {} REL_SOLVER_STEP = {} K_0 = {} D_0 = {} L_S = {} D_S = {} CONFIG = {}\config.txt DATAOUT = {}""".format(conv_crit, iterations, step, K_0, D_0, L_S, D_S, os.path.abspath(simulation_folder), os.path.abspath(simulation_folder)) with open(simulation_folder + "/config.txt", "w") as f: f.write(config) # create info file with all relevant parameters of the simulation parameters = r"""K_0 = {} D_0 = {} L_S = {} D_S = {} STRAIN = {} DEFORMATION = {} INNER_RADIUS = {} µm OUTER_RADIUS = {} µm INNER_NODE_SPACING = {} µm OUTER_NODE_SPACING = {} µm SURFACE_NODES = {} TOTAL_NODES = {} REL_CONV_CRIT = {} REL_ITERATIONS = {} REL_SOLVER_STEP = {} """.format(K_0, D_0, L_S, D_S, strain, deformation, r_inner*1e6 , r_outer*1e6 , inner_spacing*1e6, outer_spacing*1e6, np.sum(mask_inner), len(coords), conv_crit, iterations, step) with open(simulation_folder + "/parameters.txt", "w") as f: f.write(parameters) # Create log file if activated if logfile == True: # create log file with system output logfile = open(simulation_folder + "/saeno_log.txt", 'w') cmd = subprocess.Popen(SAENOPATH+" CONFIG {}/config.txt".format(os.path.abspath(simulation_folder)), stdout=subprocess.PIPE , universal_newlines=True, shell=False) # print and save a reduced version of saeno log for line in cmd.stdout: if not '%' in line: print (line, end='') logfile.write(str(line)) # close again to avoid loops cmd.stdout.close() # if false just show the non reduced system output else: cmd = subprocess.call(SAENOPATH+" CONFIG {}/config.txt".format(os.path.abspath(simulation_folder))) #if __name__ == "__main__":
[ "os.path.exists", "numpy.sqrt", "numpy.float", "os.makedirs", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.savetxt", "os.path.abspath" ]
[((2847, 2877), 'numpy.zeros', 'np.zeros', (['(number_of_nodes, 3)'], {}), '((number_of_nodes, 3))\n', (2855, 2877), True, 'import numpy as np\n'), ((3008, 3061), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/coords.dat')", 'coords'], {}), "(simulation_folder + '/coords.dat', coords)\n", (3018, 3061), True, 'import numpy as np\n'), ((3203, 3236), 'numpy.zeros', 'np.zeros', (['(number_of_elements, 4)'], {}), '((number_of_elements, 4))\n', (3211, 3236), True, 'import numpy as np\n'), ((3338, 3397), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/tets.dat')", 'tets'], {'fmt': '"""%i"""'}), "(simulation_folder + '/tets.dat', tets, fmt='%i')\n", (3348, 3397), True, 'import numpy as np\n'), ((3925, 3946), 'numpy.sqrt', 'np.sqrt', (['A_node_outer'], {}), '(A_node_outer)\n', (3932, 3946), True, 'import numpy as np\n'), ((4114, 4135), 'numpy.sqrt', 'np.sqrt', (['A_node_inner'], {}), '(A_node_inner)\n', (4121, 4135), True, 'import numpy as np\n'), ((5859, 5910), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/bcond.dat')", 'bcond'], {}), "(simulation_folder + '/bcond.dat', bcond)\n", (5869, 5910), True, 'import numpy as np\n'), ((6195, 6246), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/iconf.dat')", 'iconf'], {}), "(simulation_folder + '/iconf.dat', iconf)\n", (6205, 6246), True, 'import numpy as np\n'), ((11641, 11671), 'numpy.zeros', 'np.zeros', (['(number_of_nodes, 3)'], {}), '((number_of_nodes, 3))\n', (11649, 11671), True, 'import numpy as np\n'), ((11802, 11855), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/coords.dat')", 'coords'], {}), "(simulation_folder + '/coords.dat', coords)\n", (11812, 11855), True, 'import numpy as np\n'), ((12341, 12368), 'numpy.array', 'np.array', (['tets'], {'dtype': '"""int"""'}), "(tets, dtype='int')\n", (12349, 12368), True, 'import numpy as np\n'), ((12373, 12432), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/tets.dat')", 'tets'], {'fmt': '"""%i"""'}), "(simulation_folder + '/tets.dat', tets, fmt='%i')\n", (12383, 12432), True, 'import numpy as np\n'), ((12736, 12786), 'numpy.sqrt', 'np.sqrt', (['((x - distance / 2) ** 2 + y ** 2 + z ** 2)'], {}), '((x - distance / 2) ** 2 + y ** 2 + z ** 2)\n', (12743, 12786), True, 'import numpy as np\n'), ((12940, 12990), 'numpy.sqrt', 'np.sqrt', (['((x + distance / 2) ** 2 + y ** 2 + z ** 2)'], {}), '((x + distance / 2) ** 2 + y ** 2 + z ** 2)\n', (12947, 12990), True, 'import numpy as np\n'), ((14495, 14528), 'numpy.array', 'np.array', (['[deformation / 2, 0, 0]'], {}), '([deformation / 2, 0, 0])\n', (14503, 14528), True, 'import numpy as np\n'), ((15182, 15233), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/bcond.dat')", 'bcond'], {}), "(simulation_folder + '/bcond.dat', bcond)\n", (15192, 15233), True, 'import numpy as np\n'), ((15398, 15449), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/iconf.dat')", 'iconf'], {}), "(simulation_folder + '/iconf.dat', iconf)\n", (15408, 15449), True, 'import numpy as np\n'), ((20162, 20184), 'numpy.zeros', 'np.zeros', (['(n_nodes, 3)'], {}), '((n_nodes, 3))\n', (20170, 20184), True, 'import numpy as np\n'), ((20310, 20363), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/coords.dat')", 'coords'], {}), "(simulation_folder + '/coords.dat', coords)\n", (20320, 20363), True, 'import numpy as np\n'), ((20491, 20516), 'numpy.zeros', 'np.zeros', (['(n_elements, 4)'], {}), '((n_elements, 4))\n', (20499, 20516), True, 'import numpy as np\n'), ((20614, 20673), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/tets.dat')", 'tets'], {'fmt': '"""%i"""'}), "(simulation_folder + '/tets.dat', tets, fmt='%i')\n", (20624, 20673), True, 'import numpy as np\n'), ((21037, 21058), 'numpy.sqrt', 'np.sqrt', (['A_node_inner'], {}), '(A_node_inner)\n', (21044, 21058), True, 'import numpy as np\n'), ((21207, 21228), 'numpy.sqrt', 'np.sqrt', (['A_node_outer'], {}), '(A_node_outer)\n', (21214, 21228), True, 'import numpy as np\n'), ((22120, 22171), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/bcond.dat')", 'bcond'], {}), "(simulation_folder + '/bcond.dat', bcond)\n", (22130, 22171), True, 'import numpy as np\n'), ((22251, 22302), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/iconf.dat')", 'iconf'], {}), "(simulation_folder + '/iconf.dat', iconf)\n", (22261, 22302), True, 'import numpy as np\n'), ((26388, 26410), 'numpy.zeros', 'np.zeros', (['(n_nodes, 3)'], {}), '((n_nodes, 3))\n', (26396, 26410), True, 'import numpy as np\n'), ((26536, 26589), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/coords.dat')", 'coords'], {}), "(simulation_folder + '/coords.dat', coords)\n", (26546, 26589), True, 'import numpy as np\n'), ((26717, 26742), 'numpy.zeros', 'np.zeros', (['(n_elements, 4)'], {}), '((n_elements, 4))\n', (26725, 26742), True, 'import numpy as np\n'), ((26840, 26899), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/tets.dat')", 'tets'], {'fmt': '"""%i"""'}), "(simulation_folder + '/tets.dat', tets, fmt='%i')\n", (26850, 26899), True, 'import numpy as np\n'), ((27263, 27284), 'numpy.sqrt', 'np.sqrt', (['A_node_inner'], {}), '(A_node_inner)\n', (27270, 27284), True, 'import numpy as np\n'), ((27433, 27454), 'numpy.sqrt', 'np.sqrt', (['A_node_outer'], {}), '(A_node_outer)\n', (27440, 27454), True, 'import numpy as np\n'), ((28031, 28082), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/bcond.dat')", 'bcond'], {}), "(simulation_folder + '/bcond.dat', bcond)\n", (28041, 28082), True, 'import numpy as np\n'), ((28357, 28408), 'numpy.savetxt', 'np.savetxt', (["(simulation_folder + '/iconf.dat')", 'iconf'], {}), "(simulation_folder + '/iconf.dat', iconf)\n", (28367, 28408), True, 'import numpy as np\n'), ((2362, 2395), 'os.path.exists', 'os.path.exists', (['simulation_folder'], {}), '(simulation_folder)\n', (2376, 2395), False, 'import os\n'), ((2405, 2435), 'os.makedirs', 'os.makedirs', (['simulation_folder'], {}), '(simulation_folder)\n', (2416, 2435), False, 'import os\n'), ((3515, 3544), 'numpy.sum', 'np.sum', (['(coords ** 2.0)'], {'axis': '(1)'}), '(coords ** 2.0, axis=1)\n', (3521, 3544), True, 'import numpy as np\n'), ((3854, 3872), 'numpy.sum', 'np.sum', (['mask_outer'], {}), '(mask_outer)\n', (3860, 3872), True, 'import numpy as np\n'), ((4046, 4064), 'numpy.sum', 'np.sum', (['mask_inner'], {}), '(mask_inner)\n', (4052, 4064), True, 'import numpy as np\n'), ((7384, 7402), 'numpy.sum', 'np.sum', (['mask_inner'], {}), '(mask_inner)\n', (7390, 7402), True, 'import numpy as np\n'), ((11156, 11189), 'os.path.exists', 'os.path.exists', (['simulation_folder'], {}), '(simulation_folder)\n', (11170, 11189), False, 'import os\n'), ((11199, 11229), 'os.makedirs', 'os.makedirs', (['simulation_folder'], {}), '(simulation_folder)\n', (11210, 11229), False, 'import os\n'), ((12552, 12581), 'numpy.sum', 'np.sum', (['(coords ** 2.0)'], {'axis': '(1)'}), '(coords ** 2.0, axis=1)\n', (12558, 12581), True, 'import numpy as np\n'), ((12806, 12856), 'numpy.sqrt', 'np.sqrt', (['((x - distance / 2) ** 2 + y ** 2 + z ** 2)'], {}), '((x - distance / 2) ** 2 + y ** 2 + z ** 2)\n', (12813, 12856), True, 'import numpy as np\n'), ((13007, 13057), 'numpy.sqrt', 'np.sqrt', (['((x + distance / 2) ** 2 + y ** 2 + z ** 2)'], {}), '((x + distance / 2) ** 2 + y ** 2 + z ** 2)\n', (13014, 13057), True, 'import numpy as np\n'), ((14606, 14634), 'numpy.array', 'np.array', (['[p1_x, p1_y, p1_z]'], {}), '([p1_x, p1_y, p1_z])\n', (14614, 14634), True, 'import numpy as np\n'), ((14633, 14661), 'numpy.array', 'np.array', (['[p2_x, p2_y, p2_z]'], {}), '([p2_x, p2_y, p2_z])\n', (14641, 14661), True, 'import numpy as np\n'), ((19827, 19860), 'os.path.exists', 'os.path.exists', (['simulation_folder'], {}), '(simulation_folder)\n', (19841, 19860), False, 'import os\n'), ((19870, 19900), 'os.makedirs', 'os.makedirs', (['simulation_folder'], {}), '(simulation_folder)\n', (19881, 19900), False, 'import os\n'), ((20731, 20760), 'numpy.sum', 'np.sum', (['(coords ** 2.0)'], {'axis': '(1)'}), '(coords ** 2.0, axis=1)\n', (20737, 20760), True, 'import numpy as np\n'), ((20968, 20986), 'numpy.sum', 'np.sum', (['mask_inner'], {}), '(mask_inner)\n', (20974, 20986), True, 'import numpy as np\n'), ((21136, 21154), 'numpy.sum', 'np.sum', (['mask_outer'], {}), '(mask_outer)\n', (21142, 21154), True, 'import numpy as np\n'), ((22646, 22680), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (22661, 22680), False, 'import os\n'), ((22682, 22716), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (22697, 22716), False, 'import os\n'), ((23364, 23382), 'numpy.sum', 'np.sum', (['mask_inner'], {}), '(mask_inner)\n', (23370, 23382), True, 'import numpy as np\n'), ((26053, 26086), 'os.path.exists', 'os.path.exists', (['simulation_folder'], {}), '(simulation_folder)\n', (26067, 26086), False, 'import os\n'), ((26096, 26126), 'os.makedirs', 'os.makedirs', (['simulation_folder'], {}), '(simulation_folder)\n', (26107, 26126), False, 'import os\n'), ((26957, 26986), 'numpy.sum', 'np.sum', (['(coords ** 2.0)'], {'axis': '(1)'}), '(coords ** 2.0, axis=1)\n', (26963, 26986), True, 'import numpy as np\n'), ((27194, 27212), 'numpy.sum', 'np.sum', (['mask_inner'], {}), '(mask_inner)\n', (27200, 27212), True, 'import numpy as np\n'), ((27362, 27380), 'numpy.sum', 'np.sum', (['mask_outer'], {}), '(mask_outer)\n', (27368, 27380), True, 'import numpy as np\n'), ((28752, 28786), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (28767, 28786), False, 'import os\n'), ((28788, 28822), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (28803, 28822), False, 'import os\n'), ((29435, 29453), 'numpy.sum', 'np.sum', (['mask_inner'], {}), '(mask_inner)\n', (29441, 29453), True, 'import numpy as np\n'), ((5614, 5667), 'numpy.sqrt', 'np.sqrt', (['((l_cyl / 2 + -deformation / 2) / (l_cyl / 2))'], {}), '((l_cyl / 2 + -deformation / 2) / (l_cyl / 2))\n', (5621, 5667), True, 'import numpy as np\n'), ((13610, 13638), 'numpy.array', 'np.array', (['[p1_x, p1_y, p1_z]'], {}), '([p1_x, p1_y, p1_z])\n', (13618, 13638), True, 'import numpy as np\n'), ((13637, 13665), 'numpy.array', 'np.array', (['[p2_x, p2_y, p2_z]'], {}), '([p2_x, p2_y, p2_z])\n', (13645, 13665), True, 'import numpy as np\n'), ((21812, 21830), 'numpy.sum', 'np.sum', (['mask_inner'], {}), '(mask_inner)\n', (21818, 21830), True, 'import numpy as np\n'), ((22047, 22065), 'numpy.sum', 'np.sum', (['mask_inner'], {}), '(mask_inner)\n', (22053, 22065), True, 'import numpy as np\n'), ((2945, 2956), 'numpy.float', 'np.float', (['x'], {}), '(x)\n', (2953, 2956), True, 'import numpy as np\n'), ((11739, 11750), 'numpy.float', 'np.float', (['x'], {}), '(x)\n', (11747, 11750), True, 'import numpy as np\n'), ((20244, 20255), 'numpy.float', 'np.float', (['x'], {}), '(x)\n', (20252, 20255), True, 'import numpy as np\n'), ((26470, 26481), 'numpy.float', 'np.float', (['x'], {}), '(x)\n', (26478, 26481), True, 'import numpy as np\n'), ((8237, 8271), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (8252, 8271), False, 'import os\n'), ((8888, 8922), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (8903, 8922), False, 'import os\n'), ((17400, 17434), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (17415, 17434), False, 'import os\n'), ((17934, 17968), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (17949, 17968), False, 'import os\n'), ((23802, 23836), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (23817, 23836), False, 'import os\n'), ((24337, 24371), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (24352, 24371), False, 'import os\n'), ((29860, 29894), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (29875, 29894), False, 'import os\n'), ((30395, 30429), 'os.path.abspath', 'os.path.abspath', (['simulation_folder'], {}), '(simulation_folder)\n', (30410, 30429), False, 'import os\n')]
"""Arbitrary waveform generation.""" from __future__ import division import numpy as np from functools import partial class Waveform(object): """Base arbitrary waveform class. :param list data: A list of points to convert to a waveform in units of volts. :param float sample_rate: Rate in Hz of waveform. """ def __init__(self, data, sample_rate): data = np.array(data) assert len(data.shape) == 1 self.sample_rate = sample_rate self.amplitude = max(abs(data)) self.data = data / self.amplitude def write_file(self, filename): """Override to write to a file in the appropriate format.""" def write_to_device(self, dev, name="func", toggle_output=True, echo=False): """Override to write to the VISA device. :param FunctionGenerator dev: :param str name: Name to give the waveform (default: ``"func"``). :param bool toggle_output: When True, first turn the output off before making changes, then turn it back on when complete. If False, the output state won't be changed. """ write = partial(dev.write, echo=echo) if toggle_output: write("OUTPUT%s OFF" %(dev.channel)) write("SOURCE%s:data:arb %s, %s" % (dev.channel, name, ",".join([str(x) for x in self.data]))) write("SOURCE%s:func:arb %s" % (dev.channel, name)) write("SOURCE%s:func:arb:srate %s" % (dev.channel, str(self.sample_rate))) write("SOURCE%s:voltage:amplitude %s V" % (dev.channel, str(self.amplitude))) if toggle_output: write("OUTPUT%s ON" %(dev.channel)) if __name__ == "__main__": from .device import FunctionGenerator import matplotlib.pyplot as plt num = 50 data = [x**2 for x in range(num)] data.extend([0]*num) data = np.array(data)/max(data) * 300e-3 plt.ion() plt.plot(data) plt.show() # data += np.random.choice((1, -1), data.shape) * np.random.random(data.shape) waveform = Waveform(data, 100e3) for point in waveform.data: print(point) with FunctionGenerator("USB0::2391::9991::MY52303330::0::INSTR") as dev: if True: dev.write("data:vol:clear") waveform.write_to_device(dev)
[ "matplotlib.pyplot.plot", "numpy.array", "functools.partial", "matplotlib.pyplot.ion", "matplotlib.pyplot.show" ]
[((1896, 1905), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1903, 1905), True, 'import matplotlib.pyplot as plt\n'), ((1910, 1924), 'matplotlib.pyplot.plot', 'plt.plot', (['data'], {}), '(data)\n', (1918, 1924), True, 'import matplotlib.pyplot as plt\n'), ((1929, 1939), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1937, 1939), True, 'import matplotlib.pyplot as plt\n'), ((396, 410), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (404, 410), True, 'import numpy as np\n'), ((1148, 1177), 'functools.partial', 'partial', (['dev.write'], {'echo': 'echo'}), '(dev.write, echo=echo)\n', (1155, 1177), False, 'from functools import partial\n'), ((1858, 1872), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1866, 1872), True, 'import numpy as np\n')]
#This file plots the positivity rate (=true positives) and the frequency in each class in a boxplot and a histogram after platt scaling. import sparsechem as sc import numpy as np import argparse import scipy import pandas as pd import matplotlib.pyplot as plt import math import scipy.stats as sci import matplotlib.gridspec as gridspec from datetime import datetime date=datetime.now().strftime('%Y_%m_%d-%I:%M:%S_%p') parser = argparse.ArgumentParser(description="Obtaining Histograms for Probability Calibration for singular Taget") parser.add_argument("--y_class", "--y", "--y_classification", help="Sparse pattern file for classification, optional. If provided returns predictions for given locations only (matrix market, .npy or .npz)", type=str, default=None) parser.add_argument("--y_hat_platt", help="predicted Values after platt scaling", type=str, default=None) parser.add_argument("--folding", help="Folds for rows of y, optional. Needed if only one fold should be predicted.", type=str, required=False) parser.add_argument("--predict_fold", help="One or more folds, integer(s). Needed if --folding is provided.", nargs="+", type=int, required=False) parser.add_argument("--targetID", help="TargetID", type=int, required=True) args = parser.parse_args() #load data TargetID=args.targetID y_class = sc.load_sparse(args.y_class) y_hat_platt=sc.load_sparse(args.y_hat_platt) #select correct fold for y_class folding = np.load(args.folding) if args.folding else None keep = np.isin(folding, args.predict_fold) y_class = sc.keep_row_data(y_class, keep) #Sparse Matrix to csc-fil y_hat_platt=y_hat_platt.A y_hat_platt=y_hat_platt.flatten() y_class=y_class.tocsc() #Selection of TargetID; Keep rows with measurements y_class_TargetID=y_class[:, TargetID] y_class_selected=y_class_TargetID[np.nonzero(y_class_TargetID)] y_class_selected=y_class_selected.A.flatten() #Split array according to condition def split(arr, cond): return arr[cond] #Calculate positive ratio def posRatio(arr): return (arr==1).sum()/arr.shape[0] #split into positives and negatives def selectPosNeg(arr): pos=np.count_nonzero(arr==1) neg=np.count_nonzero(arr==-1) return pos, neg #count number of positives/negatives def selectPos(arr): pos=np.count_nonzero(arr==1) return pos def selectNeg(arr): neg=np.count_nonzero(arr==-1) return neg #obtain postive Ratio and negative/positive count for each class of predicted probablities clas=[] acc=[] NumPos=[] NumNeg=[] values=[0.0, 0.1, 0.2 ,0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] j=0 k=0 for j in range(10): clas.append(split(y_class_selected,np.logical_and(y_hat_platt>=values[j], y_hat_platt<values[j+1]))) j+=1 values[j] for k in range(10): acc.append(posRatio(clas[k])) NumPos.append(selectPos(clas[k])) NumNeg.append(selectNeg(clas[k])) k+=1 # Confidence Intervals for Positive ratio # iterate through classes and calculate Variance of the mean Q1=[] Q3=[] Me=[] Med=[] i=0 WhisLo=[] WhisHi=[] stats_box=[] for i in range(10): Stats={} q1=0 q3=0 whislo=0 whishi=0 me=0 med=0 q1,q3=sci.beta.interval(0.5, NumPos[i], NumNeg[i]) whislo, whishi=sci.beta.interval(0.95, NumPos[i], NumNeg[i]) me=sci.beta.mean(NumPos[i], NumNeg[i]) med=sci.beta.median(NumPos[i], NumNeg[i]) Stats['med']=med Stats['q1']=q1 Stats['q3']=q3 Stats['whislo']=whislo Stats['whishi']=whishi stats_box.append(Stats) i+=1 #Specify labels for X-axis X_axis_bar= ['0.0-0.1', '0.1-0.2', '0.2-0.3', '0.3-0.4', '0.4-0.5','0.5-0.6', '0.6-0.7', '0.7-0.8', '0.8-0-9', '0.9-1.0'] fig, axs=plt.subplots(2, 1, figsize=(9,9)) # Boxplot for each 'probability class' axs[0].bxp(stats_box, showfliers=False, meanline=True) axs[0].set_xticklabels(X_axis_bar) axs[0].set_title('Positive Ratio', fontsize='x-large') axs[0].set_xlabel('predicted activity') axs[0].set_ylabel('positive ratio') axs[0].axline([1,0.05], [10,0.95], color='r', linestyle='--') #Plot number of compounds of each 'class' heights, bins= np.histogram(np.transpose(y_hat_platt)) axs[1].bar(bins[:-1], heights/heights.sum(), align='center', tick_label=X_axis_bar, width=bins[1]-bins[0]) axs[1].set_title('Counts', fontsize='x-large') axs[1].set_xlabel('predicted activity') axs[1].set_ylabel('relative frequency') fig.suptitle('Target-ID:'+ str(TargetID) + '\n Total Number of Bioactivities:' + str(y_hat_platt.shape[0]),fontsize='xx-large' ) fig.tight_layout() #save figure plt.savefig('./ProbCal_plots/BoxPlot_Count and_PositiveRate_TargetID_plattScaling'+str(TargetID)+'_'+str(date)+'.pdf')
[ "numpy.transpose", "scipy.stats.beta.median", "scipy.stats.beta.interval", "sparsechem.load_sparse", "argparse.ArgumentParser", "numpy.logical_and", "numpy.isin", "numpy.count_nonzero", "sparsechem.keep_row_data", "datetime.datetime.now", "numpy.nonzero", "scipy.stats.beta.mean", "numpy.load...
[((432, 543), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Obtaining Histograms for Probability Calibration for singular Taget"""'}), "(description=\n 'Obtaining Histograms for Probability Calibration for singular Taget')\n", (455, 543), False, 'import argparse\n'), ((1314, 1342), 'sparsechem.load_sparse', 'sc.load_sparse', (['args.y_class'], {}), '(args.y_class)\n', (1328, 1342), True, 'import sparsechem as sc\n'), ((1355, 1387), 'sparsechem.load_sparse', 'sc.load_sparse', (['args.y_hat_platt'], {}), '(args.y_hat_platt)\n', (1369, 1387), True, 'import sparsechem as sc\n'), ((1490, 1525), 'numpy.isin', 'np.isin', (['folding', 'args.predict_fold'], {}), '(folding, args.predict_fold)\n', (1497, 1525), True, 'import numpy as np\n'), ((1536, 1567), 'sparsechem.keep_row_data', 'sc.keep_row_data', (['y_class', 'keep'], {}), '(y_class, keep)\n', (1552, 1567), True, 'import sparsechem as sc\n'), ((3638, 3672), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(9, 9)'}), '(2, 1, figsize=(9, 9))\n', (3650, 3672), True, 'import matplotlib.pyplot as plt\n'), ((1432, 1453), 'numpy.load', 'np.load', (['args.folding'], {}), '(args.folding)\n', (1439, 1453), True, 'import numpy as np\n'), ((1805, 1833), 'numpy.nonzero', 'np.nonzero', (['y_class_TargetID'], {}), '(y_class_TargetID)\n', (1815, 1833), True, 'import numpy as np\n'), ((2113, 2139), 'numpy.count_nonzero', 'np.count_nonzero', (['(arr == 1)'], {}), '(arr == 1)\n', (2129, 2139), True, 'import numpy as np\n'), ((2146, 2173), 'numpy.count_nonzero', 'np.count_nonzero', (['(arr == -1)'], {}), '(arr == -1)\n', (2162, 2173), True, 'import numpy as np\n'), ((2257, 2283), 'numpy.count_nonzero', 'np.count_nonzero', (['(arr == 1)'], {}), '(arr == 1)\n', (2273, 2283), True, 'import numpy as np\n'), ((2325, 2352), 'numpy.count_nonzero', 'np.count_nonzero', (['(arr == -1)'], {}), '(arr == -1)\n', (2341, 2352), True, 'import numpy as np\n'), ((3125, 3169), 'scipy.stats.beta.interval', 'sci.beta.interval', (['(0.5)', 'NumPos[i]', 'NumNeg[i]'], {}), '(0.5, NumPos[i], NumNeg[i])\n', (3142, 3169), True, 'import scipy.stats as sci\n'), ((3189, 3234), 'scipy.stats.beta.interval', 'sci.beta.interval', (['(0.95)', 'NumPos[i]', 'NumNeg[i]'], {}), '(0.95, NumPos[i], NumNeg[i])\n', (3206, 3234), True, 'import scipy.stats as sci\n'), ((3242, 3277), 'scipy.stats.beta.mean', 'sci.beta.mean', (['NumPos[i]', 'NumNeg[i]'], {}), '(NumPos[i], NumNeg[i])\n', (3255, 3277), True, 'import scipy.stats as sci\n'), ((3286, 3323), 'scipy.stats.beta.median', 'sci.beta.median', (['NumPos[i]', 'NumNeg[i]'], {}), '(NumPos[i], NumNeg[i])\n', (3301, 3323), True, 'import scipy.stats as sci\n'), ((4066, 4091), 'numpy.transpose', 'np.transpose', (['y_hat_platt'], {}), '(y_hat_platt)\n', (4078, 4091), True, 'import numpy as np\n'), ((375, 389), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (387, 389), False, 'from datetime import datetime\n'), ((2624, 2693), 'numpy.logical_and', 'np.logical_and', (['(y_hat_platt >= values[j])', '(y_hat_platt < values[j + 1])'], {}), '(y_hat_platt >= values[j], y_hat_platt < values[j + 1])\n', (2638, 2693), True, 'import numpy as np\n')]
import numpy as np import torch from baselines.common.vec_env import VecEnvWrapper from gym import spaces, ActionWrapper from envs.ImageObsVecEnvWrapper import get_image_obs_wrapper from envs.ResidualVecEnvWrapper import get_residual_layers from pose_estimator.utils import unnormalise_y class PoseEstimatorVecEnvWrapper(VecEnvWrapper): """ Uses a pose estimator to estimate the state from the image. Wrapping this environment around a ResidualVecEnvWrapper makes it possible to use a full state policy on an environment with images as observations """ def __init__(self, venv, device, pose_estimator, state_to_estimate, low, high, abs_to_rel=False): super().__init__(venv) self.image_obs_wrapper = get_image_obs_wrapper(venv) assert self.image_obs_wrapper is not None self.estimator = pose_estimator.to(device) self.estimator.eval() self.policy_layers = get_residual_layers(venv) self.state_obs_space = self.policy_layers[0].observation_space self.state_to_estimate = state_to_estimate self.state_to_use = [i for i in range(self.state_obs_space.shape[0]) if i not in state_to_estimate] self.low = low self.high = high self.curr_image = None self.abs_to_rel = abs_to_rel self.target_z = np.array(self.get_images(mode="target_height")) self.junk = None self.abs_estimations = None def step_async(self, actions): with torch.no_grad(): net_output = self.estimator.predict(self.curr_image).cpu().numpy() estimation = net_output if self.low is None else unnormalise_y(net_output, self.low, self.high) if self.abs_estimations is None: self.abs_estimations = np.array([estimation]) else: self.abs_estimations = np.append(self.abs_estimations, [estimation], axis=0) obs = np.zeros((self.num_envs, *self.state_obs_space.shape)) estimation = np.median(self.abs_estimations, axis=0) obs[:, self.state_to_use] = self.image_obs_wrapper.curr_state_obs[:, self.state_to_use] if self.abs_to_rel: full_pos_estimation = np.append(estimation[:, :2], self.target_z, axis=1) # rack_to_trg = self.base_env.get_position(self.base_env.target_handle) - \ # self.base_env.get_position(self.base_env.rack_handle) # full_pos_estimation += rack_to_trg actual_plate_pos = np.array(self.get_images(mode='plate')) relative_estimation = full_pos_estimation - actual_plate_pos estimation = np.append(relative_estimation, estimation[:, 2:], axis=1) # FOR ADJUSTING FROM RACK ESTIMATION TO TARGET OBSERVATIONS # rack_to_trg = self.base_env.get_position(self.base_env.target_handle) - \ # self.base_env.get_position(self.base_env.rack_handle) # estimation[:, :-1] += rack_to_trg[:-1] obs[:, self.state_to_estimate] = estimation for policy in self.policy_layers: policy.curr_obs = obs self.venv.step_async(actions) def step_wait(self): self.curr_image, rew, done, info = self.venv.step_wait() if np.all(done): self.abs_estimations = None return self.curr_image, rew, done, info def reset(self): self.curr_image = self.venv.reset() return self.curr_image class ClipActions(ActionWrapper): def __init__(self, env): super(ClipActions, self).__init__(env) def action(self, action): return np.clip(action, self.action_space.low, self.action_space.high) # TODO: Scale properly to support boundaries where low != -high class BoundPositionVelocity(ActionWrapper): def __init__(self, env): super(BoundPositionVelocity, self).__init__(env) def action(self, action): pos = action[:3] if not ((pos >= self.action_space.low[0]) & (pos <= self.action_space.high[0])).all(): pos /= np.max(np.abs(pos)) pos *= self.action_space.high[0] return action class ScaleActions(ActionWrapper): def __init__(self, env, factor): self.factor = factor super(ScaleActions, self).__init__(env) def action(self, action): action *= self.factor return action class E2EVecEnvWrapper(VecEnvWrapper): """ Used to train an end-to-end policy. Not useful in this project, training unfeasibly long. """ def __init__(self, venv): res = venv.get_images(mode='activate')[0] image_obs_space = spaces.Box(0, 255, [3, *res], dtype=np.uint8) state_obs_space = venv.observation_space observation_space = spaces.Tuple((image_obs_space, state_obs_space)) observation_space.shape = (image_obs_space.shape, state_obs_space.shape) super().__init__(venv, observation_space) self.curr_state_obs = None self.last_4_image_obs = None def reset(self): self.curr_state_obs = self.venv.reset() image_obs = np.transpose(self.venv.get_images(), (0, 3, 1, 2)) return image_obs, self.curr_state_obs # Swap out state for image def step_wait(self): obs, rew, done, info = self.venv.step_wait() self.curr_state_obs = obs image_obs = np.transpose(self.venv.get_images(), (0, 3, 1, 2)) return (image_obs, self.curr_state_obs), rew, done, info class InitialController(ActionWrapper): """ This environment wrapper moves the subject directly toward the target position at every step. It can be used to initialise learning without the need for reward shaping. """ def __init__(self, env): super(InitialController, self).__init__(env) self.base_env = env.unwrapped def action(self, action): vec = self.base_env.target_pos - self.base_env.subject_pos if not ((vec >= self.action_space.low[0]) & (vec <= self.action_space.high[0])).all(): vec /= np.max(np.abs(vec)) vec *= self.action_space.high[0] full_vec = vec + action[:3] rot = action[3:] full_action = np.append(full_vec, rot) return full_action
[ "numpy.clip", "numpy.abs", "numpy.median", "gym.spaces.Tuple", "pose_estimator.utils.unnormalise_y", "gym.spaces.Box", "envs.ImageObsVecEnvWrapper.get_image_obs_wrapper", "numpy.append", "numpy.zeros", "numpy.array", "torch.no_grad", "numpy.all", "envs.ResidualVecEnvWrapper.get_residual_laye...
[((759, 786), 'envs.ImageObsVecEnvWrapper.get_image_obs_wrapper', 'get_image_obs_wrapper', (['venv'], {}), '(venv)\n', (780, 786), False, 'from envs.ImageObsVecEnvWrapper import get_image_obs_wrapper\n'), ((947, 972), 'envs.ResidualVecEnvWrapper.get_residual_layers', 'get_residual_layers', (['venv'], {}), '(venv)\n', (966, 972), False, 'from envs.ResidualVecEnvWrapper import get_residual_layers\n'), ((3433, 3445), 'numpy.all', 'np.all', (['done'], {}), '(done)\n', (3439, 3445), True, 'import numpy as np\n'), ((3790, 3852), 'numpy.clip', 'np.clip', (['action', 'self.action_space.low', 'self.action_space.high'], {}), '(action, self.action_space.low, self.action_space.high)\n', (3797, 3852), True, 'import numpy as np\n'), ((4799, 4844), 'gym.spaces.Box', 'spaces.Box', (['(0)', '(255)', '[3, *res]'], {'dtype': 'np.uint8'}), '(0, 255, [3, *res], dtype=np.uint8)\n', (4809, 4844), False, 'from gym import spaces, ActionWrapper\n'), ((4922, 4970), 'gym.spaces.Tuple', 'spaces.Tuple', (['(image_obs_space, state_obs_space)'], {}), '((image_obs_space, state_obs_space))\n', (4934, 4970), False, 'from gym import spaces, ActionWrapper\n'), ((6359, 6383), 'numpy.append', 'np.append', (['full_vec', 'rot'], {}), '(full_vec, rot)\n', (6368, 6383), True, 'import numpy as np\n'), ((1530, 1545), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1543, 1545), False, 'import torch\n'), ((2046, 2100), 'numpy.zeros', 'np.zeros', (['(self.num_envs, *self.state_obs_space.shape)'], {}), '((self.num_envs, *self.state_obs_space.shape))\n', (2054, 2100), True, 'import numpy as np\n'), ((2126, 2165), 'numpy.median', 'np.median', (['self.abs_estimations'], {'axis': '(0)'}), '(self.abs_estimations, axis=0)\n', (2135, 2165), True, 'import numpy as np\n'), ((1687, 1733), 'pose_estimator.utils.unnormalise_y', 'unnormalise_y', (['net_output', 'self.low', 'self.high'], {}), '(net_output, self.low, self.high)\n', (1700, 1733), False, 'from pose_estimator.utils import unnormalise_y\n'), ((1893, 1915), 'numpy.array', 'np.array', (['[estimation]'], {}), '([estimation])\n', (1901, 1915), True, 'import numpy as np\n'), ((1973, 2026), 'numpy.append', 'np.append', (['self.abs_estimations', '[estimation]'], {'axis': '(0)'}), '(self.abs_estimations, [estimation], axis=0)\n', (1982, 2026), True, 'import numpy as np\n'), ((2336, 2387), 'numpy.append', 'np.append', (['estimation[:, :2]', 'self.target_z'], {'axis': '(1)'}), '(estimation[:, :2], self.target_z, axis=1)\n', (2345, 2387), True, 'import numpy as np\n'), ((2800, 2857), 'numpy.append', 'np.append', (['relative_estimation', 'estimation[:, 2:]'], {'axis': '(1)'}), '(relative_estimation, estimation[:, 2:], axis=1)\n', (2809, 2857), True, 'import numpy as np\n'), ((4227, 4238), 'numpy.abs', 'np.abs', (['pos'], {}), '(pos)\n', (4233, 4238), True, 'import numpy as np\n'), ((6215, 6226), 'numpy.abs', 'np.abs', (['vec'], {}), '(vec)\n', (6221, 6226), True, 'import numpy as np\n')]
'''light_curve_class.py - <NAME> - Feb 2019 This contains a class useful for organizing an object's light curve and other useful data, just to keep things clean going forward. ''' import numpy as np class light_curve(): ''' A base class for storing the basic light curve data: times, magnitudes, and errors. The initialization takes three arguments: times - the times of the observations mags - the measured brightnesses, in magnitudes errs - the measurement errors ''' def __init__(self,times_,mags_,errs_): # First, make sure that times_, mags_, and errs_ all have # a len attribute and are the same length if not hasattr(times_,'__len__'): raise AttributeError("times does not have a len attribute") if not hasattr(mags_,'__len__'): raise AttributeError("mags does not have a len attribute") if not hasattr(errs_,'__len__'): raise AttributeError("errs does not have a len attribute") if len(times_) != len(mags_): raise ValueError("The lengths of times and mags are not the same") if len(mags_) != len(errs_): raise ValueError("The lengths of mags and errs are not the same") # Make sure these are numpy arrays, since that is what the astrobase # period search functions will take if isinstance(times_,np.ndarray): self.times = times_ else: self.times = np.array(times_) if isinstance(mags_,np.ndarray): self.mags = mags_ else: self.mags = np.array(mags_) if isinstance(errs_,np.ndarray): self.errs = errs_ else: self.errs = np.array(errs_) class single_lc_object(light_curve): ''' A class for storing light curve info (time, mags, errs) coupled with an object's position and ID. Arbitrary extra information can be stored as well in a dictionary. Subclasses the light_curve class. The initialization takes six arguments, with a seventh optional: times - the times of the observations mags - the measured brightnesses, in magnitudes errs - the measurement errors x - the x-position of the object in pixel coordinates y - the y-position of the object in pixel coordinates ID - A unique ID for the object extra_info - (optional) a dictionary containing extra information for the object ''' def __init__(self,times_,mags_,errs_,x_,y_,ID_,extra_info={}): light_curve.__init__(self,times_,mags_,errs_) self.x = x_ self.y = y_ self.ID = ID_ self.neighbors = [] # Empty list of nearby stars self.extra_info = extra_info class lc_objects(): '''A class for storing single_lc_object instances for a whole suite of objects. This class also determines which objects are neighbors when they get added to the collection, as well as ensures uniqueness of object IDs. The initialization takes one argument: radius - the circular radius, in pixels, for objects to be in sufficient proximity to be regarded as neighbors ''' def __init__(self,radius_): self.neighbor_radius_squared = radius_**2 # Storing radius squared self.objects = [] # To store all the objects self.index_dict = {} # Dictionary to map IDs to self.objects indices self.results = {} # Dictionary to save results # Method to add a single_lc_object def add_object(self,times,mags,errs,x,y,ID,extra_info={}):#,object): # Make sure the object's ID does not match any other object if ID in self.index_dict.keys(): raise ValueError("Not a unique ID, " + str(ID)) # Add the object to the list self.objects.append(single_lc_object(times,mags,errs,x,y,ID, extra_info=extra_info)) # Map the object's ID to its position in self.objects self.index_dict[ID] = len(self.objects)-1 # Give it a place in self.results self.results[ID] = {} # Check if the new object is neighbor to any other objects for o in self.objects[:-1]: if (x - o.x)**2 + (y - o.y)**2 < self.neighbor_radius_squared: self.objects[-1].neighbors.append(o.ID) o.neighbors.append(ID)
[ "numpy.array" ]
[((1473, 1489), 'numpy.array', 'np.array', (['times_'], {}), '(times_)\n', (1481, 1489), True, 'import numpy as np\n'), ((1599, 1614), 'numpy.array', 'np.array', (['mags_'], {}), '(mags_)\n', (1607, 1614), True, 'import numpy as np\n'), ((1724, 1739), 'numpy.array', 'np.array', (['errs_'], {}), '(errs_)\n', (1732, 1739), True, 'import numpy as np\n')]
################################################################################ ## ## 新浪微博热点事件发现与脉络生成系统 ## ## @Filename ./HotspotsAnalysis/CorrelationAnalysis.py ## @Author 李林峰, 刘臻, 徐润邦, 马伯乐, 朱杰, 瞿凤业 ## @Version 3.1 ## @Date 2019/09/06 ## @Copyright Copyright (c) 2019. All rights reserved. ## @Description 本文件实现热点事件相关性分析模块 ## ################################################################################ import numpy as np import os from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer MYDIR = os.path.dirname(__file__) ## 模块内部接口 # <summary> 计算两个向量之间的余弦相似度 </summary> # <param> # vector_a (一维列表): [num1, num2, ...] # vector_a (一维列表): [num1, num2, ...] # </param> # <return> # sim (float): 相关性系数 # </return> def cos_sim(vector_a, vector_b): vector_a = np.mat(vector_a) vector_b = np.mat(vector_b) num = float(vector_a * vector_b.T) denom = np.linalg.norm(vector_a) * np.linalg.norm(vector_b) if denom == 0: sim = 0.0 else: cos = num / denom sim = 0.5*cos + 0.5 return sim ## 模块对外接口 # <summary> 生成相关性矩阵 </summary> # <param> # input_file_path (str) 热点事件的文件路径 # output_filepath (str) 输出关联性矩阵的文件路径 # </param> # <io> # file input: 从 input_file_path (str) 路径读入热点事件 # file output:向 output_filepath (str) 路径写入事件关联性矩阵 "num11 num12 ...\n num21 num22 ...\n ..." # </io> def generate_correlation_matrics(input_file_path, output_file_path): blogs = [] with open(os.path.join(MYDIR,input_file_path), 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: content = line.split(',')[2] blogs.append(content) # print(blogs) # 构建TF-IDF向量 vectorizer = CountVectorizer() count = vectorizer.fit_transform(blogs) transformer = TfidfTransformer() tfidf = transformer.fit_transform(count) weight = tfidf.toarray() # 计算相关性系数,存入矩阵 correlation_matrics = [] n = len(blogs) for i in range(n): tmp = [] for j in range(n): cos_between_two_matric = cos_sim(weight[i], weight[j]) tmp.append(cos_between_two_matric) correlation_matrics.append(tmp) with open(os.path.join(MYDIR,output_file_path), 'w', encoding='utf-8') as f: for i in correlation_matrics: content = " ".join('%s' % num for num in i) f.write(content+'\n') f.close()
[ "numpy.mat", "sklearn.feature_extraction.text.TfidfTransformer", "sklearn.feature_extraction.text.CountVectorizer", "os.path.join", "os.path.dirname", "numpy.linalg.norm" ]
[((594, 619), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (609, 619), False, 'import os\n'), ((887, 903), 'numpy.mat', 'np.mat', (['vector_a'], {}), '(vector_a)\n', (893, 903), True, 'import numpy as np\n'), ((919, 935), 'numpy.mat', 'np.mat', (['vector_b'], {}), '(vector_b)\n', (925, 935), True, 'import numpy as np\n'), ((1831, 1848), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {}), '()\n', (1846, 1848), False, 'from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\n'), ((1911, 1929), 'sklearn.feature_extraction.text.TfidfTransformer', 'TfidfTransformer', ([], {}), '()\n', (1927, 1929), False, 'from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\n'), ((987, 1011), 'numpy.linalg.norm', 'np.linalg.norm', (['vector_a'], {}), '(vector_a)\n', (1001, 1011), True, 'import numpy as np\n'), ((1014, 1038), 'numpy.linalg.norm', 'np.linalg.norm', (['vector_b'], {}), '(vector_b)\n', (1028, 1038), True, 'import numpy as np\n'), ((1579, 1615), 'os.path.join', 'os.path.join', (['MYDIR', 'input_file_path'], {}), '(MYDIR, input_file_path)\n', (1591, 1615), False, 'import os\n'), ((2308, 2345), 'os.path.join', 'os.path.join', (['MYDIR', 'output_file_path'], {}), '(MYDIR, output_file_path)\n', (2320, 2345), False, 'import os\n')]
# -*- coding: utf-8 -*- """ Created on Mon Sep 3 17:58:37 2018 @author: Basil """ import matplotlib.pyplot as plt import gc import numpy import scipy.special from LightPipes import cm, mm, nm import PropogationFunctions import PlotFunctions import namedtuplesAxiconTF import SaveLoad def Normalized(v, n = 0): if(n == 0): return v / max(numpy.abs(v)) elif(n > 0): return v / sum(numpy.power(numpy.abs(v), n)) print("n < 0, no normalization can be performed") return v def AxiconZ(z): return 2*numpy.pi* k0**2 * w0**6 *z/a**2/(k0**2 * w0**4 + z**2)**(3/2) *numpy.exp( - z**2 * w0**2 /a**2 /(k0**2 * w0**4 + z**2) ) * numpy.heaviside(z, 0) # 2*numpy.pi*z/a**2/k0*numpy.exp( - z**2 /a**2 /k0**2 / w0**2 ) Izt0yx = None; Iztyx = None; Ixtyz = None; Iytxz = None; Iyz2p = None; Ixz2p = None; Ixy2p = None gc.collect() #dirname = 'C:\\Users\\Basil\\ResearchData\\FourierOptics\\AxiconTF\\' + \ # '20181031194535_f=0.05_w1=6.37E-05_alpha=1.50E-04_b=1.50E+05' Iztyx,s,lp,cp,g = SaveLoad.ReadDumpFromDisk(dirname, namedtuplesAxiconTF.LaunchParams, namedtuplesAxiconTF.ComputParmas) # for different Z #PlotFunctions.PlotMovie(numpy.sum(numpy.swapaxes(Iztyx, 1, 3), axis =2 ), # (g.t.start/mm, g.t.end/mm), (-lp.size/2/mm, lp.size/2/mm), # g.z.points, 'T, mm', 'X, mm', aspect = lp.Nx/g.t.steps*0.2) wt_z,wx_z,wy_z = PropogationFunctions.Ws_z(lp, g, Iztyx) plt.plot(g.z.points, wt_z/3e-7, 'o') plt.plot(g.z.points, numpy.repeat(s.tau/3e-7/numpy.sqrt(2), g.z.steps )) plt.plot(g.z.points, s.tau/3e-7/numpy.sqrt(2) * numpy.sqrt(r2(g.z.points, cp)/r1(g.z.points, cp))) plt.xlabel('Z, m'); plt.ylabel('\Delta T, fs') plt.ylim( 0, max(wt_z)*1.1/3e-7 ) plt.show() plt.plot(g.z.points, wx_z/mm, 'o') plt.plot(g.z.points, s.lambda0/(2*numpy.pi)*lp.f/lp.w1 * numpy.sqrt(r1(g.z.points, cp)) / mm ) plt.plot(g.z.points, wy_z/mm, 'o') plt.xlabel('Z, m'); plt.ylabel('\Delta X & Y, mm') plt.show() #Iztyx = ConvertToRealTime(Izt0yx, start_t, delta_t, steps_t2, start_t2) #Iztyx = Izt0yx Izyx2p = numpy.sum(numpy.power(Iztyx, 2), axis = 1) max_intensity2p = numpy.max(Izyx2p[:,lp.Nx//2,:]) plt.imshow(numpy.log(numpy.add(numpy.transpose(Izyx2p[:,lp.Nx//2,:]), max_intensity2p/200 )), cmap='hot', vmin=numpy.log( max_intensity2p/200 ), vmax= numpy.log(max_intensity2p + max_intensity2p/200 ), extent = [g.z.start, g.z.end, -lp.size/2/mm, lp.size/2/mm], aspect=0.00005*lp.Nx/g.z.steps); plt.show() max_intensity2p = numpy.max(Izyx2p[:,:,lp.Nx//2]) plt.imshow(numpy.log(numpy.add(numpy.transpose(Izyx2p[:,:,lp.Nx//2]), max_intensity2p/200 )), cmap='hot', vmin=numpy.log( max_intensity2p/200 ), vmax= numpy.log(max_intensity2p + max_intensity2p/200 ), extent = [g.z.start, g.z.end, -lp.size/2/mm, lp.size/2/mm], aspect=0.00005*lp.Nx/g.z.steps); plt.show() plt.plot(g.z.points/mm, Normalized( Izyx2p[:,lp.Nx//2,lp.Nx//2] ), 'o-') plt.plot(g.z.points/mm, Normalized( 1/numpy.sqrt(r1(g.z.points, cp)*r2(g.z.points, cp)) )) k0 = (2*numpy.pi/s.lambda0) w1 = lp.w1 a = lp.a plt.plot(g.z.points/mm, Normalized( numpy.sum(Iztyx, axis = 1)[:, lp.Nx//2, lp.Nx//2] ), 'o-') plt.plot(g.z.points/mm, Normalized( AxiconZ(g.z.points -lp.f + lp.sz/numpy.sqrt(2)) )) plt.plot(g.z.points/mm, Normalized( 1/numpy.sqrt(r1(g.z.points, cp)) )) plt.xlabel('Z, mm'); plt.ylabel('I(axis)') plt.show() ifoc = numpy.argmax( Izyx2p[:,lp.Nx//2,lp.Nx//2] ) r = range( int(lp.Nx//(7/3)), int(lp.Nx//(7/4)) ) xp = g.x.points[((g.x.steps - lp.Nx)//2) : ((g.x.steps + lp.Nx)//2), ] plt.plot(xp[r]/mm, Normalized( numpy.sum(Iztyx, axis = 1)[ifoc,lp.Nx//2,r] ), 'o-') plt.plot(xp[r]/mm, scipy.special.jv(0, xp[r]/lp.a)**2 ) plt.plot(xp[r]/mm, Normalized( Izyx2p[ifoc,lp.Nx//2,r] / max(Izyx2p[ifoc,lp.Nx//2,r]) ), 'o-') plt.xlabel('X, mm'); plt.ylabel('I(foc)') plt.show() # print('x scale FWHM is ', # 1e6*(lp.size)*sum(Ixy2p[ifoc][lp.Nx//2] > numpy.max(Ixy2p[ifoc][lp.Nx//2])*0.5)/len(Ixy2p[ifoc][lp.Nx//2]), # 'mkm (', sum(Ixy2p[ifoc][lp.Nx//2] > numpy.max(Ixy2p[ifoc][lp.Nx//2])*0.5), ' points)')
[ "numpy.abs", "numpy.sqrt", "matplotlib.pyplot.ylabel", "numpy.power", "matplotlib.pyplot.xlabel", "PropogationFunctions.Ws_z", "matplotlib.pyplot.plot", "numpy.argmax", "numpy.heaviside", "numpy.max", "numpy.log", "numpy.exp", "numpy.sum", "SaveLoad.ReadDumpFromDisk", "gc.collect", "nu...
[((869, 881), 'gc.collect', 'gc.collect', ([], {}), '()\n', (879, 881), False, 'import gc\n'), ((1049, 1155), 'SaveLoad.ReadDumpFromDisk', 'SaveLoad.ReadDumpFromDisk', (['dirname', 'namedtuplesAxiconTF.LaunchParams', 'namedtuplesAxiconTF.ComputParmas'], {}), '(dirname, namedtuplesAxiconTF.LaunchParams,\n namedtuplesAxiconTF.ComputParmas)\n', (1074, 1155), False, 'import SaveLoad\n'), ((1437, 1476), 'PropogationFunctions.Ws_z', 'PropogationFunctions.Ws_z', (['lp', 'g', 'Iztyx'], {}), '(lp, g, Iztyx)\n', (1462, 1476), False, 'import PropogationFunctions\n'), ((1478, 1517), 'matplotlib.pyplot.plot', 'plt.plot', (['g.z.points', '(wt_z / 3e-07)', '"""o"""'], {}), "(g.z.points, wt_z / 3e-07, 'o')\n", (1486, 1517), True, 'import matplotlib.pyplot as plt\n'), ((1687, 1705), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Z, m"""'], {}), "('Z, m')\n", (1697, 1705), True, 'import matplotlib.pyplot as plt\n'), ((1707, 1734), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""\\\\Delta T, fs"""'], {}), "('\\\\Delta T, fs')\n", (1717, 1734), True, 'import matplotlib.pyplot as plt\n'), ((1770, 1780), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1778, 1780), True, 'import matplotlib.pyplot as plt\n'), ((1782, 1818), 'matplotlib.pyplot.plot', 'plt.plot', (['g.z.points', '(wx_z / mm)', '"""o"""'], {}), "(g.z.points, wx_z / mm, 'o')\n", (1790, 1818), True, 'import matplotlib.pyplot as plt\n'), ((1912, 1948), 'matplotlib.pyplot.plot', 'plt.plot', (['g.z.points', '(wy_z / mm)', '"""o"""'], {}), "(g.z.points, wy_z / mm, 'o')\n", (1920, 1948), True, 'import matplotlib.pyplot as plt\n'), ((1947, 1965), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Z, m"""'], {}), "('Z, m')\n", (1957, 1965), True, 'import matplotlib.pyplot as plt\n'), ((1967, 1998), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""\\\\Delta X & Y, mm"""'], {}), "('\\\\Delta X & Y, mm')\n", (1977, 1998), True, 'import matplotlib.pyplot as plt\n'), ((1999, 2009), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2007, 2009), True, 'import matplotlib.pyplot as plt\n'), ((2179, 2214), 'numpy.max', 'numpy.max', (['Izyx2p[:, lp.Nx // 2, :]'], {}), '(Izyx2p[:, lp.Nx // 2, :])\n', (2188, 2214), False, 'import numpy\n'), ((2530, 2540), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2538, 2540), True, 'import matplotlib.pyplot as plt\n'), ((2561, 2596), 'numpy.max', 'numpy.max', (['Izyx2p[:, :, lp.Nx // 2]'], {}), '(Izyx2p[:, :, lp.Nx // 2])\n', (2570, 2596), False, 'import numpy\n'), ((2912, 2922), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2920, 2922), True, 'import matplotlib.pyplot as plt\n'), ((3405, 3424), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Z, mm"""'], {}), "('Z, mm')\n", (3415, 3424), True, 'import matplotlib.pyplot as plt\n'), ((3426, 3447), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""I(axis)"""'], {}), "('I(axis)')\n", (3436, 3447), True, 'import matplotlib.pyplot as plt\n'), ((3449, 3459), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3457, 3459), True, 'import matplotlib.pyplot as plt\n'), ((3469, 3516), 'numpy.argmax', 'numpy.argmax', (['Izyx2p[:, lp.Nx // 2, lp.Nx // 2]'], {}), '(Izyx2p[:, lp.Nx // 2, lp.Nx // 2])\n', (3481, 3516), False, 'import numpy\n'), ((3873, 3892), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X, mm"""'], {}), "('X, mm')\n", (3883, 3892), True, 'import matplotlib.pyplot as plt\n'), ((3894, 3914), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""I(foc)"""'], {}), "('I(foc)')\n", (3904, 3914), True, 'import matplotlib.pyplot as plt\n'), ((3916, 3926), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3924, 3926), True, 'import matplotlib.pyplot as plt\n'), ((2126, 2147), 'numpy.power', 'numpy.power', (['Iztyx', '(2)'], {}), '(Iztyx, 2)\n', (2137, 2147), False, 'import numpy\n'), ((684, 705), 'numpy.heaviside', 'numpy.heaviside', (['z', '(0)'], {}), '(z, 0)\n', (699, 705), False, 'import numpy\n'), ((2334, 2366), 'numpy.log', 'numpy.log', (['(max_intensity2p / 200)'], {}), '(max_intensity2p / 200)\n', (2343, 2366), False, 'import numpy\n'), ((2374, 2424), 'numpy.log', 'numpy.log', (['(max_intensity2p + max_intensity2p / 200)'], {}), '(max_intensity2p + max_intensity2p / 200)\n', (2383, 2424), False, 'import numpy\n'), ((2716, 2748), 'numpy.log', 'numpy.log', (['(max_intensity2p / 200)'], {}), '(max_intensity2p / 200)\n', (2725, 2748), False, 'import numpy\n'), ((2756, 2806), 'numpy.log', 'numpy.log', (['(max_intensity2p + max_intensity2p / 200)'], {}), '(max_intensity2p + max_intensity2p / 200)\n', (2765, 2806), False, 'import numpy\n'), ((624, 692), 'numpy.exp', 'numpy.exp', (['(-z ** 2 * w0 ** 2 / a ** 2 / (k0 ** 2 * w0 ** 4 + z ** 2))'], {}), '(-z ** 2 * w0 ** 2 / a ** 2 / (k0 ** 2 * w0 ** 4 + z ** 2))\n', (633, 692), False, 'import numpy\n'), ((1560, 1573), 'numpy.sqrt', 'numpy.sqrt', (['(2)'], {}), '(2)\n', (1570, 1573), False, 'import numpy\n'), ((1620, 1633), 'numpy.sqrt', 'numpy.sqrt', (['(2)'], {}), '(2)\n', (1630, 1633), False, 'import numpy\n'), ((2242, 2283), 'numpy.transpose', 'numpy.transpose', (['Izyx2p[:, lp.Nx // 2, :]'], {}), '(Izyx2p[:, lp.Nx // 2, :])\n', (2257, 2283), False, 'import numpy\n'), ((2624, 2665), 'numpy.transpose', 'numpy.transpose', (['Izyx2p[:, :, lp.Nx // 2]'], {}), '(Izyx2p[:, :, lp.Nx // 2])\n', (2639, 2665), False, 'import numpy\n'), ((3186, 3210), 'numpy.sum', 'numpy.sum', (['Iztyx'], {'axis': '(1)'}), '(Iztyx, axis=1)\n', (3195, 3210), False, 'import numpy\n'), ((3668, 3692), 'numpy.sum', 'numpy.sum', (['Iztyx'], {'axis': '(1)'}), '(Iztyx, axis=1)\n', (3677, 3692), False, 'import numpy\n'), ((358, 370), 'numpy.abs', 'numpy.abs', (['v'], {}), '(v)\n', (367, 370), False, 'import numpy\n'), ((3315, 3328), 'numpy.sqrt', 'numpy.sqrt', (['(2)'], {}), '(2)\n', (3325, 3328), False, 'import numpy\n'), ((424, 436), 'numpy.abs', 'numpy.abs', (['v'], {}), '(v)\n', (433, 436), False, 'import numpy\n')]
import sklearn import numpy as np import time, sys import matplotlib.pyplot as plt import pickle, json from sklearn.cluster import KMeans # K-means from sklearn import metrics from sklearn.datasets import make_blobs from kmodes.kmodes import KModes from kmodes.kprototypes import KPrototypes class pipeline: def __init__(self): self.data_cleaned = 'data_cleaned.csv' self.cluster_result = 'cluster_result.tsv' self.data_processed = 'data_processed_file' self.label_file = 'label_file' self.result_binary = 'result_binary_file' def data_load(self): temp = np.loadtxt(fname=self.data_cleaned, dtype=object, delimiter=',') self.dataset = temp[1:,3:] self.label = temp[0,3:].astype(str) print(np.shape(self.dataset)) print(self.label) print(self.dataset) def data_process(self): #process 'NA' value and normalisation def process_capacity(x): if x == 'NA': return 0 else: return int(x) def process_quality(x): if x == 'Very Good': return 3 elif x == 'Good': return 2 elif x == 'Fair': return 1 else: return 2 def process_crv(x): if x == 'NA': return np.nan else: return float(x) def process_crv2(x): if str(x) == 'nan': return temp_mean/temp_max else: return x/temp_max #1. room_capacity: NA as 0, softmax normalisation room_capacity = list(map(process_capacity, self.dataset[:, 0])) capacity_max = np.max(room_capacity) room_capacity = np.array(list(map(lambda x:x/capacity_max, room_capacity))) print("data type of Room capacity:", type(room_capacity[0])) #2. Room Category remain as str variable room_category = self.dataset[:, 1] print("data type of Room Category:", type(room_category[0])) #3. Space Quality as ordinal variable. 'Very Good' as 3, 'Good' as 2, 'Fair' as 1 room_space_quality = np.array(list(map(process_quality, self.dataset[:, 2]))) print("data type of space quality:", type(room_space_quality[0])) #4. Room Area as numerical value. softmax normalisation room_area = list(map(process_crv, self.dataset[:, 3])) rm_max = np.max([v for v in room_area if str(v) != 'nan']) room_area = np.array(list(map(lambda x:x/rm_max, room_area))) print("data type of room area:", type(room_area[0])) #5. RIV_rate as numerical value. NA as mean, softmax normalisation room_riv_rate = list(map(process_crv, self.dataset[:, 4])) temp_max = np.max([v for v in room_riv_rate if str(v) != 'nan']) temp_mean = np.mean([v for v in room_riv_rate if str(v) != 'nan']) room_riv_rate = np.array(list(map(process_crv2, room_riv_rate))) print("data type of RIV_rate:", type(room_riv_rate[0])) #6. room age as numerical value. NA as mean, softmax normalisation room_age = list(map(process_crv, self.dataset[:, 5])) temp_max = np.max([v for v in room_age if str(v) != 'nan']) temp_mean = np.mean([v for v in room_age if str(v) != 'nan']) room_age = np.array(list(map(process_crv2, room_age))) print("data type of room_age:", type(room_age[0])) #7. Assessment Condition Rating remains as float, NA as mean, softmax normalisation room_assessment_condition_rating = list(map(process_crv, self.dataset[:, 6])) temp_max = np.max([v for v in room_assessment_condition_rating if str(v) != 'nan']) temp_mean = np.mean([v for v in room_assessment_condition_rating if str(v) != 'nan']) room_assessment_condition_rating = np.array(list(map(process_crv2, room_assessment_condition_rating))) print("data type of Room Assessment Condition Rating:", type(room_assessment_condition_rating[0])) # merge all features self.dataset = np.column_stack((room_capacity, room_category, room_space_quality, room_area, \ room_riv_rate, room_age, room_assessment_condition_rating)) self.dataset[:, 0] = self.dataset[:, 0].astype(float) self.dataset[:, 2] = self.dataset[:, 2].astype(int) self.dataset[:, 3] = self.dataset[:, 3].astype(float) self.dataset[:, 4] = self.dataset[:, 4].astype(float) self.dataset[:, 5] = self.dataset[:, 5].astype(float) self.dataset[:, 6] = self.dataset[:, 6].astype(float) print(self.dataset) print(type(self.dataset[1][0]), type(self.dataset[1][1]), type(self.dataset[1][2]), \ type(self.dataset[1][3]), type(self.dataset[1][4]), type(self.dataset[1][5]), type(self.dataset[1][6])) print(self.dataset[:, 0].dtype, self.dataset[:, 1].dtype, self.dataset[:, 2].dtype, \ self.dataset[:, 3].dtype, self.dataset[:, 4].dtype, self.dataset[:, 5].dtype, self.dataset[:, 6].dtype) with open(self.data_processed, 'wb') as f: pickle.dump(self.dataset, f) with open(self.label_file, 'wb') as f: pickle.dump(self.label, f) def predict(self): with open(self.data_processed, 'rb') as f: self.dataset = pickle.load(f) with open(self.label_file, 'rb') as f: self.label = pickle.load(f) # self.y_pred = KMeans(n_clusters=5, random_state=9).fit_predict(self.dataset) # np.savetxt(self.cluster_result, np.hstack(self.y_pred, self.dataset) , delimiter=',') # score = metrics.calinski_harabaz_score(self.dataset, self.y_pred) # print(score) kproto = KPrototypes(n_clusters=5, init='Cao', verbose=2) clusters = kproto.fit_predict(self.dataset, categorical=[1]) temp = np.loadtxt(fname=self.data_cleaned, dtype=object, delimiter=',') room_identity = temp[1:,:3] self.result = np.column_stack((room_identity, self.dataset, clusters)) print(kproto.cluster_centroids_) # Print training statistics print(kproto.cost_) print(kproto.n_iter_) with open(self.result_binary, 'wb') as f: pickle.dump(self.result, f) with open('kproto_res', 'wb') as f: pickle.dump(kproto, f) with open(self.cluster_result, 'w') as f: re = self.result.tolist() for line in re: f.write("\t".join(list(map(str, line)))+'\n') for s, c in zip(self.label, clusters): print("Room identity: {}, cluster:{}".format(s, c)) def present(self): with open(self.cluster_result, 'r') as f1: with open(self.data_cleaned, 'r') as f2: self.d1 = {str((x, y)):0 for x in ('Fair', 'Very Good', 'Good', 'None') for y in range(5)} self.d2 = {str((y, x)):0 for y in range(5) for x in ('Fair', 'Very Good', 'Good', 'None')} label = f2.readline() while True: line1 = f1.readline().strip() line2 = f2.readline().strip() if not line1: break new_label = int(line1.split()[-1]) old_label = line2.split(',')[5] self.d1[str((old_label, new_label))] += 1 self.d2[str((new_label, old_label))] += 1 self.d = self.d1.copy() self.d.update(self.d2) with open('kmeans_stat.json', 'w') as f: json.dump(self.d, f) def calculation(self): with open('kproto_res', 'rb') as f: kproto = pickle.load(f) matrix = kproto.cluster_centroids_ print(matrix) class_0 = matrix[0][0] class_1 = matrix[0][1] class_2 = matrix[0][2] class_3 = matrix[0][3] class_4 = matrix[0][4] with open('calculation.txt', 'w') as f: for array, class_type in [(class_0, 0), (class_2, 2), (class_4, 4)]: distance1 = np.sqrt(np.sum(np.square(array-class_1))) distance2 = np.sqrt(np.sum(np.square(array-class_3))) line = "class: {}, distance from Premium: {}, distance from Poor: {}".format(class_type, distance1, distance2) print(line) f.write(line+'\r') def plot(self): with open('kmeans_stat.json', 'r') as f: self.d = json.load(f) new_d = {i:0 for i in range(5)} for k, v in self.d.items(): if str.isdigit(k[1]): new_d[int(k[1])] += v name_list = ['Poor','Fair','Good','Very Good', 'Premium'] num_list = [new_d[3], new_d[2], new_d[0], new_d[4], new_d[1]] plt.bar(range(len(num_list)), num_list, color='ygcmb', tick_label=name_list) plt.title('Room Frequencies for K-Prototypes') plt.xlabel('Space Quality') plt.ylabel('Number of Rooms') plt.show() pipeline = pipeline() # pipeline.data_load() # pipeline.data_process() # pipeline.predict() # pipeline.present() # pipeline.calculation() pipeline.plot()
[ "numpy.shape", "pickle.dump", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "pickle.load", "kmodes.kprototypes.KPrototypes", "numpy.column_stack", "numpy.max", "numpy.square", "json.load", "matplotlib.pyplot.title", "numpy.loadtxt", "json.dump", "matplotlib.pyplot.show" ]
[((617, 681), 'numpy.loadtxt', 'np.loadtxt', ([], {'fname': 'self.data_cleaned', 'dtype': 'object', 'delimiter': '""","""'}), "(fname=self.data_cleaned, dtype=object, delimiter=',')\n", (627, 681), True, 'import numpy as np\n'), ((1763, 1784), 'numpy.max', 'np.max', (['room_capacity'], {}), '(room_capacity)\n', (1769, 1784), True, 'import numpy as np\n'), ((4139, 4280), 'numpy.column_stack', 'np.column_stack', (['(room_capacity, room_category, room_space_quality, room_area, room_riv_rate,\n room_age, room_assessment_condition_rating)'], {}), '((room_capacity, room_category, room_space_quality,\n room_area, room_riv_rate, room_age, room_assessment_condition_rating))\n', (4154, 4280), True, 'import numpy as np\n'), ((5812, 5860), 'kmodes.kprototypes.KPrototypes', 'KPrototypes', ([], {'n_clusters': '(5)', 'init': '"""Cao"""', 'verbose': '(2)'}), "(n_clusters=5, init='Cao', verbose=2)\n", (5823, 5860), False, 'from kmodes.kprototypes import KPrototypes\n'), ((5946, 6010), 'numpy.loadtxt', 'np.loadtxt', ([], {'fname': 'self.data_cleaned', 'dtype': 'object', 'delimiter': '""","""'}), "(fname=self.data_cleaned, dtype=object, delimiter=',')\n", (5956, 6010), True, 'import numpy as np\n'), ((6070, 6126), 'numpy.column_stack', 'np.column_stack', (['(room_identity, self.dataset, clusters)'], {}), '((room_identity, self.dataset, clusters))\n', (6085, 6126), True, 'import numpy as np\n'), ((9041, 9087), 'matplotlib.pyplot.title', 'plt.title', (['"""Room Frequencies for K-Prototypes"""'], {}), "('Room Frequencies for K-Prototypes')\n", (9050, 9087), True, 'import matplotlib.pyplot as plt\n'), ((9096, 9123), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Space Quality"""'], {}), "('Space Quality')\n", (9106, 9123), True, 'import matplotlib.pyplot as plt\n'), ((9132, 9161), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Rooms"""'], {}), "('Number of Rooms')\n", (9142, 9161), True, 'import matplotlib.pyplot as plt\n'), ((9170, 9180), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9178, 9180), True, 'import matplotlib.pyplot as plt\n'), ((775, 797), 'numpy.shape', 'np.shape', (['self.dataset'], {}), '(self.dataset)\n', (783, 797), True, 'import numpy as np\n'), ((5175, 5203), 'pickle.dump', 'pickle.dump', (['self.dataset', 'f'], {}), '(self.dataset, f)\n', (5186, 5203), False, 'import pickle, json\n'), ((5264, 5290), 'pickle.dump', 'pickle.dump', (['self.label', 'f'], {}), '(self.label, f)\n', (5275, 5290), False, 'import pickle, json\n'), ((5402, 5416), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (5413, 5416), False, 'import pickle, json\n'), ((5489, 5503), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (5500, 5503), False, 'import pickle, json\n'), ((6326, 6353), 'pickle.dump', 'pickle.dump', (['self.result', 'f'], {}), '(self.result, f)\n', (6337, 6353), False, 'import pickle, json\n'), ((6410, 6432), 'pickle.dump', 'pickle.dump', (['kproto', 'f'], {}), '(kproto, f)\n', (6421, 6432), False, 'import pickle, json\n'), ((7809, 7823), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7820, 7823), False, 'import pickle, json\n'), ((8650, 8662), 'json.load', 'json.load', (['f'], {}), '(f)\n', (8659, 8662), False, 'import pickle, json\n'), ((7695, 7715), 'json.dump', 'json.dump', (['self.d', 'f'], {}), '(self.d, f)\n', (7704, 7715), False, 'import pickle, json\n'), ((8256, 8282), 'numpy.square', 'np.square', (['(array - class_1)'], {}), '(array - class_1)\n', (8265, 8282), True, 'import numpy as np\n'), ((8330, 8356), 'numpy.square', 'np.square', (['(array - class_3)'], {}), '(array - class_3)\n', (8339, 8356), True, 'import numpy as np\n')]
import torch import numpy import bionetwork import plotting import pandas import argparse #Get data number parser = argparse.ArgumentParser(prog='Macrophage simulation') parser.add_argument('--selectedCondition', action='store', default=None) args = parser.parse_args() curentId = int(args.selectedCondition) testCondtions = pandas.read_csv('synthNetScreen/conditions.tsv', sep='\t', low_memory=False) simultaniousInput = int(testCondtions.loc[curentId == testCondtions['Index'],:]['Ligands'].values) N = int(testCondtions.loc[curentId == testCondtions['Index'],:]['DataSize'].values) print(curentId, simultaniousInput, N) inputAmplitude = 3 projectionAmplitude = 1.2 #Setup optimizer noiseLevel = 10 batchSize = 5 MoAFactor = 0.1 spectralFactor = 1e-3 maxIter = 10000 #Load network networkList, nodeNames, modeOfAction = bionetwork.loadNetwork('data/KEGGnet-Model.tsv') annotation = pandas.read_csv('data/KEGGnet-Annotation.tsv', sep='\t') bionetParams = bionetwork.trainingParameters(iterations = 150, clipping=1, leak=0.01) inName = annotation.loc[annotation['ligand'],'code'].values outName = annotation.loc[annotation['TF'],'code'].values inName = numpy.intersect1d(nodeNames, inName) outName = numpy.intersect1d(nodeNames, outName) model = bionetwork.model(networkList, nodeNames, modeOfAction, inputAmplitude, projectionAmplitude, inName, outName, bionetParams, torch.double) model.inputLayer.weights.requires_grad = False model.projectionLayer.weights.requires_grad = False model.network.preScaleWeights() parameterizedModel = bionetwork.model(networkList, nodeNames, modeOfAction, inputAmplitude, projectionAmplitude, inName, outName, bionetParams, torch.double) parameterizedModel = bionetwork.loadParam('synthNetScreen/equationParams.txt', parameterizedModel, nodeNames) #Generate data X = torch.zeros(N, len(inName), dtype=torch.double) for i in range(1, N): #skip 0 to include a ctrl sample i.e. zero input X[i, (i-1) % len(inName)] = torch.rand(1, dtype=torch.double) #stimulate each receptor at least once X[i, numpy.random.randint(0, len(inName), simultaniousInput-1)] = torch.rand(simultaniousInput-1, dtype=torch.double) controlIndex = 0 Y, YfullRef = parameterizedModel(X) Y = Y.detach() #%% spectralTarget = numpy.exp(numpy.log(10**-2)/bionetParams['iterations']) criterion1 = torch.nn.MSELoss(reduction='mean') optimizer = torch.optim.Adam(model.parameters(), lr=1, weight_decay=0) resetState = optimizer.state.copy() mLoss = criterion1(torch.mean(Y, dim=0)*torch.ones(Y.shape), Y) print(mLoss) #Evaluate network stats = plotting.initProgressObject(maxIter) curState = torch.rand((N, model.network.bias.shape[0]), dtype=torch.double, requires_grad=False) e = 0 for e in range(e, maxIter): curLr = bionetwork.oneCycle(e, maxIter, maxHeight = 2e-3, minHeight = 1e-8, peak = 1000) optimizer.param_groups[0]['lr'] = curLr curLoss = [] curEig = [] trainloader = bionetwork.getSamples(N, batchSize) #max(10, round(N * e/maxIter) for dataIndex in trainloader: dataIn = X[dataIndex, :].view(len(dataIndex), X.shape[1]) dataOut = Y[dataIndex, :].view(len(dataIndex), Y.shape[1]) model.train() optimizer.zero_grad() Yin = model.inputLayer(dataIn) Yin = Yin + noiseLevel * curLr * torch.randn(Yin.shape) YhatFull = model.network(Yin) Yhat = model.projectionLayer(YhatFull) curState[dataIndex, :] = YhatFull.detach() fitLoss = criterion1(dataOut, Yhat) signConstraint = MoAFactor * torch.sum(torch.abs(model.network.weights[model.network.getViolations(model.network.weights)])) ligandConstraint = 1e-5 * torch.sum(torch.square(model.network.bias[model.inputLayer.nodeOrder])) stateLoss = 1e-4 * bionetwork.uniformLoss(curState, dataIndex, YhatFull, maxConstraintFactor = 50) biasLoss = 1e-8 * torch.sum(torch.square(model.network.bias)) weightLoss = 1e-8 * (torch.sum(torch.square(model.network.weights)) + torch.sum(1/(torch.square(model.network.weights) + 0.5))) spectralRadiusLoss, spectralRadius = bionetwork.spectralLoss(model, YhatFull, model.network.weights, expFactor = 21) loss = fitLoss + signConstraint + ligandConstraint + weightLoss + biasLoss + spectralFactor * spectralRadiusLoss + stateLoss# + rangeAplification + stdAmplification + meanAmplification + loss.backward() optimizer.step() curEig.append(spectralRadius.item()) curLoss.append(fitLoss.item()) stats['loss'][e] = numpy.mean(numpy.array(curLoss)) stats['lossSTD'][e] = numpy.std(numpy.array(curLoss)) stats['eig'][e] = numpy.mean(numpy.array(curEig)) stats['eigSTD'][e] = numpy.std(numpy.array(curEig)) stats['rate'][e] = optimizer.param_groups[0]['lr'] stats['violations'][e] = torch.sum(model.network.getViolations(model.network.weights)).item() if e % 100 == 0: plotting.printStats(e, stats) if numpy.logical_and(e % 200 == 0, e>0): optimizer.state = resetState.copy() stats = plotting.finishProgress(stats) model.eval() model(X) torch.save(model, 'synthNetScreen/model_' + str(curentId) + '.pt') torch.save(X, 'synthNetScreen/X_' + str(curentId) + '.pt')
[ "bionetwork.getSamples", "bionetwork.loadParam", "pandas.read_csv", "bionetwork.loadNetwork", "numpy.log", "torch.square", "torch.nn.MSELoss", "bionetwork.spectralLoss", "numpy.array", "bionetwork.uniformLoss", "bionetwork.oneCycle", "bionetwork.model", "argparse.ArgumentParser", "bionetwo...
[((118, 171), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""Macrophage simulation"""'}), "(prog='Macrophage simulation')\n", (141, 171), False, 'import argparse\n'), ((329, 405), 'pandas.read_csv', 'pandas.read_csv', (['"""synthNetScreen/conditions.tsv"""'], {'sep': '"""\t"""', 'low_memory': '(False)'}), "('synthNetScreen/conditions.tsv', sep='\\t', low_memory=False)\n", (344, 405), False, 'import pandas\n'), ((829, 877), 'bionetwork.loadNetwork', 'bionetwork.loadNetwork', (['"""data/KEGGnet-Model.tsv"""'], {}), "('data/KEGGnet-Model.tsv')\n", (851, 877), False, 'import bionetwork\n'), ((891, 947), 'pandas.read_csv', 'pandas.read_csv', (['"""data/KEGGnet-Annotation.tsv"""'], {'sep': '"""\t"""'}), "('data/KEGGnet-Annotation.tsv', sep='\\t')\n", (906, 947), False, 'import pandas\n'), ((963, 1031), 'bionetwork.trainingParameters', 'bionetwork.trainingParameters', ([], {'iterations': '(150)', 'clipping': '(1)', 'leak': '(0.01)'}), '(iterations=150, clipping=1, leak=0.01)\n', (992, 1031), False, 'import bionetwork\n'), ((1163, 1199), 'numpy.intersect1d', 'numpy.intersect1d', (['nodeNames', 'inName'], {}), '(nodeNames, inName)\n', (1180, 1199), False, 'import numpy\n'), ((1210, 1247), 'numpy.intersect1d', 'numpy.intersect1d', (['nodeNames', 'outName'], {}), '(nodeNames, outName)\n', (1227, 1247), False, 'import numpy\n'), ((1256, 1396), 'bionetwork.model', 'bionetwork.model', (['networkList', 'nodeNames', 'modeOfAction', 'inputAmplitude', 'projectionAmplitude', 'inName', 'outName', 'bionetParams', 'torch.double'], {}), '(networkList, nodeNames, modeOfAction, inputAmplitude,\n projectionAmplitude, inName, outName, bionetParams, torch.double)\n', (1272, 1396), False, 'import bionetwork\n'), ((1547, 1687), 'bionetwork.model', 'bionetwork.model', (['networkList', 'nodeNames', 'modeOfAction', 'inputAmplitude', 'projectionAmplitude', 'inName', 'outName', 'bionetParams', 'torch.double'], {}), '(networkList, nodeNames, modeOfAction, inputAmplitude,\n projectionAmplitude, inName, outName, bionetParams, torch.double)\n', (1563, 1687), False, 'import bionetwork\n'), ((1705, 1797), 'bionetwork.loadParam', 'bionetwork.loadParam', (['"""synthNetScreen/equationParams.txt"""', 'parameterizedModel', 'nodeNames'], {}), "('synthNetScreen/equationParams.txt',\n parameterizedModel, nodeNames)\n", (1725, 1797), False, 'import bionetwork\n'), ((2324, 2358), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (2340, 2358), False, 'import torch\n'), ((2572, 2608), 'plotting.initProgressObject', 'plotting.initProgressObject', (['maxIter'], {}), '(maxIter)\n', (2599, 2608), False, 'import plotting\n'), ((2621, 2710), 'torch.rand', 'torch.rand', (['(N, model.network.bias.shape[0])'], {'dtype': 'torch.double', 'requires_grad': '(False)'}), '((N, model.network.bias.shape[0]), dtype=torch.double,\n requires_grad=False)\n', (2631, 2710), False, 'import torch\n'), ((5054, 5084), 'plotting.finishProgress', 'plotting.finishProgress', (['stats'], {}), '(stats)\n', (5077, 5084), False, 'import plotting\n'), ((1966, 1999), 'torch.rand', 'torch.rand', (['(1)'], {'dtype': 'torch.double'}), '(1, dtype=torch.double)\n', (1976, 1999), False, 'import torch\n'), ((2109, 2162), 'torch.rand', 'torch.rand', (['(simultaniousInput - 1)'], {'dtype': 'torch.double'}), '(simultaniousInput - 1, dtype=torch.double)\n', (2119, 2162), False, 'import torch\n'), ((2753, 2829), 'bionetwork.oneCycle', 'bionetwork.oneCycle', (['e', 'maxIter'], {'maxHeight': '(0.002)', 'minHeight': '(1e-08)', 'peak': '(1000)'}), '(e, maxIter, maxHeight=0.002, minHeight=1e-08, peak=1000)\n', (2772, 2829), False, 'import bionetwork\n'), ((2930, 2965), 'bionetwork.getSamples', 'bionetwork.getSamples', (['N', 'batchSize'], {}), '(N, batchSize)\n', (2951, 2965), False, 'import bionetwork\n'), ((4963, 5001), 'numpy.logical_and', 'numpy.logical_and', (['(e % 200 == 0)', '(e > 0)'], {}), '(e % 200 == 0, e > 0)\n', (4980, 5001), False, 'import numpy\n'), ((2265, 2284), 'numpy.log', 'numpy.log', (['(10 ** -2)'], {}), '(10 ** -2)\n', (2274, 2284), False, 'import numpy\n'), ((2487, 2507), 'torch.mean', 'torch.mean', (['Y'], {'dim': '(0)'}), '(Y, dim=0)\n', (2497, 2507), False, 'import torch\n'), ((2508, 2527), 'torch.ones', 'torch.ones', (['Y.shape'], {}), '(Y.shape)\n', (2518, 2527), False, 'import torch\n'), ((4104, 4181), 'bionetwork.spectralLoss', 'bionetwork.spectralLoss', (['model', 'YhatFull', 'model.network.weights'], {'expFactor': '(21)'}), '(model, YhatFull, model.network.weights, expFactor=21)\n', (4127, 4181), False, 'import bionetwork\n'), ((4552, 4572), 'numpy.array', 'numpy.array', (['curLoss'], {}), '(curLoss)\n', (4563, 4572), False, 'import numpy\n'), ((4610, 4630), 'numpy.array', 'numpy.array', (['curLoss'], {}), '(curLoss)\n', (4621, 4630), False, 'import numpy\n'), ((4665, 4684), 'numpy.array', 'numpy.array', (['curEig'], {}), '(curEig)\n', (4676, 4684), False, 'import numpy\n'), ((4721, 4740), 'numpy.array', 'numpy.array', (['curEig'], {}), '(curEig)\n', (4732, 4740), False, 'import numpy\n'), ((4925, 4954), 'plotting.printStats', 'plotting.printStats', (['e', 'stats'], {}), '(e, stats)\n', (4944, 4954), False, 'import plotting\n'), ((3772, 3849), 'bionetwork.uniformLoss', 'bionetwork.uniformLoss', (['curState', 'dataIndex', 'YhatFull'], {'maxConstraintFactor': '(50)'}), '(curState, dataIndex, YhatFull, maxConstraintFactor=50)\n', (3794, 3849), False, 'import bionetwork\n'), ((3298, 3320), 'torch.randn', 'torch.randn', (['Yin.shape'], {}), '(Yin.shape)\n', (3309, 3320), False, 'import torch\n'), ((3681, 3741), 'torch.square', 'torch.square', (['model.network.bias[model.inputLayer.nodeOrder]'], {}), '(model.network.bias[model.inputLayer.nodeOrder])\n', (3693, 3741), False, 'import torch\n'), ((3888, 3920), 'torch.square', 'torch.square', (['model.network.bias'], {}), '(model.network.bias)\n', (3900, 3920), False, 'import torch\n'), ((3961, 3996), 'torch.square', 'torch.square', (['model.network.weights'], {}), '(model.network.weights)\n', (3973, 3996), False, 'import torch\n'), ((4013, 4048), 'torch.square', 'torch.square', (['model.network.weights'], {}), '(model.network.weights)\n', (4025, 4048), False, 'import torch\n')]
import numpy as np import cv2 import glob # termination criteria #criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((7*7,3), np.float32) objp[:,:2] = np.mgrid[0:7,0:7].T.reshape(-1,2) # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. cap = cv2.VideoCapture(0) print('obtendo pontos') count = 0 while count < 50: ret, img = cap.read() if not ret: break gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (7,7), None) # If found, add object points, image points (after refining them) if ret == True: count += 1 objpoints.append(objp) #corners2 = cv2.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria) imgpoints.append(corners) # Draw and display the corners #cv2.drawChessboardCorners(gray, (7,7), corners2, ret) print(gray.shape) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.imshow("Window", gray) cv2.destroyAllWindows() print('calibrando camera...') ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None) print('escrevendo output') if ret: output = cv2.FileStorage('intrinsic.yml', cv2.FILE_STORAGE_WRITE) output.write('mtx', mtx) output.write('dist', dist) output.release()
[ "cv2.FileStorage", "cv2.imshow", "numpy.zeros", "cv2.destroyAllWindows", "cv2.VideoCapture", "cv2.cvtColor", "cv2.calibrateCamera", "cv2.findChessboardCorners", "cv2.waitKey" ]
[((217, 249), 'numpy.zeros', 'np.zeros', (['(7 * 7, 3)', 'np.float32'], {}), '((7 * 7, 3), np.float32)\n', (225, 249), True, 'import numpy as np\n'), ((459, 478), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (475, 478), False, 'import cv2\n'), ((1201, 1224), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1222, 1224), False, 'import cv2\n'), ((1288, 1359), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['objpoints', 'imgpoints', 'gray.shape[::-1]', 'None', 'None'], {}), '(objpoints, imgpoints, gray.shape[::-1], None, None)\n', (1307, 1359), False, 'import cv2\n'), ((600, 637), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (612, 637), False, 'import cv2\n'), ((692, 737), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['gray', '(7, 7)', 'None'], {}), '(gray, (7, 7), None)\n', (717, 737), False, 'import cv2\n'), ((1174, 1200), 'cv2.imshow', 'cv2.imshow', (['"""Window"""', 'gray'], {}), "('Window', gray)\n", (1184, 1200), False, 'import cv2\n'), ((1410, 1466), 'cv2.FileStorage', 'cv2.FileStorage', (['"""intrinsic.yml"""', 'cv2.FILE_STORAGE_WRITE'], {}), "('intrinsic.yml', cv2.FILE_STORAGE_WRITE)\n", (1425, 1466), False, 'import cv2\n'), ((1121, 1135), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1132, 1135), False, 'import cv2\n')]
# -*- coding: utf-8 -*- """ Widget for exporting / importing and saving / loading filter data Author: <NAME> """ from __future__ import print_function, division, unicode_literals, absolute_import import sys, os, io import logging logger = logging.getLogger(__name__) from pyfda.pyfda_qt_lib import (qstyle_widget, qset_cmb_box, qget_cmb_box, qstr, qcopy_to_clipboard, qcopy_from_clipboard, qget_selected) from pyfda.pyfda_lib import PY3 from ..compat import (QtCore, QFD, Qt, QWidget, QPushButton, QComboBox, QLabel, QFont, QFrame, QVBoxLayout, QHBoxLayout) import scipy.io import numpy as np import datetime try: import cPickle as pickle except: import pickle try: import xlwt except ImportError: XLWT = False logger.info("Module xlwt not installed -> no *.xls coefficient export") else: XLWT = True try: import XlsxWriter as xlsx except ImportError: XLSX = False logger.info("Module XlsxWriter not installed -> no *.xlsx coefficient export") else: XLSX = True #try: # import xlrd #except ImportError: # XLRD = False # logger.info("Module xlrd not installed -> no *.xls coefficient import") #else: # XLRD = True import pyfda.filterbroker as fb # importing filterbroker initializes all its globals import pyfda.pyfda_rc as rc import pyfda.pyfda_fix_lib as fix_lib from pyfda.pyfda_lib import extract_file_ext # TODO: Save P/Z as well if possible class File_IO(QWidget): """ Create the widget for entering exporting / importing / saving / loading data """ sigFilterLoaded = QtCore.pyqtSignal() # emitted when filter has been loaded successfully def __init__(self, parent): super(File_IO, self).__init__(parent) self._construct_UI() def _construct_UI(self): """ Intitialize the user interface - """ # widget / subwindow for parameter selection self.butExport = QPushButton("Export Coefficients", self) self.butExport.setToolTip("Export Coefficients in various formats.") self.butImport = QPushButton("Import Coefficients", self) self.butImport.setToolTip("Import Coefficients in various formats.") self.butSave = QPushButton("Save Filter", self) self.butLoad = QPushButton("Load Filter", self) lblSeparator = QLabel("CSV-Separator:") self.cmbSeparator = QComboBox(self) self.cmbSeparator.addItems(['","','";"','<TAB>','<CR>']) self.cmbSeparator.setToolTip("Specify separator for number fields.") # ============== UI Layout ===================================== bfont = QFont() bfont.setBold(True) bifont = QFont() bifont.setBold(True) bifont.setItalic(True) ifont = QFont() ifont.setItalic(True) layVIO = QVBoxLayout() layVIO.addWidget(self.butSave) # save filter dict -> various formats layVIO.addWidget(self.butLoad) # load filter dict -> various formats layVIO.addStretch(1) layVIO.addWidget(self.butExport) # export coeffs -> various formats layVIO.addWidget(self.butImport) # export coeffs -> various formats layVIO.addStretch(1) layHIO = QHBoxLayout() layHIO.addWidget(lblSeparator) layHIO.addWidget(self.cmbSeparator) layVIO.addLayout(layHIO) layVIO.addStretch(20) # This is the top level widget, encompassing the other widgets frmMain = QFrame(self) frmMain.setLayout(layVIO) layVMain = QVBoxLayout() layVMain.setAlignment(Qt.AlignTop) # layVMain.addLayout(layVIO) layVMain.addWidget(frmMain) layVMain.setContentsMargins(*rc.params['wdg_margins']) self.setLayout(layVMain) #---------------------------------------------------------------------- # SIGNALS & SLOTs #---------------------------------------------------------------------- self.butExport.clicked.connect(self.export_coeffs) self.butImport.clicked.connect(self.import_coeffs) self.butSave.clicked.connect(self.save_filter) self.butLoad.clicked.connect(self.load_filter) #------------------------------------------------------------------------------ def load_filter(self): """ Load filter from zipped binary numpy array or (c)pickled object to filter dictionary and update input and plot widgets """ file_filters = ("Zipped Binary Numpy Array (*.npz);;Pickled (*.pkl)") dlg = QFD(self) file_name, file_type = dlg.getOpenFileName_( caption = "Load filter ", directory = rc.save_dir, filter = file_filters) file_name = str(file_name) # QString -> str for t in extract_file_ext(file_filters): # get a list of file extensions if t in str(file_type): file_type = t if file_name != "": # cancelled file operation returns empty string # strip extension from returned file name (if any) + append file type: file_name = os.path.splitext(file_name)[0] + file_type file_type_err = False try: with io.open(file_name, 'rb') as f: if file_type == '.npz': # http://stackoverflow.com/questions/22661764/storing-a-dict-with-np-savez-gives-unexpected-result a = np.load(f) # array containing dict, dtype 'object' for key in a: if np.ndim(a[key]) == 0: # scalar objects may be extracted with the item() method fb.fil[0][key] = a[key].item() else: # array objects are converted to list first fb.fil[0][key] = a[key].tolist() elif file_type == '.pkl': if sys.version_info[0] < 3: fb.fil = pickle.load(f) else: # this only works for python >= 3.3 fb.fil = pickle.load(f, fix_imports = True, encoding = 'bytes') else: logger.error('Unknown file type "%s"', file_type) file_type_err = True if not file_type_err: logger.info('Loaded filter "%s"', file_name) # emit signal -> InputTabWidgets.load_all: self.sigFilterLoaded.emit() rc.save_dir = os.path.dirname(file_name) except IOError as e: logger.error("Failed loading %s!\n%s", file_name, e) except Exception as e: logger.error("Unexpected error:", e) #------------------------------------------------------------------------------ def save_filter(self): """ Save filter as zipped binary numpy array or pickle object """ file_filters = ("Zipped Binary Numpy Array (*.npz);;Pickled (*.pkl)") dlg = QFD(self) # return selected file name (with or without extension) and filter (Linux: full text) file_name, file_type = dlg.getSaveFileName_( caption = "Save filter as", directory = rc.save_dir, filter = file_filters) file_name = str(file_name) # QString -> str() needed for Python 2.x # Qt5 has QFileDialog.mimeTypeFilters(), but under Qt4 the mime type cannot # be extracted reproducibly across file systems, so it is done manually: for t in extract_file_ext(file_filters): # get a list of file extensions if t in str(file_type): file_type = t # return the last matching extension if file_name != "": # cancelled file operation returns empty string # strip extension from returned file name (if any) + append file type: file_name = os.path.splitext(file_name)[0] + file_type file_type_err = False try: with io.open(file_name, 'wb') as f: if file_type == '.npz': np.savez(f, **fb.fil[0]) elif file_type == '.pkl': # save as a pickle version compatible with Python 2.x pickle.dump(fb.fil, f, protocol = 2) else: file_type_err = True logger.error('Unknown file type "%s"', file_type) if not file_type_err: logger.info('Filter saved as "%s"', file_name) rc.save_dir = os.path.dirname(file_name) # save new dir except IOError as e: logger.error('Failed saving "%s"!\n%s\n', file_name, e) #------------------------------------------------------------------------------ def export_coeffs(self): """ Export filter coefficients in various formats - see also Summerfield p. 192 ff """ dlg = QFD(self) file_filters = ("CSV (*.csv);;Matlab-Workspace (*.mat)" ";;Binary Numpy Array (*.npy);;Zipped Binary Numpy Array (*.npz)") if fb.fil[0]['ft'] == 'FIR': file_filters += ";;Xilinx coefficient format (*.coe)" # Add further file types when modules are available: if XLWT: file_filters += ";;Excel Worksheet (.xls)" if XLSX: file_filters += ";;Excel 2007 Worksheet (.xlsx)" # return selected file name (with or without extension) and filter (Linux: full text) file_name, file_type = dlg.getSaveFileName_( caption = "Export filter coefficients as", directory = rc.save_dir, filter = file_filters) file_name = str(file_name) # QString -> str needed for Python 2 for t in extract_file_ext(file_filters): # extract the list of file extensions if t in str(file_type): file_type = t if file_name != '': # cancelled file operation returns empty string # strip extension from returned file name (if any) + append file type: file_name = os.path.splitext(file_name)[0] + file_type ba = fb.fil[0]['ba'] file_type_err = False try: if file_type == '.coe': # text / string format with io.open(file_name, 'w', encoding="utf8") as f: self.save_file_coe(f) else: # binary format with io.open(file_name, 'wb') as f: if file_type == '.mat': scipy.io.savemat(f, mdict={'ba':fb.fil[0]['ba']}) elif file_type == '.csv': np.savetxt(f, ba, delimiter = ', ') # newline='\n', header='', footer='', comments='# ', fmt='%.18e' elif file_type == '.npy': # can only store one array in the file: np.save(f, ba) elif file_type == '.npz': # would be possible to store multiple arrays in the file np.savez(f, ba = ba) elif file_type == '.xls': # see # http://www.dev-explorer.com/articles/excel-spreadsheets-and-python # https://github.com/python-excel/xlwt/blob/master/xlwt/examples/num_formats.py # http://reliablybroken.com/b/2011/07/styling-your-excel-data-with-xlwt/ workbook = xlwt.Workbook(encoding="utf-8") worksheet = workbook.add_sheet("Python Sheet 1") bold = xlwt.easyxf('font: bold 1') worksheet.write(0, 0, 'b', bold) worksheet.write(0, 1, 'a', bold) for col in range(2): for row in range(np.shape(ba)[1]): worksheet.write(row+1, col, ba[col][row]) # vertical workbook.save(f) elif file_type == '.xlsx': # from https://pypi.python.org/pypi/XlsxWriter # Create an new Excel file and add a worksheet. workbook = xlsx.Workbook(f) worksheet = workbook.add_worksheet() # Widen the first column to make the text clearer. worksheet.set_column('A:A', 20) # Add a bold format to use to highlight cells. bold = workbook.add_format({'bold': True}) # Write labels with formatting. worksheet.write('A1', 'b', bold) worksheet.write('B1', 'a', bold) # Write some numbers, with row/column notation. for col in range(2): for row in range(np.shape(ba)[1]): worksheet.write(row+1, col, ba[col][row]) # vertical # worksheet.write(row, col, coeffs[col][row]) # horizontal # Insert an image - useful for documentation export ?!. # worksheet.insert_image('B5', 'logo.png') workbook.close() else: logger.error('Unknown file type "%s"', file_type) file_type_err = True if not file_type_err: logger.info('Filter saved as "%s"', file_name) rc.save_dir = os.path.dirname(file_name) # save new dir except IOError as e: logger.error('Failed saving "%s"!\n%s\n', file_name, e) # Download the Simple ods py module: # http://simple-odspy.sourceforge.net/ # http://codextechnicanum.blogspot.de/2014/02/write-ods-for-libreoffice-calc-from_1.html #------------------------------------------------------------------------------ def import_coeffs(self): """ Import filter coefficients from a file """ file_filters = ("Matlab-Workspace (*.mat);;Binary Numpy Array (*.npy);;" "Zipped Binary Numpy Array(*.npz);;Comma / Tab Separated Values (*.csv)") dlg = QFD(self) file_name, file_type = dlg.getOpenFileName_( caption = "Import filter coefficients ", directory = rc.save_dir, filter = file_filters) file_name = str(file_name) # QString -> str for t in extract_file_ext(file_filters): # extract the list of file extensions if t in str(file_type): file_type = t if file_name != '': # cancelled file operation returns empty string # strip extension from returned file name (if any) + append file type: file_name = os.path.splitext(file_name)[0] + file_type file_type_err = False try: if file_type == '.csv': if PY3: mode = 'r'# don't read in binary mode (data as bytes) under Py 3 else: mode = 'rb' # do read in binary mode under Py 2 (why?!) with io.open(file_name, mode) as f: fb.fil[0]['ba'] = qcopy_from_clipboard(f) else: with io.open(file_name, 'rb') as f: if file_type == '.mat': data = scipy.io.loadmat(f) fb.fil[0]['ba'] = data['ba'] elif file_type == '.npy': fb.fil[0]['ba'] = np.load(f) # can only store one array in the file elif file_type == '.npz': fb.fil[0]['ba'] = np.load(f)['ba'] # would be possible to store several arrays in one file else: logger.error('Unknown file type "%s"', file_type) file_type_err = True if not file_type_err: logger.info('Loaded coefficient file\n"%s"', file_name) self.sigFilterLoaded.emit() rc.save_dir = os.path.dirname(file_name) except IOError as e: logger.error("Failed loading %s!\n%s", file_name, e) #------------------------------------------------------------------------------ def save_file_coe(self, file_name): """ Save filter coefficients in Xilinx coefficient format, specifying the number base and the quantized coefficients """ frmt = fb.fil[0]['q_coeff']['frmt'] # store old format fb.fil[0]['q_coeff']['frmt'] = 'int' # 'hex' qc = fix_lib.Fixed(fb.fil[0]['q_coeff']) bq = qc.fix(fb.fil[0]['ba'][0]) # Quantize coefficients to integer format coe_width = qc.WF + qc.WI + 1 # quantized word length; Int. + Frac. + Sign bit if fb.fil[0]['q_coeff']['frmt'] == 'int': coe_radix = 10 else: coe_radix = 16 fb.fil[0]['q_coeff']['frmt'] = frmt # restore old coefficient format info_str = ( "; #############################################################################\n" ";\n; XILINX CORE Generator(tm) Distributed Arithmetic FIR filter coefficient (.COE) file\n" ";\n; Generated by pyFDA 0.1 (https://github.com/chipmuenk/pyfda)\n;\n; ") date_str = datetime.datetime.now().strftime("%d-%B-%Y %H:%M:%S") file_name.write(info_str + date_str + "\n;\n") filt_str = "; Filter order = %d, type: %s\n" %(fb.fil[0]["N"], fb.fil[0]['rt']) file_name.write(filt_str) file_name.write("; #############################################################################\n") file_name.write("Radix = %d;\n" %coe_radix) file_name.write("Coefficient_width = %d;\n" %coe_width) coeff_str = "CoefData = " for b in bq: coeff_str += str(b) + ",\n" file_name.write(coeff_str[:-2] + ";") # replace last "," by ";" #------------------------------------------------------------------------------ if __name__ == '__main__': from ..compat import QApplication app = QApplication(sys.argv) mainw = File_IO(None) app.setActiveWindow(mainw) mainw.show() sys.exit(app.exec_())
[ "logging.getLogger", "pyfda.pyfda_fix_lib.Fixed", "io.open", "XlsxWriter.Workbook", "numpy.save", "numpy.savez", "pyfda.pyfda_qt_lib.qcopy_from_clipboard", "pyfda.pyfda_lib.extract_file_ext", "numpy.ndim", "xlwt.easyxf", "os.path.splitext", "pickle.load", "os.path.dirname", "numpy.savetxt"...
[((240, 267), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (257, 267), False, 'import logging\n'), ((4845, 4875), 'pyfda.pyfda_lib.extract_file_ext', 'extract_file_ext', (['file_filters'], {}), '(file_filters)\n', (4861, 4875), False, 'from pyfda.pyfda_lib import extract_file_ext\n'), ((7750, 7780), 'pyfda.pyfda_lib.extract_file_ext', 'extract_file_ext', (['file_filters'], {}), '(file_filters)\n', (7766, 7780), False, 'from pyfda.pyfda_lib import extract_file_ext\n'), ((10060, 10090), 'pyfda.pyfda_lib.extract_file_ext', 'extract_file_ext', (['file_filters'], {}), '(file_filters)\n', (10076, 10090), False, 'from pyfda.pyfda_lib import extract_file_ext\n'), ((15089, 15119), 'pyfda.pyfda_lib.extract_file_ext', 'extract_file_ext', (['file_filters'], {}), '(file_filters)\n', (15105, 15119), False, 'from pyfda.pyfda_lib import extract_file_ext\n'), ((17390, 17425), 'pyfda.pyfda_fix_lib.Fixed', 'fix_lib.Fixed', (["fb.fil[0]['q_coeff']"], {}), "(fb.fil[0]['q_coeff'])\n", (17403, 17425), True, 'import pyfda.pyfda_fix_lib as fix_lib\n'), ((18122, 18145), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (18143, 18145), False, 'import datetime\n'), ((5160, 5187), 'os.path.splitext', 'os.path.splitext', (['file_name'], {}), '(file_name)\n', (5176, 5187), False, 'import sys, os, io\n'), ((5276, 5300), 'io.open', 'io.open', (['file_name', '"""rb"""'], {}), "(file_name, 'rb')\n", (5283, 5300), False, 'import sys, os, io\n'), ((8112, 8139), 'os.path.splitext', 'os.path.splitext', (['file_name'], {}), '(file_name)\n', (8128, 8139), False, 'import sys, os, io\n'), ((8228, 8252), 'io.open', 'io.open', (['file_name', '"""wb"""'], {}), "(file_name, 'wb')\n", (8235, 8252), False, 'import sys, os, io\n'), ((10380, 10407), 'os.path.splitext', 'os.path.splitext', (['file_name'], {}), '(file_name)\n', (10396, 10407), False, 'import sys, os, io\n'), ((15410, 15437), 'os.path.splitext', 'os.path.splitext', (['file_name'], {}), '(file_name)\n', (15426, 15437), False, 'import sys, os, io\n'), ((16855, 16881), 'os.path.dirname', 'os.path.dirname', (['file_name'], {}), '(file_name)\n', (16870, 16881), False, 'import sys, os, io\n'), ((5502, 5512), 'numpy.load', 'np.load', (['f'], {}), '(f)\n', (5509, 5512), True, 'import numpy as np\n'), ((6718, 6744), 'os.path.dirname', 'os.path.dirname', (['file_name'], {}), '(file_name)\n', (6733, 6744), False, 'import sys, os, io\n'), ((8327, 8351), 'numpy.savez', 'np.savez', (['f'], {}), '(f, **fb.fil[0])\n', (8335, 8351), True, 'import numpy as np\n'), ((8834, 8860), 'os.path.dirname', 'os.path.dirname', (['file_name'], {}), '(file_name)\n', (8849, 8860), False, 'import sys, os, io\n'), ((10597, 10637), 'io.open', 'io.open', (['file_name', '"""w"""'], {'encoding': '"""utf8"""'}), "(file_name, 'w', encoding='utf8')\n", (10604, 10637), False, 'import sys, os, io\n'), ((10753, 10777), 'io.open', 'io.open', (['file_name', '"""wb"""'], {}), "(file_name, 'wb')\n", (10760, 10777), False, 'import sys, os, io\n'), ((15793, 15817), 'io.open', 'io.open', (['file_name', 'mode'], {}), '(file_name, mode)\n', (15800, 15817), False, 'import sys, os, io\n'), ((15867, 15890), 'pyfda.pyfda_qt_lib.qcopy_from_clipboard', 'qcopy_from_clipboard', (['f'], {}), '(f)\n', (15887, 15890), False, 'from pyfda.pyfda_qt_lib import qstyle_widget, qset_cmb_box, qget_cmb_box, qstr, qcopy_to_clipboard, qcopy_from_clipboard, qget_selected\n'), ((15939, 15963), 'io.open', 'io.open', (['file_name', '"""rb"""'], {}), "(file_name, 'rb')\n", (15946, 15963), False, 'import sys, os, io\n'), ((8500, 8534), 'pickle.dump', 'pickle.dump', (['fb.fil', 'f'], {'protocol': '(2)'}), '(fb.fil, f, protocol=2)\n', (8511, 8534), False, 'import pickle\n'), ((14126, 14152), 'os.path.dirname', 'os.path.dirname', (['file_name'], {}), '(file_name)\n', (14141, 14152), False, 'import sys, os, io\n'), ((5623, 5638), 'numpy.ndim', 'np.ndim', (['a[key]'], {}), '(a[key])\n', (5630, 5638), True, 'import numpy as np\n'), ((6107, 6121), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (6118, 6121), False, 'import pickle\n'), ((6249, 6299), 'pickle.load', 'pickle.load', (['f'], {'fix_imports': '(True)', 'encoding': '"""bytes"""'}), "(f, fix_imports=True, encoding='bytes')\n", (6260, 6299), False, 'import pickle\n'), ((10988, 11021), 'numpy.savetxt', 'np.savetxt', (['f', 'ba'], {'delimiter': '""", """'}), "(f, ba, delimiter=', ')\n", (10998, 11021), True, 'import numpy as np\n'), ((16226, 16236), 'numpy.load', 'np.load', (['f'], {}), '(f)\n', (16233, 16236), True, 'import numpy as np\n'), ((11263, 11277), 'numpy.save', 'np.save', (['f', 'ba'], {}), '(f, ba)\n', (11270, 11277), True, 'import numpy as np\n'), ((11441, 11459), 'numpy.savez', 'np.savez', (['f'], {'ba': 'ba'}), '(f, ba=ba)\n', (11449, 11459), True, 'import numpy as np\n'), ((16400, 16410), 'numpy.load', 'np.load', (['f'], {}), '(f)\n', (16407, 16410), True, 'import numpy as np\n'), ((11891, 11922), 'xlwt.Workbook', 'xlwt.Workbook', ([], {'encoding': '"""utf-8"""'}), "(encoding='utf-8')\n", (11904, 11922), False, 'import xlwt\n'), ((12035, 12062), 'xlwt.easyxf', 'xlwt.easyxf', (['"""font: bold 1"""'], {}), "('font: bold 1')\n", (12046, 12062), False, 'import xlwt\n'), ((12677, 12693), 'XlsxWriter.Workbook', 'xlsx.Workbook', (['f'], {}), '(f)\n', (12690, 12693), True, 'import XlsxWriter as xlsx\n'), ((12283, 12295), 'numpy.shape', 'np.shape', (['ba'], {}), '(ba)\n', (12291, 12295), True, 'import numpy as np\n'), ((13401, 13413), 'numpy.shape', 'np.shape', (['ba'], {}), '(ba)\n', (13409, 13413), True, 'import numpy as np\n')]
import cv2 import numpy as np import strel # Fonction permettant de realiser l'erosion d'une image par un element structurant def erosion(image, element_structurant): return cv2.erode(image, element_structurant) # Fonction permettant de realiser la dilatation d'une image par un element structurant def dilatation(image, element_structurant): return cv2.dilate(image, element_structurant) # Fonction permettant de realiser l'ouverture d'une image par un element structurant def ouverture(image, element_structurant): return dilatation(erosion(image, element_structurant), element_structurant) # Fonction permettant de realiser la fermeture d'une image par un element structurant def fermeture(image, element_structurant): return erosion(dilatation(image, element_structurant), element_structurant) # Fonction permettant de calculer le gradient morphologique d'une image (par rapport a un element structurant) def gradient(image, element_structurant): return dilatation(image, element_structurant) - erosion(image, element_structurant) # Fonction permettant de realiser la reconstructions inferieure d'un marqueur dans une image, a l'aide d'un element structurant def reconstruction_inferieure(image, marqueur, element_structurant): backup = marqueur dil = np.minimum(image, dilatation(backup, element_structurant)) while( not np.array_equal(backup, dil)): backup = dil dil = np.minimum(image, dilatation(backup, element_structurant)) return dil # Fonction permettant de realiser l'ouverture par reconstruction d'une image def ouverture_reconstruction(image, element_ouverture, element_reconstruction): op = ouverture(image, element_ouverture) return reconstruction_inferieure(image, op, element_reconstruction) #Fonction permettant de realiser le h-maxima d'une image #Prend en parametre l'image, le niveau h, et l'element structurant a utiliser pour la reconstruction def hmaxima(image, h, element_reconstruction): #On rehausse toutes les valeurs de image inferieure a h, a la valeur h image = np.maximum(np.ones(image.shape, image.dtype)*h, image) #On soustrait h a image image2 = image - h #A completer return reconstruction_inferieure(image, image2, element_reconstruction) #Fonction permettant de compter les composantes 8 connexes d'une image binaire #Prend en parametre l'image binaire def compter_morceaux(image_binaire): result = np.zeros(image_binaire.shape, np.uint32) masque = np.zeros(image_binaire.shape, image_binaire.dtype) compteur=0 for i in range(0, image_binaire.shape[0]): for j in range(0, image_binaire.shape[1]): if(image_binaire[i,j] > 0): compteur = compteur + 1 masque[i,j]=image_binaire[i,j] r = reconstruction_inferieure(image_binaire, masque, strel.build('carre', 1, None)) image_binaire = image_binaire - r r = r / np.iinfo(image_binaire.dtype).max * compteur result = np.maximum(result, r) masque[i,j]=0 return result, compteur #Fonction permettant de realiser le seuil d'une image #Prend en parametre l'image ainsi que la valeur du seuil def seuil(image, seuil): image[image < seuil] = 0 image[image >= seuil] = 255 return image
[ "numpy.ones", "cv2.erode", "numpy.iinfo", "numpy.zeros", "numpy.array_equal", "numpy.maximum", "cv2.dilate", "strel.build" ]
[((181, 218), 'cv2.erode', 'cv2.erode', (['image', 'element_structurant'], {}), '(image, element_structurant)\n', (190, 218), False, 'import cv2\n'), ((363, 401), 'cv2.dilate', 'cv2.dilate', (['image', 'element_structurant'], {}), '(image, element_structurant)\n', (373, 401), False, 'import cv2\n'), ((2450, 2490), 'numpy.zeros', 'np.zeros', (['image_binaire.shape', 'np.uint32'], {}), '(image_binaire.shape, np.uint32)\n', (2458, 2490), True, 'import numpy as np\n'), ((2504, 2554), 'numpy.zeros', 'np.zeros', (['image_binaire.shape', 'image_binaire.dtype'], {}), '(image_binaire.shape, image_binaire.dtype)\n', (2512, 2554), True, 'import numpy as np\n'), ((1372, 1399), 'numpy.array_equal', 'np.array_equal', (['backup', 'dil'], {}), '(backup, dil)\n', (1386, 1399), True, 'import numpy as np\n'), ((2094, 2127), 'numpy.ones', 'np.ones', (['image.shape', 'image.dtype'], {}), '(image.shape, image.dtype)\n', (2101, 2127), True, 'import numpy as np\n'), ((3039, 3060), 'numpy.maximum', 'np.maximum', (['result', 'r'], {}), '(result, r)\n', (3049, 3060), True, 'import numpy as np\n'), ((2864, 2893), 'strel.build', 'strel.build', (['"""carre"""', '(1)', 'None'], {}), "('carre', 1, None)\n", (2875, 2893), False, 'import strel\n'), ((2969, 2998), 'numpy.iinfo', 'np.iinfo', (['image_binaire.dtype'], {}), '(image_binaire.dtype)\n', (2977, 2998), True, 'import numpy as np\n')]
import numpy as np import cv2 as cv # function to read image at a given path def readImage(path): return cv.imread(path, cv.CV_8UC1) # function to save image using given image name def saveImage(img, image_name): cv.imwrite(image_name, img) # function to show image until user pressed any key to close it def showImage(img): cv.imshow('img', img) cv.waitKey(0) # ones-kernel of dimensions size*size def blockKernel(size): return np.ones((size, size), np.uint8) # disk kernel of radius "size" def diskKernel(size): return cv.getStructuringElement(cv.MORPH_ELLIPSE, (2*size - 1, 2*size - 1)) path = 'line.bmp' # read image from given path img = readImage(path) # apply opening operation to remove lines/rectangles openImg = cv.morphologyEx(img, cv.MORPH_OPEN, diskKernel(6)) # save output of opening saveImage(openImg, '2_open.jpg') # find number of connected components in the image output = cv.connectedComponentsWithStats(np.uint8(openImg), 4, cv.CV_32S) num_labels = output[0] # number of circles = number of connected components - 1 print("Number of circles:",num_labels - 1)
[ "numpy.uint8", "cv2.imwrite", "numpy.ones", "cv2.imshow", "cv2.getStructuringElement", "cv2.waitKey", "cv2.imread" ]
[((110, 137), 'cv2.imread', 'cv.imread', (['path', 'cv.CV_8UC1'], {}), '(path, cv.CV_8UC1)\n', (119, 137), True, 'import cv2 as cv\n'), ((220, 247), 'cv2.imwrite', 'cv.imwrite', (['image_name', 'img'], {}), '(image_name, img)\n', (230, 247), True, 'import cv2 as cv\n'), ((334, 355), 'cv2.imshow', 'cv.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (343, 355), True, 'import cv2 as cv\n'), ((357, 370), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (367, 370), True, 'import cv2 as cv\n'), ((441, 472), 'numpy.ones', 'np.ones', (['(size, size)', 'np.uint8'], {}), '((size, size), np.uint8)\n', (448, 472), True, 'import numpy as np\n'), ((535, 607), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_ELLIPSE', '(2 * size - 1, 2 * size - 1)'], {}), '(cv.MORPH_ELLIPSE, (2 * size - 1, 2 * size - 1))\n', (559, 607), True, 'import cv2 as cv\n'), ((938, 955), 'numpy.uint8', 'np.uint8', (['openImg'], {}), '(openImg)\n', (946, 955), True, 'import numpy as np\n')]
import unittest from frds.measures import general import numpy as np class KyleLambdaCase(unittest.TestCase): def test_lamdba(self): volumes = np.array( [ [100, 180, 900, 970, 430, 110], [300, 250, 400, 590, 260, 600], [200, 700, 220, 110, 290, 310], ] ) prices = np.array( [ [44, 39, 36, 28, 23, 18], [82, 81, 79, 40, 26, 13], [55, 67, 13, 72, 10, 65], ] ) mil = np.mean(general.kyle_lambda(prices, volumes)) self.assertAlmostEqual(mil, 0.0035, 4) class HHIIndexCase(unittest.TestCase): def test_hhi_index(self): self.assertEqual(general.hhi_index(np.array([1, 1])), 0.5) self.assertAlmostEqual( general.hhi_index(np.array([1, 1, 100, 1, 1, 1, 1])), 0.8905, 4 ) def test_weighted_hhi_index(self): self.assertEqual( general.hhi_index(np.array([1, 1]), weights=np.array([1, 0])), 0.25 )
[ "numpy.array", "frds.measures.general.kyle_lambda" ]
[((157, 268), 'numpy.array', 'np.array', (['[[100, 180, 900, 970, 430, 110], [300, 250, 400, 590, 260, 600], [200, 700,\n 220, 110, 290, 310]]'], {}), '([[100, 180, 900, 970, 430, 110], [300, 250, 400, 590, 260, 600], [\n 200, 700, 220, 110, 290, 310]])\n', (165, 268), True, 'import numpy as np\n'), ((366, 459), 'numpy.array', 'np.array', (['[[44, 39, 36, 28, 23, 18], [82, 81, 79, 40, 26, 13], [55, 67, 13, 72, 10, 65]]'], {}), '([[44, 39, 36, 28, 23, 18], [82, 81, 79, 40, 26, 13], [55, 67, 13, \n 72, 10, 65]])\n', (374, 459), True, 'import numpy as np\n'), ((562, 598), 'frds.measures.general.kyle_lambda', 'general.kyle_lambda', (['prices', 'volumes'], {}), '(prices, volumes)\n', (581, 598), False, 'from frds.measures import general\n'), ((761, 777), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (769, 777), True, 'import numpy as np\n'), ((847, 880), 'numpy.array', 'np.array', (['[1, 1, 100, 1, 1, 1, 1]'], {}), '([1, 1, 100, 1, 1, 1, 1])\n', (855, 880), True, 'import numpy as np\n'), ((999, 1015), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (1007, 1015), True, 'import numpy as np\n'), ((1025, 1041), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (1033, 1041), True, 'import numpy as np\n')]
"""Plot utilities for the DESI ETC. Requires that matplotlib is installed. """ import datetime import copy # for shallow copies of matplotlib colormaps try: import DOSlib.logger as logging except ImportError: # Fallback when we are not running as a DOS application. import logging import numpy as np import matplotlib.pyplot as plt import matplotlib.lines import matplotlib.patheffects import matplotlib.dates import desietc.util def plot_colorhist(D, ax, imshow, mode='reverse', color='w', alpha=0.75): """Draw a hybrid colorbar and histogram. """ ax.axis('off') # Extract parameters of the original imshow. cmap = imshow.get_cmap() vmin, vmax = imshow.get_clim() # Get the pixel dimension of the axis to fill. fig = plt.gcf() bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) width, height = int(round(bbox.width * fig.dpi)), int(round(bbox.height * fig.dpi)) # Draw the colormap gradient. img = np.zeros((height, width, 3)) xgrad = np.linspace(0, 1, width) img[:] = cmap(xgrad)[:, :-1] # Superimpose a histogram of pixel values. counts, _ = np.histogram(D.reshape(-1), bins=np.linspace(vmin, vmax, width + 1)) hist_height = ((height - 1) * counts / counts[1:-1].max()).astype(int) mask = np.arange(height).reshape(-1, 1) < hist_height if mode == 'color': img[mask] = (1 - alpha) * img[mask] + alpha * np.asarray(matplotlib.colors.to_rgb(color)) elif mode == 'reverse': cmap_r = cmap.reversed() for i, x in enumerate(xgrad): img[mask[:, i], i] = cmap_r(x)[:-1] elif mode == 'complement': # https://stackoverflow.com/questions/40233986/ # python-is-there-a-function-or-formula-to-find-the-complementary-colour-of-a-rgb hilo = np.amin(img, axis=2, keepdims=True) + np.amax(img, axis=2, keepdims=True) img[mask] = hilo[mask] - img[mask] else: raise ValueError('Invalid mode "{0}".'.format(mode)) ax.imshow(img, interpolation='none', origin='lower') def plot_pixels(D, label=None, colorhist=False, zoom=1, masked_color='cyan', imshow_args={}, text_args={}, colorhist_args={}): """Plot pixel data at 1:1 scale with an optional label and colorhist. """ dpi = 100 # value only affects metadata in an output file, not appearance on screen. ny, nx = D.shape width, height = zoom * nx, zoom * ny if colorhist: colorhist_height = 32 height += colorhist_height fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi, frameon=False) ax = plt.axes((0, 0, 1, zoom * ny / height)) args = dict(imshow_args) for name, default in dict(interpolation='none', origin='lower', cmap='plasma_r').items(): if name not in args: args[name] = default # Set the masked color in the specified colormap. cmap = copy.copy(matplotlib.cm.get_cmap(args['cmap'])) cmap.set_bad(color=masked_color) args['cmap'] = cmap # Draw the image. I = ax.imshow(D, **args) ax.axis('off') if label: args = dict(text_args) for name, default in dict(color='w', fontsize=18).items(): if name not in args: args[name] = default outline = [ matplotlib.patheffects.Stroke(linewidth=1, foreground='k'), matplotlib.patheffects.Normal()] text = ax.text(0.01, 0.01 * nx / ny, label, transform=ax.transAxes, **args) text.set_path_effects(outline) if colorhist: axcb = plt.axes((0, zoom * ny / height, 1, colorhist_height / height)) plot_colorhist(D, axcb, I, **colorhist_args) return fig, ax def plot_data(D, W, downsampling=4, zoom=1, label=None, colorhist=False, stamps=[], preprocess_args={}, imshow_args={}, text_args={}, colorhist_args={}): """Plot weighted image data using downsampling, optional preprocessing, and decorators. """ # Downsample the input data. D, W = desietc.util.downsample_weighted(D, W, downsampling) # Preprocess the data for display. D = desietc.util.preprocess(D, W, **preprocess_args) ny, nx = D.shape # Display the image. args = dict(imshow_args) if 'extent' not in args: # Use the input pixel space for the extent, without downsampling. args['extent'] = [-0.5, nx * downsampling - 0.5, -0.5, ny * downsampling - 0.5] fig, ax = plot_pixels(D, zoom=zoom, label=label, colorhist=colorhist, imshow_args=args, text_args=text_args, colorhist_args=colorhist_args) outline = [ matplotlib.patheffects.Stroke(linewidth=1, foreground='k'), matplotlib.patheffects.Normal()] for k, stamp in enumerate(stamps): yslice, xslice = stamp[:2] xlo, xhi = xslice.start, xslice.stop ylo, yhi = yslice.start, yslice.stop rect = plt.Rectangle((xlo, ylo), xhi - xlo, yhi - ylo, fc='none', ec='w', lw=1) ax.add_artist(rect) if xhi < nx // 2: xtext, halign = xhi, 'left' else: xtext, halign = xlo, 'right' text = ax.text( xtext, 0.5 * (ylo + yhi), str(k), fontsize=12, color='w', va='center', ha=halign) text.set_path_effects(outline) return fig, ax def save_acquisition_summary( mjd, exptag, psf_model, psf_stack, fwhm, ffrac, nstars, badfit, noisy, path, show_north=True, show_fiber=True, zoom=5, dpi=128, cmap='magma', masked_color='gray'): """ """ # Get the size of the PSF model and stack images. shapes = [D.shape for D in psf_stack.values() if D is not None] if len(shapes) == 0: return size = shapes[0][1] # Get the number of expected in-focus GFAs. names = desietc.gfa.GFACamera.guide_names ngfa = len(names) # Initialize the figure. width = size * zoom * ngfa height = size * zoom * 2 fig, axes = plt.subplots(2, ngfa, figsize=(width / dpi, height / dpi), dpi=dpi, frameon=False) plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0, hspace=0) # Prepare a colormap with our custom ivar=0 color. cmap = copy.copy(matplotlib.cm.get_cmap(cmap)) cmap.set_bad(color=masked_color) # Get the colormap scale to use for all images. model_sum = {name: psf_model[name].sum() for name in psf_model} model_max = np.median([psf_model[camera].max() / model_sum[camera] for camera in psf_model]) vmin, vmax = -0.1 * model_max, 1.0 * model_max # Calculate the image extent. # Outline text to ensure that it is visible whatever pixels are below. outline = [ matplotlib.patheffects.Stroke(linewidth=1, foreground='k'), matplotlib.patheffects.Normal()] # Calculate the fiber diameter to overlay in GFA pixels. fiber_diam_um = 107 pixel_size_um = 15 radius = 0.5 * fiber_diam_um / pixel_size_um center = ((size - 1) / 2, (size - 1) / 2) # Loop over cameras. default_norm = np.median([s for s in model_sum.values()]) for i, name in enumerate(names): for ax in axes[:,i]: ax.axis('off') ax.add_artist(plt.Rectangle([0,0], 1, 1, fc='k', ec='none', transform=ax.transAxes, zorder=-1)) if name in psf_stack and psf_stack[name] is not None: data = psf_stack[name][0].copy() norm = model_sum.get(name, default_norm) data /= norm # do not show ivar=0 pixels data[psf_stack[name][1] == 0] = np.nan axes[0, i].imshow(data, vmin=vmin, vmax=vmax, cmap=cmap, interpolation='none', origin='lower') if show_north: # Draw an arrow point north in this GFA's pixel basis. n = int(name[5]) angle = np.deg2rad(36 * (n - 2)) xc, yc = 0.5 * size, 0.16 * size du = 0.02 * size * np.cos(angle) dv = 0.02 * size * np.sin(angle) xpt = np.array([-4 * du, dv, du, -dv, -4 * du]) ypt = np.array([4 * dv, du, -dv, -du, 4 * dv]) axes[0, i].add_line(matplotlib.lines.Line2D(xpt + xc, ypt + yc, c='c', lw=1, ls='-')) if name in psf_model and psf_model[name] is not None: data = psf_model[name] data /= model_sum[name] axes[1, i].imshow(psf_model[name], vmin=vmin, vmax=vmax, cmap=cmap, interpolation='bicubic', origin='lower') if show_fiber: # Draw an outline of the fiber. fiber = matplotlib.patches.Circle(center, radius, color='c', ls='-', lw=1, alpha=0.7, fill=False) axes[1,i].add_artist(fiber) # Generate a text overlay. ax = plt.axes((0, 0, 1, 1)) ax.axis('off') if mjd is not None: night = desietc.util.mjd_to_night(mjd) localtime = desietc.util.mjd_to_date(mjd, utc_offset=-7) center = localtime.strftime('%H:%M:%S') + ' (UTC-7)' else: night = 'YYYYMMDD' center = 'HH:MM:SS (UTC-7)' left = f'{night}/{exptag}' right = f'FWHM={fwhm:.2f}" ({100*ffrac:.1f}%)' for (x, ha, label) in zip((0, 0.5, 1), ('left', 'center', 'right'), (left, center, right)): text = ax.text(x, 0, label, color='w', ha=ha, va='bottom', size=10, transform=ax.transAxes) text.set_path_effects(outline) # Add per-GFA labels. xtext = (np.arange(ngfa) + 0.5) / ngfa for x, name in zip(xtext, names): text = ax.text(x, 0.5, name, color='w', ha='center', va='center', size=8, transform=ax.transAxes) text.set_path_effects(outline) nstar = nstars[name] label = f'{nstar} star' if nstar > 1: label += 's' text = ax.text(x, 0.45, label, color='w', ha='center', va='center', size=7, transform=ax.transAxes) text.set_path_effects(outline) warn_args = dict(size=10, color='c', fontweight='bold') if nstar == 0: text = ax.text(x, 0.92, 'NO STARS?', ha='center', va='top', transform=ax.transAxes, **warn_args) text.set_path_effects(outline) elif name in badfit: text = ax.text(x, 0.92, 'BAD PSF?', ha='center', va='top', transform=ax.transAxes, **warn_args) text.set_path_effects(outline) if name in noisy: text = ax.text(x, 1, 'NOISY?', ha='center', va='top', transform=ax.transAxes, **warn_args) text.set_path_effects(outline) # Save the image. plt.savefig(path) plt.close(fig) def plot_measurements(buffer, mjd1, mjd2, ymin=0, resolution=1, label=None, ax=None): """Plot measurements spanning (mjd1, mjd2) in the specified buffer. """ ax = ax or plt.gca() # Convert from MJD to minutes after mjd1. minutes = lambda mjd: (mjd - mjd1) * 720 # Plot measurements covering (mjd1, mjd2) with some extra padding. xlo, xhi = mjd1 - 3 * buffer.padding, mjd2 + 3 * buffer.padding padded = buffer.inside(xlo, xhi) used = buffer.inside(mjd1 - buffer.padding, mjd2 + buffer.padding) extra = padded & ~used for sel, color in ((extra, 'lightgray'), (used, 'b')): x = 0.5 * (buffer.entries['mjd1'][sel] + buffer.entries['mjd2'][sel]) dx = 0.5 * (buffer.entries['mjd2'][sel] - buffer.entries['mjd1'][sel]) y = buffer.entries['value'][sel] dy = buffer.entries['error'][sel] ax.errorbar(minutes(x), y, xerr=dx * 720, yerr=dy, fmt='.', color=color, ms=2, lw=1) # Draw the linear interpolation through the selected points. ngrid = int(np.ceil((mjd2 - mjd1) / (resolution / buffer.SECS_PER_DAY))) x_grid = np.linspace(mjd1, mjd2, ngrid) y_grid = buffer.sample_grid(x_grid) ax.fill_between(minutes(x_grid), ymin, y_grid, color='b', lw=0, alpha=0.2) # Highlight samples used for the trend. sel = buffer.inside(mjd2 - buffer.recent, mjd2) x = 0.5 * (buffer.entries['mjd1'][sel] + buffer.entries['mjd2'][sel]) y = buffer.entries['value'][sel] ax.plot(minutes(x), y, 'r.', ms=4, zorder=10) # Extrapolate the trend. offset, slope = buffer.trend(mjd2) x = np.array([mjd2, xhi]) y = offset + slope * (x - mjd2) ax.fill_between(minutes(x), ymin, y, color='r', lw=0, alpha=0.2) # Draw vertical lines to show the (mjd1, mjd2) interval. for xv in (mjd1, mjd2): ax.axvline(minutes(xv), c='b', ls='--') ax.set_xlim(minutes(xlo), minutes(xhi)) ax.set_ylim(ymin, None) ax.set_xlabel(f'Minutes relative to MJD {mjd1:.6f}') if label is not None: ax.set_ylabel(label) def mjd_plot(mjd, *args, axis=None, utc_offset=-7, date_format='%H:%M', **kwargs): """Replacement for plt.plot or axis.plot where the x-axis value is an MJD interpreted as a local datetime. """ axis = axis or plt.gca() plot_epoch = matplotlib.dates.date2num(datetime.datetime(1858, 11, 17) + datetime.timedelta(hours=utc_offset)) axis.plot_date(mjd + plot_epoch, *args, **kwargs) axis.xaxis.set_major_formatter(matplotlib.dates.DateFormatter(date_format)) return axis
[ "numpy.array", "numpy.sin", "datetime.timedelta", "numpy.arange", "datetime.datetime", "matplotlib.pyplot.close", "numpy.linspace", "matplotlib.pyplot.Rectangle", "numpy.ceil", "matplotlib.pyplot.savefig", "numpy.amin", "matplotlib.pyplot.gcf", "matplotlib.pyplot.gca", "numpy.deg2rad", "...
[((769, 778), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (776, 778), True, 'import matplotlib.pyplot as plt\n'), ((989, 1017), 'numpy.zeros', 'np.zeros', (['(height, width, 3)'], {}), '((height, width, 3))\n', (997, 1017), True, 'import numpy as np\n'), ((1030, 1054), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'width'], {}), '(0, 1, width)\n', (1041, 1054), True, 'import numpy as np\n'), ((2530, 2601), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(width / dpi, height / dpi)', 'dpi': 'dpi', 'frameon': '(False)'}), '(figsize=(width / dpi, height / dpi), dpi=dpi, frameon=False)\n', (2540, 2601), True, 'import matplotlib.pyplot as plt\n'), ((2611, 2650), 'matplotlib.pyplot.axes', 'plt.axes', (['(0, 0, 1, zoom * ny / height)'], {}), '((0, 0, 1, zoom * ny / height))\n', (2619, 2650), True, 'import matplotlib.pyplot as plt\n'), ((5919, 6006), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', 'ngfa'], {'figsize': '(width / dpi, height / dpi)', 'dpi': 'dpi', 'frameon': '(False)'}), '(2, ngfa, figsize=(width / dpi, height / dpi), dpi=dpi, frameon\n =False)\n', (5931, 6006), True, 'import matplotlib.pyplot as plt\n'), ((6006, 6079), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0)', 'right': '(1)', 'bottom': '(0)', 'top': '(1)', 'wspace': '(0)', 'hspace': '(0)'}), '(left=0, right=1, bottom=0, top=1, wspace=0, hspace=0)\n', (6025, 6079), True, 'import matplotlib.pyplot as plt\n'), ((8712, 8734), 'matplotlib.pyplot.axes', 'plt.axes', (['(0, 0, 1, 1)'], {}), '((0, 0, 1, 1))\n', (8720, 8734), True, 'import matplotlib.pyplot as plt\n'), ((10454, 10471), 'matplotlib.pyplot.savefig', 'plt.savefig', (['path'], {}), '(path)\n', (10465, 10471), True, 'import matplotlib.pyplot as plt\n'), ((10476, 10490), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (10485, 10490), True, 'import matplotlib.pyplot as plt\n'), ((11596, 11626), 'numpy.linspace', 'np.linspace', (['mjd1', 'mjd2', 'ngrid'], {}), '(mjd1, mjd2, ngrid)\n', (11607, 11626), True, 'import numpy as np\n'), ((12079, 12100), 'numpy.array', 'np.array', (['[mjd2, xhi]'], {}), '([mjd2, xhi])\n', (12087, 12100), True, 'import numpy as np\n'), ((3555, 3618), 'matplotlib.pyplot.axes', 'plt.axes', (['(0, zoom * ny / height, 1, colorhist_height / height)'], {}), '((0, zoom * ny / height, 1, colorhist_height / height))\n', (3563, 3618), True, 'import matplotlib.pyplot as plt\n'), ((4894, 4966), 'matplotlib.pyplot.Rectangle', 'plt.Rectangle', (['(xlo, ylo)', '(xhi - xlo)', '(yhi - ylo)'], {'fc': '"""none"""', 'ec': '"""w"""', 'lw': '(1)'}), "((xlo, ylo), xhi - xlo, yhi - ylo, fc='none', ec='w', lw=1)\n", (4907, 4966), True, 'import matplotlib.pyplot as plt\n'), ((10674, 10683), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (10681, 10683), True, 'import matplotlib.pyplot as plt\n'), ((11522, 11581), 'numpy.ceil', 'np.ceil', (['((mjd2 - mjd1) / (resolution / buffer.SECS_PER_DAY))'], {}), '((mjd2 - mjd1) / (resolution / buffer.SECS_PER_DAY))\n', (11529, 11581), True, 'import numpy as np\n'), ((12754, 12763), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (12761, 12763), True, 'import matplotlib.pyplot as plt\n'), ((1184, 1218), 'numpy.linspace', 'np.linspace', (['vmin', 'vmax', '(width + 1)'], {}), '(vmin, vmax, width + 1)\n', (1195, 1218), True, 'import numpy as np\n'), ((9381, 9396), 'numpy.arange', 'np.arange', (['ngfa'], {}), '(ngfa)\n', (9390, 9396), True, 'import numpy as np\n'), ((12807, 12838), 'datetime.datetime', 'datetime.datetime', (['(1858)', '(11)', '(17)'], {}), '(1858, 11, 17)\n', (12824, 12838), False, 'import datetime\n'), ((12841, 12877), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': 'utc_offset'}), '(hours=utc_offset)\n', (12859, 12877), False, 'import datetime\n'), ((1306, 1323), 'numpy.arange', 'np.arange', (['height'], {}), '(height)\n', (1315, 1323), True, 'import numpy as np\n'), ((7134, 7219), 'matplotlib.pyplot.Rectangle', 'plt.Rectangle', (['[0, 0]', '(1)', '(1)'], {'fc': '"""k"""', 'ec': '"""none"""', 'transform': 'ax.transAxes', 'zorder': '(-1)'}), "([0, 0], 1, 1, fc='k', ec='none', transform=ax.transAxes,\n zorder=-1)\n", (7147, 7219), True, 'import matplotlib.pyplot as plt\n'), ((7754, 7778), 'numpy.deg2rad', 'np.deg2rad', (['(36 * (n - 2))'], {}), '(36 * (n - 2))\n', (7764, 7778), True, 'import numpy as np\n'), ((7948, 7989), 'numpy.array', 'np.array', (['[-4 * du, dv, du, -dv, -4 * du]'], {}), '([-4 * du, dv, du, -dv, -4 * du])\n', (7956, 7989), True, 'import numpy as np\n'), ((8012, 8052), 'numpy.array', 'np.array', (['[4 * dv, du, -dv, -du, 4 * dv]'], {}), '([4 * dv, du, -dv, -du, 4 * dv])\n', (8020, 8052), True, 'import numpy as np\n'), ((1814, 1849), 'numpy.amin', 'np.amin', (['img'], {'axis': '(2)', 'keepdims': '(True)'}), '(img, axis=2, keepdims=True)\n', (1821, 1849), True, 'import numpy as np\n'), ((1852, 1887), 'numpy.amax', 'np.amax', (['img'], {'axis': '(2)', 'keepdims': '(True)'}), '(img, axis=2, keepdims=True)\n', (1859, 1887), True, 'import numpy as np\n'), ((7863, 7876), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (7869, 7876), True, 'import numpy as np\n'), ((7912, 7925), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (7918, 7925), True, 'import numpy as np\n')]
import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from cogdl.layers import MeanAggregator from .. import BaseModel, register_model @register_model("fastgcn") class FastGCN(BaseModel): @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" # fmt: off parser.add_argument("--num-features", type=int) parser.add_argument("--num-classes", type=int) parser.add_argument("--hidden-size", type=int, nargs='+',default=[128]) parser.add_argument("--num-layers", type=int, default=2) parser.add_argument("--sample-size",type=int,nargs='+',default=[512,256,256]) parser.add_argument("--dropout", type=float, default=0.5) # fmt: on @classmethod def build_model_from_args(cls, args): return cls( args.num_features, args.num_classes, args.hidden_size, args.num_layers, args.sample_size, args.dropout, ) # edge index based sampler # @profile def construct_adjlist(self, edge_index): # print(edge_index) if self.adjlist == {}: edge_index = edge_index.t().cpu().tolist() for i in edge_index: if not (i[0] in self.adjlist): self.adjlist[i[0]] = [i[1]] else: self.adjlist[i[0]].append(i[1]) # print(self.adjlist) return 0 # @profile def generate_index(self, sample1, sample2): edgelist = [] values = [] iddict1 = {} for i in range(len(sample1)): iddict1[sample1[i]] = i for i in range(len(sample2)): case = self.adjlist[sample2[i]] for adj in case: if adj in iddict1: edgelist.append([i, iddict1[adj]]) values.append(1) edgetensor = torch.LongTensor(edgelist) valuetensor = torch.FloatTensor(values) # print(edgetensor,valuetensor,len(sample2),len(sample1)) t = torch.sparse.FloatTensor( edgetensor.t(), valuetensor, torch.Size([len(sample2), len(sample1)]) ).cuda() return t # @profile def sample_one_layer(self, init_index, sample_size): alllist = [] for i in init_index: alllist.extend(self.adjlist[i]) alllist = list(np.unique(alllist)) if sample_size > len(alllist): sample_size = len(alllist) # print(init_index,alllist,sample_size) alllist = random.sample(alllist, sample_size) return alllist def __init__( self, num_features, num_classes, hidden_size, num_layers, sample_size, dropout ): super(FastGCN, self).__init__() self.adjlist = {} self.num_features = num_features self.num_classes = num_classes self.hidden_size = hidden_size self.num_layers = num_layers self.sample_size = sample_size self.dropout = dropout shapes = [num_features] + hidden_size + [num_classes] # print(shapes) self.convs = nn.ModuleList( [ MeanAggregator(shapes[layer], shapes[layer + 1], cached=True) for layer in range(num_layers) ] ) # @profile def forward(self, x, train_index): sampled = [[]] * (self.num_layers + 1) sampled[self.num_layers] = train_index # print("train",train_index) for i in range(self.num_layers - 1, -1, -1): sampled[i] = self.sample_one_layer(sampled[i + 1], self.sample_size[i]) # construct_tensor w = torch.LongTensor(sampled[0]).cuda() x = torch.index_select(x, 0, w) for i in range(self.num_layers): # print(i,len(sampled[i]),len(sampled[i+1])) edge_index_sp = self.generate_index(sampled[i], sampled[i + 1]) x = self.convs[i](x, edge_index_sp, sampled[i + 1]) if i != self.num_layers - 1: x = F.relu(x) x = F.dropout(x, p=self.dropout, training=self.training) return F.log_softmax(x, dim=1)
[ "torch.index_select", "random.sample", "numpy.unique", "torch.LongTensor", "cogdl.layers.MeanAggregator", "torch.nn.functional.dropout", "torch.nn.functional.log_softmax", "torch.nn.functional.relu", "torch.FloatTensor" ]
[((1981, 2007), 'torch.LongTensor', 'torch.LongTensor', (['edgelist'], {}), '(edgelist)\n', (1997, 2007), False, 'import torch\n'), ((2030, 2055), 'torch.FloatTensor', 'torch.FloatTensor', (['values'], {}), '(values)\n', (2047, 2055), False, 'import torch\n'), ((2635, 2670), 'random.sample', 'random.sample', (['alllist', 'sample_size'], {}), '(alllist, sample_size)\n', (2648, 2670), False, 'import random\n'), ((3794, 3821), 'torch.index_select', 'torch.index_select', (['x', '(0)', 'w'], {}), '(x, 0, w)\n', (3812, 3821), False, 'import torch\n'), ((4221, 4244), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['x'], {'dim': '(1)'}), '(x, dim=1)\n', (4234, 4244), True, 'import torch.nn.functional as F\n'), ((2466, 2484), 'numpy.unique', 'np.unique', (['alllist'], {}), '(alllist)\n', (2475, 2484), True, 'import numpy as np\n'), ((3251, 3312), 'cogdl.layers.MeanAggregator', 'MeanAggregator', (['shapes[layer]', 'shapes[layer + 1]'], {'cached': '(True)'}), '(shapes[layer], shapes[layer + 1], cached=True)\n', (3265, 3312), False, 'from cogdl.layers import MeanAggregator\n'), ((3746, 3774), 'torch.LongTensor', 'torch.LongTensor', (['sampled[0]'], {}), '(sampled[0])\n', (3762, 3774), False, 'import torch\n'), ((4122, 4131), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (4128, 4131), True, 'import torch.nn.functional as F\n'), ((4152, 4204), 'torch.nn.functional.dropout', 'F.dropout', (['x'], {'p': 'self.dropout', 'training': 'self.training'}), '(x, p=self.dropout, training=self.training)\n', (4161, 4204), True, 'import torch.nn.functional as F\n')]
import os import re import numpy as np import matplotlib.pyplot as plt from periodictable import elements class Tfactors(object): """ precompute temperature factors for speed """ def __init__(self, T): """ return the Tfactors object. Here, T is temperature in Kelvin """ self.T9 = T/1.e9 self.T9i = 1.0/self.T9 self.T913i = self.T9i**(1./3.) self.T913 = self.T9**(1./3.) self.T953 = self.T9**(5./3.) self.lnT9 = np.log(self.T9) class SingleSet(object): """ a set in Reaclib is one piece of a rate, in the form lambda = exp[ a_0 + sum_{i=1}^5 a_i T_9**(2i-5)/3 + a_6 log T_9] A single rate in Reaclib can be composed of multiple sets """ def __init__(self, a, label=None): """here a is iterable (e.g., list or numpy array), storing the coefficients, a0, ..., a6 """ self.a = a self.label = label def f(self): """ return a function for this set -- note: Tf here is a Tfactors object """ return lambda tf: np.exp(self.a[0] + self.a[1]*tf.T9i + self.a[2]*tf.T913i + self.a[3]*tf.T913 + self.a[4]*tf.T9 + self.a[5]*tf.T953 + self.a[6]*tf.lnT9) def set_string(self, prefix="set", plus_equal=False): """ return a string containing the python code for this set """ if plus_equal: string = "{} += np.exp( ".format(prefix) else: string = "{} = np.exp( ".format(prefix) string += " {}".format(self.a[0]) if not self.a[1] == 0.0: string += " + {}*tf.T9i".format(self.a[1]) if not self.a[2] == 0.0: string += " + {}*tf.T913i".format(self.a[2]) if not self.a[3] == 0.0: string += " + {}*tf.T913".format(self.a[3]) if not (self.a[4] == 0.0 and self.a[5] == 0.0 and self.a[6] == 0.0): string += "\n{} ".format(len(prefix)*" ") if not self.a[4] == 0.0: string += " + {}*tf.T9".format(self.a[4]) if not self.a[5] == 0.0: string += " + {}*tf.T953".format(self.a[5]) if not self.a[6] == 0.0: string += " + {}*tf.lnT9".format(self.a[6]) string += ")" return string class Nucleus(object): """ a nucleus that participates in a reaction -- we store it in a class to hold its properties, define a sorting, and give it a pretty printing string """ def __init__(self, name): self.raw = name # element symbol and atomic weight if name == "p": self.el = "H" self.A = 1 self.short_spec_name = "h1" elif name == "d": self.el = "H" self.A = 2 self.short_spec_name = "h2" elif name == "t": self.el = "H" self.A = 3 self.short_spec_name = "h3" elif name == "n": self.el = "n" self.A = 1 self.short_spec_name = "n" else: e = re.match("([a-zA-Z]*)(\d*)", name) self.el = e.group(1).title() # chemical symbol self.A = int(e.group(2)) self.short_spec_name = name # atomic number comes from periodtable i = elements.isotope("{}-{}".format(self.A, self.el)) self.Z = i.number self.N = self.A - self.Z # long name if i.name == 'neutron': self.spec_name = i.name else: self.spec_name = '{}-{}'.format(i.name, self.A) # latex formatted style self.pretty = r"{{}}^{{{}}}\mathrm{{{}}}".format(self.A, self.el) def __repr__(self): return self.raw def __hash__(self): return hash(self.__repr__()) def __eq__(self, other): return self.raw == other.raw def __lt__(self, other): if not self.Z == other.Z: return self.Z < other.Z else: return self.A < other.A class Rate(object): """ a single Reaclib rate, which can be composed of multiple sets """ def __init__(self, file): self.file = os.path.basename(file) self.chapter = None # the Reaclib chapter for this reaction self.original_source = None # the contents of the original rate file self.reactants = [] self.products = [] self.sets = [] # Tells if this rate is eligible for screening # using screenz.f90 provided by BoxLib Microphysics. # If not eligible for screening, set to None # If eligible for screening, then # Rate.ion_screen is a 2-element list of Nucleus objects for screening self.ion_screen = None idx = self.file.rfind("-") self.fname = self.file[:idx].replace("--","-").replace("-","_") self.Q = 0.0 # read in the file, parse the different sets and store them as # SingleSet objects in sets[] f = open(file, "r") lines = f.readlines() self.original_source = "".join(lines) # first line is the chapter self.chapter = lines[0].strip() # catch table prescription if self.chapter != "t": self.chapter = int(self.chapter) # remove any black lines set_lines = [l for l in lines[1:] if not l.strip() == ""] if self.chapter == "t": # e1 -> e2, Tabulated s1 = set_lines.pop(0) s2 = set_lines.pop(0) s3 = set_lines.pop(0) s4 = set_lines.pop(0) s5 = set_lines.pop(0) f = s1.split() self.reactants.append(Nucleus(f[0])) self.products.append(Nucleus(f[1])) self.table_file = s2.strip() self.table_header_lines = int(s3.strip()) self.table_rhoy_lines = int(s4.strip()) self.table_temp_lines = int(s5.strip()) self.table_num_vars = 6 # Hard-coded number of variables in tables for now. self.table_index_name = 'j_{}_{}'.format(self.reactants[0], self.products[0]) else: # the rest is the sets first = 1 while len(set_lines) > 0: # sets are 3 lines long s1 = set_lines.pop(0) s2 = set_lines.pop(0) s3 = set_lines.pop(0) # first line of a set has up to 6 nuclei, then the label, # and finally the Q value f = s1.split() Q = f.pop() label = f.pop() if first: self.Q = Q # what's left are the nuclei -- their interpretation # depends on the chapter if self.chapter == 1: # e1 -> e2 self.reactants.append(Nucleus(f[0])) self.products.append(Nucleus(f[1])) elif self.chapter == 2: # e1 -> e2 + e3 self.reactants.append(Nucleus(f[0])) self.products += [Nucleus(f[1]), Nucleus(f[2])] elif self.chapter == 3: # e1 -> e2 + e3 + e4 self.reactants.append(Nucleus(f[0])) self.products += [Nucleus(f[1]), Nucleus(f[2]), Nucleus(f[3])] elif self.chapter == 4: # e1 + e2 -> e3 self.reactants += [Nucleus(f[0]), Nucleus(f[1])] self.products.append(Nucleus(f[2])) elif self.chapter == 5: # e1 + e2 -> e3 + e4 self.reactants += [Nucleus(f[0]), Nucleus(f[1])] self.products += [Nucleus(f[2]), Nucleus(f[3])] elif self.chapter == 6: # e1 + e2 -> e3 + e4 + e5 self.reactants += [Nucleus(f[0]), Nucleus(f[1])] self.products += [Nucleus(f[2]), Nucleus(f[3]), Nucleus(f[4])] elif self.chapter == 7: # e1 + e2 -> e3 + e4 + e5 + e6 self.reactants += [Nucleus(f[0]), Nucleus(f[1])] self.products += [Nucleus(f[2]), Nucleus(f[3]), Nucleus(f[4]), Nucleus(f[5])] elif self.chapter == 8: # e1 + e2 + e3 -> e4 self.reactants += [Nucleus(f[0]), Nucleus(f[1]), Nucleus(f[2])] self.products.append(Nucleus(f[3])) elif self.chapter == 9: # e1 + e2 + e3 -> e4 + e5 self.reactants += [Nucleus(f[0]), Nucleus(f[1]), Nucleus(f[2])] self.products += [Nucleus(f[3]), Nucleus(f[4])] elif self.chapter == 10: # e1 + e2 + e3 + e4 -> e5 + e6 self.reactants += [Nucleus(f[0]), Nucleus(f[1]), Nucleus(f[2]), Nucleus(f[3])] self.products += [Nucleus(f[4]), Nucleus(f[5])] elif self.chapter == 11: # e1 -> e2 + e3 + e4 + e5 self.reactants.append(Nucleus(f[0])) self.products += [Nucleus(f[1]), Nucleus(f[2]), Nucleus(f[3]), Nucleus(f[4])] first = 0 # the second line contains the first 4 coefficients # the third lines contains the final 3 # we can't just use split() here, since the fields run into one another n = 13 # length of the field a = [s2[i:i+n] for i in range(0, len(s2), n)] a += [s3[i:i+n] for i in range(0, len(s3), n)] a = [float(e) for e in a if not e.strip() == ""] self.sets.append(SingleSet(a, label=label)) # compute self.prefactor and self.dens_exp from the reactants self.prefactor = 1.0 # this is 1/2 for rates like a + a (double counting) self.inv_prefactor = 1 for r in set(self.reactants): self.inv_prefactor = self.inv_prefactor * np.math.factorial(self.reactants.count(r)) self.prefactor = self.prefactor/float(self.inv_prefactor) self.dens_exp = len(self.reactants)-1 # determine if this rate is eligible for screening nucz = [] for parent in self.reactants: if parent.Z != 0: nucz.append(parent) if len(nucz) > 1: nucz.sort(key=lambda x: x.Z) self.ion_screen = [] self.ion_screen.append(nucz[0]) self.ion_screen.append(nucz[1]) self.string = "" self.pretty_string = r"$" # put p, n, and alpha second treactants = [] for n in self.reactants: if n.raw not in ["p", "he4", "n"]: treactants.insert(0, n) else: treactants.append(n) for n, r in enumerate(treactants): self.string += "{}".format(r) self.pretty_string += r"{}".format(r.pretty) if not n == len(self.reactants)-1: self.string += " + " self.pretty_string += r" + " self.string += " --> " self.pretty_string += r" \rightarrow " for n, p in enumerate(self.products): self.string += "{}".format(p) self.pretty_string += r"{}".format(p.pretty) if not n == len(self.products)-1: self.string += " + " self.pretty_string += r" + " self.pretty_string += r"$" def __repr__(self): return self.string def eval(self, T): """ evauate the reaction rate for temperature T """ tf = Tfactors(T) r = 0.0 for s in self.sets: f = s.f() r += f(tf) return r def get_rate_exponent(self, T0): """ for a rate written as a power law, r = r_0 (T/T0)**nu, return nu corresponding to T0 """ # nu = dln r /dln T, so we need dr/dT r1 = self.eval(T0) dT = 1.e-8*T0 r2 = self.eval(T0 + dT) drdT = (r2 - r1)/dT return (T0/r1)*drdT def plot(self, Tmin=1.e7, Tmax=1.e10): T = np.logspace(np.log10(Tmin), np.log10(Tmax), 100) r = np.zeros_like(T) for n in range(len(T)): r[n] = self.eval(T[n]) plt.loglog(T, r) plt.xlabel(r"$T$") if self.dens_exp == 0: plt.ylabel(r"\tau") elif self.dens_exp == 1: plt.ylabel(r"$N_A <\sigma v>$") elif self.dens_exp == 2: plt.ylabel(r"$N_A^2 <n_a n_b n_c v>$") plt.title(r"{}".format(self.pretty_string)) plt.show()
[ "numpy.log10", "matplotlib.pyplot.loglog", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.log", "re.match", "numpy.exp", "os.path.basename", "numpy.zeros_like", "matplotlib.pyplot.show" ]
[((480, 495), 'numpy.log', 'np.log', (['self.T9'], {}), '(self.T9)\n', (486, 495), True, 'import numpy as np\n'), ((4277, 4299), 'os.path.basename', 'os.path.basename', (['file'], {}), '(file)\n', (4293, 4299), False, 'import os\n'), ((12803, 12819), 'numpy.zeros_like', 'np.zeros_like', (['T'], {}), '(T)\n', (12816, 12819), True, 'import numpy as np\n'), ((12897, 12913), 'matplotlib.pyplot.loglog', 'plt.loglog', (['T', 'r'], {}), '(T, r)\n', (12907, 12913), True, 'import matplotlib.pyplot as plt\n'), ((12923, 12940), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$T$"""'], {}), "('$T$')\n", (12933, 12940), True, 'import matplotlib.pyplot as plt\n'), ((13229, 13239), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13237, 13239), True, 'import matplotlib.pyplot as plt\n'), ((1095, 1246), 'numpy.exp', 'np.exp', (['(self.a[0] + self.a[1] * tf.T9i + self.a[2] * tf.T913i + self.a[3] * tf.\n T913 + self.a[4] * tf.T9 + self.a[5] * tf.T953 + self.a[6] * tf.lnT9)'], {}), '(self.a[0] + self.a[1] * tf.T9i + self.a[2] * tf.T913i + self.a[3] *\n tf.T913 + self.a[4] * tf.T9 + self.a[5] * tf.T953 + self.a[6] * tf.lnT9)\n', (1101, 1246), True, 'import numpy as np\n'), ((12754, 12768), 'numpy.log10', 'np.log10', (['Tmin'], {}), '(Tmin)\n', (12762, 12768), True, 'import numpy as np\n'), ((12770, 12784), 'numpy.log10', 'np.log10', (['Tmax'], {}), '(Tmax)\n', (12778, 12784), True, 'import numpy as np\n'), ((12986, 13005), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""\\\\tau"""'], {}), "('\\\\tau')\n", (12996, 13005), True, 'import matplotlib.pyplot as plt\n'), ((13051, 13082), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$N_A <\\\\sigma v>$"""'], {}), "('$N_A <\\\\sigma v>$')\n", (13061, 13082), True, 'import matplotlib.pyplot as plt\n'), ((13128, 13165), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$N_A^2 <n_a n_b n_c v>$"""'], {}), "('$N_A^2 <n_a n_b n_c v>$')\n", (13138, 13165), True, 'import matplotlib.pyplot as plt\n'), ((3191, 3226), 're.match', 're.match', (['"""([a-zA-Z]*)(\\\\d*)"""', 'name'], {}), "('([a-zA-Z]*)(\\\\d*)', name)\n", (3199, 3226), False, 'import re\n')]
from .Random import random import numpy as np from .logging import logging from abc import ABC class sim_base(ABC): def __init__(self, events:list, system, verbose=False, name="base",log=True, debug=False): # random number generator self.rand = random() self.events = events self.num_events = len(self.events) self.verbose= verbose # This should ideally be off self.debug = debug # initialize time self.t = 0 self.system = system # stores the indices of the possible events on each site self.ev_ind = [[] for _ in range(self.num_events)] # All the rate of the events as well as the cumulative sum self.ev_R = np.zeros((self.num_events,)) self.ev_cumsum = np.zeros((self.num_events,)) # Total rate self.total_rate= 0.0 self.name = name self.log = log if self.log: self.logger = logging(name) self.logger_state = logging("state") # track number of times each event is performed self.num_times = np.zeros((self.num_events, )) if self.log: self.init() def init(self): """ Function that initializes the logger and anything necessary """ print("Init not implemented.") def update(self): """ Update the system and see which new events became possible """ self.ev_ind = [[] for _ in range(len(self.events))] self.total_rate = 0.0 self.ev_R = np.zeros((len(self.events),)) self.ev_cumsum = np.zeros((len(self.events),)) # update the indices of the system for i in range(self.system.lattice.Nx): for j in range(self.system.lattice.Ny): index = np.array([i,j]) for k, ev in enumerate(self.events): if ev.is_possible(self.system, index): rate = self.events[k].get_rate(self.system, index) self.ev_R[k] += rate self.ev_ind[k].append(index) # update the rate of the system self.ev_cumsum = np.cumsum(self.ev_R) self.total_rate = self.ev_R.sum() assert self.total_rate == self.ev_cumsum[-1], \ "The total rate does not match the largest of the cumsum, something is wrong" # Divide cumulative sum by total rate self.ev_cumsum /= self.total_rate def step(self): """ Take a Monte Carlo step """ choose_ev = self.rand.uniform() time = self.rand.exponential(self.total_rate) # we just want the number while digitize returns a np.ndarray order_ = np.digitize(choose_ev,self.ev_cumsum)[0] # Update the count of the event by 1 self.num_times[order_] += 1 # Check the number of sites that are possible for this event num_sites = len(self.ev_ind[order_]) site_num = np.random.choice(np.arange(num_sites)) site_idx = self.ev_ind[order_][site_num] if self.verbose: print("Time: {} ms".format(self.t + time[0])) for i in range(self.num_events): print("The rate for event {} is {}".format(self.events[i].name, self.ev_R[i])) print("The event carried out is {}".format(self.events[order_].name)) # perform the event chosen, this will actually do another check (if_possible) self.events[order_].do_event(self.system, site_idx) self.t += time[0] # Write to data if self.log: self.log_data() self.log_state() # check debug if self.debug: self.check_if_debug() def log_data(self): """ Function that writes data to file every time step """ print("log_data not implemented") def log_state(self): """ This logs the state of the system """ print("log_state not implemented.") def check_if_debug(self): """ This is a helper function that checks whether or not 2 rectangles overlap if we are in the debug mode """ print("Debug not implemented.")
[ "numpy.digitize", "numpy.array", "numpy.zeros", "numpy.cumsum", "numpy.arange" ]
[((756, 784), 'numpy.zeros', 'np.zeros', (['(self.num_events,)'], {}), '((self.num_events,))\n', (764, 784), True, 'import numpy as np\n'), ((810, 838), 'numpy.zeros', 'np.zeros', (['(self.num_events,)'], {}), '((self.num_events,))\n', (818, 838), True, 'import numpy as np\n'), ((1150, 1178), 'numpy.zeros', 'np.zeros', (['(self.num_events,)'], {}), '((self.num_events,))\n', (1158, 1178), True, 'import numpy as np\n'), ((2251, 2271), 'numpy.cumsum', 'np.cumsum', (['self.ev_R'], {}), '(self.ev_R)\n', (2260, 2271), True, 'import numpy as np\n'), ((2846, 2884), 'numpy.digitize', 'np.digitize', (['choose_ev', 'self.ev_cumsum'], {}), '(choose_ev, self.ev_cumsum)\n', (2857, 2884), True, 'import numpy as np\n'), ((3130, 3150), 'numpy.arange', 'np.arange', (['num_sites'], {}), '(num_sites)\n', (3139, 3150), True, 'import numpy as np\n'), ((1871, 1887), 'numpy.array', 'np.array', (['[i, j]'], {}), '([i, j])\n', (1879, 1887), True, 'import numpy as np\n')]
from enum import Enum import numpy as np from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate from qiskit.circuit import Gate from qiskit.circuit import QuantumRegister def gen_predefined_payoffs(game_name: str, num_players: int, payoff_input: dict): """Generates payoff table based on game name""" num_players = num_players payoff_table = {} if game_name == "minority": for i in range(2**num_players): outcome = format(i, '0'+str(num_players)+'b') payoff = np.zeros(num_players) if outcome.count('0') != 1 and outcome.count('1') != 1: payoff_table[outcome] = tuple(payoff) else: if outcome.count('0') == 1: win_ind = outcome.find('0') payoff[win_ind] = 1 payoff_table[outcome] = tuple(payoff) if outcome.count('1') == 1: win_ind = outcome.find('1') payoff[win_ind] = 1 payoff_table[outcome] = tuple(payoff) elif game_name == "chicken": for i in range(2**num_players): outcome = format(i, '0'+str(num_players)+'b') if outcome.count('1') == 0: payoff_table[outcome] = tuple(np.zeros(num_players)) elif outcome.count('1') == 1: payoff = np.array([]) for j in range(num_players): if outcome[j] == '0': payoff = np.append(payoff, -1) else: payoff = np.append(payoff, 1) payoff_table[outcome] = tuple(payoff) else: payoff = np.array([]) for j in range(num_players): if outcome[j] == '0': payoff = np.append(payoff, 0) else: payoff = np.append(payoff, -10) payoff_table[outcome] = tuple(payoff) elif game_name == 'prisoner': payoff_table = {'00': (-1, -1), '01': (-3, 0), '10': (0, -3), '11': (-2, -2)} elif game_name == 'BoS': payoff_table = {'00': (3, 2), '01': (0, 0), '10': (0, 0), '11': (2, 3)} elif game_name == 'custom': payoff_table = {key: tuple(map(int, value.split(','))) for key, value in payoff_input.items()} return payoff_table class WGate(Gate): """ Creates the custom W gate """ def __init__(self): """Create new W gate.""" super().__init__("W", 1, []) def _define(self): """ gate W a { Rz(-3*pi/8) a; Rz(pi/2) a; Ry(pi/2) } """ definition = [] q = QuantumRegister(1, "q") rule = [ (RZGate(-3 * np.pi / 8), [q[0]], []), (RZGate(np.pi / 2), [q[0]], []), (RYGate(np.pi / 2), [q[0]], []) ] for inst in rule: definition.append(inst) self.definition = definition def parse_angle(angle_str: str) -> float: angle_str = angle_str.replace(" ", "") numbers = [] ops = [] no_dec = True prev_char = None for i in range(len(angle_str)): # If the character is a digit either append it to the previous digit or make a new string of digits starting # with that if the previous is not a string of digits if angle_str[i].isdigit(): if prev_char is None: numbers.append('') numbers[-1] += angle_str[i] prev_char = 'number' # If the character is a decimal append it to the previous digit as long as there are no decimals already or make # a new set string of digits starting with that if the previous is not a string of digits elif angle_str[i] == '.' and no_dec: if prev_char is None: numbers.append('') numbers[-1] += angle_str[i] prev_char = 'number' no_dec = False # If the first character is a minus sign make a new set string of digits starting with that character elif angle_str[i] == '-' and prev_char is None: numbers.append('-') prev_char = 'operator' # If the character is a multiplication or division sign make a new empty string of digits and add operator elif (angle_str[i] == '*' or angle_str[i] == '/') and prev_char == 'number' and (angle_str[i+1].isdigit() or angle_str[i+1] == '.' or angle_str[i+1] == 'p'): ops.append(angle_str[i]) numbers.append('') prev_char = 'operator' no_dec = True # If the characters are 'pi', add np.pi to the numbers list elif angle_str[i] =='p' and angle_str[i+1] == 'i': pass elif angle_str[i] == 'i' and angle_str[i-1] == 'p': if prev_char is None: numbers.append('') numbers[-1] = np.pi prev_char = 'number' else: raise ValueError(f'{angle_str} is invalid') # Combine numbers given operators angle = float(numbers[0]) if len(numbers) == 1: return angle for i in range(len(numbers)-1): if ops[i] == '*': angle *= float(numbers[i+1]) elif ops[i] == '/': angle /= float(numbers[i+1]) return angle def generate_unitary_gate(gate_name: str) -> Gate: # Rx, Ry and Rz gates that look like 'Rx(pi/2) if gate_name[0] == 'R' and gate_name[2] == '(': angle = parse_angle(gate_name[3:-1]) if gate_name[1] == 'x': return RXGate(angle) elif gate_name[1] == 'y': return RYGate(angle) elif gate_name[1] == 'z': return RZGate(angle) else: unitary_gates = {"X": XGate(), "Y": YGate(), "S": SGate(), "Z": ZGate(), "H": HGate(), "T": TGate(), "I": IdGate(), "W": WGate(), "Rz1": RZGate(-3 * np.pi / 8), "Rz2": RZGate(np.pi/2), "Ry1": RYGate(np.pi/2)} return unitary_gates[gate_name] class Protocol(Enum): """ The various different quantum/classical game theory game protocols """ EWL = "EWL quantization protocol" MW = "MW quantization protocol" Classical = "Classical protocol" def describe(self): # Self is the member here return self.name, self.value
[ "qiskit.extensions.TGate", "qiskit.extensions.RYGate", "qiskit.extensions.YGate", "qiskit.extensions.XGate", "qiskit.extensions.SGate", "qiskit.extensions.IdGate", "qiskit.circuit.QuantumRegister", "numpy.array", "numpy.zeros", "numpy.append", "qiskit.extensions.HGate", "qiskit.extensions.RZGa...
[((2874, 2897), 'qiskit.circuit.QuantumRegister', 'QuantumRegister', (['(1)', '"""q"""'], {}), "(1, 'q')\n", (2889, 2897), False, 'from qiskit.circuit import QuantumRegister\n'), ((560, 581), 'numpy.zeros', 'np.zeros', (['num_players'], {}), '(num_players)\n', (568, 581), True, 'import numpy as np\n'), ((5928, 5941), 'qiskit.extensions.RXGate', 'RXGate', (['angle'], {}), '(angle)\n', (5934, 5941), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6116, 6123), 'qiskit.extensions.XGate', 'XGate', ([], {}), '()\n', (6121, 6123), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6155, 6162), 'qiskit.extensions.YGate', 'YGate', ([], {}), '()\n', (6160, 6162), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6194, 6201), 'qiskit.extensions.SGate', 'SGate', ([], {}), '()\n', (6199, 6201), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6233, 6240), 'qiskit.extensions.ZGate', 'ZGate', ([], {}), '()\n', (6238, 6240), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6272, 6279), 'qiskit.extensions.HGate', 'HGate', ([], {}), '()\n', (6277, 6279), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6311, 6318), 'qiskit.extensions.TGate', 'TGate', ([], {}), '()\n', (6316, 6318), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6350, 6358), 'qiskit.extensions.IdGate', 'IdGate', ([], {}), '()\n', (6356, 6358), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6431, 6453), 'qiskit.extensions.RZGate', 'RZGate', (['(-3 * np.pi / 8)'], {}), '(-3 * np.pi / 8)\n', (6437, 6453), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6487, 6504), 'qiskit.extensions.RZGate', 'RZGate', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (6493, 6504), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6536, 6553), 'qiskit.extensions.RYGate', 'RYGate', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (6542, 6553), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((2928, 2950), 'qiskit.extensions.RZGate', 'RZGate', (['(-3 * np.pi / 8)'], {}), '(-3 * np.pi / 8)\n', (2934, 2950), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((2978, 2995), 'qiskit.extensions.RZGate', 'RZGate', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (2984, 2995), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((3023, 3040), 'qiskit.extensions.RYGate', 'RYGate', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (3029, 3040), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((5995, 6008), 'qiskit.extensions.RYGate', 'RYGate', (['angle'], {}), '(angle)\n', (6001, 6008), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((6062, 6075), 'qiskit.extensions.RZGate', 'RZGate', (['angle'], {}), '(angle)\n', (6068, 6075), False, 'from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate\n'), ((1319, 1340), 'numpy.zeros', 'np.zeros', (['num_players'], {}), '(num_players)\n', (1327, 1340), True, 'import numpy as np\n'), ((1409, 1421), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1417, 1421), True, 'import numpy as np\n'), ((1741, 1753), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1749, 1753), True, 'import numpy as np\n'), ((1542, 1563), 'numpy.append', 'np.append', (['payoff', '(-1)'], {}), '(payoff, -1)\n', (1551, 1563), True, 'import numpy as np\n'), ((1623, 1643), 'numpy.append', 'np.append', (['payoff', '(1)'], {}), '(payoff, 1)\n', (1632, 1643), True, 'import numpy as np\n'), ((1874, 1894), 'numpy.append', 'np.append', (['payoff', '(0)'], {}), '(payoff, 0)\n', (1883, 1894), True, 'import numpy as np\n'), ((1954, 1976), 'numpy.append', 'np.append', (['payoff', '(-10)'], {}), '(payoff, -10)\n', (1963, 1976), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os import numpy as np from scipy import linalg sys.path.append(sys.path.join("..","..","..")) from massFun.GeneralDataFunctions import rolling_window,moving_sdev,local_minimums,median_diffarr class baselineCorrection: # def rolling_window(self,a, window): # shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) # strides = a.strides + (a.strides[-1],) # return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) # def moving_sdev(self,x,sdev_width): # if sdev_width % 2 == 0: # print "stdev width has to be an odd number" # return x # movDev=np.std(self.rolling_window(x,sdev_width),1) # # adding the begin and end numbers to have the # # size the same as the original array # tails=np.ones((sdev_width-1)/2) # movDev=np.append(movDev[0]*tails,movDev) # movDev=np.append(movDev,movDev[movDev.size-1]*tails) # return movDev def stage1_fujchrom2016(self,x): return local_minimums(x) def stage2_fujchrom2016(self,x,window): x1=self.medSNR_elim(x,window) x2=self.firstDeriv_elim(x) retDict=dict() for i in x1: retDict[i]=min(x1[i],x2[i]) return retDict def stage3_fujchrom2016(self,x,y,st2wind): st1=self.stage1_fujchrom2016(y) st2=self.stage2_fujchrom2016(st1,st2wind) xf=list() yf=list() for oneX in sorted(st2): xf.append(oneX) yf.append(st2[oneX]) baseline=np.interp(x,xf,yf) baseline=np.minimum(baseline,y) return baseline # def local_minimums(self,x): # x=np.array(x) # xdata=self.rolling_window(x,3) # minDict=dict() # for i in range(xdata.shape[0]): # oneX=xdata[i,:] # #print oneX # if oneX[1]==min(oneX): # minDict[i+1]=oneX[1] # return minDict # def median_diffarr(self,x): # dx=x[1:]-x[0:-1] # dx=np.append(dx[0],dx) # return abs(dx-np.median(dx)) def medSNR_elim(self,x,window=30,prevResult=np.Inf): xkeys=x.keys() x1=np.array(x.values()) medx=np.median(x1) medDiffArr=median_diffarr(x1) sigma=1.483*np.median(medDiffArr) xdata=rolling_window(x1,window) beginshape=xdata.shape addp=(x1.shape[0]-xdata.shape[0])/2 for n in range(addp): xdata=np.append(xdata[0,:],xdata) xdata.shape=(beginshape[0]+addp,beginshape[1]) for n in range(addp): xdata=np.append(xdata,xdata[-1,:]) xdata.shape=(beginshape[0]+2*addp,beginshape[1]) retArr=dict() for i in range(1,x1.size-1): uno=np.abs(x1[i]-np.median(xdata[i]))/sigma due=np.abs(x1[i]-x1[i-1])/sigma tre=np.abs(x1[i]-x1[i+1])/sigma SNRi = max(uno,due,tre) if SNRi>2.5: retArr[xkeys[i]]=np.interp(xkeys[i],(xkeys[i-1],xkeys[i+1]),(x1[i-1],x1[i+1])) else: retArr[xkeys[i]]=x1[i] retArr[xkeys[0]]=retArr[xkeys[1]] retArr[xkeys[-1]]=retArr[xkeys[-2]] result=np.linalg.norm(np.array(retArr.values())-x1)/np.linalg.norm(x1) if result==prevResult: return retArr elif result > 1e-4: retArr=self.medSNR_elim(retArr,window, result) return retArr return x def firstDeriv_elim(self,x): xkeys=x.keys() x1=np.array(x.values()) medx=np.median(x1) medDiffArr=median_diffarr(x1)/x1 retArr=dict() for i in range(x1.size): #print medDiffArr[i] if medDiffArr[i]>2.5: if i==0: retArr[xkeys[i]]=x1[i+1] elif i==x1.size-1: retArr[xkeys[i]]=x1[i-1] else: retArr[xkeys[i]]=np.interp(xkeys[i],(xkeys[i-1],xkeys[i+1]),(x1[i-1],x1[i+1])) else: retArr[xkeys[i]]=x1[i] return retArr
[ "numpy.abs", "numpy.median", "massFun.GeneralDataFunctions.median_diffarr", "numpy.minimum", "sys.path.join", "massFun.GeneralDataFunctions.rolling_window", "numpy.append", "massFun.GeneralDataFunctions.local_minimums", "numpy.interp", "numpy.linalg.norm" ]
[((123, 154), 'sys.path.join', 'sys.path.join', (['""".."""', '""".."""', '""".."""'], {}), "('..', '..', '..')\n", (136, 154), False, 'import sys, os\n'), ((1082, 1099), 'massFun.GeneralDataFunctions.local_minimums', 'local_minimums', (['x'], {}), '(x)\n', (1096, 1099), False, 'from massFun.GeneralDataFunctions import rolling_window, moving_sdev, local_minimums, median_diffarr\n'), ((1610, 1630), 'numpy.interp', 'np.interp', (['x', 'xf', 'yf'], {}), '(x, xf, yf)\n', (1619, 1630), True, 'import numpy as np\n'), ((1646, 1669), 'numpy.minimum', 'np.minimum', (['baseline', 'y'], {}), '(baseline, y)\n', (1656, 1669), True, 'import numpy as np\n'), ((2277, 2290), 'numpy.median', 'np.median', (['x1'], {}), '(x1)\n', (2286, 2290), True, 'import numpy as np\n'), ((2310, 2328), 'massFun.GeneralDataFunctions.median_diffarr', 'median_diffarr', (['x1'], {}), '(x1)\n', (2324, 2328), False, 'from massFun.GeneralDataFunctions import rolling_window, moving_sdev, local_minimums, median_diffarr\n'), ((2385, 2411), 'massFun.GeneralDataFunctions.rolling_window', 'rolling_window', (['x1', 'window'], {}), '(x1, window)\n', (2399, 2411), False, 'from massFun.GeneralDataFunctions import rolling_window, moving_sdev, local_minimums, median_diffarr\n'), ((3633, 3646), 'numpy.median', 'np.median', (['x1'], {}), '(x1)\n', (3642, 3646), True, 'import numpy as np\n'), ((2349, 2370), 'numpy.median', 'np.median', (['medDiffArr'], {}), '(medDiffArr)\n', (2358, 2370), True, 'import numpy as np\n'), ((2544, 2573), 'numpy.append', 'np.append', (['xdata[0, :]', 'xdata'], {}), '(xdata[0, :], xdata)\n', (2553, 2573), True, 'import numpy as np\n'), ((2675, 2705), 'numpy.append', 'np.append', (['xdata', 'xdata[-1, :]'], {}), '(xdata, xdata[-1, :])\n', (2684, 2705), True, 'import numpy as np\n'), ((3325, 3343), 'numpy.linalg.norm', 'np.linalg.norm', (['x1'], {}), '(x1)\n', (3339, 3343), True, 'import numpy as np\n'), ((3666, 3684), 'massFun.GeneralDataFunctions.median_diffarr', 'median_diffarr', (['x1'], {}), '(x1)\n', (3680, 3684), False, 'from massFun.GeneralDataFunctions import rolling_window, moving_sdev, local_minimums, median_diffarr\n'), ((2893, 2918), 'numpy.abs', 'np.abs', (['(x1[i] - x1[i - 1])'], {}), '(x1[i] - x1[i - 1])\n', (2899, 2918), True, 'import numpy as np\n'), ((2937, 2962), 'numpy.abs', 'np.abs', (['(x1[i] - x1[i + 1])'], {}), '(x1[i] - x1[i + 1])\n', (2943, 2962), True, 'import numpy as np\n'), ((3059, 3132), 'numpy.interp', 'np.interp', (['xkeys[i]', '(xkeys[i - 1], xkeys[i + 1])', '(x1[i - 1], x1[i + 1])'], {}), '(xkeys[i], (xkeys[i - 1], xkeys[i + 1]), (x1[i - 1], x1[i + 1]))\n', (3068, 3132), True, 'import numpy as np\n'), ((2850, 2869), 'numpy.median', 'np.median', (['xdata[i]'], {}), '(xdata[i])\n', (2859, 2869), True, 'import numpy as np\n'), ((4019, 4092), 'numpy.interp', 'np.interp', (['xkeys[i]', '(xkeys[i - 1], xkeys[i + 1])', '(x1[i - 1], x1[i + 1])'], {}), '(xkeys[i], (xkeys[i - 1], xkeys[i + 1]), (x1[i - 1], x1[i + 1]))\n', (4028, 4092), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/21 17:29 # @Author : ganliang # @File : screenshot.py # @Desc : 屏幕截图 import time import numpy as np def window_capture(): """ window截屏 不跨平台 :return: """ def _window_capature(filename): import win32gui, win32ui, win32con, win32api hwnd = 0 # 窗口的编号,0号表示当前活跃窗口 # 根据窗口句柄获取窗口的设备上下文DC(Divice Context) hwndDC = win32gui.GetWindowDC(hwnd) # 根据窗口的DC获取mfcDC mfcDC = win32ui.CreateDCFromHandle(hwndDC) # mfcDC创建可兼容的DC saveDC = mfcDC.CreateCompatibleDC() # 创建bigmap准备保存图片 saveBitMap = win32ui.CreateBitmap() # 获取监控器信息 MoniterDev = win32api.EnumDisplayMonitors(None, None) w = MoniterDev[0][2][2] h = MoniterDev[0][2][3] # print w,h   #图片大小 # 为bitmap开辟空间 saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) # 高度saveDC,将截图保存到saveBitmap中 saveDC.SelectObject(saveBitMap) # 截取从左上角(0,0)长宽为(w,h)的图片 saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY) saveBitMap.SaveBitmapFile(saveDC, filename) beg = time.time() for i in range(10): _window_capature("haha{0}.jpg".format(time.time())) end = time.time() print(end - beg) print ((end - beg) / 10) def selenium_capature(): """ selenium web页面截屏 :return: """ from selenium import webdriver import time def capture(url, filename="capture.png"): browser = webdriver.Chrome(r"C:\Program Files (x86)\Google Chrome\chromedriver.exe") browser.set_window_size(1200, 900) browser.get(url) # Load page browser.execute_script(""" (function () { var y = 0; var step = 100; window.scroll(0, 0); function f() { if (y < document.body.scrollHeight) { y += step; window.scroll(0, y); setTimeout(f, 50); } else { window.scroll(0, 0); document.title += "scroll-done"; } } setTimeout(f, 1000); })(); """) for i in range(30): if "scroll-done" in browser.title: break time.sleep(1) beg = time.time() for i in range(10): browser.save_screenshot(filename) end = time.time() print(end - beg) browser.close() capture("//www.jb51.net") def pil_capature(): """ python pil模块截屏 :return: """ import time import numpy as np from PIL import ImageGrab # 每抓取一次屏幕需要的时间约为1s,如果图像尺寸小一些效率就会高一些 beg = time.time() for i in range(10): img = ImageGrab.grab(bbox=(250, 161, 1141, 610)) img = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 3) img.save('{0}.png'.format(time.time())) end = time.time() print(end - beg) def grap_capature(): """ pythonpil模块截屏 :return: """ from PIL import ImageGrab im = ImageGrab.grab() im.save('{0}.png'.format(time.time())) def pyqt_capature(): """ pyqt截屏 指定程序抓屏 被指定的程序不能最小化 否则抓取不到屏幕 :return: """ from PyQt5.QtWidgets import QApplication import win32gui import sys # hwnd = win32gui.FindWindow(None, 'C:\Windows\system32\cmd.exe') hwnd = win32gui.FindWindow(None, r'D:\Program Files\JetBrains\PyCharm Community Edition 2018.3.5\bin\pycharm64.exe') app = QApplication(sys.argv) screen = app.primaryScreen() img = screen.grabWindow(hwnd).toImage() img.save("screenshot.jpg") def pyautogui_capature(): """ pyautogui截屏 :return: """ import pyautogui import cv2 # img = pyautogui.screenshot(region=[0, 0, 100, 100]) # x,y,w,h img = pyautogui.screenshot() # x,y,w,h # img.save('screenshot.png') img.save("pyautogui_{0}.png".format(time.time())) cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) pyqt_capature()
[ "win32gui.GetWindowDC", "win32gui.FindWindow", "PIL.ImageGrab.grab", "pyautogui.screenshot", "selenium.webdriver.Chrome", "numpy.asarray", "time.sleep", "win32ui.CreateDCFromHandle", "PyQt5.QtWidgets.QApplication", "win32ui.CreateBitmap", "time.time", "win32api.EnumDisplayMonitors" ]
[((1168, 1179), 'time.time', 'time.time', ([], {}), '()\n', (1177, 1179), False, 'import time\n'), ((1274, 1285), 'time.time', 'time.time', ([], {}), '()\n', (1283, 1285), False, 'import time\n'), ((2631, 2642), 'time.time', 'time.time', ([], {}), '()\n', (2640, 2642), False, 'import time\n'), ((2867, 2878), 'time.time', 'time.time', ([], {}), '()\n', (2876, 2878), False, 'import time\n'), ((3009, 3025), 'PIL.ImageGrab.grab', 'ImageGrab.grab', ([], {}), '()\n', (3023, 3025), False, 'from PIL import ImageGrab\n'), ((3322, 3444), 'win32gui.FindWindow', 'win32gui.FindWindow', (['None', '"""D:\\\\Program Files\\\\JetBrains\\\\PyCharm Community Edition 2018.3.5\\\\bin\\\\pycharm64.exe"""'], {}), "(None,\n 'D:\\\\Program Files\\\\JetBrains\\\\PyCharm Community Edition 2018.3.5\\\\bin\\\\pycharm64.exe'\n )\n", (3341, 3444), False, 'import win32gui, win32ui, win32con, win32api\n'), ((3442, 3464), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (3454, 3464), False, 'from PyQt5.QtWidgets import QApplication\n'), ((3762, 3784), 'pyautogui.screenshot', 'pyautogui.screenshot', ([], {}), '()\n', (3782, 3784), False, 'import pyautogui\n'), ((435, 461), 'win32gui.GetWindowDC', 'win32gui.GetWindowDC', (['hwnd'], {}), '(hwnd)\n', (455, 461), False, 'import win32gui, win32ui, win32con, win32api\n'), ((503, 537), 'win32ui.CreateDCFromHandle', 'win32ui.CreateDCFromHandle', (['hwndDC'], {}), '(hwndDC)\n', (529, 537), False, 'import win32gui, win32ui, win32con, win32api\n'), ((652, 674), 'win32ui.CreateBitmap', 'win32ui.CreateBitmap', ([], {}), '()\n', (672, 674), False, 'import win32gui, win32ui, win32con, win32api\n'), ((714, 754), 'win32api.EnumDisplayMonitors', 'win32api.EnumDisplayMonitors', (['None', 'None'], {}), '(None, None)\n', (742, 754), False, 'import win32gui, win32ui, win32con, win32api\n'), ((1528, 1604), 'selenium.webdriver.Chrome', 'webdriver.Chrome', (['"""C:\\\\Program Files (x86)\\\\Google Chrome\\\\chromedriver.exe"""'], {}), "('C:\\\\Program Files (x86)\\\\Google Chrome\\\\chromedriver.exe')\n", (1544, 1604), False, 'from selenium import webdriver\n'), ((2250, 2261), 'time.time', 'time.time', ([], {}), '()\n', (2259, 2261), False, 'import time\n'), ((2350, 2361), 'time.time', 'time.time', ([], {}), '()\n', (2359, 2361), False, 'import time\n'), ((2681, 2723), 'PIL.ImageGrab.grab', 'ImageGrab.grab', ([], {'bbox': '(250, 161, 1141, 610)'}), '(bbox=(250, 161, 1141, 610))\n', (2695, 2723), False, 'from PIL import ImageGrab\n'), ((3900, 3915), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (3910, 3915), True, 'import numpy as np\n'), ((2222, 2235), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2232, 2235), False, 'import time\n'), ((3055, 3066), 'time.time', 'time.time', ([], {}), '()\n', (3064, 3066), False, 'import time\n'), ((3869, 3880), 'time.time', 'time.time', ([], {}), '()\n', (3878, 3880), False, 'import time\n'), ((1250, 1261), 'time.time', 'time.time', ([], {}), '()\n', (1259, 1261), False, 'import time\n'), ((2843, 2854), 'time.time', 'time.time', ([], {}), '()\n', (2852, 2854), False, 'import time\n')]
""" =========== classify.py =========== This module contains functionality for classifying nanopore captures. """ import os import re from abc import ABC, abstractmethod from dataclasses import dataclass from pathlib import PosixPath from typing import * # I know people don't like import *, but I think it has benefits for types (doesn't impede people from being generous with typing) import numpy as np import torch import torch.nn as nn from ..logger import Logger, getLogger from ..signals import Capture, FractionalizedSignal, RawSignal # TODO: Pipe through filtering https://github.com/uwmisl/poretitioner/issues/43 https://github.com/uwmisl/poretitioner/issues/68 # from .models import NTERs_trained_cnn_05152019 as pretrained_model from . import filtering from .configuration import ClassifierConfiguration from .core import NumpyArrayLike, PathLikeOrString, ReadId use_cuda = False # True # TODO : Don't hardcode use of CUDA : https://github.com/uwmisl/poretitioner/issues/41 ClassLabel = NewType("ClassLabel", str) # Maps a numpy array like (some vector encoding that represents a label) to a the label string. LabelForResult = Callable[[NumpyArrayLike], ClassLabel] __all__ = [ "predict_class", "ClassificationRunId", "ClassifierDetails", "ClassifierPlugin", "CLASSIFICATION_PATH", "ClassificationResult", "PytorchClassifierPlugin", ] # Uniquely identifies a classification run that happened (e.g. 'NTER_2018_RandomForest_Attempt_3'). ClassificationRunId = NewType("ClassificationRunId", str) @dataclass(frozen=True) class ClassifierDetails: model: str model_version: str classification_threshold: float # Timestamp of when this classification occurred, in seconds from epoch (as a float). # # Q: Why not date-time? # # A: Sadly, as of 2020, h5py doesn't provide a good way of storing dates [1]. # Doing so would also be less precise than storing epoch time. # # Q: Why seconds (knowing it will be fractionalized)? # # A: On most modern machines, python time.time() provides micro-second precision. # But this can't be guaranteed (on older machines, it might only provide second precision) [1]. # # If we really wanted an int, the alternative to guarantee an int would be to store # the timestamp in nanoseconds [3], but that feels verbose to me. # # [1] - https://stackoverflow.com/questions/23570632/store-datetimes-in-hdf5-with-h5py # [2] - https://docs.python.org/3/library/time.html#time.time # [3] - https://docs.python.org/3/library/time.html#time.time_ns timestamp_ms: float model_file: PathLikeOrString @dataclass(frozen=True) class CLASSIFICATION_PATH: ROOT = f"/Classification/" @classmethod def for_classification_run(cls, classification_run: ClassificationRunId) -> str: path = str(PosixPath(CLASSIFICATION_PATH.ROOT, classification_run)) return path @classmethod def pass_path(cls, classification_run: ClassificationRunId) -> str: """Path to the group that contains the readIds that passed classification during this classification run. Parameters ---------- classification_run : ClassificationRunId A unique identifier for the classification run that generated these results (e.g. "my_classication_run_04"). Returns ------- str Pathlike to path. (e.g. /Classifcation/my_classication_run_04/pass) """ CLASSICATION_RUN_PATH = cls.for_classification_run(classification_run) path = str(PosixPath(CLASSICATION_RUN_PATH, "pass")) return path @classmethod def fail_path(cls, classification_run: ClassificationRunId) -> str: """Path to the group that contains the readIds that failed classification during this classification run. Parameters ---------- classification_run : ClassificationRunId A unique identifier for the classification run that generated these results (e.g. "my_classication_run_04"). Returns ------- str Pathlike to path. (e.g. /Classifcation/my_classication_run_04/fail) """ CLASSICATION_RUN_PATH = cls.for_classification_run(classification_run) path = str(PosixPath(CLASSICATION_RUN_PATH, "fail")) return path def read_id_path(cls, classification_run: ClassificationRunId, read_id: ReadId) -> str: """Path to the group that contains the classification results for a given readId. Parameters ---------- classification_run : ClassificationRunId A unique identifier for the classification run that generated these results (e.g. "my_classication_run_04"). read_id : ReadId The readId of the read we want to know the classification results for. Returns ------- str Path to the group that contains the classification results for a given readId. """ CLASSICATION_RUN_PATH = cls.for_classification_run(classification_run) path = str(PosixPath(CLASSICATION_RUN_PATH, f"{read_id}")) return path @dataclass(frozen=True) class ClassificationResult: """The result of passing the capture data to the classifier. Fields ---------- score : float A value representing the 'score' of a label predicted by the classifier. Abstractly, the score is a measure of confidence that this label is correct, as determined by the score being greater than some threshold. What exact values this score can take on depends on your classifier (e.g. if you pass the final result through a soft-max, this score will represent a probability from 0 to 1.0). label : ClassLabel The label assigned to this prediction. Returns ------- [ClassificationResult] ClassificationResult instance. """ label: ClassLabel score: float # TODO: Finish writing Classifier plugin architecture: https://github.com/uwmisl/poretitioner/issues/91 class ClassifierPlugin(ABC): @abstractmethod def model_name(self) -> str: raise NotImplementedError("model_name hasn't been implemented for this classifier.") @abstractmethod def model_version(self) -> str: raise NotImplementedError("model_version hasn't been implemented for this classifier.") @abstractmethod def model_file(self) -> str: raise NotImplementedError("model_file hasn't been implemented for this classifier.") @abstractmethod def load(self, use_cuda: bool = False): """Loads a model for classification. This method is where you should do any pre processing needed. For exammple, loading and configuring a Pytorch model, or a sci-kit learn model. Parameters ---------- use_cuda : bool Whether to use cuda. Raises ------ NotImplementedError If this method hasn't been implemented. """ raise NotImplementedError("load hasn't been implemented for this classifier.") @abstractmethod def evaluate(self, capture) -> ClassificationResult: raise NotImplementedError("Evaluate hasn't been implemented for this classifier.") # TODO: Implement Classification with the new data model: https://github.com/uwmisl/poretitioner/issues/92 def filter_and_classify( config, capture_filepaths: List[PathLikeOrString], overwrite=False, filter_name=None ): local_logger = logger.getLogger() clf_config = config["classify"] classifier_name = clf_config["classifier"] classification_path = clf_config["classification_path"] # Load classifier local_logger.info(f"Loading classifier {classifier_name}.") assert classifier_name in ["NTER_cnn", "NTER_rf"] assert classification_path is not None and len(classification_path) > 0 classifier = init_classifier(classifier_name, classification_path) # Filter (optional) TODO: Restore filtering https://github.com/uwmisl/poretitioner/issues/43 https://github.com/uwmisl/poretitioner/issues/68 read_path = "/" # if filter_name is not None: # local_logger.info("Beginning filtering.") # filter.filter_and_store_result(config, fast5_fnames, filter_name, overwrite=overwrite) # read_path = f"/Filter/{filter_name}/pass" # else: # read_path = "/" # Classify classify_fast5_file(f5, clf_config, classifier, classifier_name, read_path) # def classify_file( # capturef5: ClassifierFile, configuration: ClassifierConfiguration, classifier: Classifier, classifier_run_name, read_path, class_labels=None): # for read in capturef5.reads: # pass # TODO: Implement Classification with the new data model: https://github.com/uwmisl/poretitioner/issues/92 def classify_fast5_file( capture_filepath: PathLikeOrString, clf_config, classifier, classifier_run_name, read_path, class_labels=None, ): local_logger = logger.getLogger() local_logger.debug(f"Beginning classification for file {capture_filepath}.") classifier_name = clf_config["classifier"] classifier_version = clf_config["version"] classifier_location = clf_config["filepath"] classify_start = clf_config["start_obs"] # 100 in NTER paper classify_end = clf_config["end_obs"] # 21000 in NTER paper classifier_confidence_threshold = clf_config["min_confidence"] configuration = ClassifierConfiguration( classifier_name, classifier_version, classify_start, classify_end, classifier_confidence_threshold, ) # details = ClassifierDetails(classifier_name, , , ) # ClassifierFile(filepath, ) details = None # ClassifierDetails(classifier_name, ) assert classify_start >= 0 and classify_end >= 0 assert classifier_confidence_threshold is None or (0 <= classifier_confidence_threshold <= 1) local_logger.debug( f"Classification parameters: name: {classifier_name}, " f"range of data points: ({classify_start}, {classify_end})" f"confidence required to pass: {classifier_confidence_threshold}" ) results_path = f"/Classification/{classifier_run_name}" write_classifier_details(f5, clf_config, results_path) with ClassifierFile(capture_filepath, "r+") as classifier_f5: details = ClassifierDetails( classifier_name, classifier_version, classifier_location, classifier_confidence_threshold, ) classifier_f5.write_details(details) for read in classifier_f5.reads: signal = classifier_f5.get_fractionalized_read( read, start=classify_start, end=classify_end ) labels, probability = predict_class( classifier_name, classifier, signal, class_labels=class_labels ) if classifier_confidence_threshold is not None: passed_classification = probability > classifier_confidence_threshold else: passed_classification = None write_classifier_result() # read_h5group_names = f5.get(read_path) # for grp in read_h5group_names: # if "read" not in grp: # continue # read_id = re.findall(r"read_(.*)", str(grp))[0] # signal = get_fractional_blockage_for_read( # f5, grp, start=classify_start, end=classify_end # ) # y, p = predict_class(classifier_name, classifier, signal, class_labels=class_labels) # if classifier_confidence_threshold is not None: # passed_classification = False if p <= classifier_confidence_threshold else True # else: # passed_classification = None # write_classifier_result(f5, results_path, read_id, y, p, passed_classification) # TODO: Implement Classification with the new data model: https://github.com/uwmisl/poretitioner/issues/92 # TODO: This classifier initialization should be a special case of a Plugin: https://github.com/uwmisl/poretitioner/issues/91 def init_classifier(classifier_name, classification_path): """Initialize the classification model. Supported classifier names include "NTER_cnn" and "NTER_rf". According to documentation for original NTER code: Prediction classes are 1-9: 0:Y00, 1:Y01, 2:Y02, 3:Y03, 4:Y04, 5:Y05, 6:Y06, 7:Y07, 8:Y08, 9:noise, -1:below conf_thesh Parameters ---------- classifier_name : str The name of any supported classifier, currently "NTER_cnn" and "NTER_rf". classification_path : str Location of the pre-trained model file. Returns ------- model Classification model (type depends on the spceified model). Raises ------ ValueError Raised if the classifier name is not supported. OSError Raised if the classifier path does not exist. """ if classifier_name == "NTER_cnn": # CNN classifier if not os.path.exists(classification_path): raise OSError(f"Classifier path doesn't exist: {classification_path}") nanoporeTER_cnn = pretrained_model.load_cnn(classification_path) return nanoporeTER_cnn elif classifier_name == "NTER_rf": # Random forest classifier if not os.path.exists(classification_path): raise OSError(f"Classifier path doesn't exist: {classification_path}") # TODO : Improve model maintainability : https://github.com/uwmisl/poretitioner/issues/38 # return joblib.load(open(classification_path, "rb")) pass else: raise ValueError(f"Invalid classifier name: {classifier_name}") # TODO: Implement Classification with the new data model: https://github.com/uwmisl/poretitioner/issues/92 def predict_class(classifier_name, classifier, raw, class_labels=None) -> ClassificationResult: """Runs the classifier using the given raw data as input. Does not apply any kind of confidence threshold. Parameters ---------- classifier_name : str The name of any supported classifier, currently "NTER_cnn" and "NTER_rf". classifier : model Classification model returned by init_classifier. raw : iterable of floats Time series of nanopore current values (in units of fractionalized current). Returns ------- int or string Class label float Model score (for NTER_cnn and NTER_rf, it's a probability) Raises ------ NotImplementedError Raised if the input classifier_name is not supported. """ if classifier_name == "NTER_cnn": X_test = np.array([raw]) # 2D --> 3D array (each obs in a capture becomes its own array) X_test = X_test.reshape(len(X_test), X_test.shape[1], 1) if X_test.shape[1] < 19881: temp = np.zeros((X_test.shape[0], 19881, 1)) temp[:, : X_test.shape[1], :] = X_test X_test = temp X_test = X_test[:, :19881] # First 19881 obs as per NTER paper # Break capture into 141x141 (19881 total data points) X_test = X_test.reshape(len(X_test), 1, 141, 141) X_test = torch.from_numpy(X_test) if use_cuda: X_test = X_test.cuda() outputs = classifier(X_test) out = nn.functional.softmax(outputs, dim=1) prob, label = torch.topk(out, 1) if use_cuda: label = label.cpu().numpy()[0][0] else: label = label.numpy()[0][0] if class_labels is not None: label = class_labels[label] probability = prob[0][0].data # TODO: Implement Classification with the new data model: https://github.com/uwmisl/poretitioner/issues/92 # TODO: Katie Q: Where does assigned class come from? ClassificationResult(label, probability) return label, probability elif classifier_name == "NTER_rf": class_proba = classifier.predict_proba( [[np.mean(raw), np.std(raw), np.min(raw), np.max(raw), np.median(raw)]] )[0] max_proba = np.amax(class_proba) label = np.where(class_proba == max_proba)[0][0] if class_labels is not None: label = class_labels[label] return label, class_proba else: raise NotImplementedError(f"Classifier {classifier_name} not implemented.") # def get_classification_for_read(f5, read_id, results_path) -> ClassificationResult: # local_logger = logger.getLogger() # results_path = f"{results_path}/{read_id}" # result = NULL_CLASSIFICATION_RESULT # if results_path not in f5: # local_logger.info( # f"Read {read_id} has not been classified yet, or result" # f"is not stored at {results_path} in file {f5.filename}." # ) # else: # predicted_class = f5[results_path].attrs["best_class"] # probability = f5[results_path].attrs["best_score"] # assigned_class = f5[results_path].attrs["assigned_class"] # result = ClassificationResult(predicted_class, probability, assigned_class) # return result def write_classifier_details( f5, classifier_confidence_thresholdig: ClassifierConfiguration, results_path ): """Write metadata about the classifier that doesn't need to be repeated for each read. Parameters ---------- f5 : h5py.File Opened fast5 file in a writable mode. classifier_confidence_threshold : dict Subset of the configuration parameters that belong to the classifier. results_path : str Where the classification results will be stored in the f5 file. """ if results_path not in f5: f5.require_group(results_path) f5[results_path].attrs["model"] = classifier_confidence_thresholdig.classifier f5[results_path].attrs["model_version"] = classifier_confidence_thresholdig f5[results_path].attrs["model_file"] = classifier_confidence_thresholdig["classification_path"] f5[results_path].attrs["classification_threshold"] = classifier_confidence_thresholdig[ "min_confidence" ] def write_classifier_result( f5, results_path, read_id, predicted_class, prob, passed_classification ): results_path = f"{results_path}/{read_id}" if results_path not in f5: f5.require_group(results_path) f5[results_path].attrs["best_class"] = predicted_class f5[results_path].attrs["best_score"] = prob f5[results_path].attrs["assigned_class"] = predicted_class if passed_classification else -1 class PytorchClassifierPlugin(ClassifierPlugin): def __init__( self, module: nn.Module, name: str, version: str, state_dict_filepath: PathLikeOrString, use_cuda: bool = False, ): """An abstract class for classifier that are built from PyTorch. Subclass this and implement `evaluate` Optionally, if you'd like to do some special pre-processing on the data or load the PyTorch module in a specific way do so by writing `pre_process` and `load` functions as well, and call them before evaluating the module in `evalaute`. For an example of this in action, see the `models/NTERs_trained_cnn_05152019.py` module. Parameters ---------- module : nn.Module The PyTorch module to use as a classifier. This can be either the instantiated module, or the class itself. If the class is passed, a bare module will be instantiated from it. name : str Uniquely identifying name for this module. version : str Version of the model. Useful for keeping track of differently learned parameters. state_dict_filepath : PathLikeOrString Path to the state_dict describing the module's parameters. For more on PyTorch state_dicts, see https://pytorch.org/tutorials/recipes/recipes/what_is_state_dict.html. use_cuda : bool, optional Whether to use CUDA for GPU processing, by default False """ super().__init__() self.module = ( module if isinstance(module, nn.Module) else module() ) # Instantiate the module, if the user passed in the class rather than an instance. self.name = name self.version = version self.state_dict_filepath = state_dict_filepath self.use_cuda = use_cuda def load(self, use_cuda: bool = False): """Loads the PyTorch module. This means instantiating it, setting its state dict [1], and setting it to evaluation mode (so we perform an inference)[2]. [1] - https://pytorch.org/tutorials/recipes/recipes/what_is_state_dict.html [2] - https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.eval Parameters ---------- filepath : str Filepath to a PyTorch state dict. use_cuda : bool, optional Whether to use CUDA, by default False """ torch_module = self.module # For more on Torch devices, please see: # https://pytorch.org/docs/stable/tensor_attributes.html#torch-device device = "cpu" if not use_cuda else "cuda" state_dict = torch.load(str(state_dict_filepath), map_location=torch.device(device)) torch_module.load_state_dict(state_dict, strict=True) # Sets the model to inference mode torch_module.eval() # Ensures subsequent uses of self.module are correctly configured. self.module = torch_module def pre_process(self, capture: Capture) -> torch.Tensor: """Do some pre-processing on the data, if desired. Otherwise, this method just converts the fractionalized capture to a torch Tensor. Parameters ---------- capture : Capture Capture we want to classify. Returns ------- torch.Tensor A tensor that resulted from pre-processing the capture data. """ tensor = torch.from_numpy(capture.fractionalized()) if self.use_cuda: tensor = tensor.cuda() return tensor @abstractmethod def evaluate(self, capture: Capture): raise NotImplementedError("Evaluate hasn't been implemented for this classifier.") def model_name(self) -> str: return self.name def model_version(self) -> str: return self.version def model_file(self) -> str: return self.state_dict_filepath
[ "os.path.exists", "numpy.mean", "numpy.median", "pathlib.PosixPath", "numpy.where", "torch.topk", "dataclasses.dataclass", "numpy.min", "torch.from_numpy", "numpy.max", "numpy.array", "numpy.zeros", "numpy.std", "numpy.amax", "torch.nn.functional.softmax", "torch.device" ]
[((1546, 1568), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (1555, 1568), False, 'from dataclasses import dataclass\n'), ((2667, 2689), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (2676, 2689), False, 'from dataclasses import dataclass\n'), ((5201, 5223), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (5210, 5223), False, 'from dataclasses import dataclass\n'), ((14740, 14755), 'numpy.array', 'np.array', (['[raw]'], {}), '([raw])\n', (14748, 14755), True, 'import numpy as np\n'), ((15273, 15297), 'torch.from_numpy', 'torch.from_numpy', (['X_test'], {}), '(X_test)\n', (15289, 15297), False, 'import torch\n'), ((15405, 15442), 'torch.nn.functional.softmax', 'nn.functional.softmax', (['outputs'], {'dim': '(1)'}), '(outputs, dim=1)\n', (15426, 15442), True, 'import torch.nn as nn\n'), ((15465, 15483), 'torch.topk', 'torch.topk', (['out', '(1)'], {}), '(out, 1)\n', (15475, 15483), False, 'import torch\n'), ((2870, 2925), 'pathlib.PosixPath', 'PosixPath', (['CLASSIFICATION_PATH.ROOT', 'classification_run'], {}), '(CLASSIFICATION_PATH.ROOT, classification_run)\n', (2879, 2925), False, 'from pathlib import PosixPath\n'), ((3603, 3643), 'pathlib.PosixPath', 'PosixPath', (['CLASSICATION_RUN_PATH', '"""pass"""'], {}), "(CLASSICATION_RUN_PATH, 'pass')\n", (3612, 3643), False, 'from pathlib import PosixPath\n'), ((4321, 4361), 'pathlib.PosixPath', 'PosixPath', (['CLASSICATION_RUN_PATH', '"""fail"""'], {}), "(CLASSICATION_RUN_PATH, 'fail')\n", (4330, 4361), False, 'from pathlib import PosixPath\n'), ((5130, 5176), 'pathlib.PosixPath', 'PosixPath', (['CLASSICATION_RUN_PATH', 'f"""{read_id}"""'], {}), "(CLASSICATION_RUN_PATH, f'{read_id}')\n", (5139, 5176), False, 'from pathlib import PosixPath\n'), ((13093, 13128), 'os.path.exists', 'os.path.exists', (['classification_path'], {}), '(classification_path)\n', (13107, 13128), False, 'import os\n'), ((14948, 14985), 'numpy.zeros', 'np.zeros', (['(X_test.shape[0], 19881, 1)'], {}), '((X_test.shape[0], 19881, 1))\n', (14956, 14985), True, 'import numpy as np\n'), ((16184, 16204), 'numpy.amax', 'np.amax', (['class_proba'], {}), '(class_proba)\n', (16191, 16204), True, 'import numpy as np\n'), ((13399, 13434), 'os.path.exists', 'os.path.exists', (['classification_path'], {}), '(classification_path)\n', (13413, 13434), False, 'import os\n'), ((21384, 21404), 'torch.device', 'torch.device', (['device'], {}), '(device)\n', (21396, 21404), False, 'import torch\n'), ((16221, 16255), 'numpy.where', 'np.where', (['(class_proba == max_proba)'], {}), '(class_proba == max_proba)\n', (16229, 16255), True, 'import numpy as np\n'), ((16081, 16093), 'numpy.mean', 'np.mean', (['raw'], {}), '(raw)\n', (16088, 16093), True, 'import numpy as np\n'), ((16095, 16106), 'numpy.std', 'np.std', (['raw'], {}), '(raw)\n', (16101, 16106), True, 'import numpy as np\n'), ((16108, 16119), 'numpy.min', 'np.min', (['raw'], {}), '(raw)\n', (16114, 16119), True, 'import numpy as np\n'), ((16121, 16132), 'numpy.max', 'np.max', (['raw'], {}), '(raw)\n', (16127, 16132), True, 'import numpy as np\n'), ((16134, 16148), 'numpy.median', 'np.median', (['raw'], {}), '(raw)\n', (16143, 16148), True, 'import numpy as np\n')]
from .o3d import kdtree as o3d_kdtree from concurrent.futures import ThreadPoolExecutor from importlib import import_module import numpy as np FAISS_INSTALLED = False try: faiss = import_module('faiss') FAISS_INSTALLED = True except Exception as e: print(e) print('Cannot import faiss for GPU nearest neighbout search, use Open3d instead.') class _NearestNeighbors(object): def __init__(self, set_k=None, **kwargs): self.model = None self.set_k = set_k def train(self, data): pass def search(self, data, k, return_distance=True): if self.set_k is not None: assert self.set_k == k, \ 'K not match to setting {}'.format(self.set_k) D, I = None, None return D, I class Open3dNN(_NearestNeighbors): def __init__(self, set_k=None, **kwargs): super(Open3dNN, self).__init__(set_k, **kwargs) self.model = None def train(self, data): assert data.shape[1] == 3, 'Must be shape [?, 3] for point data' self.model = o3d_kdtree(data) def search(self, data, k, return_distance=False): assert self.model is not None, "Model have not been trained" if data.shape[0] == 1: [__, I, _] = self.model.search_knn_vector_3d(data[0], k) else: I = np.zeros((data.shape[0], k), dtype=np.int) with ThreadPoolExecutor(256) as executor: for i in range(I.shape[0]): executor.submit(self._search_multiple, (self.model, I, data, k, i,)) return None, I @staticmethod def _search_multiple(knn_searcher, I, data, k, i): [__, I_, _] = knn_searcher.search_knn_vector_3d(data[i, :], k) I[i, :] = np.asarray(I_) class FaissNN(_NearestNeighbors): #GPU KNN Search for large scale def __init__(self, set_k=None, **kwargs): super(FaissNN, self).__init__(set_k, **kwargs) self.IVF_number = 32786 self.GPU_id = None if isinstance(kwargs, dict): if 'IVF_number' in kwargs: self.IVF_number = kwargs['IVF_number'] if 'GPU_id' in kwargs: self.GPU_id = kwargs['GPU_id'] self.model = None self.dimension = None def train(self, data): d = data.shape[1] data = data.astype(np.float32) self.model = faiss.index_factory(int(d), 'IVF{}_HNSW32,Flat'.format(self.IVF_number)) #_HNSW32 if self.GPU_id is not None and isinstance(self.GPU_id, int): res = faiss.StandardGpuResources() self.model = faiss.index_cpu_to_gpu(res, self.GPU_id, self.model) elif isinstance(self.GPU_id, list): #os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = ','.join([str(i) for i in self.GPU_id]) self.model = faiss.index_cpu_to_all_gpus(self.model) else: self.model = faiss.index_cpu_to_all_gpus(self.model) self.model.train(data) self.model.add(data) self.model.nprobe = d ** 2 def search(self, data, k, return_distance=True): data = data.astype(np.float32) assert self.model is not None, "Model have not been trained" #assert self.model.is_trained, "Model not trained." D, I = self.model.search(data, k) if return_distance: D = None return D, I if __name__ == "__main__": import sys import time import os #os.environ['CUDA_VISIBLE_DEVICES'] = '1' nb = 10**5 nq = 10**5 np.random.seed(1) datab = np.random.rand(nb, 3).astype('float32') dataq = np.random.rand(nq, 3).astype('float32') tic = time.time() nn = SkNN(set_k=3) nn.train(datab) print(time.time() - tic) tic = time.time() D, I = nn.search(dataq, 3) print(time.time() - tic)
[ "importlib.import_module", "numpy.random.rand", "concurrent.futures.ThreadPoolExecutor", "numpy.asarray", "numpy.zeros", "numpy.random.seed", "time.time" ]
[((185, 207), 'importlib.import_module', 'import_module', (['"""faiss"""'], {}), "('faiss')\n", (198, 207), False, 'from importlib import import_module\n'), ((3532, 3549), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (3546, 3549), True, 'import numpy as np\n'), ((3665, 3676), 'time.time', 'time.time', ([], {}), '()\n', (3674, 3676), False, 'import time\n'), ((3759, 3770), 'time.time', 'time.time', ([], {}), '()\n', (3768, 3770), False, 'import time\n'), ((1750, 1764), 'numpy.asarray', 'np.asarray', (['I_'], {}), '(I_)\n', (1760, 1764), True, 'import numpy as np\n'), ((1326, 1368), 'numpy.zeros', 'np.zeros', (['(data.shape[0], k)'], {'dtype': 'np.int'}), '((data.shape[0], k), dtype=np.int)\n', (1334, 1368), True, 'import numpy as np\n'), ((3562, 3583), 'numpy.random.rand', 'np.random.rand', (['nb', '(3)'], {}), '(nb, 3)\n', (3576, 3583), True, 'import numpy as np\n'), ((3614, 3635), 'numpy.random.rand', 'np.random.rand', (['nq', '(3)'], {}), '(nq, 3)\n', (3628, 3635), True, 'import numpy as np\n'), ((3730, 3741), 'time.time', 'time.time', ([], {}), '()\n', (3739, 3741), False, 'import time\n'), ((3812, 3823), 'time.time', 'time.time', ([], {}), '()\n', (3821, 3823), False, 'import time\n'), ((1386, 1409), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', (['(256)'], {}), '(256)\n', (1404, 1409), False, 'from concurrent.futures import ThreadPoolExecutor\n')]
import utils.cs_vqe_tools_original as c import utils.qonversion_tools as qonvert #from openfermion.linalg import get_ground_state import utils.linalg_tools as la from copy import deepcopy import numpy as np import itertools import matplotlib.pyplot as plt class cs_vqe_model: """Class for constructing instances of CS-VQE Hamiltonians Attributes ---------- ham : dict Dictionary of Hamiltnonian terms (Pauli strings) and corresponding coefficients terms_noncon : list Noncontextual subset of Hamiltonian terms num_qubits : int The number of qubits in the Hamiltonian Methods ------- ham_noncon Return the noncontextual Hamiltnoian gs_noncon Noncontextual ground state parameter setting and energy gs_noncon_energy Noncontextual ground state energy ep_state Noncontextual ground state parameter setting ep_dist Probability distribution corresponding with the epistemic state model generate the epistricted model fn_form rotations Determine necessary rotations such the commuting noncontextual generators consist of single Pauli Z get_ham Retrieve full, noncontextual or contextual Hamiltonian with or without rotations applied generators Retrieve commuting noncontextual generators and observable A with or without rotations applied move_generator Manually remove generators and all operators in their support from noncontextual to contextual Hamiltonian reduced_hamiltonian Generate the contextual subspace Hamiltonians for a given number of qubits true_gs Obtain true ground state via linear algebra (inefficient) true_gs_hist Plot histogram of basis state probability weightings in true ground state init_state Determing the reference state of the ansatz """ def __init__(self, ham, terms_noncon, num_qubits):#, rot_G=True, rot_A=False): assert(type(ham)==dict) self.ham = ham self.terms_noncon = terms_noncon self.num_qubits = num_qubits #self.rot_A = rot_A #self.rot_G = rot_G # required for the following methods - use get_ham to retrieve hamiltonians in practice def ham_noncon(self): """Return the noncontextual Hamiltnoian Returns ------- dict Dictionary of noncontextual Hamiltnonian terms (Pauli strings) and corresponding coefficients """ #print(self.terms_noncon) return {t:self.ham[t] for t in self.terms_noncon} def gs_noncon(self): """Noncontextual ground state parameter setting and energy Returns ------- list """ return c.find_gs_noncon(self.ham_noncon()) def gs_noncon_energy(self): """Noncontextual ground state energy """ return (self.gs_noncon())[0] def ep_state(self): """Noncontextual ground state parameter setting """ return (self.gs_noncon())[1] def ep_dist(self): """Probability distribution corresponding with the epistemic state Returns ------- """ ep = self.ep_state() size_G = len(ep[0]) size_Ci = len(ep[1]) size_R = size_G + size_Ci ep_prob = {} ontic_states = list(itertools.product([1, -1], repeat=size_R)) for o in ontic_states: o_state = [list(o[0:size_G]), list(o[size_G:size_R])] o_prob = c.ontic_prob(ep, o_state) if o_prob != 0: ep_prob[o] = o_prob return ep_prob def model(self): """generate the epistricted model Returns ------- """ return c.quasi_model(self.ham_noncon()) def fn_form(self): """ Returns ------- """ return c.energy_function_form(self.ham_noncon(), self.model()) def rotations(self, rot_override=False): """Determine necessary rotations such the commuting noncontextual generators consist of single Pauli Z Returns ------- """ if not rot_override: return (c.diagonalize_epistemic(self.model(),self.fn_form(),self.ep_state()))[0] else: return (c.diagonalize_epistemic(self.model(),self.fn_form(),self.ep_state(),rot_A=False))[0] # get the noncontextual and contextual Hamiltonians def get_ham(self, h_type='full'): """Retrieve full, noncontextual or contextual Hamiltonian with or without rotations applied Paramters --------- h_type: str optional allowed value are 'full', 'noncon', 'context' for corresponding Hamiltonian to be returned rot: bool optional Specifies either unrotated or rotated Hamiltonian Returns ------- dict returns the full, noncontextual or contextual Hamiltonian specified by h_type """ if h_type == 'full': ham_ref = self.ham elif h_type == 'noncon': ham_ref = {t:self.ham[t] for t in self.terms_noncon} elif h_type == 'context': ham_ref = {t:self.ham[t] for t in self.ham.keys() if t not in self.terms_noncon} else: raise ValueError('Invalid value given for h_type: must be full, noncon or context') #if self.rot_G: ham_ref = c.rotate_operator(self.rotations(), ham_ref) return ham_ref # get generators and observable A def generators(self): """Retrieve commuting noncontextual generators and observable A with or without rotations applied Paramters --------- rot: bool optional Specifies either unrotated or rotated Hamiltonian Returns ------- set Generators and observable A in form (dict(G), dict(A_obsrv)) """ ep = self.ep_state() mod = self.model() G_list = {g:ep[0][index] for index, g in enumerate(mod[0])} A_obsrv = {Ci1:ep[1][index] for index, Ci1 in enumerate(mod[1])} G_list = c.rotate_operator(self.rotations(), G_list) A_obsrv = c.rotate_operator(self.rotations(), A_obsrv) return G_list, A_obsrv def move_generator(self, rem_gen): """Manually remove generators and all operators in their support from noncontextual to contextual Hamiltonian Paramters --------- rem_gen: list list of generators (Paulis strings) to remove from noncontextual Hamiltonian rot: bool optional Specifies either unrotated or rotated Hamiltonian Returns ------- set In form (new_ham_noncon, new_ham_context) """ return c.discard_generator(self.get_ham(h_type='noncon'), self.get_ham(h_type='context'), rem_gen) def reduced_hamiltonian(self, order=None, num_sim_q=None): """Generate the contextual subspace Hamiltonians for a given number of qubits Parameters ---------- order: list optional list of integers specifying order in which to remove qubits sim_qubits : int optional number of qubits in final Hamiltonian Returns ------- dict reduced Hamiltonian for number of qubits specified. Returns all if sim_qubits==None. """ if order is None: order = list(range(self.num_qubits)) order_ref = deepcopy(order) ham_red = c.get_reduced_hamiltonians(self.ham,self.model(),self.fn_form(),self.ep_state(),order_ref)#,self.rot_A) if num_sim_q is None: return ham_red else: return ham_red[num_sim_q-1] def true_gs(self, rot_override=False): """Obtain true ground state via linear algebra (inefficient) Parameters ---------- rot: bool optional Specifies either unrotated or rotated Hamiltonian Returns ------- list (true gs energy, true gs eigenvector) """ ham_mat = qonvert.dict_to_WeightedPauliOperator(self.ham).to_matrix() gs = la.get_ground_state(ham_mat) return gs def true_gs_hist(self, threshold, rot_override=False): """Plot histogram of basis state probability weightings in true ground state Parameters ---------- threshold: float minimum probability threshold to include in plot, i.e. 1e-n rot: bool optional Specifies either unrotated or rotated Hamiltonian Returns ------- Figure histogram of probabilities """ gs_vec = (self.true_gs(rot_override))[1] amp_list = [abs(a)**2 for a in list(gs_vec)] sig_amp_list = sorted([(str(index), a) for index, a in enumerate(amp_list) if a > threshold], key=lambda x:x[1]) sig_amp_list.reverse() XY = list(zip(*sig_amp_list)) X = XY[0] Y = XY[1] Y_log = [np.log10(a) for a in Y] fig = plt.figure(figsize=(15, 6), dpi=300) plt.grid(zorder=0) plt.bar(X, Y, zorder=2, label='Probability of observing basis state') plt.bar(X, Y_log, zorder=3, label = 'log (base 10) of probability') plt.xticks(rotation=90) plt.title('Probability weighting of basis states in the true ground state (above %s)' % str(threshold)) plt.xlabel('Basis state index') plt.legend() return fig # corresponds with the Hartree-Fock state def init_state(self): """ TODO - should work for non-rotated generators too """ G = self.generators()[0] zeroes = list(''.zfill(self.num_qubits)) for g in G.keys(): if G[g] == -1: Z_index = g.find('Z') zeroes[Z_index] = '1' return ''.join(zeroes)
[ "utils.linalg_tools.get_ground_state", "utils.qonversion_tools.dict_to_WeightedPauliOperator", "matplotlib.pyplot.grid", "numpy.log10", "matplotlib.pyplot.xticks", "matplotlib.pyplot.xlabel", "itertools.product", "matplotlib.pyplot.figure", "matplotlib.pyplot.bar", "copy.deepcopy", "utils.cs_vqe...
[((7635, 7650), 'copy.deepcopy', 'deepcopy', (['order'], {}), '(order)\n', (7643, 7650), False, 'from copy import deepcopy\n'), ((8343, 8371), 'utils.linalg_tools.get_ground_state', 'la.get_ground_state', (['ham_mat'], {}), '(ham_mat)\n', (8362, 8371), True, 'import utils.linalg_tools as la\n'), ((9247, 9283), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 6)', 'dpi': '(300)'}), '(figsize=(15, 6), dpi=300)\n', (9257, 9283), True, 'import matplotlib.pyplot as plt\n'), ((9293, 9311), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'zorder': '(0)'}), '(zorder=0)\n', (9301, 9311), True, 'import matplotlib.pyplot as plt\n'), ((9320, 9389), 'matplotlib.pyplot.bar', 'plt.bar', (['X', 'Y'], {'zorder': '(2)', 'label': '"""Probability of observing basis state"""'}), "(X, Y, zorder=2, label='Probability of observing basis state')\n", (9327, 9389), True, 'import matplotlib.pyplot as plt\n'), ((9398, 9463), 'matplotlib.pyplot.bar', 'plt.bar', (['X', 'Y_log'], {'zorder': '(3)', 'label': '"""log (base 10) of probability"""'}), "(X, Y_log, zorder=3, label='log (base 10) of probability')\n", (9405, 9463), True, 'import matplotlib.pyplot as plt\n'), ((9474, 9497), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (9484, 9497), True, 'import matplotlib.pyplot as plt\n'), ((9618, 9649), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Basis state index"""'], {}), "('Basis state index')\n", (9628, 9649), True, 'import matplotlib.pyplot as plt\n'), ((9658, 9670), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (9668, 9670), True, 'import matplotlib.pyplot as plt\n'), ((3391, 3432), 'itertools.product', 'itertools.product', (['[1, -1]'], {'repeat': 'size_R'}), '([1, -1], repeat=size_R)\n', (3408, 3432), False, 'import itertools\n'), ((3561, 3586), 'utils.cs_vqe_tools_original.ontic_prob', 'c.ontic_prob', (['ep', 'o_state'], {}), '(ep, o_state)\n', (3573, 3586), True, 'import utils.cs_vqe_tools_original as c\n'), ((9208, 9219), 'numpy.log10', 'np.log10', (['a'], {}), '(a)\n', (9216, 9219), True, 'import numpy as np\n'), ((8270, 8317), 'utils.qonversion_tools.dict_to_WeightedPauliOperator', 'qonvert.dict_to_WeightedPauliOperator', (['self.ham'], {}), '(self.ham)\n', (8307, 8317), True, 'import utils.qonversion_tools as qonvert\n')]
import math import numpy as np import functions.optimiser as op # finds the change in tremor output def calc_delta(feature, index_difference=1): past_feature = shift(feature, index_difference) # replaces all zeros with the first non-zero value for i in range(index_difference): past_feature[i] = past_feature[index_difference] return np.subtract(feature, past_feature) # uses numpy to quickly/efficiently get the difference # calculates the average of every [horizon] values in an array def calc_average(feature, horizon): avg_array = [] horizon_midpoint = int(math.floor(horizon / 2)) for i in range(len(feature)): # ensures the average is still calculated correctly at the beginning of the feature list if i < horizon_midpoint: temp_array = feature[:2 * i + 1] elif i >= (len(feature) - horizon_midpoint): first_index = i - round((len(feature) - i) / 2) temp_array = feature[first_index:len(feature)] else: # the correct values are selected (i in the middle) even if the horizon is even if horizon % 2 == 0: temp_array = feature[(i - horizon_midpoint):(i + horizon_midpoint)] else: temp_array = feature[(i - horizon_midpoint):(i + horizon_midpoint + 1)] avg_array.append(sum(temp_array) / len(temp_array)) # saves average to the array return avg_array def calc_median(feature, horizon): avg_array = [] horizon_midpoint = int(math.floor(horizon / 2)) for i in range(len(feature)): # ensures the median is still registered at the beginning or end of the feature list if i < horizon_midpoint: avg_array.append(np.median(feature[:horizon])) elif i > (len(feature) - horizon_midpoint): avg_array.append(np.median(feature[len(feature) - horizon:len(feature)])) else: if horizon % 2 == 0: avg_array.append(np.median(feature[(i - horizon_midpoint):(i + horizon_midpoint)])) else: avg_array.append(np.median(feature[(i - horizon_midpoint):(i + horizon_midpoint + 1)])) return avg_array # shifts values in an array using np.roll def shift(data, shift_value=1): # prevents index out of bounds error while performing the same function if shift_value > len(data): shift_value -= len(data) new_data = np.roll(data, shift_value) # fills up new shifted slots with the first or last element value (beginning or end of array) if shift_value > 0: first_element = new_data[shift_value] np.put(new_data, range(shift_value), first_element) # fills the beginning elif shift_value < 0: last_element = new_data[len(new_data) + shift_value] np.put(new_data, range(len(new_data) - shift_value, len(new_data)), last_element) # fills the end return new_data def gen_all_features(motion, labels=None, horizon=None): velocity = [] # feature 2 acceleration = [] # feature 3 past_motion = [] # feature 4 for i in range(len(motion)): # calculates the rate of change of 3D motion velocity.append(calc_delta(motion[i])) # calculates the rate of change of rate of change of 3D motion (rate of change of velocity) acceleration.append(calc_delta(velocity[i])) # uses the past data as a feature past_motion.append(shift(motion[i])) # previous value # smoothens the features and removes sudden spikes velocity[i] = normalise(calc_median(velocity[i], 5)) acceleration[i] = normalise(calc_median(acceleration[i], 5)) # finds the optimum C and horizon values if no horizon values are inputted if (horizon is None) and (labels is not None): features = [] # puts all existing features in a list for model optimisation for i in range(len(motion)): features.append([ motion[i], velocity[i], acceleration[i], past_motion[i] ]) # finds the optimum value for horizon (DEPRECIATED) # print("Optimising horizons...") # horizon = [] # # only required to run once # for i in range(len(features)): # horizon.append(op.optimise_horizon(features[i], labels[i])) # print("Done!") # number of data used for averaging horizon = [30, 30, 30] # X, Y, Z for i in range(len(motion)): # calculates the average 3D motion average = calc_average(motion[i], horizon[i]) # last feature # adds the average feature to the features list features[i].append(average) return features, horizon elif horizon is not None: features = [] # puts existing features in a list for i in range(len(motion)): features.append([ motion[i], velocity[i], acceleration[i], past_motion[i] ]) for i in range(len(motion)): # calculates the average 3D motion average = calc_average(motion[i], horizon[i]) # last feature # adds the average feature to the features list features[i].append(average) return features else: # quits the program if an argument is missing print("\nMissing argument! (horizon or labels)") exit() def gen_features(motion, labels=None, horizon=None): # calculates the rate of change of 3D motion velocity = calc_delta(motion) # calculates the rate of change of rate of change of 3D motion (rate of change of velocity) acceleration = calc_delta(velocity) # uses the past data as a feature past_motion = shift(motion) # previous value # smoothens the features and removes sudden spikes velocity = normalise(calc_median(velocity, 5)) acceleration = normalise(calc_median(acceleration, 5)) # finds the optimum C and horizon values if no horizon values are inputted if (horizon is None) and (labels is not None): # puts all existing features in a list for model optimisation features = [ motion, velocity, acceleration, past_motion ] # finds the optimum value for horizon (DEPRECIATED) # print("Optimising horizons...") # # only required to run once # horizon = op.optimise_horizon(features, labels) # print("Done!") # number of data used for averaging horizon = 5 # calculates the average 3D motion average = normalise(calc_average(motion, horizon)) # adds the average feature to the features list features.append(average) return features, horizon elif horizon is not None: # calculates the average 3D motion average = normalise(calc_average(motion, horizon)) # returns features as a list return [ motion, velocity, acceleration, past_motion, average ] else: # quits the program if an argument is missing print("\nMissing argument! (horizon or labels)") exit() def gen_tremor_feature(motion): # calculates the rate of change of 3D motion velocity = calc_delta(motion) # calculates the rate of change of rate of change of 3D motion (rate of change of velocity) acceleration = calc_delta(velocity) # smoothens the features velocity = calc_average(velocity, 5) acceleration = calc_average(acceleration, 5) return [velocity, acceleration] # normalises a list to be between -1 and 1 def normalise(data, mid=None, sigma=None): # if no norm attributes are provided, they are calculated based on the inputted list if mid is None: mid = (np.max(data) + np.min(data)) / 2 # finds the midpoint of the data if sigma is None: sigma = (np.max(data) - np.min(data)) / 2 # calculates the spread of the data (range / 2) return np.subtract(data, mid) / sigma # normalises the values to be between -1 and 1 # reverses the normalisation def denormalise(data, mid, sigma): return np.multiply(data, sigma) + mid # gets midpoint and spread of data (used for denormalisation) def get_norm_attributes(data): mid = (np.max(data) + np.min(data)) / 2 # finds the midpoint of the data sigma = (np.max(data) - np.min(data)) / 2 # calculates the spread of the data (range / 2) return mid, sigma
[ "numpy.multiply", "numpy.median", "numpy.roll", "math.floor", "numpy.subtract", "numpy.max", "numpy.min" ]
[((360, 394), 'numpy.subtract', 'np.subtract', (['feature', 'past_feature'], {}), '(feature, past_feature)\n', (371, 394), True, 'import numpy as np\n'), ((2432, 2458), 'numpy.roll', 'np.roll', (['data', 'shift_value'], {}), '(data, shift_value)\n', (2439, 2458), True, 'import numpy as np\n'), ((598, 621), 'math.floor', 'math.floor', (['(horizon / 2)'], {}), '(horizon / 2)\n', (608, 621), False, 'import math\n'), ((1527, 1550), 'math.floor', 'math.floor', (['(horizon / 2)'], {}), '(horizon / 2)\n', (1537, 1550), False, 'import math\n'), ((8121, 8143), 'numpy.subtract', 'np.subtract', (['data', 'mid'], {}), '(data, mid)\n', (8132, 8143), True, 'import numpy as np\n'), ((8277, 8301), 'numpy.multiply', 'np.multiply', (['data', 'sigma'], {}), '(data, sigma)\n', (8288, 8301), True, 'import numpy as np\n'), ((8414, 8426), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (8420, 8426), True, 'import numpy as np\n'), ((8429, 8441), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (8435, 8441), True, 'import numpy as np\n'), ((8494, 8506), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (8500, 8506), True, 'import numpy as np\n'), ((8509, 8521), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (8515, 8521), True, 'import numpy as np\n'), ((1741, 1769), 'numpy.median', 'np.median', (['feature[:horizon]'], {}), '(feature[:horizon])\n', (1750, 1769), True, 'import numpy as np\n'), ((7922, 7934), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (7928, 7934), True, 'import numpy as np\n'), ((7937, 7949), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (7943, 7949), True, 'import numpy as np\n'), ((8028, 8040), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (8034, 8040), True, 'import numpy as np\n'), ((8043, 8055), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (8049, 8055), True, 'import numpy as np\n'), ((1989, 2050), 'numpy.median', 'np.median', (['feature[i - horizon_midpoint:i + horizon_midpoint]'], {}), '(feature[i - horizon_midpoint:i + horizon_midpoint])\n', (1998, 2050), True, 'import numpy as np\n'), ((2107, 2172), 'numpy.median', 'np.median', (['feature[i - horizon_midpoint:i + horizon_midpoint + 1]'], {}), '(feature[i - horizon_midpoint:i + horizon_midpoint + 1])\n', (2116, 2172), True, 'import numpy as np\n')]