code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
#!/usr/bin/python import numpy as np import inkscapeMadeEasy.inkscapeMadeEasy_Base as inkBase import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw # reference: https://www.electronics-tutorials.ws/resources/transformer-symbols.html class transformer(inkBase.inkscapeMadeEasy): def add(self, vector, delta): # vector does not need to be numpy array. delta will be converted to numpy array. Numpy can then deal with np.array + list return vector + np.array(delta) # --------------------------------------------- def drawTransfWinding(self, parent, position=[0, 0], label='transfWinding', size=50, flagTapped=False, wireExtraSize=0, forceEven=True, turnRadius=3.5,polarityIndication=0,flagAddSideTerminals=False): """ draws one winding of the transformer parent: parent object position: position [x,y]. the center of the winding will be places at this position label: label of the object (it can be repeated) size: size of the coil (default 50) flagTapped: add central tap wireExtraSize: extra terminal wire length forceEven: force even number of coil turns turnRadius: radius of each turn polarityIndication: 0: no indication 1: indication in one size -1: indication in the other side flagAddSideTerminals (bool): used to create side terminas for transformers """ elem = self.createGroup(parent, label) Nturns = int(size / (2 * turnRadius)) # makes sure Nturns is even if forceEven and Nturns % 2 == 1: Nturns -= 1 # terminals length = size / 2 + wireExtraSize - (turnRadius * 2) * (Nturns / 2) if flagAddSideTerminals: inkDraw.line.relCoords(elem, [[-length, 0], [0, -20]], self.add(position, [-(turnRadius * 2) * (Nturns / 2), 0])) inkDraw.line.relCoords(elem, [[length, 0], [0, -20]], self.add(position, [(turnRadius * 2) * (Nturns / 2), 0])) else: inkDraw.line.relCoords(elem, [[-length, 0]], self.add(position, [-(turnRadius * 2) * (Nturns / 2), 0])) inkDraw.line.relCoords(elem, [[length, 0]], self.add(position, [(turnRadius * 2) * (Nturns / 2), 0])) # wire loops center = -(Nturns / 2) * (turnRadius * 2) + turnRadius for i in range(Nturns): inkDraw.ellipseArc.centerAngStartAngEnd(elem, self.add(position, [center, 0]), turnRadius, turnRadius + 2, 0.0, 180.0, [0, 0], largeArc=False) center += 2 * turnRadius # tapped if flagTapped: myLine = inkDraw.lineStyle.set(lineWidth=1.0, lineColor=inkDraw.color.defined('black'), fillColor=inkDraw.color.defined('black')) inkDraw.line.relCoords(elem, [[0, -20]], position,lineStyle=myLine) # phase indication if polarityIndication!=0: inkDraw.circle.centerRadius(elem, self.add(position, [-polarityIndication*(size / 2 - 5), -5]), 0.6) return elem # --------------------------------------------- def inductor(self, parent, position=[0, 0], angleDeg=0, coreType='air', flagTapped=False, flagVolt=True, voltName='v', flagCurr=True, currName='i', invertArrows=False, convention='passive', wireExtraSize=0): """ draws an inductor parent: parent object position: position [x,y] angleDeg: rotation angle in degrees counter-clockwise (default 0) coreType='air', 'iron', 'ferrite' flagTapped: add taps to the windings flagVolt: indicates whether the voltage arrow must be drawn (default: true) voltName: voltage drop name (default: v) flagCurr: indicates whether the current arrow must be drawn (default: true) currName: current drop name (default: i) invertArrows: invert V/I arrow directions (default: False) convention: passive/active sign convention. available types: 'passive' (default) , 'active' wireExtraSize: additional length added to the terminals. If negative, the length will be reduced. default: 0) """ group = self.createGroup(parent) elem = self.createGroup(group) sizeCoil = 50 turnRadius = 3 #draw winding self.drawTransfWinding(elem, position=position, size=sizeCoil - 10, flagTapped=False, wireExtraSize=wireExtraSize + 5, forceEven=True, turnRadius=turnRadius, polarityIndication=0, flagAddSideTerminals=False) # manual tap if flagTapped: inkDraw.line.relCoords(elem, [[0, -10]], position) if flagVolt: if coreType.lower() == 'air': posY = 8 else: posY = 15 if convention == 'passive': self.drawVoltArrowSimple(group, self.add(position, [0,posY]), name=voltName, color=self.voltageColor, angleDeg=angleDeg, invertArrows=not invertArrows, size=sizeCoil - 20, invertCurvatureDirection=False, extraAngleText=0.0) if convention == 'active': self.drawVoltArrowSimple(group, self.add(position, [0, posY]), name=voltName, color=self.voltageColor, angleDeg=angleDeg, invertArrows= invertArrows, size=sizeCoil - 20, invertCurvatureDirection=False, extraAngleText=0.0) if flagCurr: posText = -( sizeCoil / 2 -10) self.drawCurrArrowSimple(group, self.add(position, [posText - wireExtraSize,-5]), name=currName, color=self.currentColor, angleDeg=angleDeg, invertArrows=invertArrows,invertTextSide=False, size=10) # core if coreType.lower() == 'iron': inkDraw.line.relCoords(elem, [[40, 0]], self.add(position, [-20,8.5])) inkDraw.line.relCoords(elem, [[40, 0]], self.add(position, [-20,11.5])) if coreType.lower() == 'ferrite': myDash = inkDraw.lineStyle.createDashedLinePattern(dashLength=3.0, gapLength=3.0) myDashedStyle = inkDraw.lineStyle.set(lineWidth=0.8, strokeDashArray=myDash) inkDraw.line.relCoords(elem, [[40, 0]], self.add(position, [-20,8.5]), lineStyle=myDashedStyle) inkDraw.line.relCoords(elem, [[40, 0]], self.add(position, [-20,11.5]), lineStyle=myDashedStyle) if angleDeg != 0: self.rotateElement(group, position, angleDeg) return group # --------------------------------------------- def drawTransformer(self, parent, position=[0, 0], angleDeg=0, transformerLabel='', coreType='air', stepType='one2one', flagPolaritySymbol=False, nCoils=[1, 1], invertPolarity=[False, False], flagTapped=[False, False], flagVolt=[True, True], voltName=['v', 'v'], flagCurr=[True, True], currName=['i', 'i'], invertArrows=[False, False], convention=['passive', 'passive'], wireExtraSize=0): """ draws a transformer parent: parent object position: position [x,y] label: label of the object (it can be repeated) angleDeg: rotation angle in degrees counter-clockwise (default 0) coreType='air', 'iron', 'ferrite' stepType='up', 'down', 'one2one' flagPolaritySymbol: if True, add the dots to indicate the phase of the primary and secondary nCoils: (list) integer number of coils of the primary and secondary invertPolarity: (list) inverts phase symbol of the primary and secondary flagTapped: (list) add taps to the windings flagVolt: (list) indicates whether the voltage arrow must be drawn (default: true) voltName: (list) voltage drop name (default: v) flagCurr: (list) indicates whether the current arrow must be drawn (default: true) currName: (list) current drop name (default: i) invertArrows: (list) invert V/I arrow directions (default: False) convention: (list) passive/active sign convention. available types: 'passive' (default) , 'active' wireExtraSize: additional length added to the terminals. If negative, the length will be reduced. default: 0) """ group = self.createGroup(parent) elem = self.createGroup(group) # ---------------------- # primary # ---------------------- extraSize = 0 if nCoils[0] == 1: sizeCoil = 50 posCoil = [position] turnRadius = 3.5 if nCoils[0] == 2: sizeCoil = 25 posCoil = [self.add(position, [0, -17.5]), self.add(position, [0, 17.5])] turnRadius = 3.0 # step up/down only if primary/secondary have 1 coil each if nCoils[0] == 1 and nCoils[1] == 1: if stepType == 'up': extraSize = 5 sizeCoil -= 10 for pos in posCoil: # polarity indication polarity=0 if flagPolaritySymbol and invertPolarity[0]: polarity=1 if flagPolaritySymbol and not invertPolarity[0]: polarity=-1 #draw winding wind = self.drawTransfWinding(elem, position=self.add(pos, [-10, 0]), size=sizeCoil, flagTapped=flagTapped[0], wireExtraSize=wireExtraSize + extraSize, forceEven=True, turnRadius=turnRadius, polarityIndication= polarity, flagAddSideTerminals=True) self.rotateElement(wind, self.add(pos, [-10, 0]), 90) if flagVolt[0]: distX=-30 if convention[0] == 'passive': self.drawVoltArrowSimple(group, self.add(pos, [distX, 0]), name=voltName[0], color=self.voltageColor, angleDeg=angleDeg + 90, invertArrows=invertArrows[0], size=sizeCoil - 10, invertCurvatureDirection=True, extraAngleText=0.0) if convention[0] == 'active': self.drawVoltArrowSimple(group, self.add(pos, [distX, 0]), name=voltName[0], color=self.voltageColor, angleDeg=angleDeg + 90, invertArrows=not invertArrows[0], size=sizeCoil - 10, invertCurvatureDirection=True, extraAngleText=0.0) if flagCurr[0]: posText = -( sizeCoil / 2 -5) invertTextSide=True arrowDir = invertArrows[0] if flagPolaritySymbol and invertPolarity[0]: posText = -( sizeCoil / 2 -5) invertTextSide=True arrowDir = invertArrows[0] if flagPolaritySymbol and not invertPolarity[0]: posText = ( sizeCoil / 2 -5) invertTextSide=False arrowDir = not invertArrows[0] self.drawCurrArrowSimple(group, self.add(pos, [-20, posText - wireExtraSize]), name=currName[0], color=self.currentColor, angleDeg=angleDeg, invertArrows=arrowDir,invertTextSide=invertTextSide, size=10) # ---------------------- # secondary # ---------------------- extraSize = 0 if nCoils[1] == 1: sizeCoil = 50 posCoil = [position] turnRadius = 3.5 offsetCurrText = 0 if nCoils[1] == 2: sizeCoil = 25 posCoil = [self.add(position, [0, -17.5]), self.add(position, [0, 17.5])] turnRadius = 3.0 offsetCurrText = -3 # step up/down only if primary/secondary have 1 coil each if nCoils[0] == 1 and nCoils[1] == 1: if stepType == 'down': extraSize = 5 sizeCoil -= 10 for pos in posCoil: # polarity indication polarity=0 if flagPolaritySymbol and invertPolarity[1]: polarity=-1 if flagPolaritySymbol and not invertPolarity[1]: polarity=1 wind = self.drawTransfWinding(elem, position=self.add(pos, [10, 0]), size=sizeCoil, flagTapped=flagTapped[1], wireExtraSize=wireExtraSize + extraSize, forceEven=True, turnRadius=turnRadius, polarityIndication=polarity, flagAddSideTerminals=True) self.rotateElement(wind, self.add(pos, [10, 0]), -90) if flagVolt[1]: if convention[1] == 'passive': self.drawVoltArrowSimple(group, self.add(pos, [30, 0]), name=voltName[1], color=self.voltageColor, angleDeg=angleDeg + 90, invertArrows=not invertArrows[1], size=sizeCoil - 10, invertCurvatureDirection=False, extraAngleText=0.0) if convention[1] == 'active': self.drawVoltArrowSimple(group, self.add(pos, [30, 0]), name=voltName[1], color=self.voltageColor, angleDeg=angleDeg + 90, invertArrows= invertArrows[1], size=sizeCoil - 10, invertCurvatureDirection=False, extraAngleText=0.0) if flagCurr[1]: posText = -( sizeCoil / 2 -5) invertTextSide=True arrowDir = invertArrows[1] if flagPolaritySymbol and invertPolarity[0]: posText = -( sizeCoil / 2 -5) invertTextSide=True arrowDir = invertArrows[1] if flagPolaritySymbol and not invertPolarity[1]: posText = ( sizeCoil / 2 -5) invertTextSide=False arrowDir = not invertArrows[1] self.drawCurrArrowSimple(group, self.add(pos, [20, posText - wireExtraSize]), name=currName[1], color=self.currentColor, angleDeg=angleDeg, invertArrows=arrowDir,invertTextSide=invertTextSide, size=10) # core if coreType.lower() == 'iron': inkDraw.line.relCoords(elem, [[0, 50]], self.add(position, [1.5, -25])) inkDraw.line.relCoords(elem, [[0, 50]], self.add(position, [-1.5, -25])) if coreType.lower() == 'ferrite': myDash = inkDraw.lineStyle.createDashedLinePattern(dashLength=3.0, gapLength=3.0) myDashedStyle = inkDraw.lineStyle.set(lineWidth=0.8, strokeDashArray=myDash) inkDraw.line.relCoords(elem, [[0, 50]], self.add(position, [1.5, -25]), lineStyle=myDashedStyle) inkDraw.line.relCoords(elem, [[0, 50]], self.add(position, [-1.5, -25]), lineStyle=myDashedStyle) if angleDeg != 0: self.rotateElement(group, position, angleDeg) return group
[ "inkscapeMadeEasy.inkscapeMadeEasy_Draw.line.relCoords", "inkscapeMadeEasy.inkscapeMadeEasy_Draw.lineStyle.createDashedLinePattern", "inkscapeMadeEasy.inkscapeMadeEasy_Draw.color.defined", "numpy.array", "inkscapeMadeEasy.inkscapeMadeEasy_Draw.lineStyle.set" ]
[((475, 490), 'numpy.array', 'np.array', (['delta'], {}), '(delta)\n', (483, 490), True, 'import numpy as np\n'), ((2803, 2871), 'inkscapeMadeEasy.inkscapeMadeEasy_Draw.line.relCoords', 'inkDraw.line.relCoords', (['elem', '[[0, -20]]', 'position'], {'lineStyle': 'myLine'}), '(elem, [[0, -20]], position, lineStyle=myLine)\n', (2825, 2871), True, 'import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw\n'), ((4618, 4668), 'inkscapeMadeEasy.inkscapeMadeEasy_Draw.line.relCoords', 'inkDraw.line.relCoords', (['elem', '[[0, -10]]', 'position'], {}), '(elem, [[0, -10]], position)\n', (4640, 4668), True, 'import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw\n'), ((6045, 6117), 'inkscapeMadeEasy.inkscapeMadeEasy_Draw.lineStyle.createDashedLinePattern', 'inkDraw.lineStyle.createDashedLinePattern', ([], {'dashLength': '(3.0)', 'gapLength': '(3.0)'}), '(dashLength=3.0, gapLength=3.0)\n', (6086, 6117), True, 'import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw\n'), ((6146, 6206), 'inkscapeMadeEasy.inkscapeMadeEasy_Draw.lineStyle.set', 'inkDraw.lineStyle.set', ([], {'lineWidth': '(0.8)', 'strokeDashArray': 'myDash'}), '(lineWidth=0.8, strokeDashArray=myDash)\n', (6167, 6206), True, 'import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw\n'), ((14343, 14415), 'inkscapeMadeEasy.inkscapeMadeEasy_Draw.lineStyle.createDashedLinePattern', 'inkDraw.lineStyle.createDashedLinePattern', ([], {'dashLength': '(3.0)', 'gapLength': '(3.0)'}), '(dashLength=3.0, gapLength=3.0)\n', (14384, 14415), True, 'import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw\n'), ((14444, 14504), 'inkscapeMadeEasy.inkscapeMadeEasy_Draw.lineStyle.set', 'inkDraw.lineStyle.set', ([], {'lineWidth': '(0.8)', 'strokeDashArray': 'myDash'}), '(lineWidth=0.8, strokeDashArray=myDash)\n', (14465, 14504), True, 'import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw\n'), ((2717, 2747), 'inkscapeMadeEasy.inkscapeMadeEasy_Draw.color.defined', 'inkDraw.color.defined', (['"""black"""'], {}), "('black')\n", (2738, 2747), True, 'import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw\n'), ((2759, 2789), 'inkscapeMadeEasy.inkscapeMadeEasy_Draw.color.defined', 'inkDraw.color.defined', (['"""black"""'], {}), "('black')\n", (2780, 2789), True, 'import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw\n')]
# -*- coding: utf-8 -*- """ SCRIPT TO TEST DG CLASSIFICATION @date: 2018.04.10 @author: <NAME> (<EMAIL>) """ # IMPORTS from time import time from sys import stdout import h5py import numpy as np #from matplotlib import pyplot as plt import math from transforms3d import euler from sklearn.model_selection import train_test_split from sklearn import preprocessing, decomposition #from sklearn.metrics import confusion_matrix # ENSURE REPRODUCIBILITY ###################################################### import os import random import tensorflow as tf from keras import backend as K def reset_random(): os.environ['PYTHONHASHSEED'] = '0' np.random.seed(1337) random.seed(12345) session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) tf.set_random_seed(123) sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess) reset_random() ############################################################################### from keras.models import Model from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout from keras import utils, regularizers from keras.optimizers import SGD, Adam from keras.callbacks import EarlyStopping #%% LOAD SOURCE DATA dir_dataset_dg = '/home/simao/Drive/PhD/0-Datasets/UC2017/DG10/DG10_dataset_euler.h5' # Open H5 files to read f = h5py.File(dir_dataset_dg,'r') # Load static gesture data set X = f['Predictors'] T = f['Target'] U = f['User'] X = np.asarray(X).transpose([2,0,1]) T = np.asarray(T).transpose()[:,0] U = np.asarray(U).transpose()[:,0] # Dataset statistics for u in np.unique(U): print('User %i: %i samples out of total %i (%.1f%%)' % (u, sum(U==u), len(U), sum(U==u)/len(U)*100)) #%% PREPROCESSING (SET INDEPENDENT) def Tinv(T): r = T[:3,:3] rinv = r.transpose() p = T[:3,3] T2 = np.eye(4) T2[:3,:3] = rinv T2[:3,3] = np.matmul(rinv,-p) return T2 # Backup data: Xb = X.copy() print('Preprocessing data : ') # For EULER dataset only: X[:,:,3:6] = X[:,:,3:6] / 180 * math.pi # Angle lifiting function def angle_lift(y, n): for i in range(1, n): if np.isclose(y[i] - y[i-1], 2*np.pi, atol=0.1): # low to high y[i] -= 2*np.pi elif np.isclose(y[i] - y[i-1], -2*np.pi, atol=0.1): y[i] += 2*np.pi # for each sample for i,sample in enumerate(X): ### LIFT EULER ANGLES n = np.argwhere(np.all(sample==0,axis=1)) n = n[0] if len(n)>0 else sample.shape[0] angle_lift(sample[:,3], int(n)) angle_lift(sample[:,4], int(n)) angle_lift(sample[:,5], int(n)) ############################################################### ### Establish the base coordinate frame for the gesture sample # We can either use the first of the last frame of the gesture as the # transformation basis. For the following two lines, comment out the one # you don't want. zeroind = 0 #FIRST # zeroind = np.append(np.argwhere(np.all(sample==0,axis=1)), sample.shape[0])[0] - 1 #LAST f0 = sample[zeroind].copy() # frame zero ### YAW CORRECTION ONLY (ORIGINAL SOLUTION) # Create basis homogeneous transformation matrix # t0 = np.eye(4) # t0[:3,:3] = euler.euler2mat(f0[3],0,0,'rzyx') # t0[:3,3] = f0[:3] r0p = np.matrix(euler.euler2mat(f0[3],0,0,'rzyx')) ** -1 p0 = np.matrix(f0[:3].reshape((-1,1))) # for each gesture frame for j,frame in enumerate(sample): if np.all(frame==0) : break # t1 = np.eye(4) # t1[:3,:3] = euler.euler2mat(frame[3],frame[4],frame[5],axes='rzyx') # t1[:3,-1] = frame[:3] # t2 = np.dot(Tinv(t0),t1) # framep = frame # framep[:3] = t2[:3,-1] # framep[3:6] = euler.mat2euler(t2[:3,:3],axes='rzyx') # X[i,j] = framep p1 = np.matrix(frame[:3].reshape((-1,1))) p2 = r0p * (p1 - p0) frame[:3] = np.squeeze(p2) frame[3] = frame[3] - f0[3] ### QUATERNION IMPLEMENTATION # q0 = f0[3:7] # quaternion components # # Create basis transformation matrix # t0 = np.eye(4) # t0[:3,:3] = quaternions.quat2mat(q0) # t0[:3,-1] = f0[:3] # r0 = quaternions.quat2mat(q0) # # for each gesture frame # for j,frame in enumerate(sample): # if np.all(frame==0) : break # t1 = np.eye(4) # t1[:3,:3] = quaternions.quat2mat(frame[3:7]) # t1[:3,-1] = frame[:3] # t2 = np.matmul(Tinv(t1), t0) # framep = frame # framep[:3] = t2[:3,-1] # framep[3:7] = quaternions.mat2quat(t2[:3,:3]) # X[i,j] = framep stdout.write('\r% 5.1f%%' % ((i+1)/(X.shape[0])*100)) stdout.write('\n') #%% SET SPLITTTING #ind_all = np.asarray(range(X.shape[0])) # ## Data splitting 1 : all -> train and rest #sss = StratifiedShuffleSplit(n_splits=1, test_size=0.4, random_state=42).split(ind_all,T) #ind_train,ind_test = next(sss) # ## Data splitting 2 : test -> validation and test #sss = StratifiedShuffleSplit(n_splits=1, test_size=0.5, random_state=42).split(ind_test,T[ind_test]) #i1, i2 = next(sss) #ind_val = ind_test[i1] #ind_test = ind_test[i2] # #X_train = X[ind_train,:,:] #X_val = X[ind_val,:,:] #X_test = X[ind_test,:,:] ind_all = np.arange(X.shape[0]) ind_train, ind_test = train_test_split(ind_all, shuffle=True, stratify=T[ind_all], test_size=0.3, random_state=42) ind_val, ind_test = train_test_split(ind_test, shuffle=True, stratify=T[ind_test], test_size=0.5, random_state=41) ## Set user 8 aside ind_train_u8 = ind_train[U[ind_train]==8] # indexes of samples of U8 ind_train = ind_train[U[ind_train]!=8] # remove U8 samples # number of samples to replace in each set n_train = ind_train_u8.shape[0] n_val = n_train // 2 n_test = n_train - n_val ind_val = np.concatenate((ind_val, ind_train_u8[:n_val])) # append u8 samples ind_test = np.concatenate((ind_test, ind_train_u8[-n_test:])) ind_train = np.concatenate((ind_train, ind_val[:n_val], ind_test[:n_test])) ind_val = ind_val[n_val:] # remove first n_val samples ind_test = ind_test[n_test:] # remove first n_test samples X_train = X[ind_train,:] X_val = X[ind_val,:] X_test = X[ind_test,:] t_train = T[ind_train] t_val = T[ind_val] t_test = T[ind_test] u_train = U[ind_train] u_val = U[ind_val] u_test = U[ind_test] #%% PRESCALING FEATURE EXTRACTION # Variable scaling: tmpX = X_train.reshape((-1,X_train.shape[2])) tmpX = tmpX[~np.all(tmpX==0,1),] # DO NOT USE PADDING TO STANDARDIZE scaler = preprocessing.StandardScaler().fit(tmpX) def standardize(X,scaler): old_shape = X.shape X = X.reshape((-1,X.shape[2])) padIdx = np.all(X==0,axis=1) X = scaler.transform(X) X[padIdx] = 0 X = X.reshape(old_shape) return X X_train = standardize(X_train,scaler) X_val = standardize(X_val,scaler) X_test = standardize(X_test,scaler) # One hot-encoding def tsonehotencoding(t,x,maxclasses): T = np.zeros((x.shape[0],x.shape[1],maxclasses)) # function to turn sample indexes for i,sample in enumerate(x): T[i,:,t[i]-1] = 1 return T #T_train = utils.to_categorical(T[ind_train]-1,10) #T_val = utils.to_categorical(T[ind_val]-1,10) #T_test = utils.to_categorical(T[ind_test]-1,10) #%% EXTRACT FEATURES # FEATURE SET 3 (PCA TS) def tspvfeatures(X): Xf = np.zeros(X.shape) # For each sample for i,sample in enumerate(X): # Find first index of padding: padind = np.append(np.argwhere(np.all(sample==0,axis=1)), sample.shape[0])[0] # For each timestep for j in range(padind): pca = decomposition.PCA().fit(sample[:j+1]) Xf[i][j] = pca.components_[0] return Xf F_train = tspvfeatures(X_train) F_val = tspvfeatures(X_val) F_test = tspvfeatures(X_test) # Encode targets T_train = tsonehotencoding(T[ind_train], X_train, 10) T_val = tsonehotencoding(T[ind_val], X_val, 10) T_test = tsonehotencoding(T[ind_test], X_test, 10) def tsunroll(X,T): x = [] t = [] for i,sample in enumerate(X): ind_include = ~np.all(sample==0,axis=1) sample = sample[ind_include] x.append(sample) t.append(T[i][ind_include]) return np.concatenate(x), np.concatenate(t) def tsunroll_testsubset(X,T): #function to unroll the test set. we are only interested at a limited #subset of timesteps (25, 50, 75 and 100% of gesture completion) x = [] t = [] # For each sample for i,sample in enumerate(X): ind_include = ~np.all(sample==0,axis=1) sample = sample[ind_include] ind_subset = (sample.shape[0] - 1) * np.asarray([0.25,0.5,0.75,1.0]) ind_subset = np.ceil(ind_subset).astype(np.int) x.append(sample[ind_subset]) t.append(T[i][ind_subset]) return np.concatenate(x), np.concatenate(t) # Feature scaling tmpX = F_train.reshape((-1,F_train.shape[2])) tmpX = tmpX[~np.all(tmpX==0,1),] # DO NOT USE PADDING TO STANDARDIZE scaler_features = preprocessing.StandardScaler().fit(tmpX) F_train = standardize(F_train, scaler_features) F_val = standardize(F_val, scaler_features) F_test = standardize(F_test, scaler_features) ### Change data structure for training and testing ### # Testing subset FT_train,TT_train = tsunroll_testsubset(F_train,T_train) FT_val,TT_val = tsunroll_testsubset(F_val,T_val) FT_test,TT_test = tsunroll_testsubset(F_test[u_test!=8],T_test[u_test!=8]) FT_test8,TT_test8 = tsunroll_testsubset(F_test[u_test==8],T_test[u_test==8]) # Training F_train,T_train = tsunroll(F_train,T_train) F_val,T_val = tsunroll(F_val,T_val) F_test,T_test = tsunroll(F_test,T_test) ############################################################################### #%% DEFINE NETWORK # CONTROL RANDOM GENERATION reset_random() new_seed = int(time()) # inputs = Input(shape=(F_train.shape[1],)) x = Dense(512, activation='tanh')(inputs) x = GaussianNoise(0.1)(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(256, activation='tanh')(x) x = GaussianNoise(0.05)(x) x = BatchNormalization()(x) outputs = Dense(T_train.shape[1], activation='softmax')(x) net = Model(inputs, outputs, name='DG_FFNN') #opt = SGD(lr=0.01, decay=1e-7) opt = Adam(0.0001, decay=1e-6) net.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['acc']) # Show network summary: net.summary() # Train and time: timestart = time() history = net.fit(x=F_train,y=T_train, validation_data=(F_val,T_val), batch_size=256, epochs=1000, callbacks=[EarlyStopping('val_loss',patience=8)], verbose=1) print('Training time: %.1f seconds.' % (time() - timestart)) # Evaluate and score timestart = time() acc_train = [] acc_train.append(net.evaluate(FT_train[0::4],TT_train[0::4])[1] * 100) acc_train.append(net.evaluate(FT_train[1::4],TT_train[1::4])[1] * 100) acc_train.append(net.evaluate(FT_train[2::4],TT_train[2::4])[1] * 100) acc_train.append(net.evaluate(FT_train[3::4],TT_train[3::4])[1] * 100) acc_val = [] acc_val.append(net.evaluate(FT_val[0::4],TT_val[0::4])[1] * 100) acc_val.append(net.evaluate(FT_val[1::4],TT_val[1::4])[1] * 100) acc_val.append(net.evaluate(FT_val[2::4],TT_val[2::4])[1] * 100) acc_val.append(net.evaluate(FT_val[3::4],TT_val[3::4])[1] * 100) acc_test = [] acc_test.append(net.evaluate(FT_test[0::4],TT_test[0::4])[1] * 100) acc_test.append(net.evaluate(FT_test[1::4],TT_test[1::4])[1] * 100) acc_test.append(net.evaluate(FT_test[2::4],TT_test[2::4])[1] * 100) acc_test.append(net.evaluate(FT_test[3::4],TT_test[3::4])[1] * 100) acc_test8 = [] acc_test8.append(net.evaluate(FT_test8[0::4],TT_test8[0::4])[1] * 100) acc_test8.append(net.evaluate(FT_test8[1::4],TT_test8[1::4])[1] * 100) acc_test8.append(net.evaluate(FT_test8[2::4],TT_test8[2::4])[1] * 100) acc_test8.append(net.evaluate(FT_test8[3::4],TT_test8[3::4])[1] * 100) print('Testing time: %.1f seconds.' % (time() - timestart)) print('TRAIN: %.1f | %.1f | %.1f | %.1f' % (acc_train[0],acc_train[1],acc_train[2],acc_train[3])) print(' VAL: %.1f | %.1f | %.1f | %.1f' % (acc_val[0],acc_val[1],acc_val[2],acc_val[3])) print(' TEST: %.1f | %.1f | %.1f | %.1f' % (acc_test[0],acc_test[1],acc_test[2],acc_test[3])) print('TEST8: %.1f | %.1f | %.1f | %.1f' % (acc_test8[0],acc_test8[1],acc_test8[2],acc_test8[3])) print('Seed: %i' % new_seed) #%% PLOT F_TEST from matplotlib import pyplot as plt from sklearn.manifold import TSNE plt.rc('font', family='serif') plt.rc('xtick', labelsize='x-small') plt.rc('ytick', labelsize='x-small') plt.rc('text', usetex=True) plt.rc('legend', edgecolor=(0,0,0),fancybox=False) plt.rc('lines', markeredgewidth=0.5,linewidth=0.5) x = decomposition.PCA(n_components=2).fit(FT_train).transform(FT_train) #x = TSNE(n_components=2, early_exaggeration=8,init='pca').fit_transform(F_test) t = np.argmax(TT_train,axis=1) k = ['$J_{0.25}$', '$J_{0.50}$', '$J_{0.75}$', '$J_{1.00}$'] cmap = plt.get_cmap('tab10',10) f = plt.figure(figsize=(7.12,1.8)) for i in range(4): if i==0: ax = plt.subplot(1,4,i+1) plt.ylabel('PC2') plt.xlabel('PC1') else: ax = plt.subplot(1,4,i+1,sharex=ax,sharey=ax) ax.set_yticklabels=[] xi = x[i::4] ti = t[i::4] for j in range(10): xij = xi[ti==j] plt.scatter(xij[:,0],xij[:,1],s=12,c=cmap.colors[j],edgecolors='k',linewidths=0.5,alpha=0.8) plt.text(0.98,0.98,k[i], horizontalalignment='right',verticalalignment='top', transform=ax.transAxes) lg_labels = np.unique(ti+1).tolist() lg = ax.legend(lg_labels,markerfirst=True,ncol=11,handletextpad=0.2,columnspacing=0.3,borderpad=.1, bbox_to_anchor=(0.7,-0.1),loc='upper right') lg.get_frame().set_linewidth(0.5) f.tight_layout(pad=0.0) f.savefig('test.pdf',bbox_inches='tight',pad_inches=0.0,dpi=300) f.savefig('test.png',bbox_inches='tight',pad_inches=0.0,dpi=300)
[ "sys.stdout.write", "numpy.random.seed", "sklearn.preprocessing.StandardScaler", "numpy.argmax", "sklearn.model_selection.train_test_split", "keras.models.Model", "tensorflow.ConfigProto", "matplotlib.pyplot.figure", "numpy.isclose", "numpy.arange", "keras.layers.Input", "tensorflow.get_default_graph", "numpy.unique", "tensorflow.set_random_seed", "random.seed", "matplotlib.pyplot.rc", "h5py.File", "matplotlib.pyplot.get_cmap", "numpy.ceil", "keras.layers.Dropout", "numpy.asarray", "keras.backend.set_session", "keras.optimizers.Adam", "matplotlib.pyplot.text", "numpy.squeeze", "matplotlib.pyplot.ylabel", "numpy.concatenate", "numpy.all", "keras.layers.BatchNormalization", "matplotlib.pyplot.subplot", "matplotlib.pyplot.scatter", "numpy.zeros", "transforms3d.euler.euler2mat", "time.time", "keras.layers.Dense", "keras.callbacks.EarlyStopping", "sklearn.decomposition.PCA", "numpy.matmul", "numpy.eye", "matplotlib.pyplot.xlabel", "keras.layers.GaussianNoise" ]
[((1394, 1424), 'h5py.File', 'h5py.File', (['dir_dataset_dg', '"""r"""'], {}), "(dir_dataset_dg, 'r')\n", (1403, 1424), False, 'import h5py\n'), ((1645, 1657), 'numpy.unique', 'np.unique', (['U'], {}), '(U)\n', (1654, 1657), True, 'import numpy as np\n'), ((4708, 4726), 'sys.stdout.write', 'stdout.write', (['"""\n"""'], {}), "('\\n')\n", (4720, 4726), False, 'from sys import stdout\n'), ((5284, 5305), 'numpy.arange', 'np.arange', (['X.shape[0]'], {}), '(X.shape[0])\n', (5293, 5305), True, 'import numpy as np\n'), ((5329, 5425), 'sklearn.model_selection.train_test_split', 'train_test_split', (['ind_all'], {'shuffle': '(True)', 'stratify': 'T[ind_all]', 'test_size': '(0.3)', 'random_state': '(42)'}), '(ind_all, shuffle=True, stratify=T[ind_all], test_size=0.3,\n random_state=42)\n', (5345, 5425), False, 'from sklearn.model_selection import train_test_split\n'), ((5598, 5697), 'sklearn.model_selection.train_test_split', 'train_test_split', (['ind_test'], {'shuffle': '(True)', 'stratify': 'T[ind_test]', 'test_size': '(0.5)', 'random_state': '(41)'}), '(ind_test, shuffle=True, stratify=T[ind_test], test_size=\n 0.5, random_state=41)\n', (5614, 5697), False, 'from sklearn.model_selection import train_test_split\n'), ((6124, 6171), 'numpy.concatenate', 'np.concatenate', (['(ind_val, ind_train_u8[:n_val])'], {}), '((ind_val, ind_train_u8[:n_val]))\n', (6138, 6171), True, 'import numpy as np\n'), ((6203, 6253), 'numpy.concatenate', 'np.concatenate', (['(ind_test, ind_train_u8[-n_test:])'], {}), '((ind_test, ind_train_u8[-n_test:]))\n', (6217, 6253), True, 'import numpy as np\n'), ((6266, 6329), 'numpy.concatenate', 'np.concatenate', (['(ind_train, ind_val[:n_val], ind_test[:n_test])'], {}), '((ind_train, ind_val[:n_val], ind_test[:n_test]))\n', (6280, 6329), True, 'import numpy as np\n'), ((10134, 10166), 'keras.layers.Input', 'Input', ([], {'shape': '(F_train.shape[1],)'}), '(shape=(F_train.shape[1],))\n', (10139, 10166), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((10442, 10480), 'keras.models.Model', 'Model', (['inputs', 'outputs'], {'name': '"""DG_FFNN"""'}), "(inputs, outputs, name='DG_FFNN')\n", (10447, 10480), False, 'from keras.models import Model\n'), ((10520, 10545), 'keras.optimizers.Adam', 'Adam', (['(0.0001)'], {'decay': '(1e-06)'}), '(0.0001, decay=1e-06)\n', (10524, 10545), False, 'from keras.optimizers import SGD, Adam\n'), ((10717, 10723), 'time.time', 'time', ([], {}), '()\n', (10721, 10723), False, 'from time import time\n'), ((11069, 11075), 'time.time', 'time', ([], {}), '()\n', (11073, 11075), False, 'from time import time\n'), ((12796, 12826), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""'}), "('font', family='serif')\n", (12802, 12826), True, 'from matplotlib import pyplot as plt\n'), ((12827, 12863), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '"""x-small"""'}), "('xtick', labelsize='x-small')\n", (12833, 12863), True, 'from matplotlib import pyplot as plt\n'), ((12864, 12900), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '"""x-small"""'}), "('ytick', labelsize='x-small')\n", (12870, 12900), True, 'from matplotlib import pyplot as plt\n'), ((12901, 12928), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (12907, 12928), True, 'from matplotlib import pyplot as plt\n'), ((12929, 12982), 'matplotlib.pyplot.rc', 'plt.rc', (['"""legend"""'], {'edgecolor': '(0, 0, 0)', 'fancybox': '(False)'}), "('legend', edgecolor=(0, 0, 0), fancybox=False)\n", (12935, 12982), True, 'from matplotlib import pyplot as plt\n'), ((12980, 13031), 'matplotlib.pyplot.rc', 'plt.rc', (['"""lines"""'], {'markeredgewidth': '(0.5)', 'linewidth': '(0.5)'}), "('lines', markeredgewidth=0.5, linewidth=0.5)\n", (12986, 13031), True, 'from matplotlib import pyplot as plt\n'), ((13191, 13218), 'numpy.argmax', 'np.argmax', (['TT_train'], {'axis': '(1)'}), '(TT_train, axis=1)\n', (13200, 13218), True, 'import numpy as np\n'), ((13287, 13312), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""tab10"""', '(10)'], {}), "('tab10', 10)\n", (13299, 13312), True, 'from matplotlib import pyplot as plt\n'), ((13317, 13348), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(7.12, 1.8)'}), '(figsize=(7.12, 1.8))\n', (13327, 13348), True, 'from matplotlib import pyplot as plt\n'), ((656, 676), 'numpy.random.seed', 'np.random.seed', (['(1337)'], {}), '(1337)\n', (670, 676), True, 'import numpy as np\n'), ((681, 699), 'random.seed', 'random.seed', (['(12345)'], {}), '(12345)\n', (692, 699), False, 'import random\n'), ((724, 802), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'intra_op_parallelism_threads': '(1)', 'inter_op_parallelism_threads': '(1)'}), '(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n', (738, 802), True, 'import tensorflow as tf\n'), ((807, 830), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(123)'], {}), '(123)\n', (825, 830), True, 'import tensorflow as tf\n'), ((908, 927), 'keras.backend.set_session', 'K.set_session', (['sess'], {}), '(sess)\n', (921, 927), True, 'from keras import backend as K\n'), ((1882, 1891), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (1888, 1891), True, 'import numpy as np\n'), ((1928, 1947), 'numpy.matmul', 'np.matmul', (['rinv', '(-p)'], {}), '(rinv, -p)\n', (1937, 1947), True, 'import numpy as np\n'), ((4654, 4711), 'sys.stdout.write', 'stdout.write', (["('\\r% 5.1f%%' % ((i + 1) / X.shape[0] * 100))"], {}), "('\\r% 5.1f%%' % ((i + 1) / X.shape[0] * 100))\n", (4666, 4711), False, 'from sys import stdout\n'), ((6971, 6993), 'numpy.all', 'np.all', (['(X == 0)'], {'axis': '(1)'}), '(X == 0, axis=1)\n', (6977, 6993), True, 'import numpy as np\n'), ((7257, 7303), 'numpy.zeros', 'np.zeros', (['(x.shape[0], x.shape[1], maxclasses)'], {}), '((x.shape[0], x.shape[1], maxclasses))\n', (7265, 7303), True, 'import numpy as np\n'), ((7658, 7675), 'numpy.zeros', 'np.zeros', (['X.shape'], {}), '(X.shape)\n', (7666, 7675), True, 'import numpy as np\n'), ((10113, 10119), 'time.time', 'time', ([], {}), '()\n', (10117, 10119), False, 'from time import time\n'), ((10171, 10200), 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""tanh"""'}), "(512, activation='tanh')\n", (10176, 10200), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((10213, 10231), 'keras.layers.GaussianNoise', 'GaussianNoise', (['(0.1)'], {}), '(0.1)\n', (10226, 10231), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((10239, 10259), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (10257, 10259), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((10267, 10279), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (10274, 10279), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((10287, 10316), 'keras.layers.Dense', 'Dense', (['(256)'], {'activation': '"""tanh"""'}), "(256, activation='tanh')\n", (10292, 10316), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((10324, 10343), 'keras.layers.GaussianNoise', 'GaussianNoise', (['(0.05)'], {}), '(0.05)\n', (10337, 10343), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((10351, 10371), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (10369, 10371), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((10385, 10430), 'keras.layers.Dense', 'Dense', (['T_train.shape[1]'], {'activation': '"""softmax"""'}), "(T_train.shape[1], activation='softmax')\n", (10390, 10430), False, 'from keras.layers import Input, Dense, GaussianNoise, BatchNormalization, Dropout\n'), ((13758, 13867), 'matplotlib.pyplot.text', 'plt.text', (['(0.98)', '(0.98)', 'k[i]'], {'horizontalalignment': '"""right"""', 'verticalalignment': '"""top"""', 'transform': 'ax.transAxes'}), "(0.98, 0.98, k[i], horizontalalignment='right', verticalalignment=\n 'top', transform=ax.transAxes)\n", (13766, 13867), True, 'from matplotlib import pyplot as plt\n'), ((1511, 1524), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (1521, 1524), True, 'import numpy as np\n'), ((2176, 2224), 'numpy.isclose', 'np.isclose', (['(y[i] - y[i - 1])', '(2 * np.pi)'], {'atol': '(0.1)'}), '(y[i] - y[i - 1], 2 * np.pi, atol=0.1)\n', (2186, 2224), True, 'import numpy as np\n'), ((2464, 2491), 'numpy.all', 'np.all', (['(sample == 0)'], {'axis': '(1)'}), '(sample == 0, axis=1)\n', (2470, 2491), True, 'import numpy as np\n'), ((3518, 3536), 'numpy.all', 'np.all', (['(frame == 0)'], {}), '(frame == 0)\n', (3524, 3536), True, 'import numpy as np\n'), ((3951, 3965), 'numpy.squeeze', 'np.squeeze', (['p2'], {}), '(p2)\n', (3961, 3965), True, 'import numpy as np\n'), ((6830, 6860), 'sklearn.preprocessing.StandardScaler', 'preprocessing.StandardScaler', ([], {}), '()\n', (6858, 6860), False, 'from sklearn import preprocessing, decomposition\n'), ((8531, 8548), 'numpy.concatenate', 'np.concatenate', (['x'], {}), '(x)\n', (8545, 8548), True, 'import numpy as np\n'), ((8550, 8567), 'numpy.concatenate', 'np.concatenate', (['t'], {}), '(t)\n', (8564, 8567), True, 'import numpy as np\n'), ((9122, 9139), 'numpy.concatenate', 'np.concatenate', (['x'], {}), '(x)\n', (9136, 9139), True, 'import numpy as np\n'), ((9141, 9158), 'numpy.concatenate', 'np.concatenate', (['t'], {}), '(t)\n', (9155, 9158), True, 'import numpy as np\n'), ((9311, 9341), 'sklearn.preprocessing.StandardScaler', 'preprocessing.StandardScaler', ([], {}), '()\n', (9339, 9341), False, 'from sklearn import preprocessing, decomposition\n'), ((13394, 13418), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(i + 1)'], {}), '(1, 4, i + 1)\n', (13405, 13418), True, 'from matplotlib import pyplot as plt\n'), ((13423, 13440), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""PC2"""'], {}), "('PC2')\n", (13433, 13440), True, 'from matplotlib import pyplot as plt\n'), ((13449, 13466), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""PC1"""'], {}), "('PC1')\n", (13459, 13466), True, 'from matplotlib import pyplot as plt\n'), ((13490, 13536), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(4)', '(i + 1)'], {'sharex': 'ax', 'sharey': 'ax'}), '(1, 4, i + 1, sharex=ax, sharey=ax)\n', (13501, 13536), True, 'from matplotlib import pyplot as plt\n'), ((13656, 13760), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xij[:, 0]', 'xij[:, 1]'], {'s': '(12)', 'c': 'cmap.colors[j]', 'edgecolors': '"""k"""', 'linewidths': '(0.5)', 'alpha': '(0.8)'}), "(xij[:, 0], xij[:, 1], s=12, c=cmap.colors[j], edgecolors='k',\n linewidths=0.5, alpha=0.8)\n", (13667, 13760), True, 'from matplotlib import pyplot as plt\n'), ((13877, 13894), 'numpy.unique', 'np.unique', (['(ti + 1)'], {}), '(ti + 1)\n', (13886, 13894), True, 'import numpy as np\n'), ((859, 881), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (879, 881), True, 'import tensorflow as tf\n'), ((1548, 1561), 'numpy.asarray', 'np.asarray', (['T'], {}), '(T)\n', (1558, 1561), True, 'import numpy as np\n'), ((1583, 1596), 'numpy.asarray', 'np.asarray', (['U'], {}), '(U)\n', (1593, 1596), True, 'import numpy as np\n'), ((2289, 2338), 'numpy.isclose', 'np.isclose', (['(y[i] - y[i - 1])', '(-2 * np.pi)'], {'atol': '(0.1)'}), '(y[i] - y[i - 1], -2 * np.pi, atol=0.1)\n', (2299, 2338), True, 'import numpy as np\n'), ((3351, 3387), 'transforms3d.euler.euler2mat', 'euler.euler2mat', (['f0[3]', '(0)', '(0)', '"""rzyx"""'], {}), "(f0[3], 0, 0, 'rzyx')\n", (3366, 3387), False, 'from transforms3d import euler\n'), ((6765, 6785), 'numpy.all', 'np.all', (['(tmpX == 0)', '(1)'], {}), '(tmpX == 0, 1)\n', (6771, 6785), True, 'import numpy as np\n'), ((8397, 8424), 'numpy.all', 'np.all', (['(sample == 0)'], {'axis': '(1)'}), '(sample == 0, axis=1)\n', (8403, 8424), True, 'import numpy as np\n'), ((8843, 8870), 'numpy.all', 'np.all', (['(sample == 0)'], {'axis': '(1)'}), '(sample == 0, axis=1)\n', (8849, 8870), True, 'import numpy as np\n'), ((8950, 8984), 'numpy.asarray', 'np.asarray', (['[0.25, 0.5, 0.75, 1.0]'], {}), '([0.25, 0.5, 0.75, 1.0])\n', (8960, 8984), True, 'import numpy as np\n'), ((9237, 9257), 'numpy.all', 'np.all', (['(tmpX == 0)', '(1)'], {}), '(tmpX == 0, 1)\n', (9243, 9257), True, 'import numpy as np\n'), ((10906, 10943), 'keras.callbacks.EarlyStopping', 'EarlyStopping', (['"""val_loss"""'], {'patience': '(8)'}), "('val_loss', patience=8)\n", (10919, 10943), False, 'from keras.callbacks import EarlyStopping\n'), ((11014, 11020), 'time.time', 'time', ([], {}), '()\n', (11018, 11020), False, 'from time import time\n'), ((12273, 12279), 'time.time', 'time', ([], {}), '()\n', (12277, 12279), False, 'from time import time\n'), ((9003, 9022), 'numpy.ceil', 'np.ceil', (['ind_subset'], {}), '(ind_subset)\n', (9010, 9022), True, 'import numpy as np\n'), ((13037, 13070), 'sklearn.decomposition.PCA', 'decomposition.PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (13054, 13070), False, 'from sklearn import preprocessing, decomposition\n'), ((7810, 7837), 'numpy.all', 'np.all', (['(sample == 0)'], {'axis': '(1)'}), '(sample == 0, axis=1)\n', (7816, 7837), True, 'import numpy as np\n'), ((7936, 7955), 'sklearn.decomposition.PCA', 'decomposition.PCA', ([], {}), '()\n', (7953, 7955), False, 'from sklearn import preprocessing, decomposition\n')]
# -*- coding: utf-8 -*- """ Colorization models for deepzipper Author: <NAME> """ import tensorflow as tf from utils import load_and_preprocess_single import matplotlib.pyplot as plt import numpy as np import random import time import os # LOAD AND PREPROCESS DATA image_folder = 'train_images' image_paths = [os.path.join('train_images', image_name) for image_name in os.listdir(image_folder)] n_paths = len(image_paths) batch_size = 32 buffer_size = 1000 AUTOTUNE = tf.data.experimental.AUTOTUNE train_generator = tf.data.Dataset.from_tensor_slices(image_paths[:int(0.8*n_paths)]) train_generator = train_generator.map(load_and_preprocess_single, num_parallel_calls=AUTOTUNE).shuffle(buffer_size) train_generator = train_generator.batch(batch_size) train_generator = train_generator.prefetch(buffer_size=AUTOTUNE) test_generator = tf.data.Dataset.from_tensor_slices(image_paths[int(0.8*n_paths):]) test_generator = test_generator.map(load_and_preprocess_single, num_parallel_calls=AUTOTUNE).shuffle(buffer_size) test_generator = test_generator.batch(batch_size) test_generator = test_generator.prefetch(buffer_size=AUTOTUNE) # DEFINE MODELS # BASELINE def ConvNet(): model = Sequential() model.add(InputLayer(input_shape=(32, 32, 1))) model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(Conv2D(64, (3, 3), activation='relu', padding='same', strides=2)) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) model.add(Conv2D(128, (3, 3), activation='relu', padding='same', strides=2)) model.add(Conv2D(256, (3, 3), activation='relu', padding='same')) model.add(Conv2D(256, (3, 3), activation='relu', padding='same', strides=2)) model.add(Conv2D(512, (3, 3), activation='relu', padding='same')) model.add(Conv2D(256, (3, 3), activation='relu', padding='same')) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) model.add(UpSampling2D((2, 2))) model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(UpSampling2D((2, 2))) model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) model.add(UpSampling2D((2, 2))) model.add(Conv2D(2, (3, 3), activation='tanh', padding='same')) model.compile(optimizer='adam', loss='mse') return model class ConvNet_Rec(tf.keras.Model): """ Convolutional Auto-Encoder (Reconstruction): Encoder: Conv2D Decoder: Conv2D + Depth2Space (Pixel shuffle) """ def __init__(self, input_shape=(32,32,1)): super(ConvNet_Rec, self).__init__() self.encoder = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(1, 1), activation='relu'), tf.keras.layers.Conv2D(filters=128, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=256, kernel_size=3, strides=(1, 1), activation='relu'), tf.keras.layers.Conv2D(filters=512, kernel_size=3, strides=(2, 2), activation='relu')]) encoder_shape = self.encoder.layers[-1].output_shape self.decoder = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(encoder_shape[1:])), tf.keras.layers.Lambda(lambda x : tf.nn.depth_to_space(x, 2)), tf.keras.layers.Conv2D(filters=256, kernel_size=2, strides=(1, 1), activation='relu', padding='same'), tf.keras.layers.Lambda(lambda x : tf.nn.depth_to_space(x, 2)), tf.keras.layers.Conv2D(filters=128, kernel_size=2, strides=(1, 1), activation='relu', padding='same'), tf.keras.layers.Lambda(lambda x : tf.nn.depth_to_space(x, 2)), tf.keras.layers.Conv2D(filters=64, kernel_size=2, strides=(1, 1), activation='relu', padding='same'), tf.keras.layers.Lambda(lambda x : tf.nn.depth_to_space(x, 2)), tf.keras.layers.Conv2D(filters=32, kernel_size=2, strides=(1, 1), activation='relu', padding='same'), tf.keras.layers.Lambda(lambda x : tf.nn.depth_to_space(x, 2)), tf.keras.layers.Conv2D(filters=1, kernel_size=2, strides=(1, 1), activation='relu', padding='same')]) def call(self, image): encoded_image = self.encoder(image) final_image = self.decoder(encoded_image) return final_image # SET OPTIMIZER optimizer = tf.keras.optimizers.Adam(1e-3) def compute_loss(model, image): pred_image = model(image) return tf.keras.losses.mean_absolute_error(pred_image, image) def compute_gradients(model, x): with tf.GradientTape() as tape: loss = compute_loss(model, x) return tape.gradient(loss, model.trainable_variables), loss def apply_gradients(optimizer, gradients, variables): optimizer.apply_gradients(zip(gradients, variables)) # SAMPLE FROM MODEL def generate_and_save_images(model, epoch, n_samples=3): fig = plt.figure(figsize=(32,32)) for i in range(n_samples): sample_ix = random.randint(0, len(image_paths)) image_path = image_paths[sample_ix] test_input = load_and_preprocess_single(image_path) test_input = np.expand_dims(test_input, 0) pred_image = model(test_input) plt.subplot(2, 2*n_samples, 2*(i+1)) plt.imshow(pred_image[0,:,:,0], cmap='gray') plt.subplot(2, 2*n_samples, 2*i+1) plt.imshow(test_input[0,:,:,0], cmap='gray') plt.axis('off') plt.savefig('image_at_epoch_{:04d}.png'.format(epoch)) plt.show() # TRAIN MODEL def train(model, train_generator, test_generator, epochs=5, sample=False): for epoch in range(1, epochs + 1): start_time = time.time() for step, train_x in enumerate(train_generator): gradients, loss = compute_gradients(model, train_x) apply_gradients(optimizer, gradients, model.trainable_variables) if step%10 == 0 and sample: generate_and_save_images(model, epoch) end_time = time.time() if epoch % 1 == 0: print('Epoch: {}, time elapse for current epoch {}'.format(epoch, end_time - start_time)) if sample: generate_and_save_images(model, epoch) return model if __name__ == '__main__': model = train(ConvNet_Rec(), train_generator, test_generator)
[ "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "tensorflow.keras.layers.Conv2D", "matplotlib.pyplot.imshow", "numpy.expand_dims", "matplotlib.pyplot.axis", "time.time", "tensorflow.keras.layers.InputLayer", "tensorflow.nn.depth_to_space", "matplotlib.pyplot.figure", "tensorflow.keras.optimizers.Adam", "tensorflow.GradientTape", "utils.load_and_preprocess_single", "os.path.join", "os.listdir", "tensorflow.keras.losses.mean_absolute_error" ]
[((4620, 4651), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', (['(0.001)'], {}), '(0.001)\n', (4644, 4651), True, 'import tensorflow as tf\n'), ((334, 374), 'os.path.join', 'os.path.join', (['"""train_images"""', 'image_name'], {}), "('train_images', image_name)\n", (346, 374), False, 'import os\n'), ((4729, 4783), 'tensorflow.keras.losses.mean_absolute_error', 'tf.keras.losses.mean_absolute_error', (['pred_image', 'image'], {}), '(pred_image, image)\n', (4764, 4783), True, 'import tensorflow as tf\n'), ((5185, 5213), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(32, 32)'}), '(figsize=(32, 32))\n', (5195, 5213), True, 'import matplotlib.pyplot as plt\n'), ((5796, 5806), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5804, 5806), True, 'import matplotlib.pyplot as plt\n'), ((393, 417), 'os.listdir', 'os.listdir', (['image_folder'], {}), '(image_folder)\n', (403, 417), False, 'import os\n'), ((4830, 4847), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (4845, 4847), True, 'import tensorflow as tf\n'), ((5373, 5411), 'utils.load_and_preprocess_single', 'load_and_preprocess_single', (['image_path'], {}), '(image_path)\n', (5399, 5411), False, 'from utils import load_and_preprocess_single\n'), ((5434, 5463), 'numpy.expand_dims', 'np.expand_dims', (['test_input', '(0)'], {}), '(test_input, 0)\n', (5448, 5463), True, 'import numpy as np\n'), ((5515, 5557), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2 * n_samples)', '(2 * (i + 1))'], {}), '(2, 2 * n_samples, 2 * (i + 1))\n', (5526, 5557), True, 'import matplotlib.pyplot as plt\n'), ((5561, 5608), 'matplotlib.pyplot.imshow', 'plt.imshow', (['pred_image[0, :, :, 0]'], {'cmap': '"""gray"""'}), "(pred_image[0, :, :, 0], cmap='gray')\n", (5571, 5608), True, 'import matplotlib.pyplot as plt\n'), ((5615, 5655), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2 * n_samples)', '(2 * i + 1)'], {}), '(2, 2 * n_samples, 2 * i + 1)\n', (5626, 5655), True, 'import matplotlib.pyplot as plt\n'), ((5659, 5706), 'matplotlib.pyplot.imshow', 'plt.imshow', (['test_input[0, :, :, 0]'], {'cmap': '"""gray"""'}), "(test_input[0, :, :, 0], cmap='gray')\n", (5669, 5706), True, 'import matplotlib.pyplot as plt\n'), ((5713, 5728), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (5721, 5728), True, 'import matplotlib.pyplot as plt\n'), ((5970, 5981), 'time.time', 'time.time', ([], {}), '()\n', (5979, 5981), False, 'import time\n'), ((6283, 6294), 'time.time', 'time.time', ([], {}), '()\n', (6292, 6294), False, 'import time\n'), ((2709, 2748), 'tensorflow.keras.layers.InputLayer', 'tf.keras.layers.InputLayer', (['input_shape'], {}), '(input_shape)\n', (2735, 2748), True, 'import tensorflow as tf\n'), ((2763, 2851), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3)', 'strides': '(2, 2)', 'activation': '"""relu"""'}), "(filters=32, kernel_size=3, strides=(2, 2),\n activation='relu')\n", (2785, 2851), True, 'import tensorflow as tf\n'), ((2862, 2950), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(64)', 'kernel_size': '(3)', 'strides': '(1, 1)', 'activation': '"""relu"""'}), "(filters=64, kernel_size=3, strides=(1, 1),\n activation='relu')\n", (2884, 2950), True, 'import tensorflow as tf\n'), ((2961, 3050), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(128)', 'kernel_size': '(3)', 'strides': '(2, 2)', 'activation': '"""relu"""'}), "(filters=128, kernel_size=3, strides=(2, 2),\n activation='relu')\n", (2983, 3050), True, 'import tensorflow as tf\n'), ((3061, 3150), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(256)', 'kernel_size': '(3)', 'strides': '(1, 1)', 'activation': '"""relu"""'}), "(filters=256, kernel_size=3, strides=(1, 1),\n activation='relu')\n", (3083, 3150), True, 'import tensorflow as tf\n'), ((3161, 3250), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(512)', 'kernel_size': '(3)', 'strides': '(2, 2)', 'activation': '"""relu"""'}), "(filters=512, kernel_size=3, strides=(2, 2),\n activation='relu')\n", (3183, 3250), True, 'import tensorflow as tf\n'), ((3382, 3439), 'tensorflow.keras.layers.InputLayer', 'tf.keras.layers.InputLayer', ([], {'input_shape': 'encoder_shape[1:]'}), '(input_shape=encoder_shape[1:])\n', (3408, 3439), True, 'import tensorflow as tf\n'), ((3532, 3637), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(256)', 'kernel_size': '(2)', 'strides': '(1, 1)', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(filters=256, kernel_size=2, strides=(1, 1),\n activation='relu', padding='same')\n", (3554, 3637), True, 'import tensorflow as tf\n'), ((3724, 3829), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(128)', 'kernel_size': '(2)', 'strides': '(1, 1)', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(filters=128, kernel_size=2, strides=(1, 1),\n activation='relu', padding='same')\n", (3746, 3829), True, 'import tensorflow as tf\n'), ((3916, 4020), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(64)', 'kernel_size': '(2)', 'strides': '(1, 1)', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(filters=64, kernel_size=2, strides=(1, 1),\n activation='relu', padding='same')\n", (3938, 4020), True, 'import tensorflow as tf\n'), ((4107, 4211), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(32)', 'kernel_size': '(2)', 'strides': '(1, 1)', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(filters=32, kernel_size=2, strides=(1, 1),\n activation='relu', padding='same')\n", (4129, 4211), True, 'import tensorflow as tf\n'), ((4298, 4402), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(1)', 'kernel_size': '(2)', 'strides': '(1, 1)', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(filters=1, kernel_size=2, strides=(1, 1), activation\n ='relu', padding='same')\n", (4320, 4402), True, 'import tensorflow as tf\n'), ((3490, 3516), 'tensorflow.nn.depth_to_space', 'tf.nn.depth_to_space', (['x', '(2)'], {}), '(x, 2)\n', (3510, 3516), True, 'import tensorflow as tf\n'), ((3682, 3708), 'tensorflow.nn.depth_to_space', 'tf.nn.depth_to_space', (['x', '(2)'], {}), '(x, 2)\n', (3702, 3708), True, 'import tensorflow as tf\n'), ((3874, 3900), 'tensorflow.nn.depth_to_space', 'tf.nn.depth_to_space', (['x', '(2)'], {}), '(x, 2)\n', (3894, 3900), True, 'import tensorflow as tf\n'), ((4065, 4091), 'tensorflow.nn.depth_to_space', 'tf.nn.depth_to_space', (['x', '(2)'], {}), '(x, 2)\n', (4085, 4091), True, 'import tensorflow as tf\n'), ((4256, 4282), 'tensorflow.nn.depth_to_space', 'tf.nn.depth_to_space', (['x', '(2)'], {}), '(x, 2)\n', (4276, 4282), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python import numpy as np import pathlib import re import tensorflow as tf class tfDataset(): def __init__(self, img_path: pathlib.Path): """ Loads images from a path in the form: path/{category}/*.jpg """ self._img_path = img_path self._dataset = tf.data.Dataset.list_files( str(img_path/'*/*.jpg') ) def image_count(self): return len(list( self._img_path.glob('*/*.jpg') )) def class_names(self, dir_pattern='.*'): class_names = [ c.name for c in self._img_path.glob('*') if re.match(dir_pattern, c.name) ] return np.array(class_names) if __name__ == "__main__": pass
[ "numpy.array", "re.match" ]
[((693, 714), 'numpy.array', 'np.array', (['class_names'], {}), '(class_names)\n', (701, 714), True, 'import numpy as np\n'), ((638, 667), 're.match', 're.match', (['dir_pattern', 'c.name'], {}), '(dir_pattern, c.name)\n', (646, 667), False, 'import re\n')]
from quail.egg import Egg import numpy as np import pytest def test_spc(): presented=[[['cat', 'bat', 'hat', 'goat'],['zoo', 'animal', 'zebra', 'horse']]] recalled=[[['bat', 'cat', 'goat', 'hat'],['animal', 'horse', 'zoo']]] egg = Egg(pres=presented,rec=recalled) assert np.array_equal(egg.analyze('spc').data.values,[np.array([ 1., 1., 1., 1.]),np.array([ 1., 1., 0., 1.])]) def test_analysis_spc_multisubj(): presented=[[['cat', 'bat', 'hat', 'goat'],['zoo', 'animal', 'zebra', 'horse']],[['cat', 'bat', 'hat', 'goat'],['zoo', 'animal', 'zebra', 'horse']]] recalled=[[['bat', 'cat', 'goat', 'hat'],['animal', 'horse', 'zoo']],[['bat', 'cat', 'goat', 'hat'],['animal', 'horse', 'zoo']]] multisubj_egg = Egg(pres=presented,rec=recalled) assert np.allclose(multisubj_egg.analyze('spc').data.values,np.array([[ 1., 1., 1., 1.],[ 1., 1., 0., 1.],[ 1., 1., 1., 1.],[ 1., 1., 0., 1.]])) def test_spc_best_euclidean(): presented=[[[10, 20, 30, 40],[10, 20, 30, 40]]] recalled=[[[20, 10, 40, 30],[20, 40, 10]]] egg = Egg(pres=presented,rec=recalled) assert np.allclose(egg.analyze('spc', match='best', distance='euclidean', features='item').data.values,[np.array([1., 1., 1., 1.]),np.array([1., 1., 0., 1.])]) def test_spc_best_euclidean(): presented = [[[{'item' : i, 'feature1' : i*10} for i in range(1, 5)] for i in range(2)]] recalled=[[[{'item' : i, 'feature1' : i*10} for i in [2, 1, 4, 3]],[{'item' : i, 'feature1' : i*10} for i in [2, 4, 1]]]] egg = Egg(pres=presented,rec=recalled) assert np.allclose(egg.analyze('spc', match='best', distance='euclidean', features='feature1').data.values,[np.array([1., 1., 1., 1.]),np.array([1., 1., 0., 1.])]) def test_spc_best_euclidean_3d(): presented = [[[{'item' : i, 'feature1' : [i*10, 0, 0]} for i in range(1, 5)] for i in range(2)]] recalled=[[[{'item' : i, 'feature1' : [i*10, 0, 0]} for i in [2, 1, 4, 3]],[{'item' : i, 'feature1' : [i*10, 0, 0]} for i in [2, 4, 1]]]] egg = Egg(pres=presented,rec=recalled) assert np.array_equal(egg.analyze('spc', match='best', distance='euclidean', features='feature1').data.values,[np.array([1., 1., 1., 1.]),np.array([1., 1., 0., 1.])]) def test_spc_best_euclidean_3d_2features(): presented = [[[{'item' : i, 'feature1' : [i*10, 0, 0], 'feature2' : [i*10, 0, 0]} for i in range(1, 5)] for i in range(2)]] recalled=[[[{'item' : i, 'feature1' : [i*10, 0, 0], 'feature2': [i*10, 0, 0]} for i in [2, 1, 4, 3]],[{'item' : i, 'feature1' : [i*10, 0, 0], 'feature2': [i*10, 0, 0]} for i in [2, 4, 1]]]] egg = Egg(pres=presented,rec=recalled) assert np.array_equal(egg.analyze('spc', match='best', distance='euclidean', features=['feature1', 'feature2']).data.values,[np.array([1., 1., 1., 1.]),np.array([1., 1., 0., 1.])]) def test_spc_best_euclidean_3d_features_not_set(): presented = [[[{'item' : i, 'feature1' : [i*10, 0, 0]} for i in range(1, 5)] for i in range(2)]] recalled=[[[{'item' : i, 'feature1' : [i*10, 0, 0]} for i in [2, 1, 4, 3]],[{'item' : i, 'feature1' : [i*10, 0, 0]} for i in [2, 4, 1]]]] egg = Egg(pres=presented,rec=recalled) assert np.array_equal(egg.analyze('spc', match='best', distance='euclidean', features='feature1').data.values,[np.array([1., 1., 1., 1.]),np.array([1., 1., 0., 1.])]) def test_spc_best_euclidean_3d_exception_no_features(): presented=[[[[10, 0, 0], [20, 0, 0], [30, 0, 0], [40, 0, 0]], [[10, 0, 0], [20, 0, 0], [30, 0, 0], [40, 0, 0]]]] recalled=[[[[20, 0, 0], [10, 0, 0], [40, 0, 0], [30, 0, 0]], [[20, 0, 0], [40, 0, 0], [10, 0, 0]]]] egg = Egg(pres=presented,rec=recalled) with pytest.raises(Exception): assert np.array_equal(egg.analyze('spc', match='best', distance='euclidean').data.values,[np.array([1., 1., 1., 1.]),np.array([1., 1., 0., 1.])]) def test_spc_best_euclidean_3d_exception_item_specified(): presented=[[[[10, 0, 0], [20, 0, 0], [30, 0, 0], [40, 0, 0]], [[10, 0, 0], [20, 0, 0], [30, 0, 0], [40, 0, 0]]]] recalled=[[[[20, 0, 0], [10, 0, 0], [40, 0, 0], [30, 0, 0]], [[20, 0, 0], [40, 0, 0], [10, 0, 0]]]] egg = Egg(pres=presented,rec=recalled) assert np.array_equal(egg.analyze('spc', match='best', distance='euclidean', features='item').data.values,[np.array([1., 1., 1., 1.]),np.array([1., 1., 0., 1.])]) def test_spc_best_correlation_3d(): presented=[[[[10, 0, 10], [20, 0, 0], [30, 0, -10], [40, 0, -20]], [[10, 0, 10], [20, 0, 0], [30, 0, -10], [40, 0, -20]]]] recalled=[[[[20, 0, 0], [10, 0, 10], [40, 0, -20], [30, 0, -10]], [[20, 0, 0], [40, 0, -20], [10, 0, 10]]]] egg = Egg(pres=presented,rec=recalled) assert np.array_equal(egg.analyze('spc', match='best', distance='correlation', features='item').data.values,[np.array([1., 1., 1., 1.]),np.array([1., 1., 0., 1.])]) def test_spc_smooth_correlation_3d(): presented=[[[[10, 0, 10], [20, 0, 0], [30, 0, -10], [40, 0, -20]], [[10, 0, 10], [20, 0, 0], [30, 0, -10], [40, 0, -20]]]] recalled=[[[[20, 0, 0], [10, 0, 10], [40, 0, -20], [30, 0, -10]], [[20, 0, 0], [40, 0, -20], [10, 0, 10]]]] egg = Egg(pres=presented,rec=recalled) egg.analyze('spc', match='smooth', distance='euclidean', features='item').data.values
[ "numpy.array", "pytest.raises", "quail.egg.Egg" ]
[((244, 277), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (247, 277), False, 'from quail.egg import Egg\n'), ((740, 773), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (743, 773), False, 'from quail.egg import Egg\n'), ((1075, 1108), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (1078, 1108), False, 'from quail.egg import Egg\n'), ((1533, 1566), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (1536, 1566), False, 'from quail.egg import Egg\n'), ((2022, 2055), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (2025, 2055), False, 'from quail.egg import Egg\n'), ((2603, 2636), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (2606, 2636), False, 'from quail.egg import Egg\n'), ((3126, 3159), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (3129, 3159), False, 'from quail.egg import Egg\n'), ((3649, 3682), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (3652, 3682), False, 'from quail.egg import Egg\n'), ((4193, 4226), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (4196, 4226), False, 'from quail.egg import Egg\n'), ((4710, 4743), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (4713, 4743), False, 'from quail.egg import Egg\n'), ((5231, 5264), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (5234, 5264), False, 'from quail.egg import Egg\n'), ((837, 939), 'numpy.array', 'np.array', (['[[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, \n 1.0, 0.0, 1.0]]'], {}), '([[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0],\n [1.0, 1.0, 0.0, 1.0]])\n', (845, 939), True, 'import numpy as np\n'), ((3691, 3715), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (3704, 3715), False, 'import pytest\n'), ((335, 365), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (343, 365), True, 'import numpy as np\n'), ((366, 396), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (374, 396), True, 'import numpy as np\n'), ((1216, 1246), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (1224, 1246), True, 'import numpy as np\n'), ((1243, 1273), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (1251, 1273), True, 'import numpy as np\n'), ((1678, 1708), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (1686, 1708), True, 'import numpy as np\n'), ((1705, 1735), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (1713, 1735), True, 'import numpy as np\n'), ((2170, 2200), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (2178, 2200), True, 'import numpy as np\n'), ((2197, 2227), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (2205, 2227), True, 'import numpy as np\n'), ((2765, 2795), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (2773, 2795), True, 'import numpy as np\n'), ((2792, 2822), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (2800, 2822), True, 'import numpy as np\n'), ((3274, 3304), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (3282, 3304), True, 'import numpy as np\n'), ((3301, 3331), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (3309, 3331), True, 'import numpy as np\n'), ((4337, 4367), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (4345, 4367), True, 'import numpy as np\n'), ((4364, 4394), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (4372, 4394), True, 'import numpy as np\n'), ((4856, 4886), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (4864, 4886), True, 'import numpy as np\n'), ((4883, 4913), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (4891, 4913), True, 'import numpy as np\n'), ((3815, 3845), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (3823, 3845), True, 'import numpy as np\n'), ((3842, 3872), 'numpy.array', 'np.array', (['[1.0, 1.0, 0.0, 1.0]'], {}), '([1.0, 1.0, 0.0, 1.0])\n', (3850, 3872), True, 'import numpy as np\n')]
import sys import argparse import logging import numpy as np from scipy.spatial import distance_matrix np.set_printoptions(precision=5) np.set_printoptions(suppress=True) # Logging options logging.basicConfig( # filename=os.path.join(dir_path, 'thomson_problem.log'), level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) # Define the parser used to process the command line input and then add a bunch of arguments parser = argparse.ArgumentParser( prog='thomson', description='Find approximate solutions to the Thomson problem in arbitrary dimension', allow_abbrev=False ) parser.add_argument( '-n', metavar='dimension', type=int, required=False, default=3, help='the dimension of Euclidean space (default: 3)' ) parser.add_argument( '-m', metavar='points', type=int, required=False, default=8, help='the number of point particles on the (n-1) sphere (default: 8)' ) parser.add_argument( '-p', metavar='power', type=int, required=False, default=1, help='the power of the inverse radius in the potential energy function (default: 1)' ) parser.add_argument( '-eps', metavar='epsilon', type=float, required=False, default=0.1, help='the gradient descent epsilon - the step size (default: 0.1)' ) parser.add_argument( '-max_iter', metavar='max_iteration', type=int, required=False, default=1e3, help='the number of steps of gradient descent the program will take (default: 1000)' ) def generate_random_vectors_of_unit_norm(n, m, fixed_seed=False): if fixed_seed: np.random.seed(0) # List comprehensions are great vector_lst = [generate_random_vector_of_unit_norm(n) for _ in range(m)] return np.stack(vector_lst, axis=0) def generate_random_vector_of_unit_norm(n): x = np.random.standard_normal(n) x = x/np.linalg.norm(x) return x def calculate_total_energy(array, p=1): n = len(array[0]) m = len(array) energy = 0 dm = distance_matrix(array, array) mask = np.ones(dm.shape, dtype=bool) np.fill_diagonal(mask, 0) energy = (1.0/dm[mask]).sum()/2.0 # This is equivalent to the calculation above, not # sure which is faster or whether it matters # for i in range(m): # for j in range(i+1,m): # energy += 1.0/dm[i, j] return energy def grad_func(array, p=1): m = len(array) n = len(array[0]) grad_mtx = np.zeros([m, n]) dm = distance_matrix(array, array) for i in range(m): grad = 0.0 # iterate over all points j where i != j for j in range(m): if i == j: pass else: new_vec = (array[i] - array[j])/dm[i, j]**(p+1) grad = grad + new_vec grad_mtx[i] = -2.0*p*grad return grad_mtx def minimise_energy(w_init, max_iter=1e3, eps=0.01, p=1): logging.debug("Starting energy minimisation") v = w_init e = calculate_total_energy(w_init, p=p) logging.debug("Energy of inital configuration is: {}".format(e)) # iterate over max_energy_iter for n in range(int(max_iter)): logging.debug("{}/{}".format(n, int(max_iter))) # One step of vanilla gradient descent v = v - eps*grad_func(v, p=p) # Normalise each row so that the points are still on the unit sphere norm_of_rows = np.linalg.norm(v, axis=1) v = v/norm_of_rows[:, np.newaxis] energy = calculate_total_energy(v) logging.debug("Energy : {}".format(energy)) return v def run_once(n, m, p, eps, max_iter): w_init = generate_random_vectors_of_unit_norm(n=n, m=m) logging.info("Initial energy: {}".format(calculate_total_energy(w_init, p=p))) logging.debug("Initial configuration:") logging.debug("{}".format(repr(w_init))) # sanity check that the norms are close to unity logging.debug("Norms of init vectors are:") [logging.debug(np.linalg.norm(w_init[i])) for i in range(m)] configuration = minimise_energy(w_init=w_init, eps=eps, max_iter=max_iter, p=p) energy = calculate_total_energy(configuration, p=p) np.savetxt('n={}_m={}_p={}.txt'.format(n, m, p), configuration) logging.info("Minimised energy: {}".format(energy)) logging.debug("Final configuration after energy minimisation:") logging.debug(repr(configuration)) def main(): args = parser.parse_args() n = args.n m = args.m p = args.p eps = args.eps max_iter = args.max_iter run_once(n=n, m=m, p=p, eps=eps, max_iter=max_iter) if __name__ == '__main__': main() # TODO: add a boolean flag to write the position of the particles to a file
[ "numpy.stack", "numpy.fill_diagonal", "numpy.set_printoptions", "logging.debug", "argparse.ArgumentParser", "logging.basicConfig", "numpy.random.seed", "numpy.zeros", "numpy.ones", "scipy.spatial.distance_matrix", "numpy.random.standard_normal", "numpy.linalg.norm" ]
[((105, 137), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(5)'}), '(precision=5)\n', (124, 137), True, 'import numpy as np\n'), ((138, 172), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (157, 172), True, 'import numpy as np\n'), ((192, 315), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s %(levelname)-8s %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(level=logging.INFO, format=\n '%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n", (211, 315), False, 'import logging\n'), ((491, 647), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""thomson"""', 'description': '"""Find approximate solutions to the Thomson problem in arbitrary dimension"""', 'allow_abbrev': '(False)'}), "(prog='thomson', description=\n 'Find approximate solutions to the Thomson problem in arbitrary dimension',\n allow_abbrev=False)\n", (514, 647), False, 'import argparse\n'), ((2135, 2163), 'numpy.stack', 'np.stack', (['vector_lst'], {'axis': '(0)'}), '(vector_lst, axis=0)\n', (2143, 2163), True, 'import numpy as np\n'), ((2219, 2247), 'numpy.random.standard_normal', 'np.random.standard_normal', (['n'], {}), '(n)\n', (2244, 2247), True, 'import numpy as np\n'), ((2397, 2426), 'scipy.spatial.distance_matrix', 'distance_matrix', (['array', 'array'], {}), '(array, array)\n', (2412, 2426), False, 'from scipy.spatial import distance_matrix\n'), ((2439, 2468), 'numpy.ones', 'np.ones', (['dm.shape'], {'dtype': 'bool'}), '(dm.shape, dtype=bool)\n', (2446, 2468), True, 'import numpy as np\n'), ((2473, 2498), 'numpy.fill_diagonal', 'np.fill_diagonal', (['mask', '(0)'], {}), '(mask, 0)\n', (2489, 2498), True, 'import numpy as np\n'), ((2842, 2858), 'numpy.zeros', 'np.zeros', (['[m, n]'], {}), '([m, n])\n', (2850, 2858), True, 'import numpy as np\n'), ((2868, 2897), 'scipy.spatial.distance_matrix', 'distance_matrix', (['array', 'array'], {}), '(array, array)\n', (2883, 2897), False, 'from scipy.spatial import distance_matrix\n'), ((3301, 3346), 'logging.debug', 'logging.debug', (['"""Starting energy minimisation"""'], {}), "('Starting energy minimisation')\n", (3314, 3346), False, 'import logging\n'), ((4153, 4192), 'logging.debug', 'logging.debug', (['"""Initial configuration:"""'], {}), "('Initial configuration:')\n", (4166, 4192), False, 'import logging\n'), ((4296, 4339), 'logging.debug', 'logging.debug', (['"""Norms of init vectors are:"""'], {}), "('Norms of init vectors are:')\n", (4309, 4339), False, 'import logging\n'), ((4677, 4740), 'logging.debug', 'logging.debug', (['"""Final configuration after energy minimisation:"""'], {}), "('Final configuration after energy minimisation:')\n", (4690, 4740), False, 'import logging\n'), ((1992, 2009), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2006, 2009), True, 'import numpy as np\n'), ((2258, 2275), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (2272, 2275), True, 'import numpy as np\n'), ((3788, 3813), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {'axis': '(1)'}), '(v, axis=1)\n', (3802, 3813), True, 'import numpy as np\n'), ((4359, 4384), 'numpy.linalg.norm', 'np.linalg.norm', (['w_init[i]'], {}), '(w_init[i])\n', (4373, 4384), True, 'import numpy as np\n')]
#!/usr/bin/env python """ NAME suServer - websocket server for su data RETURNS returns a json string """ from datetime import datetime import sys import asyncio import json import websockets import numpy as np import scipy.signal as sig #import pprint #print("loading obspy...") from obspy.io.segy.segy import _read_su #print("... done.") # FIXME - this only works with 3.5, not 3.6 if sys.version_info == (3, 6): raise "** must use python v3.4 or 3.5" class Segy(object): """Local version of the SU/SEGY file""" def __init__(self): self.filename = None self.hdrs = None self.traces = None self.nsamps = 0 self.dt = 0 self.segyfile = None def getPSD(self, ens): """ Calculate and return average power spectral density for ensemble `ens` using Welch's method """ print('in getpsd, ens=', ens, self) if not self.segyfile: raise Exception("File not opened") enstrcs = [t for t in self.segyfile.traces if t.header.original_field_record_number == ens] psds = [sig.welch(t.data, fs=1/self.dt, scaling='spectrum') for t in enstrcs] # psds is [(f,psd), (f,psd)...] freqs = psds[0][0] psdonly = [p for (f, p) in psds] psdonly = np.array(psdonly).transpose() psdavg = np.mean(psdonly, 1) print(freqs.shape, psdavg.shape) return(freqs, psdavg) def getTrc(self, trcNum=0): """ Get trace `trcNum` and return a python dict""" pass segy = Segy() #print(segy) def getTrc(t, headonly=True, decimate=False, t1=-1, t2=-1, flo=None, fhi=None): """Convert a segy trace to a python dict An obspy SegyTrace t is converted to a python dict with optional filtering of the data. Parameters: ----------- t : SegyTrc object headonly : bool, optional If True, only return the trace headers, with `samps` set to an empty array. flo, fhi : number If `flo` and `fhi` are specified, filter the data before return. t1, t2 : number If `t1` and `t2` are specified > 0, window the data and return only those Returns: -------- dict Dictionary with keys `tracl`, `tracr`, `ffid`, `offset`, and `samps` (at a minimum; see the code for the full list) """ dt = t.header.sample_interval_in_ms_for_this_trace/(1000.*1000.) nsamps = t.header.number_of_samples_in_this_trace samps = [] ampscale = 1 if not headonly: # because I used headonly in the original open, # the data are read anew from file every time data is # referenced (check this) d = t.data # read from file? #print('in gettrc', decimate) if decimate: #print('decimate', decimate, dt) try: d = sig.decimate(d, q=10, zero_phase=True) dt = dt*10 except: print('decimate failed') return if t1 > 0 and t2 > 0: i1 = int(t1/dt) i2 = int(t2/dt) d = d[i1:i2] tarr=np.arange(i1*dt,(i2+1)*dt,dt) #print(i1,i2, dt,len(d), len(tarr)) else: tarr=np.arange(0,nsamps*dt,dt) max = np.max(d) min = np.min(d) ampscale = (max-min) if ampscale != 0: d /= (max-min) #print("amp", ampscale, max, min) # if a filter is requested... if flo and fhi: fnyq = 0.5/dt #print(flo, fhi, fnyq) if flo>fnyq or fhi>fnyq: raise Exception('invalid frequencies') b,a = sig.butter(8,[flo/fnyq, fhi/fnyq], 'bandpass') # print(flo, fhi, fnyq, b, a) y = sig.filtfilt(b, a, d) # .tolist needed so that json can serialize it (it can't hand numpy arrays) varr = y.tolist() else: # otherwise use raw data varr = d.tolist() # create the samps array samps = [{'t':t,'v':v} for (t,v) in zip(tarr,varr)] trc = {"tracl": t.header.trace_sequence_number_within_line, "tracr": t.header.trace_sequence_number_within_segy_file, "ffid": t.header.original_field_record_number, "offset": t.header.distance_from_center_of_the_source_point_to_the_center_of_the_receiver_group, "ampscale" : "{}".format(ampscale), "nsamps": len(samps), "dt": dt, "samps": samps} return trc def handleMsg(msgJ): """Process the message in msgJ. Parameters: msgJ: dict Dictionary with command sent from client Returns: string JSON string with command response Commands are of the form: {'cmd' : 'getCCC', 'param0': 'param0val', ...} Response is a string of the form (note that JSON is picky that keys and strings should be enclosed in double quotes: '{"cmd" : "getCmd", "cmd" : "<response>"}' {'cmd':'getHello'} -> {"cmd":"getHello", "hello": "world"} {'cmd':'getSegyHdrs', filename: f} -> {"cmd":"getSegyHdrs", "segyhdrs": {ns:nsamps, dt:dt: hdrs:[hdr1, hdr2...]}} FIXME FIXME - this currently returns "segy", not "ensemble" as the key WARNING - you must call getSegyHdrs first flo and fhi are optional. If they are not present, no filtering {'cmd':'getEnsemble', filename:f, ensemble:n, [flo:flo, fhi: fhi]} -> {"cmd":"getEnsemble", "segy": {ns:nsamps, dt:dt: traces:[trc1, trc2...]}} """ print('msgJ: {}'.format(msgJ)) if msgJ['cmd'].lower() == 'getsegyhdrs': filename = msgJ['filename'] print('getting segyhdr >{}<, filename: {}'.format(msgJ, filename)) t0 =datetime.now() if segy.filename != filename: # new file - open it try: s = _read_su(filename, headonly=True) segy.filename = filename segy.segyfile = s except: ret = json.dumps({"cmd":"readSegy", "error": "Error reading file {}".format(filename)}) return ret print("ntrcs = {}".format(len(segy.segyfile.traces))) hdrs = [getTrc(t, headonly=True) for t in segy.segyfile.traces] nsamps = segy.segyfile.traces[0].header.number_of_samples_in_this_trace dt = segy.segyfile.traces[0].header.sample_interval_in_ms_for_this_trace/(1000.*1000.) segy.nsamps = nsamps segy.dt = dt segy.hdrs = hdrs ret = json.dumps({"cmd": "readSegyHdrs", "segy" : json.dumps({"dt":dt, "ns":nsamps, "filename": segy.filename, "hdrs":hdrs})}) return ret if msgJ['cmd'].lower() == 'getensemble': print('getting ens', msgJ) if segy.segyfile is None: ret = json.dumps({"cmd":"getEnsemble", "error": "Error reading ensemble"}) return ret decimate = False try: ens = int(msgJ['ensemble']) try: decimate = msgJ['decimate'] print('dec t', decimate) except: decimate=False print('dec f', decimate) try: t1 = float(msgJ['t1']) t2 = float(msgJ['t2']) except: t1=-1 t2=-1 try: flo = float(msgJ['flo']) fhi = float(msgJ['fhi']) print(flo, fhi) traces = [getTrc(t,headonly=False, decimate=decimate, t1=t1, t2=t2, flo=flo, fhi=fhi) for t in segy.segyfile.traces if t.header.original_field_record_number == ens] except: print('err filt') traces = [getTrc(t,headonly=False,decimate=decimate, t1=t1,t2=t2) for t in segy.segyfile.traces if t.header.original_field_record_number == ens] except: print('err ens', ens, decimate) ret = json.dumps({"cmd":"getEnsemble", "error": "Error reading ensemble number"}) return ret print("ens = {} ntrc={}".format(ens, len(traces))) # dt/nsamps could change from the original due to decimation dt = traces[0]["dt"] nsamps = traces[0]["nsamps"] print('dt, nsamps', dt, nsamps) #print(json.dumps(traces[0])) ret = json.dumps({"cmd": "segy", "segy" : json.dumps({"dt":dt, "ns":nsamps, "filename": segy.filename, "traces":traces})}) return ret if msgJ["cmd"].lower() == "getpsd": if segy.segyfile is None: ret = json.dumps({"cmd":"getpsd", "error": "Error reading ensemble"}) return ret try: ens = int(msgJ['ensemble']) print(ens) (f,psd) = segy.getPSD(ens) except: print('err ens/psd') ret = json.dumps({"cmd":"getPSD", "error": "Error reading ensemble number"}) return ret # FIXME - this should be cmd:getPSD, psd:{...} return json.dumps({"cmd":"getPSD", "ensemble":ens, "filename": segy.filename, "freqs":f.tolist(), "psd":psd.tolist()}) if msgJ["cmd"].lower() == "gethello": ret = json.dumps({"cmd": "hello", "hello": "world"}) return ret #async def api(ws, path): # all this is stolen from the websockets tutorial. @asyncio.coroutine def api(ws, path): while True: try: # msg = await ws.recv() # get a websockets string msg = yield from ws.recv() print('msg', msg) try: msgJ = json.loads(msg) except json.decoder.JSONDecodeError: print("error decoding msg >{}<".format(msg)) continue print("got json msgJ >{}<".format(msgJ)) # and handle it... retJ = handleMsg(msgJ) #print(retJ) # and return the response to the client yield from ws.send(retJ) # await ws.send(retJ) except websockets.ConnectionClosed: print('connection closed') return ss = websockets.serve(api, 'localhost', 9191) # all this is stolen from the websockets tutorial. try: print("ready...") sys.stdout.flush() asyncio.get_event_loop().run_until_complete(ss) asyncio.get_event_loop().run_forever() except KeyboardInterrupt: print("bye")
[ "obspy.io.segy.segy._read_su", "websockets.serve", "scipy.signal.welch", "scipy.signal.filtfilt", "asyncio.get_event_loop", "json.loads", "json.dumps", "numpy.max", "numpy.mean", "sys.stdout.flush", "numpy.min", "numpy.arange", "numpy.array", "scipy.signal.decimate", "datetime.datetime.now", "scipy.signal.butter" ]
[((10545, 10585), 'websockets.serve', 'websockets.serve', (['api', '"""localhost"""', '(9191)'], {}), "(api, 'localhost', 9191)\n", (10561, 10585), False, 'import websockets\n'), ((10668, 10686), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (10684, 10686), False, 'import sys\n'), ((1354, 1373), 'numpy.mean', 'np.mean', (['psdonly', '(1)'], {}), '(psdonly, 1)\n', (1361, 1373), True, 'import numpy as np\n'), ((3307, 3316), 'numpy.max', 'np.max', (['d'], {}), '(d)\n', (3313, 3316), True, 'import numpy as np\n'), ((3331, 3340), 'numpy.min', 'np.min', (['d'], {}), '(d)\n', (3337, 3340), True, 'import numpy as np\n'), ((5834, 5848), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5846, 5848), False, 'from datetime import datetime\n'), ((9611, 9657), 'json.dumps', 'json.dumps', (["{'cmd': 'hello', 'hello': 'world'}"], {}), "({'cmd': 'hello', 'hello': 'world'})\n", (9621, 9657), False, 'import json\n'), ((1111, 1164), 'scipy.signal.welch', 'sig.welch', (['t.data'], {'fs': '(1 / self.dt)', 'scaling': '"""spectrum"""'}), "(t.data, fs=1 / self.dt, scaling='spectrum')\n", (1120, 1164), True, 'import scipy.signal as sig\n'), ((3156, 3193), 'numpy.arange', 'np.arange', (['(i1 * dt)', '((i2 + 1) * dt)', 'dt'], {}), '(i1 * dt, (i2 + 1) * dt, dt)\n', (3165, 3193), True, 'import numpy as np\n'), ((3266, 3295), 'numpy.arange', 'np.arange', (['(0)', '(nsamps * dt)', 'dt'], {}), '(0, nsamps * dt, dt)\n', (3275, 3295), True, 'import numpy as np\n'), ((3700, 3751), 'scipy.signal.butter', 'sig.butter', (['(8)', '[flo / fnyq, fhi / fnyq]', '"""bandpass"""'], {}), "(8, [flo / fnyq, fhi / fnyq], 'bandpass')\n", (3710, 3751), True, 'import scipy.signal as sig\n'), ((3806, 3827), 'scipy.signal.filtfilt', 'sig.filtfilt', (['b', 'a', 'd'], {}), '(b, a, d)\n', (3818, 3827), True, 'import scipy.signal as sig\n'), ((7014, 7083), 'json.dumps', 'json.dumps', (["{'cmd': 'getEnsemble', 'error': 'Error reading ensemble'}"], {}), "({'cmd': 'getEnsemble', 'error': 'Error reading ensemble'})\n", (7024, 7083), False, 'import json\n'), ((8890, 8954), 'json.dumps', 'json.dumps', (["{'cmd': 'getpsd', 'error': 'Error reading ensemble'}"], {}), "({'cmd': 'getpsd', 'error': 'Error reading ensemble'})\n", (8900, 8954), False, 'import json\n'), ((10691, 10715), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (10713, 10715), False, 'import asyncio\n'), ((10743, 10767), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (10765, 10767), False, 'import asyncio\n'), ((1307, 1324), 'numpy.array', 'np.array', (['psdonly'], {}), '(psdonly)\n', (1315, 1324), True, 'import numpy as np\n'), ((2865, 2903), 'scipy.signal.decimate', 'sig.decimate', (['d'], {'q': '(10)', 'zero_phase': '(True)'}), '(d, q=10, zero_phase=True)\n', (2877, 2903), True, 'import scipy.signal as sig\n'), ((5957, 5990), 'obspy.io.segy.segy._read_su', '_read_su', (['filename'], {'headonly': '(True)'}), '(filename, headonly=True)\n', (5965, 5990), False, 'from obspy.io.segy.segy import _read_su\n'), ((6691, 6768), 'json.dumps', 'json.dumps', (["{'dt': dt, 'ns': nsamps, 'filename': segy.filename, 'hdrs': hdrs}"], {}), "({'dt': dt, 'ns': nsamps, 'filename': segy.filename, 'hdrs': hdrs})\n", (6701, 6768), False, 'import json\n'), ((8156, 8232), 'json.dumps', 'json.dumps', (["{'cmd': 'getEnsemble', 'error': 'Error reading ensemble number'}"], {}), "({'cmd': 'getEnsemble', 'error': 'Error reading ensemble number'})\n", (8166, 8232), False, 'import json\n'), ((8603, 8688), 'json.dumps', 'json.dumps', (["{'dt': dt, 'ns': nsamps, 'filename': segy.filename, 'traces': traces}"], {}), "({'dt': dt, 'ns': nsamps, 'filename': segy.filename, 'traces':\n traces})\n", (8613, 8688), False, 'import json\n'), ((9189, 9260), 'json.dumps', 'json.dumps', (["{'cmd': 'getPSD', 'error': 'Error reading ensemble number'}"], {}), "({'cmd': 'getPSD', 'error': 'Error reading ensemble number'})\n", (9199, 9260), False, 'import json\n'), ((10005, 10020), 'json.loads', 'json.loads', (['msg'], {}), '(msg)\n', (10015, 10020), False, 'import json\n')]
from __future__ import print_function import gym import math import random import numpy as np import matplotlib from collections import namedtuple from itertools import count import time import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import os import gym_graph from visdom import Visdom ## setup viz viz = Visdom() startup_sec = 2 while not viz.check_connection() and startup_sec > 0: time.sleep(0.1) startup_sec -= 0.1 assert viz.check_connection(), 'No visualization connection could be formed quickly. Is the server running? ' env = gym.make("simple-static-graph-v0").unwrapped Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0 def push(self, *args): """Saves a transition.""" if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position + 1) % self.capacity def sample(self, batch_size): return random.sample(self.memory, batch_size) def __len__(self): return len(self.memory) state_size = len(env.reset()) nb_actions = env.action_space.n class DQN(torch.nn.Module): def __init__(self, n_feature, n_output): super(DQN, self).__init__() self.num_actions = n_output self.dense1 = torch.nn.Linear(n_feature, 1024) # hidden layer self.dense2 = torch.nn.Linear(1024, 2048) # hidden layer self.fc1_adv = nn.Linear(in_features=2048, out_features=512) self.fc1_val = nn.Linear(in_features=2048, out_features=512) # self.fc2_adv = nn.Linear(in_features=512, out_features=self.num_actions) self.fc2_val = nn.Linear(in_features=512, out_features=1) # self.relu = nn.ReLU() self.out = self.calc_out def calc_out(self, val, adv, x): return val + adv - adv.mean(1).unsqueeze(1).expand(x.size(0), self.num_actions) def forward(self, x): x = self.relu(self.dense1(x)) # x = self.relu(self.dense2(x)) # # x = self.relu(self.dense2(x)) # print(x.shape) # x = x.view(x.size(0), -1) # print(x.shape) # adv = self.relu(self.fc1_adv(x)) val = self.relu(self.fc1_val(x)) # adv = self.fc2_adv(adv) val = self.fc2_val(val) x = self.out(val, adv, x) return x device = "cpu" BATCH_SIZE = 128 GAMMA = 0.95 EPS_START = 0.9 EPS_END = 0.05 EPS_DECAY = 50 TARGET_UPDATE = 10 ROLLING_MEAN_100 = 0 policy_net = DQN(state_size, nb_actions) target_net = DQN(state_size, nb_actions) if os.path.exists("./dqn_graph.pt"): try: print( "Found existing dqn model. Loading from checkpoint.") policy_net.load_state_dict(torch.load('./dqn_graph.pt')) except: print ("Failed to load existing model checkpoint file. Starting from scratch.") pass target_net.load_state_dict(policy_net.state_dict()) target_net.eval() optimizer = optim.Adam(policy_net.parameters()) memory = ReplayMemory(10000) steps_done = 0 def select_action(state): global steps_done sample = random.random() eps_threshold = EPS_END + (EPS_START - EPS_END) * \ math.exp(-1. * steps_done / EPS_DECAY) steps_done += 1 s = state.unsqueeze(0).to(device) if sample > eps_threshold: with torch.no_grad(): action = policy_net(s)[0].max(0)[1] view = action.view(1, 1) return view else: return torch.tensor([[random.randrange(nb_actions)]], device=device, dtype=torch.long) episode_durations = [] episode_scores = [] mean_scores = [] score_win = None step_win = None scatter_win = None text_win = None mean_score_win = None loss_win = None def plot(): X = np.array(range(0, len(episode_scores))) scores = np.array(episode_scores) steps = np.array(episode_steps) mean_100 = np.array(mean_scores) losses_np = np.array(losses) global score_win global step_win global scatter_win global mean_score_win global loss_win if not score_win: score_win = viz.line( Y=scores, X=X, opts = dict( title="Episode Reward", xlabel="Episode", ylabel="Reward" ) ) else: viz.line(Y=scores, X=X, update="replace", win=score_win) if not step_win: step_win = viz.line( Y=steps, X=X, opts=dict( title="Episode Steps", xlabel="Episode", ylabel="# Steps" ) ) else: viz.line(Y=steps, X=X, update="replace", win=step_win) if len(losses) > 0: if not loss_win: loss_win = viz.line( Y=losses_np, X=np.array(range(0, len(losses))), opts=dict( title="Loss", xlabel="Step", ylabel="Loss Value", ) ) else: viz.line(Y=losses_np, X=np.array(range(0, len(losses))), update="replace", win=loss_win) # if not scatter_win: # scatter_win = viz.scatter( # Y=scores, # X=np.expand_dims(np.array([steps]), 1), # opts = dict( # title="Steps vs. Reward", # xlabel="Episode Steps", # ylabel="Episode Reward" # ) # ) # else: # viz.scatter(Y=scores, X=steps, update="replace", win=duration_win) if len(mean_100) > 0: if not mean_score_win: mean_score_win = viz.line( Y=mean_100, X=np.array(range(0, len(mean_100))), opts = dict( title="Rolling Mean of Previous 100 Episodes", xlabel="Episodes", ylabel="Episode Reward" ) ) else: viz.line(Y=mean_100, X=np.array(range(0, len(mean_100))), update="replace", win=mean_score_win) def optimize_model(): if len(memory) < BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose the batch (see http://stackoverflow.com/a/19343/3343043 for # detailed explanation). batch = Transition(*zip(*transitions)) # Compute a mask of non-final states and concatenate the batch elements non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([torch.tensor(s) for s in batch.next_state if s is not None]) state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) # Compute Q(s_t, a) - the model computes Q(s_t), then we select the # columns of actions taken s = state_batch.reshape((BATCH_SIZE, state_size)) state_action_values = policy_net(s).gather(1, action_batch) # Compute V(s_{t+1}) for all next states. next_state_values = torch.zeros(BATCH_SIZE, device=device) k = non_final_next_states i = 0 for s in non_final_mask: if (s.item() == 1): item = torch.tensor(tuple(k[i:i+state_size])).unsqueeze(0).to(device) pred = target_net(item) # print(pred.max(0)[0][0].detach()) # print(pred.max(0)[1].detach()) next_state_values[i] = pred.max(0)[0][0].detach() i += 1 # Compute the expected Q values expected_state_action_values = (next_state_values * GAMMA) + reward_batch # Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) losses.append(loss.item()) # Optimize the model optimizer.zero_grad() loss.backward() for param in policy_net.parameters(): # try: param.grad.data.clamp_(-1, 1) # except Exception as e: # print(str(e)) optimizer.step() episode_steps = [] losses = [] i_episode = 0 MIN_EPSIODES = 250 MIN_SCORE = 9500 while ROLLING_MEAN_100 <= MIN_SCORE: i_episode +=1 print ("starting episode: ", i_episode) # for i_episode in range(num_episodes): # Initialize the environment and state state = torch.FloatTensor(env.reset()) r = 0 steps = 0 for t in count(): # Select and perform an action action = select_action(state) _state, reward, done, info = env.step(action.item()) steps += 1 reward = torch.tensor([reward], device=device, dtype=torch.float) r += reward if not done: next_state = torch.tensor(_state, device=device, dtype=torch.float) else: next_state = None # Store the transition in memory memory.push(state, action, next_state, reward) state = next_state # Perform one step of the optimization (on the target network) optimize_model() if done: episode_durations.append(t + 1) episode_scores.append(r) episode_steps.append(steps) print("Episode reward: ", r) print("Episode steps: ", steps) plot() break # Update the target network if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) torch.save(target_net.state_dict(),'./dqn_graph.pt') if i_episode > 100: ROLLING_MEAN_100 = np.mean(episode_scores[i_episode-100:i_episode]) print("Rolling mean score (100): ", ROLLING_MEAN_100) mean_scores.append(ROLLING_MEAN_100) print('Training Complete after ', i_episode, "episodes!")
[ "random.sample", "visdom.Visdom", "torch.cat", "numpy.mean", "torch.no_grad", "torch.load", "os.path.exists", "torch.nn.Linear", "torch.zeros", "itertools.count", "time.sleep", "random.random", "math.exp", "torch.nn.ReLU", "gym.make", "numpy.array", "collections.namedtuple", "random.randrange", "torch.tensor" ]
[((360, 368), 'visdom.Visdom', 'Visdom', ([], {}), '()\n', (366, 368), False, 'from visdom import Visdom\n'), ((661, 730), 'collections.namedtuple', 'namedtuple', (['"""Transition"""', "('state', 'action', 'next_state', 'reward')"], {}), "('Transition', ('state', 'action', 'next_state', 'reward'))\n", (671, 730), False, 'from collections import namedtuple\n'), ((2822, 2854), 'os.path.exists', 'os.path.exists', (['"""./dqn_graph.pt"""'], {}), "('./dqn_graph.pt')\n", (2836, 2854), False, 'import os\n'), ((443, 458), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (453, 458), False, 'import time\n'), ((601, 635), 'gym.make', 'gym.make', (['"""simple-static-graph-v0"""'], {}), "('simple-static-graph-v0')\n", (609, 635), False, 'import gym\n'), ((3339, 3354), 'random.random', 'random.random', ([], {}), '()\n', (3352, 3354), False, 'import random\n'), ((4034, 4058), 'numpy.array', 'np.array', (['episode_scores'], {}), '(episode_scores)\n', (4042, 4058), True, 'import numpy as np\n'), ((4071, 4094), 'numpy.array', 'np.array', (['episode_steps'], {}), '(episode_steps)\n', (4079, 4094), True, 'import numpy as np\n'), ((4110, 4131), 'numpy.array', 'np.array', (['mean_scores'], {}), '(mean_scores)\n', (4118, 4131), True, 'import numpy as np\n'), ((4148, 4164), 'numpy.array', 'np.array', (['losses'], {}), '(losses)\n', (4156, 4164), True, 'import numpy as np\n'), ((6963, 6985), 'torch.cat', 'torch.cat', (['batch.state'], {}), '(batch.state)\n', (6972, 6985), False, 'import torch\n'), ((7005, 7028), 'torch.cat', 'torch.cat', (['batch.action'], {}), '(batch.action)\n', (7014, 7028), False, 'import torch\n'), ((7048, 7071), 'torch.cat', 'torch.cat', (['batch.reward'], {}), '(batch.reward)\n', (7057, 7071), False, 'import torch\n'), ((7364, 7402), 'torch.zeros', 'torch.zeros', (['BATCH_SIZE'], {'device': 'device'}), '(BATCH_SIZE, device=device)\n', (7375, 7402), False, 'import torch\n'), ((8648, 8655), 'itertools.count', 'count', ([], {}), '()\n', (8653, 8655), False, 'from itertools import count\n'), ((1213, 1251), 'random.sample', 'random.sample', (['self.memory', 'batch_size'], {}), '(self.memory, batch_size)\n', (1226, 1251), False, 'import random\n'), ((1540, 1572), 'torch.nn.Linear', 'torch.nn.Linear', (['n_feature', '(1024)'], {}), '(n_feature, 1024)\n', (1555, 1572), False, 'import torch\n'), ((1612, 1639), 'torch.nn.Linear', 'torch.nn.Linear', (['(1024)', '(2048)'], {}), '(1024, 2048)\n', (1627, 1639), False, 'import torch\n'), ((1680, 1725), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(2048)', 'out_features': '(512)'}), '(in_features=2048, out_features=512)\n', (1689, 1725), True, 'import torch.nn as nn\n'), ((1749, 1794), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(2048)', 'out_features': '(512)'}), '(in_features=2048, out_features=512)\n', (1758, 1794), True, 'import torch.nn as nn\n'), ((1828, 1885), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(512)', 'out_features': 'self.num_actions'}), '(in_features=512, out_features=self.num_actions)\n', (1837, 1885), True, 'import torch.nn as nn\n'), ((1909, 1951), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(512)', 'out_features': '(1)'}), '(in_features=512, out_features=1)\n', (1918, 1951), True, 'import torch.nn as nn\n'), ((1982, 1991), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1989, 1991), True, 'import torch.nn as nn\n'), ((8831, 8887), 'torch.tensor', 'torch.tensor', (['[reward]'], {'device': 'device', 'dtype': 'torch.float'}), '([reward], device=device, dtype=torch.float)\n', (8843, 8887), False, 'import torch\n'), ((9778, 9828), 'numpy.mean', 'np.mean', (['episode_scores[i_episode - 100:i_episode]'], {}), '(episode_scores[i_episode - 100:i_episode])\n', (9785, 9828), True, 'import numpy as np\n'), ((2969, 2997), 'torch.load', 'torch.load', (['"""./dqn_graph.pt"""'], {}), "('./dqn_graph.pt')\n", (2979, 2997), False, 'import torch\n'), ((3419, 3458), 'math.exp', 'math.exp', (['(-1.0 * steps_done / EPS_DECAY)'], {}), '(-1.0 * steps_done / EPS_DECAY)\n', (3427, 3458), False, 'import math\n'), ((3560, 3575), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3573, 3575), False, 'import torch\n'), ((6836, 6851), 'torch.tensor', 'torch.tensor', (['s'], {}), '(s)\n', (6848, 6851), False, 'import torch\n'), ((8954, 9008), 'torch.tensor', 'torch.tensor', (['_state'], {'device': 'device', 'dtype': 'torch.float'}), '(_state, device=device, dtype=torch.float)\n', (8966, 9008), False, 'import torch\n'), ((3727, 3755), 'random.randrange', 'random.randrange', (['nb_actions'], {}), '(nb_actions)\n', (3743, 3755), False, 'import random\n')]
import neuro import pickle import os.path import numpy as np import matplotlib.pyplot as plt import os import data_collector import time import datetime earth_population = 8000 zero_human = 1/(earth_population*2) doomsday = 1735689600 max_gini_index = 70 min_lat = -90 max_lat = 90 min_lng = -180 max_lng = 180 covid_reports_files = './data/datasets/' files = os.listdir(covid_reports_files) input_nodes = 9 # время, заболевших, умерших, выздоровевших, уровень жизни, широта, долгота, население, соседи? hidden_nodes = 200 # экспериментально output_nodes = 3 # множители заболевших, умерших, выздоровевших learning_rate = 0.15 # экспериментально if os.path.isfile('neuro.pickle'): with open('neuro.pickle', 'rb') as f: n = pickle.load(f) else: n = neuro.NeuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate) collector = data_collector.Country_info_collector() epochs = 2 for e in range(epochs): for file_idx in range(len(files)-1): for country_idx in range(len(collector.countries)): country_name = collector.countries[country_idx]['name'] next_time_str = files[file_idx+1].split('.')[0] now_time_str = files[file_idx].split('.')[0] now_time = time.mktime(datetime.datetime.strptime(now_time_str, "%m-%d-%Y").timetuple())/doomsday gini = collector.gini(country_name) print(gini) gini_ratio = gini/max_gini_index lat = (collector.latlng(country_name)[0] - min_lat)/(max_lat - min_lat) lng = (collector.latlng(country_name)[1] - min_lng)/(max_lng - min_lng) population = (collector.population(country_name))/earth_population borders_index = collector.borders(country_name, now_time_str) next_infected = collector.infected(country_name,next_time_str) + zero_human now_infected = collector.infected(country_name,now_time_str) + zero_human next_dead = collector.dead(country_name,next_time_str) + zero_human now_dead = collector.dead(country_name,now_time_str) + zero_human next_recovered = collector.recovered(country_name,next_time_str) + zero_human now_recovered = collector.recovered(country_name,now_time_str) + zero_human infected_ratio = (next_infected/now_infected)/earth_population + zero_human dead_ratio = (next_dead/now_dead)/earth_population + zero_human recovered_ratio = (next_recovered/now_recovered)/earth_population + zero_human inputs_data = [now_time, now_infected/earth_population, now_dead/earth_population, now_recovered/earth_population, gini_ratio, lat, lng, population ,borders_index] targets_data = [infected_ratio, dead_ratio, recovered_ratio] inputs = np.asfarray(inputs_data) targets = np.asfarray(targets_data) n.train(inputs, targets) with open('neuro.pickle', 'wb') as f: pickle.dump(n, f) inputs_data = [1587040866/doomsday, 0.021032, 0.001020, 0.012, 0.4, 0.6, 0.8, 0.0004, 0.00003323] inputs = np.asfarray(inputs_data) outputs = n.query(inputs) label = np.argmax(outputs) print("ответ", label)
[ "pickle.dump", "numpy.argmax", "data_collector.Country_info_collector", "numpy.asfarray", "os.path.isfile", "pickle.load", "neuro.NeuralNetwork", "datetime.datetime.strptime", "os.listdir" ]
[((382, 413), 'os.listdir', 'os.listdir', (['covid_reports_files'], {}), '(covid_reports_files)\n', (392, 413), False, 'import os\n'), ((681, 711), 'os.path.isfile', 'os.path.isfile', (['"""neuro.pickle"""'], {}), "('neuro.pickle')\n", (695, 711), False, 'import os\n'), ((2943, 2967), 'numpy.asfarray', 'np.asfarray', (['inputs_data'], {}), '(inputs_data)\n', (2954, 2967), True, 'import numpy as np\n'), ((3004, 3022), 'numpy.argmax', 'np.argmax', (['outputs'], {}), '(outputs)\n', (3013, 3022), True, 'import numpy as np\n'), ((788, 863), 'neuro.NeuralNetwork', 'neuro.NeuralNetwork', (['input_nodes', 'hidden_nodes', 'output_nodes', 'learning_rate'], {}), '(input_nodes, hidden_nodes, output_nodes, learning_rate)\n', (807, 863), False, 'import neuro\n'), ((878, 917), 'data_collector.Country_info_collector', 'data_collector.Country_info_collector', ([], {}), '()\n', (915, 917), False, 'import data_collector\n'), ((760, 774), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (771, 774), False, 'import pickle\n'), ((2813, 2830), 'pickle.dump', 'pickle.dump', (['n', 'f'], {}), '(n, f)\n', (2824, 2830), False, 'import pickle\n'), ((2670, 2694), 'numpy.asfarray', 'np.asfarray', (['inputs_data'], {}), '(inputs_data)\n', (2681, 2694), True, 'import numpy as np\n'), ((2710, 2735), 'numpy.asfarray', 'np.asfarray', (['targets_data'], {}), '(targets_data)\n', (2721, 2735), True, 'import numpy as np\n'), ((1245, 1297), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['now_time_str', '"""%m-%d-%Y"""'], {}), "(now_time_str, '%m-%d-%Y')\n", (1271, 1297), False, 'import datetime\n')]
import numpy as np import pandas as pd import pytest from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier from sklearn.base import ClassifierMixin from sklearn.pipeline import Pipeline from poniard import PoniardClassifier def test_add(): clf = PoniardClassifier() clf.add_estimators([ExtraTreesClassifier()]) clf + {"rf2": RandomForestClassifier()} assert len(clf.estimators_) == len(clf._base_estimators) + 2 assert "rf2" in clf.estimators_ assert "ExtraTreesClassifier" in clf.estimators_ def test_remove(): clf = PoniardClassifier() clf.remove_estimators(["RandomForestClassifier"]) clf - ["LogisticRegression"] assert len(clf.estimators_) == len(clf._base_estimators) - 2 def test_remove_fitted(): clf = PoniardClassifier() y = np.array([0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1]) x = pd.DataFrame(np.random.normal(size=(len(y), 5))) clf.setup(x, y) clf.fit() clf.remove_estimators(["RandomForestClassifier"], drop_results=True) assert len(clf.estimators_) == len(clf._base_estimators) - 1 assert clf.show_results().shape[0] == len(clf._base_estimators) - 1 assert "RandomForestClassifier" not in clf.show_results().index @pytest.mark.parametrize( "include_preprocessor,output_type", [(True, Pipeline), (False, ClassifierMixin)] ) def test_get(include_preprocessor, output_type): clf = PoniardClassifier(estimators=[RandomForestClassifier()]) y = np.array([0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1]) x = pd.DataFrame(np.random.normal(size=(len(y), 5))) clf.setup(x, y) clf.fit() estimator = clf.get_estimator( "RandomForestClassifier", include_preprocessor=include_preprocessor ) assert isinstance(estimator, output_type)
[ "sklearn.ensemble.RandomForestClassifier", "poniard.PoniardClassifier", "sklearn.ensemble.ExtraTreesClassifier", "numpy.array", "pytest.mark.parametrize" ]
[((1228, 1337), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""include_preprocessor,output_type"""', '[(True, Pipeline), (False, ClassifierMixin)]'], {}), "('include_preprocessor,output_type', [(True,\n Pipeline), (False, ClassifierMixin)])\n", (1251, 1337), False, 'import pytest\n'), ((273, 292), 'poniard.PoniardClassifier', 'PoniardClassifier', ([], {}), '()\n', (290, 292), False, 'from poniard import PoniardClassifier\n'), ((571, 590), 'poniard.PoniardClassifier', 'PoniardClassifier', ([], {}), '()\n', (588, 590), False, 'from poniard import PoniardClassifier\n'), ((781, 800), 'poniard.PoniardClassifier', 'PoniardClassifier', ([], {}), '()\n', (798, 800), False, 'from poniard import PoniardClassifier\n'), ((809, 855), 'numpy.array', 'np.array', (['[0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1]'], {}), '([0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1])\n', (817, 855), True, 'import numpy as np\n'), ((1464, 1510), 'numpy.array', 'np.array', (['[0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1]'], {}), '([0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1])\n', (1472, 1510), True, 'import numpy as np\n'), ((317, 339), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {}), '()\n', (337, 339), False, 'from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier\n'), ((360, 384), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (382, 384), False, 'from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier\n'), ((1429, 1453), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (1451, 1453), False, 'from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier\n')]
import numpy as np import torch from torch.autograd import Variable import matplotlib.pyplot as plt from scipy.stats import gaussian_kde, norm from torch.distributions import multivariate_normal from tqdm import tqdm # ## debugging def numpy_p(x): return 1/3 * norm.pdf(x, -2, 1) + 2/3 * norm.pdf(x, 2, 1) def numpy_p_far(x): return 1/2 * norm.pdf(x, -10, 1) + 1/2 * norm.pdf(x, 10, 1) def numpy_p_complex(x): return (1/7) * norm.pdf(x, -2,3) + (2/7) * norm.pdf(x, 2,1) + (3/7) * norm.pdf(x, 5,5) + (1/7) * norm.pdf(x, 6,0.5) def numpy_multi(x): mean = torch.Tensor([0, 0]) covariance = torch.tensor([[5, 2], [2, 1]]) return norm.pdf(x, mean, covariance) ''' Runs T number of iterations of Stein Variational Descent to move the given initial parrticles in the direction of the target desnity p. The step sizes are determined by AdaGrad. Input: p - target density k - kernel x - initial set of points T - number of iterations alpha - momentum constant fudge - AdaGrad fudge factor step - step size scale Output: final set of points after T iterations. ''' def svgd(p, kern, x, T, alpha=0.9, fudge=1e-6, step=1e-1, mean=None, covariance=None): assert len(x.shape) == 2 n, d = x.shape x = torch.Tensor(x) ## Put the most likely x at the front of the array (leading gradient). x = put_max_first(x, p) accumulated_grad = torch.zeros((n, d)) # gauss = multivariate_normal.MultivariateNormal(mean, covariance) # target = gauss.sample(torch.Size([n])) for i in tqdm(range(T)): ### debugging if i % 50 == 0 or i == T-1: # TODO: Change mean and varince here. # twoDimPlotter(x, target) # bigDimPlotter(x,target) plt.figure() xs = np.arange(-20, 20, 0.01) plt.plot(xs, numpy_p_complex(xs), 'r') g = gaussian_kde(x.numpy().reshape(-1)) plt.plot(xs, g(xs), 'g') # plt.show() plt.savefig('../../../nparticles/500_n{}.png'.format(i)) varx = Variable(x, requires_grad = True) grad_logp = grad_log(p, varx) kernel, grad_kernel = kern(x) phi = torch.matmul(kernel, grad_logp)/n + torch.mean(grad_kernel, dim=1).view(n, d) # print(grad_logp) if i == 0: accumulated_grad += phi**2 else: accumulated_grad = alpha * accumulated_grad + (1-alpha) * phi**2 stepsize = fudge + torch.sqrt(accumulated_grad) x = x + torch.div(step * phi, stepsize) # break return x ''' Build the RBF kernel matrix and grad_kernel matrix given a set of points x. Input: n x d set of points - x Output: n x n kernel matrix, n x n x d grad_kernel matrix ''' def RBF_kernel(x): n, d = tuple(x.size()) pairdist = torch.zeros((n, n)) for i in range(n): for j in range(n): pairdist[i][j] = torch.dist(x[i], x[j]) med = torch.median(pairdist) h = med**2 / np.log(n) kernel = torch.exp(-(1/h) * pairdist**2) grad_kernel = torch.zeros((n, n, d)) for i in range(n): for j in range(n): grad_kernel[i][j] = 2/h * kernel[i][j] * (x[i]-x[j]) return torch.Tensor(kernel), torch.Tensor(grad_kernel) ''' Returns RBF kernel. Input: bandwith of the kernel - h Output: a function that returns the RBF kernel ''' def RBF(h): def kernel(x1,x2): return np.exp(-(1/h) * torch.norm(x1 - x2)**2) return kernel ''' Returns the gradient of the RBF kernel w.r.t. x2 ''' def RBF_grad(x1,x2): return (2) * (x1 - x2) * np.exp(-torch.norm(x1 -x2)**2) ''' Takes the gradient of the log of the unnormalized probability distribution. Input: p - unnormalized probability distribution x - set of current particles Output: gradient of log of distribution p at point x ''' def grad_log(p, x): n, d = tuple(x.size()) grad_log = [] for i in range(len(x)): # if float(p(x[i])) < 1e-35: # grad_log.append(grad_log[-1]) # continue # print ("p(x) is {}".format(p(x[i]))) logp = p(x[i]) # print ("logp us {}".format(logp)) logp.backward() # print ("the grad is {}".format(x.grad.data[i])) grad_log.append(x.grad.data[i].numpy()) grad_log = np.array(grad_log).reshape((n, d)) return torch.Tensor(grad_log) ''' Build the kernel matrix. Input: k - kernel function x - set of current particules Output: matrix containing the kernel evaluated at each pair of points ''' def k_matrix(k, k_grad, x): #import pdb; pdb.set_trace() n = len(x) kernel_matrix, grad_kernel_matrix = [], [] for i in range(n): kernel_matrix.append([]) grad_kernel_matrix.append([]) for j in range(n): kernel_val = k(x[i], x[j]) kernel_matrix[-1].append(float(kernel_val)) #kernel_val.backward() kernel_grad = k_grad(x[i], x[j]) grad_kernel_matrix[-1].append(float(kernel_grad)) #x.grad.data.zero_() return torch.Tensor(kernel_matrix), torch.Tensor(grad_kernel_matrix) ''' Returns the same array with the element with highest probability first. Input: x - array of samples p - probability distribution Output: arrays of samples with highest probability element first. ''' def put_max_first(x, p): n = len(x) best_index = -1 best_prob = -1 for i in range(n): prob_i = p(x[i]) if float(prob_i) > float(best_prob): best_prob = prob_i best_index = i tmp = x[0] x[0] = x[best_index] x[best_index] = tmp return x ''' Plots a scatter plot of two dimensional target samples and particules. Input: x - particules target - target distribution to sample from ''' def bigDimPlotter(x, target): n = x.shape[0] dim1, dim2 = x.numpy()[:,0], x.numpy()[:,1] target1, target2 = target.numpy()[:,0], target.numpy()[:,1] fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(dim1, dim2, s=10, c='b', marker="x", label='particles') ax.scatter(target1, target2, s=10, c='r', marker="o", label='target') plt.legend(loc='upper right'); plt.xlim((-5,10)) plt.ylim((-5,10)) plt.show()
[ "torch.sqrt", "matplotlib.pyplot.figure", "numpy.arange", "torch.median", "torch.dist", "torch.exp", "torch.Tensor", "torch.zeros", "torch.matmul", "torch.mean", "matplotlib.pyplot.show", "matplotlib.pyplot.ylim", "torch.autograd.Variable", "matplotlib.pyplot.legend", "torch.norm", "matplotlib.pyplot.xlim", "numpy.log", "scipy.stats.norm.pdf", "numpy.array", "torch.div", "torch.tensor" ]
[((576, 596), 'torch.Tensor', 'torch.Tensor', (['[0, 0]'], {}), '([0, 0])\n', (588, 596), False, 'import torch\n'), ((614, 644), 'torch.tensor', 'torch.tensor', (['[[5, 2], [2, 1]]'], {}), '([[5, 2], [2, 1]])\n', (626, 644), False, 'import torch\n'), ((656, 685), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', 'mean', 'covariance'], {}), '(x, mean, covariance)\n', (664, 685), False, 'from scipy.stats import gaussian_kde, norm\n'), ((1274, 1289), 'torch.Tensor', 'torch.Tensor', (['x'], {}), '(x)\n', (1286, 1289), False, 'import torch\n'), ((1416, 1435), 'torch.zeros', 'torch.zeros', (['(n, d)'], {}), '((n, d))\n', (1427, 1435), False, 'import torch\n'), ((2830, 2849), 'torch.zeros', 'torch.zeros', (['(n, n)'], {}), '((n, n))\n', (2841, 2849), False, 'import torch\n'), ((2962, 2984), 'torch.median', 'torch.median', (['pairdist'], {}), '(pairdist)\n', (2974, 2984), False, 'import torch\n'), ((3026, 3061), 'torch.exp', 'torch.exp', (['(-(1 / h) * pairdist ** 2)'], {}), '(-(1 / h) * pairdist ** 2)\n', (3035, 3061), False, 'import torch\n'), ((3076, 3098), 'torch.zeros', 'torch.zeros', (['(n, n, d)'], {}), '((n, n, d))\n', (3087, 3098), False, 'import torch\n'), ((4358, 4380), 'torch.Tensor', 'torch.Tensor', (['grad_log'], {}), '(grad_log)\n', (4370, 4380), False, 'import torch\n'), ((5985, 5997), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5995, 5997), True, 'import matplotlib.pyplot as plt\n'), ((6177, 6206), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (6187, 6206), True, 'import matplotlib.pyplot as plt\n'), ((6212, 6230), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-5, 10)'], {}), '((-5, 10))\n', (6220, 6230), True, 'import matplotlib.pyplot as plt\n'), ((6234, 6252), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-5, 10)'], {}), '((-5, 10))\n', (6242, 6252), True, 'import matplotlib.pyplot as plt\n'), ((6256, 6266), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6264, 6266), True, 'import matplotlib.pyplot as plt\n'), ((2083, 2114), 'torch.autograd.Variable', 'Variable', (['x'], {'requires_grad': '(True)'}), '(x, requires_grad=True)\n', (2091, 2114), False, 'from torch.autograd import Variable\n'), ((3002, 3011), 'numpy.log', 'np.log', (['n'], {}), '(n)\n', (3008, 3011), True, 'import numpy as np\n'), ((3225, 3245), 'torch.Tensor', 'torch.Tensor', (['kernel'], {}), '(kernel)\n', (3237, 3245), False, 'import torch\n'), ((3247, 3272), 'torch.Tensor', 'torch.Tensor', (['grad_kernel'], {}), '(grad_kernel)\n', (3259, 3272), False, 'import torch\n'), ((5077, 5104), 'torch.Tensor', 'torch.Tensor', (['kernel_matrix'], {}), '(kernel_matrix)\n', (5089, 5104), False, 'import torch\n'), ((5106, 5138), 'torch.Tensor', 'torch.Tensor', (['grad_kernel_matrix'], {}), '(grad_kernel_matrix)\n', (5118, 5138), False, 'import torch\n'), ((266, 284), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', '(-2)', '(1)'], {}), '(x, -2, 1)\n', (274, 284), False, 'from scipy.stats import gaussian_kde, norm\n'), ((293, 310), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', '(2)', '(1)'], {}), '(x, 2, 1)\n', (301, 310), False, 'from scipy.stats import gaussian_kde, norm\n'), ((349, 368), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', '(-10)', '(1)'], {}), '(x, -10, 1)\n', (357, 368), False, 'from scipy.stats import gaussian_kde, norm\n'), ((377, 395), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', '(10)', '(1)'], {}), '(x, 10, 1)\n', (385, 395), False, 'from scipy.stats import gaussian_kde, norm\n'), ((525, 544), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', '(6)', '(0.5)'], {}), '(x, 6, 0.5)\n', (533, 544), False, 'from scipy.stats import gaussian_kde, norm\n'), ((1779, 1791), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1789, 1791), True, 'import matplotlib.pyplot as plt\n'), ((1809, 1833), 'numpy.arange', 'np.arange', (['(-20)', '(20)', '(0.01)'], {}), '(-20, 20, 0.01)\n', (1818, 1833), True, 'import numpy as np\n'), ((2488, 2516), 'torch.sqrt', 'torch.sqrt', (['accumulated_grad'], {}), '(accumulated_grad)\n', (2498, 2516), False, 'import torch\n'), ((2533, 2564), 'torch.div', 'torch.div', (['(step * phi)', 'stepsize'], {}), '(step * phi, stepsize)\n', (2542, 2564), False, 'import torch\n'), ((2929, 2951), 'torch.dist', 'torch.dist', (['x[i]', 'x[j]'], {}), '(x[i], x[j])\n', (2939, 2951), False, 'import torch\n'), ((4312, 4330), 'numpy.array', 'np.array', (['grad_log'], {}), '(grad_log)\n', (4320, 4330), True, 'import numpy as np\n'), ((497, 514), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', '(5)', '(5)'], {}), '(x, 5, 5)\n', (505, 514), False, 'from scipy.stats import gaussian_kde, norm\n'), ((2207, 2238), 'torch.matmul', 'torch.matmul', (['kernel', 'grad_logp'], {}), '(kernel, grad_logp)\n', (2219, 2238), False, 'import torch\n'), ((440, 458), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', '(-2)', '(3)'], {}), '(x, -2, 3)\n', (448, 458), False, 'from scipy.stats import gaussian_kde, norm\n'), ((469, 486), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', '(2)', '(1)'], {}), '(x, 2, 1)\n', (477, 486), False, 'from scipy.stats import gaussian_kde, norm\n'), ((2243, 2273), 'torch.mean', 'torch.mean', (['grad_kernel'], {'dim': '(1)'}), '(grad_kernel, dim=1)\n', (2253, 2273), False, 'import torch\n'), ((3450, 3469), 'torch.norm', 'torch.norm', (['(x1 - x2)'], {}), '(x1 - x2)\n', (3460, 3469), False, 'import torch\n'), ((3608, 3627), 'torch.norm', 'torch.norm', (['(x1 - x2)'], {}), '(x1 - x2)\n', (3618, 3627), False, 'import torch\n')]
import numpy as np import numba from typing import List, Callable from scipy.constants import speed_of_light from divergence_approx import div_vec_approx, gradient_vec """Adams-Bashforth 2-step method coeffs""" adams_bashforth2_c0: float = 3. / 2. adams_bashforth2_c1: float = -1. / 2. """Adams-Bashforth 3-step method coeffs""" adams_bashforth3_c0: float = 23. / 12. adams_bashforth3_c1: float = -4. / 3. adams_bashforth3_c2: float = 5. / 12. """Adams-Bashforth 4-step method coeffs""" adams_bashforth4_c0: float = 55. / 24. adams_bashforth4_c1: float = -59. / 24. adams_bashforth4_c2: float = 37. / 24. adams_bashforth4_c3: float = -3. / 8. """Adams-Bashforth 5-step method coeffs""" adams_bashforth5_c0: float = 1901. / 720. adams_bashforth5_c1: float = -1387. / 360. adams_bashforth5_c2: float = 109. / 30. adams_bashforth5_c3: float = -637. / 360. adams_bashforth5_c4: float = 251. / 720. @numba.jit(nopython=True, parallel=True, nogil=True) def f_function(params: List[float]) -> float: """ :param params: List of float custom function parameters :return: float scalar :examples: """ if params[0] == 0. or params[0] == params[1]: return 0. if np.abs(params[1]**2 / params[0] * (params[1] - params[0])) >= 20.: return 0. if params[1] > params[0] > 0.: return np.exp(-(params[1]**2 / (params[0] * (params[1] - params[0])))) else: return 0. @numba.jit(nopython=True, parallel=True, nogil=True) def proportion_linear(time_right: float, time_between: float, time_step: float) -> tuple: """ :param time_right: right border in time :param time_between: time between borders :param time_step: step in time between borders :return: _Iterable_(alpha, beta) Typical usage example: time_between = 1.98 time_step = time_2 - time_1 alpha, beta = proportion_linear(time_2, time_between, time_step) assert alpha + beta == 1 assert alpha > beta """ beta = (time_between - time_right) / time_step return (1 - beta), beta @numba.jit(nopython=True, parallel=True, nogil=True) def component_next_euler(vec_integral: np.array = None, vec_integral_1: np.array = None, vec_integral_2: np.array = None, vec_integral_3: np.array = None, vec_integral_4: np.array = None, vec_cur: np.array = None, vec_cur_1: np.array = None, vec_cur_2: np.array = None, vec_cur_3: np.array = None, delta: float = 0.1, **kwargs) -> np.array: return vec_integral * 2 * delta + vec_cur_1 @numba.jit(nopython=True, parallel=True, nogil=True) def component_next_euler2(vec_integral: np.array = None, vec_integral_1: np.array = None, vec_integral_2: np.array = None, vec_integral_3: np.array = None, vec_integral_4: np.array = None, vec_cur: np.array = None, vec_cur_1: np.array = None, vec_cur_2: np.array = None, vec_cur_3: np.array = None, delta: float = 0.1, **kwargs) -> np.array: return 8 * vec_cur - 8 * vec_cur_2 + vec_cur_3 + 12 * delta * vec_integral_1 @numba.jit(nopython=True, parallel=True, nogil=True) def component_next_adams(vec_integral: np.array = None, vec_integral_1: np.array = None, vec_integral_2: np.array = None, vec_integral_3: np.array = None, vec_integral_4: np.array = None, vec_cur: np.array = None, vec_cur_1: np.array = None, vec_cur_2: np.array = None, vec_cur_3: np.array = None, delta: float = 0.1, **kwargs) -> np.array: return vec_cur + delta * vec_integral @numba.jit(nopython=True, parallel=True, nogil=True) def component_next_adams2(vec_integral: np.array = None, vec_integral_1: np.array = None, vec_integral_2: np.array = None, vec_integral_3: np.array = None, vec_integral_4: np.array = None, vec_cur: np.array = None, vec_cur_1: np.array = None, vec_cur_2: np.array = None, vec_cur_3: np.array = None, delta: float = 0.1, **kwargs) -> np.array: return vec_cur + delta * (adams_bashforth2_c0 * vec_integral + adams_bashforth2_c1 * vec_integral_1) @numba.jit(nopython=True, parallel=True, nogil=True) def component_next_adams3(vec_integral: np.array = None, vec_integral_1: np.array = None, vec_integral_2: np.array = None, vec_integral_3: np.array = None, vec_integral_4: np.array = None, vec_cur: np.array = None, vec_cur_1: np.array = None, vec_cur_2: np.array = None, vec_cur_3: np.array = None, delta: float = 0.1, **kwargs): return vec_cur + delta * (adams_bashforth3_c0 * vec_integral + adams_bashforth3_c1 * vec_integral_1 + adams_bashforth3_c2 * vec_integral_2) @numba.jit(nopython=True, parallel=True, nogil=True) def component_next_adams4(vec_integral: np.array = None, vec_integral_1: np.array = None, vec_integral_2: np.array = None, vec_integral_3: np.array = None, vec_integral_4: np.array = None, vec_cur: np.array = None, vec_cur_1: np.array = None, vec_cur_2: np.array = None, vec_cur_3: np.array = None, delta: float = 0.1, **kwargs): return vec_cur + delta * (adams_bashforth4_c0 * vec_integral + adams_bashforth4_c1 * vec_integral_1 + adams_bashforth4_c2 * vec_integral_2 + adams_bashforth4_c3 * vec_integral_3) @numba.jit(nopython=True, parallel=True, nogil=True) def component_next_adams5(vec_integral: np.array = None, vec_integral_1: np.array = None, vec_integral_2: np.array = None, vec_integral_3: np.array = None, vec_integral_4: np.array = None, vec_cur: np.array = None, vec_cur_1: np.array = None, vec_cur_2: np.array = None, vec_cur_3: np.array = None, delta: float = 0.1, **kwargs): return vec_cur + delta * (adams_bashforth5_c0 * vec_integral + adams_bashforth5_c1 * vec_integral_1 + adams_bashforth5_c2 * vec_integral_2 + adams_bashforth5_c3 * vec_integral_3 + adams_bashforth5_c4 * vec_integral_4) class ProblemSolving: # ------------------------------------------------------------------------------------------ number_of_frames: int # Количество разбиений объекта number_of_steps: int # Количество временных шагов эксперимента time_step: float # Временной шаг для процесса во времени max_time: float # Максимальное время расчёта timeline: np.array # Массив временных отметок в виде массива numpy timeline_index: np.array # Массив индексов временных отметок в виде массива numpy _time_current_: int # Обозначение текущего времени отсчёта # ------------------------------------------------------------------------------------------ free_function: Callable # Функция правой части free_function_params: List[float] # Параметры функции правой части orientation: np.array # Массив типа numpy - нормированный вектор направления распространения волны component_next_func: Callable # Функция для поиска следующей компоненты по определению первой производной # ------------------------------------------------------------------------------------------ Q: np.array # Массив данных поверхностных зарядов на объекте на каждый временной шаг P: np.array # Массив данных временных производных пов. зарядов на объекте на каждый шаг G: np.array # Массив данных векторов касательных токов на объекте на каждый шаг D: np.array # Массив данных временных произв. векторов кас. токов на объекте на каждый шаг # ------------------------------------------------------------------------------------------ frames: np.array # Массив данных разбиений на решаемом объекте collocations: np.array # Массив данных коллокаций на решаемом объекте norms: np.array # Массив данных нормалей к разбиениям на объекте neighbours: np.array # Массив индексов соседей для каждой ячейки разбиения tau: np.array # Параметры запаздывания во времени по объекту coefficients_G1: np.array # Массив данных коэффициентов для первого интегрального ядра G1: NxNx3 coefficients_G2: np.array # Массив данных коэффициентов для первого интегрального ядра G2: NxNx3 coefficients_G3: np.array # Массив данных коэффициентов для первого интегрального ядра G3: NxNx1 def __init__(self, time_step: float, max_time: float, number_of_frames: int, free_function: Callable = f_function, free_function_params: List[float] = None, component_next_func: Callable = component_next_euler2, orientation: np.array = np.array([0., 1., 0.]), frames: np.array = None, collocations: np.array = None, norms: np.array = None, neighbours: np.array = None, collocation_distances: np.array = None, coefficients_G1: np.array = None, coefficients_G2: np.array = None, coefficients_G3: np.array = None): """ :param time_step: - step in time for non-stationary experiment :param max_time: - maximum time of observation :param number_of_frames: - number of frames in object """ # Блок метаинформации self.time_step = time_step self.max_time = max_time self.timeline = np.arange(0, max_time, time_step) self.timeline_index = np.arange(0, self.timeline.shape[0], 1) self.number_of_frames = number_of_frames self.number_of_steps = len(self.timeline_index) - 1 self._time_current_ = 1 # t # Блок входных данных задачи self.free_function = free_function self.free_function_params = free_function_params if orientation is None: self.orientation = np.array([0., 1., 0.]) else: self.orientation = np.array(orientation) / np.sqrt(np.array(orientation) @ np.array(orientation)) self.component_next_func = component_next_func # Блок выходных данных self.Q = np.zeros((self.number_of_frames, 2, 1)) # np.array of (N, t, 1) elements self.P = np.zeros((self.number_of_frames, 2, 1)) # np.array of (N, t, 1) elements self.G = np.zeros((self.number_of_frames, 2, 3)) # np.array of (N, t, 3) elements self.D = np.zeros((self.number_of_frames, 1, 3)) # np.array of (N, t-1, 3) elements # Блок обязательно считанных ранее данных фигур, касательно объекта, на котором решаем self.frames = frames self.collocations = collocations self.norms = norms self.neighbours = neighbours self.tau = collocation_distances self.coefficients_G1 = coefficients_G1 self.coefficients_G2 = coefficients_G2 self.coefficients_G3 = coefficients_G3 def time_index_between(self, time: float) -> tuple: """ :param time: - scalar or np.array :return: tuple of np.arrays """ return np.array(np.floor(time / self.time_step), dtype="int"), \ np.array(np.ceil(time / self.time_step), dtype="int") def time_index(self, time: float) -> np.array: """ :param time: - scalar or np.array :return: np.array of indexes """ return np.array(np.round(time / self.time_step), dtype="int") def get_Q_element(self, time: float = 0.0, frame: int = 0) -> float: """ :param time: - scalar :param frame: - scalar :return: float scalar """ if frame < 0 or frame >= self.number_of_frames: return 0.0 if time < 0: return 0.0 elif time > self.timeline[self._time_current_]: return 0.0 else: time_ind = self.time_index(time) return self.Q[frame, time_ind, 0] def get_Q_vec(self, time: float = 0.0) -> np.array: """ :param time: - scalar :return: np.array of (N, ) elements """ if time < 0: return np.zeros(self.number_of_frames) elif time > self.timeline[self._time_current_]: return np.zeros(self.number_of_frames) else: time_ind = self.time_index(time) return self.Q[:, time_ind, 0] def get_Q_element_ind(self, index: int = 0, frame: int = 0) -> float: """ :param index: - scalar int :param frame: - scalar int :return: float scalar """ if frame < 0 or frame >= self.number_of_frames: return 0.0 if index < 0: return 0.0 elif index > self._time_current_: return 0.0 else: return self.Q[frame, index, 0] def get_Q_vec_ind(self, index: int = 0) -> np.array: """ :param index: - scalar int :return: np.array of (N, ) elements """ if index < 0: return np.zeros(self.number_of_frames) elif index > self._time_current_: return np.zeros(self.number_of_frames) else: return self.Q[:, index, 0] def get_P_element(self, time: float = 0.0, frame: int = 0) -> float: """ :param time: - scalar :param frame: - scalar :return: float scalar """ if frame < 0 or frame >= self.number_of_frames: return 0.0 if time < 0: return 0.0 elif time > self.timeline[self._time_current_]: return 0.0 else: time_ind = self.time_index(time) return self.P[frame, time_ind, 0] def get_P_vec(self, time: float = 0.0) -> np.array: """ :param time: - scalar :return: np.array of (N, ) elements """ if time < 0: return np.zeros(self.number_of_frames) elif time > self.timeline[self._time_current_]: return np.zeros(self.number_of_frames) else: time_ind = self.time_index(time) return self.P[:, time_ind, 0] def get_P_element_ind(self, index: int = 0, frame: int = 0) -> float: """ :param index: - scalar int :param frame: - scalar int :return: float scalar """ if frame < 0 or frame >= self.number_of_frames: return 0.0 if index < 0: return 0.0 elif index > self._time_current_: return 0.0 else: return self.P[frame, index, 0] def get_P_vec_ind(self, index: int = 0) -> np.array: """ :param index: - scalar int :return: np.array of (N, ) elements """ if index < 0: return np.zeros(self.number_of_frames) elif index > self._time_current_: return np.zeros(self.number_of_frames) else: return self.P[:, index, 0] def get_G_element(self, time: float = 0.0, frame: int = 0) -> np.array: """ :param time: - scalar :param frame: - scalar :return: np.array of 3 numbers in (i, j, k) """ if frame < 0 or frame >= self.number_of_frames: return np.zeros(3) if time < 0: return np.zeros(3) elif time > self.timeline[self._time_current_]: return np.zeros(3) else: time_ind = self.time_index(time) return self.G[frame, time_ind] def get_G_vec(self, time: float = 0.0) -> np.array: """ :param time: - scalar :return: np.array of (N, 3) elements """ if time < 0: return np.zeros((self.number_of_frames, 3)) elif time > self.timeline[self._time_current_]: return np.zeros((self.number_of_frames, 3)) else: time_ind = self.time_index(time) return self.G[:, time_ind] def get_G_element_ind(self, index: int = 0, frame: int = 0) -> np.array: """ :param index: - scalar int :param frame: - scalar int :return: np.array of 3 numbers in (i, j, k) """ if frame < 0 or frame >= self.number_of_frames: return np.zeros(3) if index < 0: return np.zeros(3) elif index > self._time_current_: return np.zeros(3) else: return self.G[frame, index] def get_G_vec_ind(self, index: int = 0) -> np.array: """ :param index: - scalar int :return: np.array of (N, 3) elements """ if index < 0: return np.zeros((self.number_of_frames, 3)) elif index > self._time_current_: return np.zeros((self.number_of_frames, 3)) else: return self.G[:, index] def get_D_element(self, time: float = 0.0, frame: int = 0) -> np.array: """ :param time: - scalar :param frame: - scalar :return: np.array of 3 numbers in (i, j, k) """ if frame < 0 or frame >= self.number_of_frames: return np.zeros(3) if time < 0: return np.zeros(3) elif time > self.timeline[self._time_current_]: return np.zeros(3) else: time_ind = self.time_index(time) return self.D[frame, time_ind] def get_D_vec(self, time: float = 0.0) -> np.array: """ :param time: - scalar :return: np.array of (N, 3) elements """ if time < 0: return np.zeros((self.number_of_frames, 3)) elif time > self.timeline[self._time_current_]: return np.zeros((self.number_of_frames, 3)) else: time_ind = self.time_index(time) return self.D[:, time_ind] def get_D_element_ind(self, index: int = 0, frame: int = 0) -> np.array: """ :param index: - scalar int :param frame: - scalar int :return: np.array of 3 numbers in (i, j, k) """ if frame < 0 or frame >= self.number_of_frames: return np.zeros(3) if index < 0: return np.zeros(3) elif index > self._time_current_ - 1: return np.zeros(3) else: return self.D[frame, index] def get_D_vec_ind(self, index: int = 0) -> np.array: """ :param index: - scalar int :return: np.array of 3 numbers in (i, j, k) """ if index < 0: return np.zeros((self.number_of_frames, 3)) elif index > self._time_current_ - 1: return np.zeros((self.number_of_frames, 3)) else: return self.D[:, index] def time_current_get(self, mode: int = 0): """ :param mode: integer key for interpret what to return :return: if mode == 0 returns integer index, else returns real time count """ if mode == 0: return self._time_current_ else: return self.timeline[self._time_current_] def time_current_inc(self): if self._time_current_ != self.max_time: self._time_current_ += 1 def set_State(self, new_Q: np.array = None, new_P: np.array = None, new_G: np.array = None, new_D: np.array = None): if new_Q is None: self.Q = np.concatenate((self.Q, np.zeros((self.number_of_frames, 1))), axis=1) else: self.Q = np.concatenate((self.Q, new_Q.reshape((self.number_of_frames, 1))), axis=1) if new_P is None: self.P = np.concatenate((self.P, np.zeros((self.number_of_frames, 1))), axis=1) else: self.P = np.concatenate((self.P, new_P.reshape((self.number_of_frames, 1))), axis=1) if new_G is None: self.G = np.concatenate((self.G, np.zeros((self.number_of_frames, 3))), axis=1) else: self.G = np.concatenate((self.G, new_G.reshape((self.number_of_frames, 3))), axis=1) if new_D is None: self.D = np.concatenate((self.D, np.zeros((self.number_of_frames, 3))), axis=1) else: self.D = np.concatenate((self.D, new_D.reshape((self.number_of_frames, 3))), axis=1) self.time_current_inc() def step(self): time = self.timeline[self._time_current_] f_vec = np.zeros((self.number_of_frames, 3)) for i in range(self.number_of_frames): coord = self.collocations[i][2] f_vec[i] = np.cross(self.orientation * self.free_function((speed_of_light * time - coord, 1)), self.norms[i])
[ "numpy.abs", "numpy.ceil", "numpy.floor", "numpy.zeros", "numpy.array", "numpy.arange", "numba.jit", "numpy.exp", "numpy.round" ]
[((901, 952), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (910, 952), False, 'import numba\n'), ((1421, 1472), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (1430, 1472), False, 'import numba\n'), ((2114, 2165), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (2123, 2165), False, 'import numba\n'), ((2808, 2859), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (2817, 2859), False, 'import numba\n'), ((3546, 3597), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (3555, 3597), False, 'import numba\n'), ((4234, 4285), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (4243, 4285), False, 'import numba\n'), ((5027, 5078), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (5036, 5078), False, 'import numba\n'), ((5878, 5929), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (5887, 5929), False, 'import numba\n'), ((6796, 6847), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (6805, 6847), False, 'import numba\n'), ((1191, 1251), 'numpy.abs', 'np.abs', (['(params[1] ** 2 / params[0] * (params[1] - params[0]))'], {}), '(params[1] ** 2 / params[0] * (params[1] - params[0]))\n', (1197, 1251), True, 'import numpy as np\n'), ((1326, 1391), 'numpy.exp', 'np.exp', (['(-(params[1] ** 2 / (params[0] * (params[1] - params[0]))))'], {}), '(-(params[1] ** 2 / (params[0] * (params[1] - params[0]))))\n', (1332, 1391), True, 'import numpy as np\n'), ((10382, 10407), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (10390, 10407), True, 'import numpy as np\n'), ((11128, 11161), 'numpy.arange', 'np.arange', (['(0)', 'max_time', 'time_step'], {}), '(0, max_time, time_step)\n', (11137, 11161), True, 'import numpy as np\n'), ((11192, 11231), 'numpy.arange', 'np.arange', (['(0)', 'self.timeline.shape[0]', '(1)'], {}), '(0, self.timeline.shape[0], 1)\n', (11201, 11231), True, 'import numpy as np\n'), ((11863, 11902), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 2, 1)'], {}), '((self.number_of_frames, 2, 1))\n', (11871, 11902), True, 'import numpy as np\n'), ((11964, 12003), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 2, 1)'], {}), '((self.number_of_frames, 2, 1))\n', (11972, 12003), True, 'import numpy as np\n'), ((12065, 12104), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 2, 3)'], {}), '((self.number_of_frames, 2, 3))\n', (12073, 12104), True, 'import numpy as np\n'), ((12166, 12205), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 1, 3)'], {}), '((self.number_of_frames, 1, 3))\n', (12174, 12205), True, 'import numpy as np\n'), ((22728, 22764), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (22736, 22764), True, 'import numpy as np\n'), ((11613, 11638), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (11621, 11638), True, 'import numpy as np\n'), ((13189, 13220), 'numpy.round', 'np.round', (['(time / self.time_step)'], {}), '(time / self.time_step)\n', (13197, 13220), True, 'import numpy as np\n'), ((13988, 14019), 'numpy.zeros', 'np.zeros', (['self.number_of_frames'], {}), '(self.number_of_frames)\n', (13996, 14019), True, 'import numpy as np\n'), ((14949, 14980), 'numpy.zeros', 'np.zeros', (['self.number_of_frames'], {}), '(self.number_of_frames)\n', (14957, 14980), True, 'import numpy as np\n'), ((15880, 15911), 'numpy.zeros', 'np.zeros', (['self.number_of_frames'], {}), '(self.number_of_frames)\n', (15888, 15911), True, 'import numpy as np\n'), ((16841, 16872), 'numpy.zeros', 'np.zeros', (['self.number_of_frames'], {}), '(self.number_of_frames)\n', (16849, 16872), True, 'import numpy as np\n'), ((17352, 17363), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (17360, 17363), True, 'import numpy as np\n'), ((17404, 17415), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (17412, 17415), True, 'import numpy as np\n'), ((17819, 17855), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (17827, 17855), True, 'import numpy as np\n'), ((18417, 18428), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (18425, 18428), True, 'import numpy as np\n'), ((18470, 18481), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (18478, 18481), True, 'import numpy as np\n'), ((18834, 18870), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (18842, 18870), True, 'import numpy as np\n'), ((19352, 19363), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (19360, 19363), True, 'import numpy as np\n'), ((19404, 19415), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (19412, 19415), True, 'import numpy as np\n'), ((19819, 19855), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (19827, 19855), True, 'import numpy as np\n'), ((20417, 20428), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (20425, 20428), True, 'import numpy as np\n'), ((20470, 20481), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (20478, 20481), True, 'import numpy as np\n'), ((20845, 20881), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (20853, 20881), True, 'import numpy as np\n'), ((11681, 11702), 'numpy.array', 'np.array', (['orientation'], {}), '(orientation)\n', (11689, 11702), True, 'import numpy as np\n'), ((12873, 12904), 'numpy.floor', 'np.floor', (['(time / self.time_step)'], {}), '(time / self.time_step)\n', (12881, 12904), True, 'import numpy as np\n'), ((12946, 12976), 'numpy.ceil', 'np.ceil', (['(time / self.time_step)'], {}), '(time / self.time_step)\n', (12953, 12976), True, 'import numpy as np\n'), ((14095, 14126), 'numpy.zeros', 'np.zeros', (['self.number_of_frames'], {}), '(self.number_of_frames)\n', (14103, 14126), True, 'import numpy as np\n'), ((15042, 15073), 'numpy.zeros', 'np.zeros', (['self.number_of_frames'], {}), '(self.number_of_frames)\n', (15050, 15073), True, 'import numpy as np\n'), ((15987, 16018), 'numpy.zeros', 'np.zeros', (['self.number_of_frames'], {}), '(self.number_of_frames)\n', (15995, 16018), True, 'import numpy as np\n'), ((16934, 16965), 'numpy.zeros', 'np.zeros', (['self.number_of_frames'], {}), '(self.number_of_frames)\n', (16942, 16965), True, 'import numpy as np\n'), ((17491, 17502), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (17499, 17502), True, 'import numpy as np\n'), ((17931, 17967), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (17939, 17967), True, 'import numpy as np\n'), ((18543, 18554), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (18551, 18554), True, 'import numpy as np\n'), ((18932, 18968), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (18940, 18968), True, 'import numpy as np\n'), ((19491, 19502), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (19499, 19502), True, 'import numpy as np\n'), ((19931, 19967), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (19939, 19967), True, 'import numpy as np\n'), ((20547, 20558), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (20555, 20558), True, 'import numpy as np\n'), ((20947, 20983), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (20955, 20983), True, 'import numpy as np\n'), ((21763, 21799), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 1)'], {}), '((self.number_of_frames, 1))\n', (21771, 21799), True, 'import numpy as np\n'), ((21992, 22028), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 1)'], {}), '((self.number_of_frames, 1))\n', (22000, 22028), True, 'import numpy as np\n'), ((22221, 22257), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (22229, 22257), True, 'import numpy as np\n'), ((22450, 22486), 'numpy.zeros', 'np.zeros', (['(self.number_of_frames, 3)'], {}), '((self.number_of_frames, 3))\n', (22458, 22486), True, 'import numpy as np\n'), ((11713, 11734), 'numpy.array', 'np.array', (['orientation'], {}), '(orientation)\n', (11721, 11734), True, 'import numpy as np\n'), ((11737, 11758), 'numpy.array', 'np.array', (['orientation'], {}), '(orientation)\n', (11745, 11758), True, 'import numpy as np\n')]
#--------------------------------- utils.py file ---------------------------------------# """ This file contains utility functions and classes that support the TBNN-s class. This includes cleaning and processing functions. """ # ------------ Import statements import os import timeit import numpy as np from tbnns import constants import tensorflow as tf def downsampleIdx(n_total, downsample): """ Produces a set of indices to index into a numpy array and shuffle/downsample it. Arguments: n_total -- int, total size of the array in that dimensionalization downsample -- number that controls how we downsample the data before saving it to disk. If None, no downsampling or shuffling is done. If this number is more than 1, then it represents the number of examples we want to save; if it is less than 1, it represents the ratio of all training examples we want to save. Returns: idx -- numpy array of ints of size (n_take), which contains the indices that we are supposed to take for downsampling. """ idx_tot = np.arange(n_total) if downsample is None: return idx_tot np.random.shuffle(idx_tot) assert downsample > 0, "downsample must be greater than 0!" if int(downsample) > 1: n_take = int(downsample) if n_take > n_total: print("Warning! This dataset has fewer than {} usable points. " + "All of them will be taken.".format(n_take)) n_take = n_total else: n_take = int(downsample * n_total) if n_take > n_total: n_take = n_total # catches bug where downsample = 1.1 idx = idx_tot[0:n_take] return idx def cleanDiffusivity(diff, g=None, test_inputs=None, n_std=None, prt_default=None, gamma_min=None, clip_elements=False, bump_diff=True, verbose=True): """ This function is called to post-process the diffusivity and g produced for stability Arguments: diff -- numpy array of shape (n_useful, 3, 3) containing the originally predicted diffusivity tensor g -- numpy array of shape (n_useful, NUM_BASIS) containing the factor that multiplies each tensor basis to produce the tensor diffusivity. Optional, if None it is not used. test_inputs -- numpy array of shape (n_useful, NUM_FEATURES) containing the test point features that produced the diffusivity tensor we are dealing with. Optional, if None it is not used. n_std -- float, number of standard deviations around the training mean that each test feature is allowed to be. Optional, if None, default value is read from constants.py prt_default -- float, default value of turbulent Prandlt number used when cleaning diffusivities that are outright negative. Optional, if None is passed, default value is read from constants.py gamma_min -- float, minimum value of gamma = diffusivity/turbulent viscosity allowed. Used to clean values that are positive but too close to zero. Optional, if None is passed, default value is read from constants.py clip_elements -- bool, optional argument. This decides whether we clip elements of the matrix to make sure they are not too big or too small. By default, this is False, so no clipping is applied. bump_diff -- bool, optional argument. This decides whether we bump the diagonal elements of the matrix in case the eigenvalues are positive but small. This helps with stability, so it's True by default. verbose -- optional argument, boolean that says whether we print some extra information to the screen. Returns: diff -- numpy array of shape (n_useful, 3, 3) containing the post-processed diffusivity tensor g -- numpy array of shape (n_useful, NUM_BASIS) containing the post-processed factor that multiplies each tensor basis to produce the tensor diffusivity. If g=None is the argument, then this is NOT returned. """ # Get default values if None is passed if n_std is None: n_std = constants.N_STD if prt_default is None: prt_default = constants.PRT_DEFAULT if gamma_min is None: gamma_min = constants.GAMMA_MIN print("Cleaning predicted diffusivity... ", end="", flush=True) tic = timeit.default_timer() # (1) Here, make sure that there is no input more or less than n_std away # from the mean. Since test_inputs was normalized, it should not be more # than n_std or less than -n_std if we don't want test points too different # from the training data. We are cleaning points that, by a very simple measure, # denote extrapolation from the training set mask_ext = np.zeros(diff.shape[0], dtype=bool) if test_inputs is not None: mask_ext = (np.amax(test_inputs,axis=1) > n_std) + \ (np.amin(test_inputs,axis=1) < -n_std) diff, g = applyMask(diff, g, mask_ext, prt_default) num_ext = np.sum(mask_ext) # total number of entries affected by this step #-------------------------------------------------------------------- # (2) Here, make sure all matrix entries are bounded according to gamma_min. # Diagonal elements must be positive, between 1/gamma_min and gamma_min. # Off-diagonal can be negative, but must lie between -1/gamma_min and 1/gamma_min. num_clip = 0 if clip_elements: for i in range(3): for j in range(3): if i == j: min = gamma_min else: min = -1.0/gamma_min max = 1.0/gamma_min diff, num = clipElements(diff, i, j, min, max) num_clip += num #-------------------------------------------------------------------- # (3) Here, make sure that all matrices are positive-semidefinite. For a general real # matrix, this holds iff its symmetric part is positive semi-definite diff_sym = 0.5*(diff+np.transpose(diff,axes=(0,2,1))) # symmetric part of diff eig_all, _ = np.linalg.eigh(diff_sym) eig_min = np.amin(eig_all, axis=1) diff, g = applyMask(diff, g, eig_min < 0, prt_default) num_eig = np.sum(eig_min < 0) # number of entries with negative eigenvalue #-------------------------------------------------------------------- # (4) Add a complement to increase the minimum eigenvalues beyond gamma_min if bump_diff: complement = np.zeros_like(eig_min) mask = (eig_min >= 0) * (eig_min < gamma_min) complement[mask] = gamma_min - eig_min[mask] assert (complement >= 0).all(), "Negative complement. Something is wrong..." diff[:,0,0] = diff[:,0,0] + complement diff[:,1,1] = diff[:,1,1] + complement diff[:,2,2] = diff[:,2,2] + complement if g is not None: g[:,0] = g[:,0] + complement num_bump = np.sum((eig_min<gamma_min)*(eig_min>=0)) # small, positive eigenvalue #-------------------------------------------------------------------- # (5) Here, make sure that no diffusivities have negative diagonals. # After cleaning non-PSD, all diagonals should be positive. Throw error if a negative # one is found t = np.amin([diff[:,0,0],diff[:,1,1],diff[:,2,2]],axis=0) # minimum diagonal entry assert (t >= 0).all(), "Negative diagonal detected. That's not supposed to happen" #-------------------------------------------------------------------- # Calculate minimum real part of eigenvalue and minimum diagonal entry # after cleaning diff_sym = 0.5*(diff+np.transpose(diff,axes=(0,2,1))) eig_all, _ = np.linalg.eigh(diff_sym) min_eig = np.amin(eig_all) min_diag = np.amin(np.concatenate((diff[:,0,0], diff[:,1,1], diff[:,2,2])),axis=0) # Print information toc = timeit.default_timer() print("Done! It took {:.1f}s".format(toc-tic), flush=True) if verbose: if test_inputs is not None: print("{} points ({:.2f}% of total) were cleaned due to outlier inputs."\ .format(num_ext, 100.0*num_ext/diff.shape[0]), flush=True) if clip_elements: print("{} entries ({:.2f}% of total) were clipped due to extreme values."\ .format(num_clip, 100.0*num_clip/(9*diff.shape[0])), flush=True) print("{} points ({:.2f}% of total) were cleaned due to non-PSD matrices."\ .format(num_eig, 100.0*num_eig/diff.shape[0]), flush=True) if bump_diff: print("{} points ({:.2f}% of total) were almost non-PSD and got fixed."\ .format(num_bump, 100.0*num_bump/diff.shape[0]), flush=True) print("In cleaned diffusivity: min eigenvalue of " + "symmetric part = {:g}".format(min_eig) + ", minimum diagonal entry = {:g}".format(min_diag), flush=True) if g is None: return diff else: return diff, g def clipElements(diff, i, j, min, max): """ Clips one entry of the diffusivity matrix diff Arguments: diff -- numpy array of shape (n_useful, 3, 3) containing the originally predicted diffusivity tensor i -- first index over which we clip, 0 <= i <= 2 j -- second index over which we clip, 0 <= i <= 2 min -- minimum value that clipped entry can have max -- maximum value that clipped entry can have Returns: diff -- numpy array of shape (n_useful, 3, 3) containing the clipped diffusivity tensor num -- total number of entries affected by this clipping """ # counts how many elements we are modifying num = np.sum(diff[:,i,j]<min) + np.sum(diff[:,i,j]>max) diff[diff[:,i,j]<min,i,j] = min diff[diff[:,i,j]>max,i,j] = max return diff, num def applyMask(diff, g, mask, prt_default): """ This simple function applies a mask to diff and g. Arguments: diff -- numpy array of shape (n_useful, 3, 3) containing the originally predicted diffusivity tensor g -- numpy array of shape (n_useful, NUM_BASIS) containing the factor that multiplies each tensor basis to produce the tensor diffusivity. Can be None. mask -- boolean numpy array of shape (n_useful,) containing a mask which is True in the places we want to blank out prt_default -- float, default value of turbulent Prandlt number used when cleaning diffusivities that are outright negative. If None is passed, default value is read from constants.py Returns: diff -- numpy array of shape (n_useful, 3, 3) containing the post-processed diffusivity tensor g -- numpy array of shape (n_useful, NUM_BASIS) containing the post-processed factor that multiplies each tensor basis to produce the tensor diffusivity. If g=None in the argument, then None is returned. """ if prt_default is None: prt_default = constants.PRT_DEFAULT diff[mask,:,:] = 0.0 diff[mask,0,0] = 1.0/prt_default diff[mask,1,1] = 1.0/prt_default diff[mask,2,2] = 1.0/prt_default if g is not None: g[mask, :] = 0 g[mask, 0] = 1.0/prt_default return diff, g def calculateLogGamma(uc, gradc, nu_t, tf_flag=False): """ This function calculates log(gamma), where gamma=1/Pr_t, given u'c', gradc, and eddy viscosity Arguments: uc -- np.array or tensor containing the u'c' vector, shape [None, 3] gradc -- np.array or tensor containing the concentration gradient, shape [None, 3] nu_t -- np.array or tensor containing the eddy viscosity, shape [None,] tf_flag -- optional argument, bool which says whether we are dealing with tensorflow tensors or with numpy arrays. Returns: log(gamma) -- np.array or tensor containing the natural log of gamma, shape [None,] """ if tf_flag: alpha_t = tf.reduce_sum(-1.0*uc*gradc, axis=1)/tf.reduce_sum(gradc*gradc, axis=1) gamma = alpha_t/nu_t gamma = tf.maximum(gamma, constants.GAMMA_MIN) gamma = tf.minimum(gamma, 1.0/constants.GAMMA_MIN) return tf.log(gamma) else: alpha_t = np.sum(-1.0*uc*gradc, axis=1) / np.sum(gradc**2, axis=1) gamma = alpha_t/nu_t gamma[gamma<constants.GAMMA_MIN] = constants.GAMMA_MIN gamma[gamma>1.0/constants.GAMMA_MIN] = 1.0/constants.GAMMA_MIN return np.log(gamma) def cleanAnisotropy(b, test_inputs=None, b_default_rans=None, n_std=None, verbose=True): """ This function is called to post-process the anisotropy b for realizability Arguments: b -- numpy array of shape (n_useful, 3, 3) containing the originally predicted anisotropy tensor test_inputs -- numpy array of shape (n_useful, NUM_FEATURES) containing the test point features that produced the anisotropy tensor we are dealing with. Optional, if None it is not used. b_default_rans -- numpy array containing the default anisotropy tensor in RANS. Shape is (num_points, 3, 3) n_std -- float, number of standard deviations around the training mean that each test feature is allowed to be. Optional, if None, default value is read from constants.py verbose -- optional argument, boolean that says whether we print some extra information to the screen. Returns: b -- numpy array of shape (n_useful, 3, 3) containing the post-processed anisotropy tensor """ # Get default values if None is passed if n_std is None: n_std = constants.N_STD print("Cleaning predicted anisotropy tensor... ", end="", flush=True) tic = timeit.default_timer() # (1) Here, make sure that there is no input more or less than n_std away # from the mean. Since test_inputs was normalized, it should not be more # than n_std or less than -n_std if we don't want test points too different # from the training data. We are cleaning points that, by a very simple measure, # denote extrapolation from the training set mask_ext = np.zeros(b.shape[0], dtype=bool) if test_inputs is not None: mask_ext = (np.amax(test_inputs,axis=1) > n_std) + \ (np.amin(test_inputs,axis=1) < -n_std) num_ext = np.sum(mask_ext) # total number of entries affected by this step if num_ext > 0: b[mask_ext, :, :] = b_default_rans[mask_ext, :, :] #-------------------------------------------------------------------- # (2) Here, make sure all matrix entries are realizable. b, n_real, _, = makeRealizableFast(b) #-------------------------------------------------------------------- # Make sure no tensor entry disobeys the criterium in Ling et al. JFM 2016 mask = np.zeros(b.shape[0], dtype=bool) for i in range(3): for j in range(3): if i == j: mask = mask + (b[:,i,j] > 2.0/3) mask = mask + (b[:,i,j] < -1.0/3) else: mask = mask + (b[:,i,j] > 0.5) mask = mask + (b[:,i,j] < -0.5) eig_all, _ = np.linalg.eigh(b) mask = mask + (eig_all[:, 2] < (3.0*np.abs(eig_all[:, 1]) - eig_all[:, 1])/2.0) mask = mask + (eig_all[:, 2] > 1.0/3 - eig_all[:, 1]) n_fail = np.sum(mask) # Print information toc = timeit.default_timer() print("Done! It took {:.1f}s".format(toc-tic), flush=True) if verbose: if test_inputs is not None: print("{} points ({:.2f}% of total) were cleaned due to outlier inputs."\ .format(num_ext, 100.0*num_ext/b.shape[0]), flush=True) print("{} points ({:.2f}% of total) were cleaned due to non-realizable tensors."\ .format(n_real, 100.0*n_real/b.shape[0]), flush=True) print("In cleaned anisotropy tensor: {} violations detected".format(n_fail)) return b def makeRealizableFast(b): """ This function takes in Reynolds stress anisotropy tensor and makes it realizable This function is based on code written by Dr. <NAME>. It checks that each point represents a realizable turbulence state by verifying that it lies within the barycentric map (c.f. Banerjee et al., Journal of Turbulence, 2017 and Emory and Iaccarino, CTR Research Briefs, 2014). If a point lies outside the triangle, it is moved to the nearest point on the boundary of the triangle. Arguments: b -- a numpy array of shape (num_points, 3, 3) containing the Reynolds stress anisotropy components Returns: b -- corrected anisotropy tensor, shape (num_points, 3, 3) n_fails -- number of points failing the realizability test ind_fail -- numpy array of shape (num_points,) containing 1 if the original data was not realizable, and 0 if it was realizable """ # Functions to transform between eigenvalues, barycentric weights, and barycentric coordinates def eval_to_C(evalues): C1 = evalues[0] - evalues[1] C2 = 2.*(evalues[1] - evalues[2]) C3 = 3.*evalues[2] + 1. C3 = 1. - C1 - C2 # Uncomment to verify sum(Ci) = 1 return C1, C2, C3 def C_to_x(C1, C2, C3): x = np.zeros(2) x[0] = C1 + 0.5*C3 x[1] = C3*np.sqrt(3)/2. return x def x_to_C(x): C3 = x[1]*2./np.sqrt(3) C1 = x[0] - 0.5*C3 C2 = 1. - C1 - C3 return C1, C2, C3 def C_to_eval(C1, C2, C3): evalues = np.zeros(3) evalues[0] = C1 + 0.5*C2 + C3/3. - 1./3. evalues[1] = 0.5*C2 + C3/3. - 1./3. evalues[2] = C3/3. - 1./3. return evalues # Get number of points, initialize number of realizability violations num_points = b.shape[0] n_fails = 0 ind_fail = np.zeros((num_points)) # Unit vectors defining edges opposite vertices 1, 2, 3 e1 = np.array([0.5, np.sqrt(3)/2.]) e1 = e1 / np.linalg.norm(e1) e2 = e1 e2[0] = -1.*e2[0] e3 = np.array([1., 0.]) e1perp = np.array([e1[1], -1.*e1[0]]) e2perp = np.array([-1.*e2[1], e2[0]]) e3perp = np.array([e3[1], e3[0]]) eperp_mat = np.transpose(np.array([e1perp, e2perp, e3perp])) pert = 1.e-8 # Array of vertices 1, 2, 3: i.e. v1 = v[:, 0] v = np.array([[1., 0., 0.5], [0., 0., np.sqrt(3)/2.]]) # Verify that b is symmetric with zero trace b = 0.5 * (b + np.transpose(b, (0, 2, 1))) trace_b = np.trace(b, axis1=1, axis2=2) for i in range(3): b[:, i, i] = b[:, i, i] - 1./3. * trace_b # Loop over points to check realizability and project to barycentric map if necessary for i in range(num_points): # Initialize point's realizability indicator fail_ID = 0 # Compute eigenvalues and eigenvectors this_b = b[i, :, :] evalues, evectors = np.linalg.eig(this_b) sort = np.argsort(evalues) sort = np.flip(sort,axis=0) evalues = evalues[sort] evectors = evectors[:, sort] # Check realizability, correct if necessary # Correction procedure: for each vertex, determine if outside triangle # opposite edge - if yes, project to nearest point on that edge. # At end, if still outside triangle, go to nearest vertex. C1, C2, C3 = eval_to_C(evalues) x = C_to_x(C1, C2, C3) if C1 < 0.0: fail_ID = 1 x = np.dot(x, e1)*e1 + pert*e1perp C1, C2, C3 = x_to_C(x) if C2 < 0.0: fail_ID = 1 x = np.dot(x - e3, e2)*e2 + e3 + pert*e2perp C1, C2, C3 = x_to_C(x) if C3 < 0.0: fail_ID = 1 x = np.dot(x, e3)*e3 + pert*e3perp C1, C2, C3 = x_to_C(x) if (C1 < 0.0) or (C2 < 0.0) or (C3 < 0.0): delta_v = np.zeros(3) for j in range(3): v_temp = v[:, j] delta_v[j] = np.linalg.norm(x - v_temp) ind_min = np.argmin(delta_v) x = v[:, ind_min] + pert*(eperp_mat[:, np.mod(ind_min-1, 3)] + eperp_mat[:, np.mod(ind_min+1, 3)]) # Compute corrected anisotropy tensor if fail_ID == 1: evalues = C_to_eval(C1, C2, C3) this_b = np.dot(np.dot(evectors, np.diag(evalues)), np.linalg.inv(evectors)) b[i, :, :] = this_b n_fails += 1 ind_fail[i] = fail_ID # Verify that b is symmetric with zero trace b = 0.5 * (b + np.transpose(b, (0, 2, 1))) trace_b = np.trace(b, axis1=1, axis2=2) for i in range(3): b[:, i, i] = b[:, i, i] - 1./3. * trace_b return b, n_fails, ind_fail def suppressWarnings(): """ This function suppresses several warnings from Tensorflow. """ if type(tf.contrib) != type(tf): tf.contrib._warning = None os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) os.environ['KMP_WARNINGS'] = 'off'
[ "numpy.trace", "tensorflow.reduce_sum", "numpy.sum", "numpy.amin", "numpy.abs", "tensorflow.maximum", "numpy.argmin", "numpy.argsort", "numpy.arange", "numpy.linalg.norm", "numpy.diag", "numpy.zeros_like", "numpy.transpose", "numpy.linalg.eig", "tensorflow.minimum", "numpy.random.shuffle", "numpy.mod", "numpy.linalg.inv", "tensorflow.log", "numpy.dot", "numpy.concatenate", "numpy.flip", "numpy.log", "timeit.default_timer", "numpy.zeros", "numpy.amax", "numpy.linalg.eigh", "numpy.array", "tensorflow.compat.v1.logging.set_verbosity", "numpy.sqrt" ]
[((1223, 1241), 'numpy.arange', 'np.arange', (['n_total'], {}), '(n_total)\n', (1232, 1241), True, 'import numpy as np\n'), ((1315, 1341), 'numpy.random.shuffle', 'np.random.shuffle', (['idx_tot'], {}), '(idx_tot)\n', (1332, 1341), True, 'import numpy as np\n'), ((4838, 4860), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4858, 4860), False, 'import timeit\n'), ((5265, 5300), 'numpy.zeros', 'np.zeros', (['diff.shape[0]'], {'dtype': 'bool'}), '(diff.shape[0], dtype=bool)\n', (5273, 5300), True, 'import numpy as np\n'), ((5535, 5551), 'numpy.sum', 'np.sum', (['mask_ext'], {}), '(mask_ext)\n', (5541, 5551), True, 'import numpy as np\n'), ((6621, 6645), 'numpy.linalg.eigh', 'np.linalg.eigh', (['diff_sym'], {}), '(diff_sym)\n', (6635, 6645), True, 'import numpy as np\n'), ((6662, 6686), 'numpy.amin', 'np.amin', (['eig_all'], {'axis': '(1)'}), '(eig_all, axis=1)\n', (6669, 6686), True, 'import numpy as np\n'), ((6772, 6791), 'numpy.sum', 'np.sum', (['(eig_min < 0)'], {}), '(eig_min < 0)\n', (6778, 6791), True, 'import numpy as np\n'), ((7840, 7902), 'numpy.amin', 'np.amin', (['[diff[:, 0, 0], diff[:, 1, 1], diff[:, 2, 2]]'], {'axis': '(0)'}), '([diff[:, 0, 0], diff[:, 1, 1], diff[:, 2, 2]], axis=0)\n', (7847, 7902), True, 'import numpy as np\n'), ((8292, 8316), 'numpy.linalg.eigh', 'np.linalg.eigh', (['diff_sym'], {}), '(diff_sym)\n', (8306, 8316), True, 'import numpy as np\n'), ((8332, 8348), 'numpy.amin', 'np.amin', (['eig_all'], {}), '(eig_all)\n', (8339, 8348), True, 'import numpy as np\n'), ((8491, 8513), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (8511, 8513), False, 'import timeit\n'), ((14682, 14704), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (14702, 14704), False, 'import timeit\n'), ((15109, 15141), 'numpy.zeros', 'np.zeros', (['b.shape[0]'], {'dtype': 'bool'}), '(b.shape[0], dtype=bool)\n', (15117, 15141), True, 'import numpy as np\n'), ((15319, 15335), 'numpy.sum', 'np.sum', (['mask_ext'], {}), '(mask_ext)\n', (15325, 15335), True, 'import numpy as np\n'), ((15839, 15871), 'numpy.zeros', 'np.zeros', (['b.shape[0]'], {'dtype': 'bool'}), '(b.shape[0], dtype=bool)\n', (15847, 15871), True, 'import numpy as np\n'), ((16183, 16200), 'numpy.linalg.eigh', 'np.linalg.eigh', (['b'], {}), '(b)\n', (16197, 16200), True, 'import numpy as np\n'), ((16359, 16371), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (16365, 16371), True, 'import numpy as np\n'), ((16426, 16448), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (16446, 16448), False, 'import timeit\n'), ((18975, 18995), 'numpy.zeros', 'np.zeros', (['num_points'], {}), '(num_points)\n', (18983, 18995), True, 'import numpy as np\n'), ((19182, 19202), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (19190, 19202), True, 'import numpy as np\n'), ((19215, 19246), 'numpy.array', 'np.array', (['[e1[1], -1.0 * e1[0]]'], {}), '([e1[1], -1.0 * e1[0]])\n', (19223, 19246), True, 'import numpy as np\n'), ((19258, 19289), 'numpy.array', 'np.array', (['[-1.0 * e2[1], e2[0]]'], {}), '([-1.0 * e2[1], e2[0]])\n', (19266, 19289), True, 'import numpy as np\n'), ((19301, 19325), 'numpy.array', 'np.array', (['[e3[1], e3[0]]'], {}), '([e3[1], e3[0]])\n', (19309, 19325), True, 'import numpy as np\n'), ((19642, 19671), 'numpy.trace', 'np.trace', (['b'], {'axis1': '(1)', 'axis2': '(2)'}), '(b, axis1=1, axis2=2)\n', (19650, 19671), True, 'import numpy as np\n'), ((21773, 21802), 'numpy.trace', 'np.trace', (['b'], {'axis1': '(1)', 'axis2': '(2)'}), '(b, axis1=1, axis2=2)\n', (21781, 21802), True, 'import numpy as np\n'), ((22153, 22215), 'tensorflow.compat.v1.logging.set_verbosity', 'tf.compat.v1.logging.set_verbosity', (['tf.compat.v1.logging.ERROR'], {}), '(tf.compat.v1.logging.ERROR)\n', (22187, 22215), True, 'import tensorflow as tf\n'), ((7042, 7064), 'numpy.zeros_like', 'np.zeros_like', (['eig_min'], {}), '(eig_min)\n', (7055, 7064), True, 'import numpy as np\n'), ((7483, 7529), 'numpy.sum', 'np.sum', (['((eig_min < gamma_min) * (eig_min >= 0))'], {}), '((eig_min < gamma_min) * (eig_min >= 0))\n', (7489, 7529), True, 'import numpy as np\n'), ((8377, 8438), 'numpy.concatenate', 'np.concatenate', (['(diff[:, 0, 0], diff[:, 1, 1], diff[:, 2, 2])'], {}), '((diff[:, 0, 0], diff[:, 1, 1], diff[:, 2, 2]))\n', (8391, 8438), True, 'import numpy as np\n'), ((10359, 10386), 'numpy.sum', 'np.sum', (['(diff[:, i, j] < min)'], {}), '(diff[:, i, j] < min)\n', (10365, 10386), True, 'import numpy as np\n'), ((10385, 10412), 'numpy.sum', 'np.sum', (['(diff[:, i, j] > max)'], {}), '(diff[:, i, j] > max)\n', (10391, 10412), True, 'import numpy as np\n'), ((12879, 12917), 'tensorflow.maximum', 'tf.maximum', (['gamma', 'constants.GAMMA_MIN'], {}), '(gamma, constants.GAMMA_MIN)\n', (12889, 12917), True, 'import tensorflow as tf\n'), ((12935, 12979), 'tensorflow.minimum', 'tf.minimum', (['gamma', '(1.0 / constants.GAMMA_MIN)'], {}), '(gamma, 1.0 / constants.GAMMA_MIN)\n', (12945, 12979), True, 'import tensorflow as tf\n'), ((12994, 13007), 'tensorflow.log', 'tf.log', (['gamma'], {}), '(gamma)\n', (13000, 13007), True, 'import tensorflow as tf\n'), ((13295, 13308), 'numpy.log', 'np.log', (['gamma'], {}), '(gamma)\n', (13301, 13308), True, 'import numpy as np\n'), ((18376, 18387), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (18384, 18387), True, 'import numpy as np\n'), ((18657, 18668), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (18665, 18668), True, 'import numpy as np\n'), ((19117, 19135), 'numpy.linalg.norm', 'np.linalg.norm', (['e1'], {}), '(e1)\n', (19131, 19135), True, 'import numpy as np\n'), ((19356, 19390), 'numpy.array', 'np.array', (['[e1perp, e2perp, e3perp]'], {}), '([e1perp, e2perp, e3perp])\n', (19364, 19390), True, 'import numpy as np\n'), ((20064, 20085), 'numpy.linalg.eig', 'np.linalg.eig', (['this_b'], {}), '(this_b)\n', (20077, 20085), True, 'import numpy as np\n'), ((20102, 20121), 'numpy.argsort', 'np.argsort', (['evalues'], {}), '(evalues)\n', (20112, 20121), True, 'import numpy as np\n'), ((20138, 20159), 'numpy.flip', 'np.flip', (['sort'], {'axis': '(0)'}), '(sort, axis=0)\n', (20145, 20159), True, 'import numpy as np\n'), ((6545, 6579), 'numpy.transpose', 'np.transpose', (['diff'], {'axes': '(0, 2, 1)'}), '(diff, axes=(0, 2, 1))\n', (6557, 6579), True, 'import numpy as np\n'), ((8241, 8275), 'numpy.transpose', 'np.transpose', (['diff'], {'axes': '(0, 2, 1)'}), '(diff, axes=(0, 2, 1))\n', (8253, 8275), True, 'import numpy as np\n'), ((12760, 12800), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(-1.0 * uc * gradc)'], {'axis': '(1)'}), '(-1.0 * uc * gradc, axis=1)\n', (12773, 12800), True, 'import tensorflow as tf\n'), ((12797, 12833), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(gradc * gradc)'], {'axis': '(1)'}), '(gradc * gradc, axis=1)\n', (12810, 12833), True, 'import tensorflow as tf\n'), ((13048, 13081), 'numpy.sum', 'np.sum', (['(-1.0 * uc * gradc)'], {'axis': '(1)'}), '(-1.0 * uc * gradc, axis=1)\n', (13054, 13081), True, 'import numpy as np\n'), ((13080, 13106), 'numpy.sum', 'np.sum', (['(gradc ** 2)'], {'axis': '(1)'}), '(gradc ** 2, axis=1)\n', (13086, 13106), True, 'import numpy as np\n'), ((18511, 18521), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (18518, 18521), True, 'import numpy as np\n'), ((19599, 19625), 'numpy.transpose', 'np.transpose', (['b', '(0, 2, 1)'], {}), '(b, (0, 2, 1))\n', (19611, 19625), True, 'import numpy as np\n'), ((21067, 21078), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (21075, 21078), True, 'import numpy as np\n'), ((21225, 21243), 'numpy.argmin', 'np.argmin', (['delta_v'], {}), '(delta_v)\n', (21234, 21243), True, 'import numpy as np\n'), ((21730, 21756), 'numpy.transpose', 'np.transpose', (['b', '(0, 2, 1)'], {}), '(b, (0, 2, 1))\n', (21742, 21756), True, 'import numpy as np\n'), ((5355, 5383), 'numpy.amax', 'np.amax', (['test_inputs'], {'axis': '(1)'}), '(test_inputs, axis=1)\n', (5362, 5383), True, 'import numpy as np\n'), ((5417, 5445), 'numpy.amin', 'np.amin', (['test_inputs'], {'axis': '(1)'}), '(test_inputs, axis=1)\n', (5424, 5445), True, 'import numpy as np\n'), ((15196, 15224), 'numpy.amax', 'np.amax', (['test_inputs'], {'axis': '(1)'}), '(test_inputs, axis=1)\n', (15203, 15224), True, 'import numpy as np\n'), ((15258, 15286), 'numpy.amin', 'np.amin', (['test_inputs'], {'axis': '(1)'}), '(test_inputs, axis=1)\n', (15265, 15286), True, 'import numpy as np\n'), ((18435, 18445), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (18442, 18445), True, 'import numpy as np\n'), ((19086, 19096), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (19093, 19096), True, 'import numpy as np\n'), ((21175, 21201), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - v_temp)'], {}), '(x - v_temp)\n', (21189, 21201), True, 'import numpy as np\n'), ((21541, 21564), 'numpy.linalg.inv', 'np.linalg.inv', (['evectors'], {}), '(evectors)\n', (21554, 21564), True, 'import numpy as np\n'), ((19505, 19515), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (19512, 19515), True, 'import numpy as np\n'), ((20652, 20665), 'numpy.dot', 'np.dot', (['x', 'e1'], {}), '(x, e1)\n', (20658, 20665), True, 'import numpy as np\n'), ((20925, 20938), 'numpy.dot', 'np.dot', (['x', 'e3'], {}), '(x, e3)\n', (20931, 20938), True, 'import numpy as np\n'), ((21522, 21538), 'numpy.diag', 'np.diag', (['evalues'], {}), '(evalues)\n', (21529, 21538), True, 'import numpy as np\n'), ((16242, 16263), 'numpy.abs', 'np.abs', (['eig_all[:, 1]'], {}), '(eig_all[:, 1])\n', (16248, 16263), True, 'import numpy as np\n'), ((20784, 20802), 'numpy.dot', 'np.dot', (['(x - e3)', 'e2'], {}), '(x - e3, e2)\n', (20790, 20802), True, 'import numpy as np\n'), ((21296, 21318), 'numpy.mod', 'np.mod', (['(ind_min - 1)', '(3)'], {}), '(ind_min - 1, 3)\n', (21302, 21318), True, 'import numpy as np\n'), ((21333, 21355), 'numpy.mod', 'np.mod', (['(ind_min + 1)', '(3)'], {}), '(ind_min + 1, 3)\n', (21339, 21355), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue Nov 17 17:43:51 2020 @author: emc1977 """ # Energy of the system can be found as # 1/2*kb*(sqrt(x1^2+(Lb+x2)^2)-Lb)^2 # 1/2*ka*(sqrt(x1^2+(La-x2)^2)-La)^2 # -F1x1-F2x2 import sympy import numpy as np x,y = sympy.symbols('x,y') #need the following to create functions out of symbolix expressions from sympy.utilities.lambdify import lambdify from sympy import symbols, Matrix, Function, simplify, exp, hessian, solve, init_printing init_printing() ka=9. kb=2. La=10. Lb=10. F1=2. F2=4. X = Matrix([x,y]) f = Matrix([0.5*(ka*((x**2+(La-y)**2)**0.5 - La)**2)+0.5*(kb*((x**2+(Lb+y)**2)**0.5 - Lb)**2)-F1*x-F2*y]) print(np.shape(f)) #Since the Hessian is 2x2, then the Jacobian should be 2x1 (for the matrix multiplication) gradf = simplify(f.jacobian(X)).transpose() # #Create function that will take the values of x, y and return a jacobian # #matrix with values fgradf = lambdify([x,y], gradf) print('Jacobian f', gradf) hessianf = simplify(hessian(f, X)) # #Create a function that will return a Jessian matrix with values fhessianf = lambdify([x,y], hessianf) print('Hessian f', hessianf) def Newton_Raphson_Optimize(Grad, Hess, x,y, epsilon=0.000001, nMax = 200): #Initialization i = 0 iter_x, iter_y, iter_count = np.empty(0),np.empty(0), np.empty(0) error = 10 X = np.array([x,y]) #Looping as long as error is greater than epsilon while np.linalg.norm(error) > epsilon and i < nMax: i +=1 iter_x = np.append(iter_x,x) iter_y = np.append(iter_y,y) iter_count = np.append(iter_count ,i) print(X) X_prev = X #X had dimensions (2,) while the 2nd term (2,1), so it had to be converted to 1D X = X - np.matmul(np.linalg.inv(Hess(x,y)), Grad(x,y)).flatten() error = X - X_prev x,y = X[0], X[1] return X, iter_x,iter_y, iter_count root,iter_x,iter_y, iter_count = Newton_Raphson_Optimize(fgradf,fhessianf,1,1) print(root)
[ "sympy.symbols", "numpy.empty", "sympy.utilities.lambdify.lambdify", "sympy.Matrix", "numpy.shape", "numpy.append", "sympy.init_printing", "sympy.hessian", "numpy.array", "numpy.linalg.norm" ]
[((263, 283), 'sympy.symbols', 'sympy.symbols', (['"""x,y"""'], {}), "('x,y')\n", (276, 283), False, 'import sympy\n'), ((494, 509), 'sympy.init_printing', 'init_printing', ([], {}), '()\n', (507, 509), False, 'from sympy import symbols, Matrix, Function, simplify, exp, hessian, solve, init_printing\n'), ((563, 577), 'sympy.Matrix', 'Matrix', (['[x, y]'], {}), '([x, y])\n', (569, 577), False, 'from sympy import symbols, Matrix, Function, simplify, exp, hessian, solve, init_printing\n'), ((584, 732), 'sympy.Matrix', 'Matrix', (['[0.5 * (ka * ((x ** 2 + (La - y) ** 2) ** 0.5 - La) ** 2) + 0.5 * (kb * ((x **\n 2 + (Lb + y) ** 2) ** 0.5 - Lb) ** 2) - F1 * x - F2 * y]'], {}), '([0.5 * (ka * ((x ** 2 + (La - y) ** 2) ** 0.5 - La) ** 2) + 0.5 * (\n kb * ((x ** 2 + (Lb + y) ** 2) ** 0.5 - Lb) ** 2) - F1 * x - F2 * y])\n', (590, 732), False, 'from sympy import symbols, Matrix, Function, simplify, exp, hessian, solve, init_printing\n'), ((954, 977), 'sympy.utilities.lambdify.lambdify', 'lambdify', (['[x, y]', 'gradf'], {}), '([x, y], gradf)\n', (962, 977), False, 'from sympy.utilities.lambdify import lambdify\n'), ((1124, 1150), 'sympy.utilities.lambdify.lambdify', 'lambdify', (['[x, y]', 'hessianf'], {}), '([x, y], hessianf)\n', (1132, 1150), False, 'from sympy.utilities.lambdify import lambdify\n'), ((693, 704), 'numpy.shape', 'np.shape', (['f'], {}), '(f)\n', (701, 704), True, 'import numpy as np\n'), ((1028, 1041), 'sympy.hessian', 'hessian', (['f', 'X'], {}), '(f, X)\n', (1035, 1041), False, 'from sympy import symbols, Matrix, Function, simplify, exp, hessian, solve, init_printing\n'), ((1389, 1405), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (1397, 1405), True, 'import numpy as np\n'), ((1327, 1338), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (1335, 1338), True, 'import numpy as np\n'), ((1339, 1350), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (1347, 1350), True, 'import numpy as np\n'), ((1352, 1363), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (1360, 1363), True, 'import numpy as np\n'), ((1552, 1572), 'numpy.append', 'np.append', (['iter_x', 'x'], {}), '(iter_x, x)\n', (1561, 1572), True, 'import numpy as np\n'), ((1590, 1610), 'numpy.append', 'np.append', (['iter_y', 'y'], {}), '(iter_y, y)\n', (1599, 1610), True, 'import numpy as np\n'), ((1632, 1656), 'numpy.append', 'np.append', (['iter_count', 'i'], {}), '(iter_count, i)\n', (1641, 1656), True, 'import numpy as np\n'), ((1473, 1494), 'numpy.linalg.norm', 'np.linalg.norm', (['error'], {}), '(error)\n', (1487, 1494), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # Copyright 2020 PyePAL authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Methods to validate inputs for the PAL classes""" import collections import warnings from typing import Any, Iterable, List, Sequence, Union import numpy as np from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.model_selection import GridSearchCV, RandomizedSearchCV __all__ = [ "base_validate_models", "validate_beta_scale", "validate_coef_var", "validate_coregionalized_gpy", "validate_delta", "validate_epsilon", "validate_gbdt_models", "validate_goals", "validate_gpy_model", "validate_interquartile_scaler", "validate_ndim", "validate_njobs", "validate_nt_models", "validate_number_models", "validate_optimizers", "validate_positive_integer_list", "validate_sklearn_gpr_models", ] def validate_ndim(ndim: Any) -> int: """Make sure that the number of dimensions makes sense Args: ndim (Any): number of dimensions Raises: ValueError: If the number of dimensions is not an integer ValueError: If the number of dimensions is not greater than 0 Returns: int: the number of dimensions """ if not isinstance(ndim, int): raise ValueError("The number of dimensions, ndim, must be a positive integer") if ndim <= 0: raise ValueError("ndmin must be greater than 0") return ndim def validate_delta(delta: Any) -> float: """Make sure that delta is in a reasonable range Args: delta (Any): Delta hyperparameter Raises: ValueError: Delta must be in [0,1]. Returns: float: delta """ if (delta > 1) | (delta < 0): raise ValueError("The delta values must be in [0,1]") return delta def validate_beta_scale(beta_scale: Any) -> float: """ Args: beta_scale (Any): scaling factor for beta Raises: ValueError: If beta is smaller than 0 Returns: float: scaling factor for beta """ if beta_scale < 0: raise ValueError("The beta_scale values must be positive") return beta_scale def validate_epsilon(epsilon: Any, ndim: int) -> np.ndarray: """Validate epsilon and return a np.array Args: epsilon (Any): Epsilon hyperparameter ndim (int): Number of dimensions/objectives Raises: ValueError: If epsilon is a list there must be one float per dimension ValueError: Epsilon must be in [0,1] ValueError: If epsilon is an array there must be one float per dimension Returns: np.ndarray: Array of one epsilon per objective """ if isinstance(epsilon, list): if len(epsilon) != ndim: raise ValueError( "If epsilon is provided as a list,\ there must be one float per dimension" ) for value in epsilon: if (value > 1) | (value < 0): raise ValueError("The epsilon values must be in [0,1]") return np.array(epsilon) if isinstance(epsilon, np.ndarray): if len(epsilon) != ndim: raise ValueError( "If epsilon is provided as a array,\ there must be one float per dimension" ) for value in epsilon: if (value > 1) | (value < 0): raise ValueError("The epsilon values must be in [0,1]") return epsilon if (epsilon > 1) | (epsilon < 0): raise ValueError("The epsilon values must be in [0,1]") warnings.warn( """Only one epsilon value provided, will automatically expand to use the same value in every dimension""", UserWarning, ) return np.array([epsilon] * ndim) def validate_goals( # pylint:disable=too-many-branches goals: Any, ndim: int ) -> np.ndarray: """Create a valid array of goals. 1 for maximization, -1 for objectives that are to be minimized. Args: goals (Any): List of goals, typically provideded as strings 'max' for maximization and 'min' for minimization ndim (int): number of dimensions Raises: ValueError: If goals is a list and the length is not equal to ndim ValueError: If goals is a list and the elements are not strings 'min', 'max' or -1 and 1 Returns: np.ndarray: Array of -1 and 1 """ if goals is None: warnings.warn( "No goals provided, will assume that every dimension should be maximized", UserWarning, ) return np.array([1] * ndim) if isinstance(goals, list): if len(goals) != ndim: raise ValueError("If goals is a list, the length must be equal to the ndim") for goal in goals: if not isinstance(goal, str) | (goal != 1) | (goal != -1): raise ValueError("If goals is a list, it must be a list of strings") clean_goals = [] for goal in goals: if isinstance(goal, str): if "max" in goal.lower(): clean_goals.append(1) elif "min" in goal.lower(): clean_goals.append(-1) else: raise ValueError("The strings in the goals list must be min or max") elif isinstance(goal, int): if goal == 1: clean_goals.append(1) elif goal == -1: clean_goals.append(-1) else: raise ValueError("The ints in the goals list must be 1 or -1") assert len(clean_goals) == ndim return np.array(clean_goals) raise ValueError( "Goal can be set to None or must be a list of strings\ or -1 and 1 of length equal to ndim" ) def base_validate_models(models: Any) -> list: """Currently no validation as the predict and train function are implemented independet of the base class""" if models: return models raise ValueError("You must provide some models to initialize pyepal") def validate_number_models(models: Any, ndim: int): """Make sure that there are as many models as objectives Args: models (Any): List of models ndim (int): Number of objectives Raises: ValueError: If the number of models does not equal the number of objectives """ if not isinstance(models, list): raise ValueError("You must provide a list of models. One model per objective") if len(models) != ndim: raise ValueError("You must provide a list of models. One model per objective") def validate_gpy_model(models: Any): """Make sure that all elements of the list a GPRegression models""" import GPy # pylint:disable=import-outside-toplevel for model in models: if not isinstance(model, GPy.models.GPRegression): raise ValueError("The models must be an instance of GPy.model") def validate_coregionalized_gpy(models: Any): """Make sure that model is a coregionalized GPR model""" if not isinstance(models, list): raise ValueError("You must provide a list of models with one element") from ..models.coregionalized import ( # pylint:disable=import-outside-toplevel GPCoregionalizedRegression, ) if not isinstance(models[0], GPCoregionalizedRegression): raise ValueError( "Model must be a GPCoregionalized regression object from this package!" ) def validate_njobs(njobs: Any) -> int: """Make sure that njobs is an int > 1""" if not isinstance(njobs, int): raise ValueError("njobs musst be of type int") if njobs < 1: raise ValueError("njobs must be a number greater equal 1") return njobs def validate_coef_var(coef_var: Any): """Make sure that the coef_var makes sense""" if not isinstance(coef_var, (float, int)): raise ValueError("coef_var must be of type float or int") if coef_var <= 0: raise ValueError("coef_var must be greater 0") return coef_var def _validate_sklearn_gpr_model(model: Any) -> GaussianProcessRegressor: """Make sure that we deal with a GaussianProcessRegressor instance, if it is a fitted random or grid search instance, extract the model""" if isinstance(model, (RandomizedSearchCV, GridSearchCV)): try: if isinstance(model.best_estimator_, GaussianProcessRegressor): return model.best_estimator_ raise ValueError( """If you provide a grid or random search instance, it needs to contain a GaussianProcessRegressor instance.""" ) except AttributeError as not_fitted_exception: raise ValueError( "If you provide a grid or random search instance it needs to be fitted." ) from not_fitted_exception elif isinstance(model, GaussianProcessRegressor): return model raise ValueError("You need to provide a GaussianProcessRegressor instance.") def validate_sklearn_gpr_models( models: Any, ndim: int ) -> List[GaussianProcessRegressor]: """Make sure that there is a list of GPR models, one model per objective""" validate_number_models(models, ndim) models_validated = [] for model in models: models_validated.append(_validate_sklearn_gpr_model(model)) return models_validated def _validate_quantile_loss(lightgbmregressor): try: alpha = lightgbmregressor.alpha loss = lightgbmregressor.objective except AttributeError as missing_attribute: raise ValueError( """Make sure that you initialize at least the first and last model with quantile loss. """ ) from missing_attribute if loss != "quantile": raise ValueError( """Make sure that you initialize at least the first and last model with quantile loss. """ ) assert alpha > 0 def validate_gbdt_models(models: Any, ndim: int) -> List[Iterable]: """Make sure that the number of iterables is equal to the number of objectives and that every iterable contains three LGBMRegressors. Also, we check that at least the first and last models use quantile loss""" validate_number_models(models, ndim) from lightgbm import LGBMRegressor # pylint:disable=import-outside-toplevel for model_tuple in models: if len(model_tuple) != 3: raise ValueError( """The model list must contain tuples with three LGBMRegressor instances. """ ) for counter, model in enumerate(model_tuple): if not isinstance(model, LGBMRegressor): raise ValueError( """The model list must contain tuples with three LGBMRegressor instances. """ ) if counter != 1: _validate_quantile_loss(model) return models def validate_interquartile_scaler(interquartile_scaler: Any) -> float: """Make sure that the interquartile_scaler makes sense""" if not isinstance(interquartile_scaler, (float, int)): raise ValueError("interquartile_scaler must be a number.") if interquartile_scaler < 0: raise ValueError("interquartile_scaler must be a number greater 0.") return interquartile_scaler def _is_jaxoptimizer(optimizer: Any) -> bool: from ..models.nt import JaxOptimizer # pylint:disable=import-outside-toplevel return isinstance(optimizer, JaxOptimizer) def validate_optimizers(optimizers: Any, ndim: int) -> Sequence: """Make sure that we can work with a Sequence if JaxOptimizer""" if not isinstance(optimizers, Sequence): raise ValueError("You must have one optimizer per objective.") if not len(optimizers) == ndim: raise ValueError( "If you provide a sequence it must have one optimizer per objective." ) for optimizer in optimizers: if not _is_jaxoptimizer(optimizer): raise ValueError( "You need to provide a `pyepal.models.nt.JaxOptimizer` instance" ) return optimizers def validate_nt_models(models: Any, ndim: int) -> Sequence: """Make sure that we can work with a sequence of :py:func:`pyepal.pal.models.nt.NTModel`""" from pyepal.models.nt import NTModel # pylint:disable=import-outside-toplevel if not isinstance(models, collections.Sequence): raise ValueError( "You need to provide a sequence of `pyepal.models.nt.NTModel` instances" ) for model in models: if not len(models) == ndim: raise ValueError("You need to provide one model per objective.") if not isinstance(model, NTModel): raise ValueError( "You need to provide a sequence of `pyepal.models.nt.NTModel` instances" ) return models def validate_positive_integer_list( seq: Any, ndim: int, parameter_name: str = "Parameter" ) -> Sequence[int]: """Can be used, e.g., to validate and standardize the ensemble size and epochs input""" if not isinstance(seq, collections.Sequence): if (not isinstance(seq, int)) or (seq < 1): raise ValueError(f"{parameter_name} must be a positive integer") return [seq] * ndim if not len(seq) == ndim: raise ValueError( f"If you provide a sequence for {parameter_name} its length must match \ the number of objectives" ) for elem in seq: if (not isinstance(elem, int)) or (elem < 1): raise ValueError(f"{parameter_name} must be a positive integer") return seq def validate_ranges(ranges: Any, ndim: int) -> Union[None, np.ndarray]: """Make sure that it has the correct numnber of elements and that all elements are positive.""" if not isinstance(ranges, (np.ndarray, list)): return None if not len(ranges) == ndim: raise ValueError( "The number of elements in ranges must match the number of objectives." ) for elem in ranges: if not elem > 0: raise ValueError("Ranges must be positive.") return np.array(ranges)
[ "warnings.warn", "numpy.array" ]
[((4101, 4244), 'warnings.warn', 'warnings.warn', (['"""Only one epsilon value provided,\nwill automatically expand to use the same value in every dimension"""', 'UserWarning'], {}), '(\n """Only one epsilon value provided,\nwill automatically expand to use the same value in every dimension"""\n , UserWarning)\n', (4114, 4244), False, 'import warnings\n'), ((4269, 4295), 'numpy.array', 'np.array', (['([epsilon] * ndim)'], {}), '([epsilon] * ndim)\n', (4277, 4295), True, 'import numpy as np\n'), ((14782, 14798), 'numpy.array', 'np.array', (['ranges'], {}), '(ranges)\n', (14790, 14798), True, 'import numpy as np\n'), ((3576, 3593), 'numpy.array', 'np.array', (['epsilon'], {}), '(epsilon)\n', (3584, 3593), True, 'import numpy as np\n'), ((4988, 5098), 'warnings.warn', 'warnings.warn', (['"""No goals provided, will assume that every dimension should be maximized"""', 'UserWarning'], {}), "(\n 'No goals provided, will assume that every dimension should be maximized',\n UserWarning)\n", (5001, 5098), False, 'import warnings\n'), ((5141, 5161), 'numpy.array', 'np.array', (['([1] * ndim)'], {}), '([1] * ndim)\n', (5149, 5161), True, 'import numpy as np\n'), ((6219, 6240), 'numpy.array', 'np.array', (['clean_goals'], {}), '(clean_goals)\n', (6227, 6240), True, 'import numpy as np\n')]
import enum import os import re from typing import Optional, Tuple import numpy as np from scipy.ndimage import median_filter from skimage.io import imread OCTOPUSLITE_FILEPATTERN = ( "img_channel(?P<channel>[0-9]+)_position(?P<position>[0-9]+)" "_time(?P<time>[0-9]+)_z(?P<z>[0-9]+)" ) @enum.unique class Channels(enum.Enum): BRIGHTFIELD = 0 GFP = 1 RFP = 2 IRFP = 3 PHASE = 4 WEIGHTS = 50 MASK_IRFP = 96 MASK_RFP = 97 MASK_GFP = 98 MASK = 99 def remove_outliers(x: np.ndarray) -> np.ndarray: """Remove bright outlier pixels from an image. Parameters ---------- x : np.ndarray An input image containing bright outlier pixels. Returns ------- x : np.ndarray An image with the bright outlier pixels removed. """ med_x = median_filter(x, size=2) mask = x > med_x x = x * (1 - mask) + (mask * med_x) return x def remove_background(x: np.ndarray) -> np.ndarray: """Remove background using a polynomial surface. Parameters ---------- x : np.ndarray An input image . Returns ------- corrected : np.ndarray The corrected input image, with the background removed. """ maskh, maskw = estimate_mask(x) x = x.astype(np.float32) bg = estimate_background(x[maskh, maskw]) corrected = x[maskh, maskw] - bg corrected = corrected - np.min(corrected) x[maskh, maskw] = corrected return x def estimate_background(x: np.ndarray) -> np.ndarray: """Estimate background using a second order polynomial surface. Estimate the background of an image using a second-order polynomial surface assuming sparse signal in the image. Essentially a massive least-squares fit of the image to the polynomial. Parameters ---------- x : np.ndarray An input image which is to be used for estimating the background. Returns ------- background_estimate : np.ndarray A second order polynomial surface representing the estimated background of the image. """ # set up arrays for params and the output surface A = np.zeros((x.shape[0] * x.shape[1], 6)) background_estimate = np.zeros((x.shape[1], x.shape[0])) u, v = np.meshgrid( np.arange(x.shape[1], dtype=np.float32), np.arange(x.shape[0], dtype=np.float32), ) A[:, 0] = 1.0 A[:, 1] = np.reshape(u, (x.shape[0] * x.shape[1],)) A[:, 2] = np.reshape(v, (x.shape[0] * x.shape[1],)) A[:, 3] = A[:, 1] * A[:, 1] A[:, 4] = A[:, 1] * A[:, 2] A[:, 5] = A[:, 2] * A[:, 2] # convert to a matrix A = np.matrix(A) # calculate the parameters k = np.linalg.inv(A.T * A) * A.T k = np.squeeze(np.array(np.dot(k, np.ravel(x)))) # calculate the surface background_estimate = ( k[0] + k[1] * u + k[2] * v + k[3] * u * u + k[4] * u * v + k[5] * v * v ) return background_estimate def estimate_mask(x: np.ndarray) -> Tuple[slice]: """Estimate the mask of a frame. Masking may occur when frame registration has been performed. Parameters ---------- x : np.ndarray An input image which is to be used for estimating the background. Returns ------- mask : tuple (2,) Slices representing the mask of the image. """ if hasattr(x, "compute"): x = x.compute() nonzero = np.nonzero(x) sh = slice(np.min(nonzero[0]), np.max(nonzero[0]) + 1, 1) sw = slice(np.min(nonzero[1]), np.max(nonzero[1]) + 1, 1) return sh, sw def parse_filename(filename: os.PathLike) -> dict: """Parse an OctopusLite filename and retreive metadata from the file. Parameters ---------- filename : PathLike The full path to a file to parse. Returns ------- metadata : dict A dictionary containing the parsed metadata. """ pth, filename = os.path.split(filename) params = re.match(OCTOPUSLITE_FILEPATTERN, filename) metadata = { "filename": filename, "channel": Channels(int(params.group("channel"))), "time": params.group("time"), "position": params.group("position"), "z": params.group("z"), # "timestamp": os.stat(filename).st_mtime, } return metadata def image_generator(files, crop: Optional[tuple] = None): """Image generator for iterative procesess For many timelapse data related procesess (such as calculating mean values and localising objects), using a generator function to iterative load single frames is quicker than computing each frame and calculating using dask. Parameters ---------- files : list A list of image files which you wish to iterate over. Can be easily generated using the DaskOctopusLiteLoader function 'files'. E.g. image_generator(DaskOctopusLiteLoader.files('channel name')) crop : tuple, optional An optional tuple which can be used to perform a centred crop on the image data. Yields ------ img : np.ndarray An image loaded from the given filename at that iteration. """ if crop is None: for filename in files: img = imread(filename) yield img else: for filename in files: img = imread(filename) img = crop_image(img, crop) yield img def crop_image(img, crop): """Crops a central window from an input image given a crop area size tuple Parameters ---------- img : np.ndarray Input image. crop : tuple An tuple which is used to perform a centred crop on the image data. """ shape = img.shape dims = img.ndim cslice = lambda d: slice( int((shape[d] - crop[d]) // 2), int((shape[d] - crop[d]) // 2 + crop[d]) ) crops = tuple([cslice(d) for d in range(dims)]) img = img[crops] return img
[ "numpy.matrix", "numpy.ravel", "numpy.zeros", "re.match", "numpy.nonzero", "numpy.min", "numpy.max", "numpy.arange", "numpy.reshape", "numpy.linalg.inv", "os.path.split", "scipy.ndimage.median_filter", "skimage.io.imread" ]
[((827, 851), 'scipy.ndimage.median_filter', 'median_filter', (['x'], {'size': '(2)'}), '(x, size=2)\n', (840, 851), False, 'from scipy.ndimage import median_filter\n'), ((2153, 2191), 'numpy.zeros', 'np.zeros', (['(x.shape[0] * x.shape[1], 6)'], {}), '((x.shape[0] * x.shape[1], 6))\n', (2161, 2191), True, 'import numpy as np\n'), ((2218, 2252), 'numpy.zeros', 'np.zeros', (['(x.shape[1], x.shape[0])'], {}), '((x.shape[1], x.shape[0]))\n', (2226, 2252), True, 'import numpy as np\n'), ((2414, 2455), 'numpy.reshape', 'np.reshape', (['u', '(x.shape[0] * x.shape[1],)'], {}), '(u, (x.shape[0] * x.shape[1],))\n', (2424, 2455), True, 'import numpy as np\n'), ((2470, 2511), 'numpy.reshape', 'np.reshape', (['v', '(x.shape[0] * x.shape[1],)'], {}), '(v, (x.shape[0] * x.shape[1],))\n', (2480, 2511), True, 'import numpy as np\n'), ((2643, 2655), 'numpy.matrix', 'np.matrix', (['A'], {}), '(A)\n', (2652, 2655), True, 'import numpy as np\n'), ((3406, 3419), 'numpy.nonzero', 'np.nonzero', (['x'], {}), '(x)\n', (3416, 3419), True, 'import numpy as np\n'), ((3912, 3935), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (3925, 3935), False, 'import os\n'), ((3949, 3992), 're.match', 're.match', (['OCTOPUSLITE_FILEPATTERN', 'filename'], {}), '(OCTOPUSLITE_FILEPATTERN, filename)\n', (3957, 3992), False, 'import re\n'), ((1408, 1425), 'numpy.min', 'np.min', (['corrected'], {}), '(corrected)\n', (1414, 1425), True, 'import numpy as np\n'), ((2286, 2325), 'numpy.arange', 'np.arange', (['x.shape[1]'], {'dtype': 'np.float32'}), '(x.shape[1], dtype=np.float32)\n', (2295, 2325), True, 'import numpy as np\n'), ((2335, 2374), 'numpy.arange', 'np.arange', (['x.shape[0]'], {'dtype': 'np.float32'}), '(x.shape[0], dtype=np.float32)\n', (2344, 2374), True, 'import numpy as np\n'), ((2696, 2718), 'numpy.linalg.inv', 'np.linalg.inv', (['(A.T * A)'], {}), '(A.T * A)\n', (2709, 2718), True, 'import numpy as np\n'), ((3435, 3453), 'numpy.min', 'np.min', (['nonzero[0]'], {}), '(nonzero[0])\n', (3441, 3453), True, 'import numpy as np\n'), ((3497, 3515), 'numpy.min', 'np.min', (['nonzero[1]'], {}), '(nonzero[1])\n', (3503, 3515), True, 'import numpy as np\n'), ((3455, 3473), 'numpy.max', 'np.max', (['nonzero[0]'], {}), '(nonzero[0])\n', (3461, 3473), True, 'import numpy as np\n'), ((3517, 3535), 'numpy.max', 'np.max', (['nonzero[1]'], {}), '(nonzero[1])\n', (3523, 3535), True, 'import numpy as np\n'), ((5218, 5234), 'skimage.io.imread', 'imread', (['filename'], {}), '(filename)\n', (5224, 5234), False, 'from skimage.io import imread\n'), ((5316, 5332), 'skimage.io.imread', 'imread', (['filename'], {}), '(filename)\n', (5322, 5332), False, 'from skimage.io import imread\n'), ((2763, 2774), 'numpy.ravel', 'np.ravel', (['x'], {}), '(x)\n', (2771, 2774), True, 'import numpy as np\n')]
""" Copyright (C) 2019 <NAME>, ETH Zurich 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. """ import numpy as np from scipy.stats import norm from functools import partial from sklearn.decomposition import PCA from drnet.models.baselines.baseline import Baseline class GPS(Baseline): def __init__(self): super(GPS, self).__init__() self.gps = None self.pca = None def install_grf(self): from rpy2.robjects.packages import importr import rpy2.robjects.packages as rpackages from rpy2.robjects.vectors import StrVector import rpy2.robjects as robjects # robjects.r.options(download_file_method='curl') # package_names = ["causaldrf"] # utils = rpackages.importr('utils') # utils.chooseCRANmirror(ind=0) # utils.chooseCRANmirror(ind=0) # # names_to_install = [x for x in package_names if not rpackages.isinstalled(x)] # if len(names_to_install) > 0: # utils.install_packages(StrVector(names_to_install)) return importr("causaldrf") def _build(self, **kwargs): from rpy2.robjects import numpy2ri, pandas2ri gps = self.install_grf() self.gps = gps numpy2ri.activate() pandas2ri.activate() self.with_exposure = kwargs["with_exposure"] return [None for _ in range(kwargs["num_treatments"])] def predict(self, x): def get_x_by_idx(idx): data = [x[0][idx], x[1][idx]] if len(x) == 1: data[0] = np.expand_dims(data[0], axis=0) if self.with_exposure: data += [x[2][idx]] return data if self.pca is not None: x[0] = self.pca.transform(x[0]) results = np.zeros((len(x[0],))) for treatment_idx in range(len(self.model)): indices = np.where(x[1] == treatment_idx)[0] this_x = get_x_by_idx(indices) y_pred = np.array(self.predict_for_model(self.model[treatment_idx], this_x)) results[indices] = y_pred return results def predict_for_model(self, old_model, x): import rpy2.robjects as robjects from rpy2.robjects import Formula, pandas2ri distribution, model = old_model r = robjects.r gps = distribution.pdf(x[-1]) data_frame = pandas2ri.py2ri( Baseline.to_data_frame(np.column_stack([x[-1], gps]), column_names=["T", "gps"]) ) result = r.predict(model, data_frame) return np.array(result) def fit_generator_for_model(self, model, train_generator, train_steps, val_generator, val_steps, num_epochs): all_outputs = [] for _ in range(train_steps): generator_output = next(train_generator) x, y = generator_output[0], generator_output[1] all_outputs.append((x, y)) x, y = zip(*all_outputs) x = map(partial(np.concatenate, axis=0), zip(*x)) y = np.concatenate(y, axis=0) if x[0].shape[-1] > 200: self.pca = PCA(16, svd_solver="randomized") x[0] = self.pca.fit_transform(x[0]) treatment_xy = self.split_by_treatment(x, y) for key in treatment_xy.keys(): x, y = treatment_xy[key] self.model[int(key)] = self.build_drf_model(x, y) def build_drf_model(self, x_old, y): from rpy2.robjects.vectors import StrVector, FactorVector, FloatVector, IntVector from rpy2.robjects import Formula, pandas2ri x, ts = x_old[:, :-1], x_old[:, -1] tmp = np.concatenate([x, np.reshape(ts, (-1, 1)), np.reshape(y, (-1, 1))], axis=-1) data_frame = pandas2ri.py2ri( Baseline.to_data_frame(tmp, column_names=np.arange(0, tmp.shape[-1] - 2).tolist() + ["T", "Y"]) ) result = self.gps.hi_est(Y="Y", treat="T", treat_formula=Formula('T ~ ' + '+'.join(data_frame.names[:-2])), outcome_formula=Formula('Y ~ T + I(T^2) + gps + T * gps'), data=data_frame, grid_val=FloatVector([float(tt) for tt in np.linspace(0, 1, 256)]), treat_mod="Normal", link_function="log") # link_function is not used with treat_mod = "Normal". treatment_model, model = result[1], result[2] fitted_values = treatment_model.rx2('fitted.values') distribution = norm(np.mean(fitted_values), np.std(fitted_values)) return distribution, model def preprocess(self, x): if self.with_exposure: return np.concatenate([x[0], np.reshape(x[2], (-1, 1))], axis=-1) else: return x[0] def postprocess(self, y): return y[:, -1]
[ "functools.partial", "rpy2.robjects.packages.importr", "rpy2.robjects.numpy2ri.activate", "numpy.std", "rpy2.robjects.pandas2ri.activate", "numpy.expand_dims", "numpy.mean", "numpy.array", "sklearn.decomposition.PCA", "numpy.where", "numpy.column_stack", "numpy.reshape", "rpy2.robjects.Formula", "numpy.linspace", "numpy.arange", "numpy.concatenate" ]
[((2039, 2059), 'rpy2.robjects.packages.importr', 'importr', (['"""causaldrf"""'], {}), "('causaldrf')\n", (2046, 2059), False, 'from rpy2.robjects.packages import importr\n'), ((2212, 2231), 'rpy2.robjects.numpy2ri.activate', 'numpy2ri.activate', ([], {}), '()\n', (2229, 2231), False, 'from rpy2.robjects import numpy2ri, pandas2ri\n'), ((2240, 2260), 'rpy2.robjects.pandas2ri.activate', 'pandas2ri.activate', ([], {}), '()\n', (2258, 2260), False, 'from rpy2.robjects import Formula, pandas2ri\n'), ((3530, 3546), 'numpy.array', 'np.array', (['result'], {}), '(result)\n', (3538, 3546), True, 'import numpy as np\n'), ((3979, 4004), 'numpy.concatenate', 'np.concatenate', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (3993, 4004), True, 'import numpy as np\n'), ((3925, 3956), 'functools.partial', 'partial', (['np.concatenate'], {'axis': '(0)'}), '(np.concatenate, axis=0)\n', (3932, 3956), False, 'from functools import partial\n'), ((4062, 4094), 'sklearn.decomposition.PCA', 'PCA', (['(16)'], {'svd_solver': '"""randomized"""'}), "(16, svd_solver='randomized')\n", (4065, 4094), False, 'from sklearn.decomposition import PCA\n'), ((5548, 5570), 'numpy.mean', 'np.mean', (['fitted_values'], {}), '(fitted_values)\n', (5555, 5570), True, 'import numpy as np\n'), ((5572, 5593), 'numpy.std', 'np.std', (['fitted_values'], {}), '(fitted_values)\n', (5578, 5593), True, 'import numpy as np\n'), ((2532, 2563), 'numpy.expand_dims', 'np.expand_dims', (['data[0]'], {'axis': '(0)'}), '(data[0], axis=0)\n', (2546, 2563), True, 'import numpy as np\n'), ((2855, 2886), 'numpy.where', 'np.where', (['(x[1] == treatment_idx)'], {}), '(x[1] == treatment_idx)\n', (2863, 2886), True, 'import numpy as np\n'), ((3401, 3430), 'numpy.column_stack', 'np.column_stack', (['[x[-1], gps]'], {}), '([x[-1], gps])\n', (3416, 3430), True, 'import numpy as np\n'), ((4600, 4623), 'numpy.reshape', 'np.reshape', (['ts', '(-1, 1)'], {}), '(ts, (-1, 1))\n', (4610, 4623), True, 'import numpy as np\n'), ((4625, 4647), 'numpy.reshape', 'np.reshape', (['y', '(-1, 1)'], {}), '(y, (-1, 1))\n', (4635, 4647), True, 'import numpy as np\n'), ((5047, 5088), 'rpy2.robjects.Formula', 'Formula', (['"""Y ~ T + I(T^2) + gps + T * gps"""'], {}), "('Y ~ T + I(T^2) + gps + T * gps')\n", (5054, 5088), False, 'from rpy2.robjects import Formula, pandas2ri\n'), ((5732, 5757), 'numpy.reshape', 'np.reshape', (['x[2]', '(-1, 1)'], {}), '(x[2], (-1, 1))\n', (5742, 5757), True, 'import numpy as np\n'), ((5215, 5237), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(256)'], {}), '(0, 1, 256)\n', (5226, 5237), True, 'import numpy as np\n'), ((4750, 4781), 'numpy.arange', 'np.arange', (['(0)', '(tmp.shape[-1] - 2)'], {}), '(0, tmp.shape[-1] - 2)\n', (4759, 4781), True, 'import numpy as np\n')]
import unittest from ..fsf import * import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal class TestFSF(unittest.TestCase): def setUp(self) -> None: self.A = np.array([[0, 1], [-2, -3]]) self.b = np.array([[0], [1]]) self.poles = np.array([-3, -4]) def test_place(self): # si k = place(self.A, self.b, self.poles) assert_array_equal(k, [10, 4]) # mi A = np.array([[0, 1, 0], [-1, -2, 0], [0, 0, -4]]) B = np.array([[0, -1], [1, 0], [0, 1]]) poles = np.array([-1, -3, -4]) K = place(A, B, poles) assert_array_almost_equal(np.roots(np.poly(A - B @ K)), [-4, -3, -1]) # bad input self.assertRaises(ValueError, place, self.A, self.b.T, self.poles) self.assertRaises(ValueError, place, self.A, np.array([[0], [0]]), self.poles)
[ "numpy.poly", "numpy.testing.assert_array_equal", "numpy.array" ]
[((210, 238), 'numpy.array', 'np.array', (['[[0, 1], [-2, -3]]'], {}), '([[0, 1], [-2, -3]])\n', (218, 238), True, 'import numpy as np\n'), ((256, 276), 'numpy.array', 'np.array', (['[[0], [1]]'], {}), '([[0], [1]])\n', (264, 276), True, 'import numpy as np\n'), ((298, 316), 'numpy.array', 'np.array', (['[-3, -4]'], {}), '([-3, -4])\n', (306, 316), True, 'import numpy as np\n'), ((411, 441), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['k', '[10, 4]'], {}), '(k, [10, 4])\n', (429, 441), False, 'from numpy.testing import assert_array_equal, assert_array_almost_equal\n'), ((468, 514), 'numpy.array', 'np.array', (['[[0, 1, 0], [-1, -2, 0], [0, 0, -4]]'], {}), '([[0, 1, 0], [-1, -2, 0], [0, 0, -4]])\n', (476, 514), True, 'import numpy as np\n'), ((527, 562), 'numpy.array', 'np.array', (['[[0, -1], [1, 0], [0, 1]]'], {}), '([[0, -1], [1, 0], [0, 1]])\n', (535, 562), True, 'import numpy as np\n'), ((579, 601), 'numpy.array', 'np.array', (['[-1, -3, -4]'], {}), '([-1, -3, -4])\n', (587, 601), True, 'import numpy as np\n'), ((860, 880), 'numpy.array', 'np.array', (['[[0], [0]]'], {}), '([[0], [0]])\n', (868, 880), True, 'import numpy as np\n'), ((676, 694), 'numpy.poly', 'np.poly', (['(A - B @ K)'], {}), '(A - B @ K)\n', (683, 694), True, 'import numpy as np\n')]
import sys import time import os import torch import random import sklearn # Ignore sklearn related warnings import warnings warnings.filterwarnings("ignore", category=RuntimeWarning) import numpy as np import torch.nn as nn import torchvision.utils as vutils import torch.optim as optim import finetune_utils as ftu import model_utils as mu import model_3d as m3d import sim_utils as su import mask_utils as masku import wandb os.environ['WANDB_DIR'] = os.environ['BASE_DIR'] sys.path.append('../backbone') from model_3d import DpcRnn, SupervisedDpcRnn from tqdm import tqdm from copy import deepcopy from collections import defaultdict sys.path.append('../utils') from utils import AverageMeter, AccuracyTable, ConfusionMeter, save_checkpoint, \ denorm, calc_topk_accuracy, calc_per_class_multilabel_counts def get_modality_list(modalities): modes = [] for m in mu.ModeList: if m in modalities: modes.append(m) return modes def get_modality_restore_ckpts(args): ckpts = {} for m in args.modes: # Replacing - with _ because of the way parser works ckpt = getattr(args, m.replace('-', '_') + "_restore_ckpt") ckpts[m] = ckpt if ckpt is not None: print("Mode: {} is being restored from: {}".format(m, ckpt)) return ckpts class ModalitySyncer(nn.Module): def get_feature_extractor_based_on_mode(self, mode_params): if mode_params.mode.split('-')[0] in [mu.ImgMode, mu.AudioMode]: return m3d.ImageFetCombiner(mode_params.img_fet_dim, mode_params.img_fet_segments) else: assert False, "Invalid mode provided: {}".format(mode_params) def __init__(self, args): super(ModalitySyncer, self).__init__() self.losses = args["losses"] self.mode0_dim = args["mode_0_params"].final_dim self.mode1_dim = args["mode_1_params"].final_dim self.mode0_fet_extractor = self.get_feature_extractor_based_on_mode(args["mode_0_params"]) self.mode1_fet_extractor = self.get_feature_extractor_based_on_mode(args["mode_1_params"]) self.instance_mask = args["instance_mask"] self.common_dim = min(self.mode0_dim, self.mode1_dim) // 2 # input is B x dim0, B x dim1 self.mode1_to_common = nn.Sequential() self.mode0_to_common = nn.Sequential() self.mode_losses = [mu.DenseCosSimLoss] self.simHandler = nn.ModuleDict( { mu.AlignLoss: su.AlignSimHandler(self.instance_mask), mu.CosSimLoss: su.CosSimHandler(), mu.CorrLoss: su.CorrSimHandler(), mu.DenseCorrLoss: su.DenseCorrSimHandler(self.instance_mask), mu.DenseCosSimLoss: su.DenseCosSimHandler(self.instance_mask), } ) # Perform initialization for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def get_total_loss(self, mode0, mode1): loss = torch.tensor(0.0).to(mode0.device) stats = {} for lossKey in self.mode_losses: lossVal0, stat = self.simHandler[lossKey](mode0, mode1) lossVal1, _ = self.simHandler[lossKey](mode1, mode0) lossVal = (lossVal0 + lossVal1) * 0.5 loss += lossVal stats[lossKey] = stat return loss, stats def forward(self, input0, input1): assert len(input0.shape) == 5, "{}".format(input0.shape) # inputs are B, N, D, S, S y0 = self.mode0_fet_extractor(input0) y1 = self.mode1_fet_extractor(input1) # outputs are B * N, dim B, N, _ = y1.shape y0_in_space_common = self.mode0_to_common(y0.view(B * N, -1)).view(B, N, -1) y1_in_space_common = self.mode1_to_common(y1.view(B * N, -1)).view(B, N, -1) return self.get_total_loss(y0_in_space_common, y1_in_space_common) class SupervisedModalitySyncer(ModalitySyncer): def __init__(self, args): super(SupervisedModalitySyncer, self).__init__(args) # input is B x dim0, B x dim1 self.mode1_to_common = m3d.NonLinearProjection(args["mode_0_params"].img_fet_dim, self.common_dim) self.mode0_to_common = m3d.NonLinearProjection(args["mode_1_params"].img_fet_dim, self.common_dim) self.mode_losses = [mu.AlignLoss] def forward(self, input0, input1): # input is B, N, D or B, 1, D assert len(input0.shape) == 3, "{}".format(input0.shape) B, _, D = input0.shape # outputs are B, dim y0_in_space_common = self.mode0_to_common(input0.view(B, -1)).view(B, 1, -1) y1_in_space_common = self.mode1_to_common(input1.view(B, -1)).view(B, 1, -1) loss, stats = self.get_total_loss(y0_in_space_common, y1_in_space_common) return loss, stats, None class AttentionModalitySyncer(SupervisedModalitySyncer): def __init__(self, args): super(AttentionModalitySyncer, self).__init__(args) # input is B x N x dim0 x s x s, B x 1 x dim1 self.mode0_attention_fn = m3d.AttentionProjection( args["mode_0_params"].img_fet_dim, (args["mode_0_params"].img_fet_segments, args["mode_0_params"].img_fet_segments)) self.mode1_attention_fn = m3d.AttentionProjection( args["mode_1_params"].img_fet_dim, (args["mode_1_params"].img_fet_segments, args["mode_1_params"].img_fet_segments)) self.mode_losses = [mu.AlignLoss] def forward(self, input0, input1): # input0, input1 is B, N, D/D', S, S assert len(input0.shape) == 5, "{}".format(input0.shape) assert len(input1.shape) == 5, "{}".format(input1.shape) B, N, D, S, S = input0.shape y0, attn0 = self.mode0_attention_fn.applyAttention(input0) y1, attn1 = self.mode1_attention_fn.applyAttention(input1) # outputs are B, dim y0_in_space_common = self.mode0_to_common(y0.view(B, -1)).view(B, 1, -1) y1_in_space_common = self.mode1_to_common(y1.view(B, -1)).view(B, 1, -1) loss, stats = self.get_total_loss(y0_in_space_common, y1_in_space_common) return loss, stats, {'0': attn0, '1': attn1} class MultiModalModelTrainer(nn.Module): def addImgGrid(self, data): ''' Plots image frames in different subsections ''' # shape of data[mode] batch, num_seq, seq_len, IC, IH, IW for mode in self.modes: IC = data[mode].shape[3] if IC == 3: images = data[mode].detach().cpu()[:, 0, 0, ...] else: # Plot the summation instead images = data[mode].detach().cpu()[:, 0, 0, ...].mean(dim=1, keepdim=True) # Shape is batch, IC, IH, IW grid = vutils.make_grid(images, nrow=int(np.sqrt(images.shape[0]))) self.writer_train.add_image('images/frames/{}'.format(mode), grid, 0) if self.use_wandb: wandb.log({'images/frames/{}'.format(mode): [wandb.Image(grid)]}, step=self.iteration) def addAttnGrid(self, attn): ''' Plots attention frames in different modalities; can be directly compared to added imgs ''' # shape of data[mode], batch, 1, 1, S0, S1 for key in attn.keys(): images = attn[key].detach().cpu()[:, 0, 0, ...].unsqueeze(1) # Shape is batch, 1, S, S grid = vutils.make_grid(images, nrow=int(np.sqrt(images.shape[0]))) self.writer_train.add_image('attn/map/{}'.format(key), grid, 0) if self.use_wandb: wandb.log({'attn/map/{}'.format(key): [wandb.Image(grid)]}, step=self.iteration) def get_modality_feature_extractor(self, final_feature_size, last_size, mode): if mode.split('-')[0] in [mu.ImgMode, mu.AudioMode]: return m3d.ImageFetCombiner(final_feature_size, last_size) else: assert False, "Invalid mode provided: {}".format(mode) def __init__(self, args): super(MultiModalModelTrainer, self).__init__() self.args = args self.modes = args["modalities"] self.model_type = args["model"] self.models = nn.ModuleDict(args["models"]) self.losses = args["losses"] self.num_classes = args["num_classes"] self.data_sources = args["data_sources"] self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.attention = args['attention'] # Gradient accumulation step interval self.grad_step_interval = 4 self.vis_log_freq = args["vis_log_freq"] # Model log writers self.img_path = args["img_path"] self.model_path = args["model_path"] self.model_name = self.model_path.split('/')[-2] self.writer_train, self.writer_val = mu.get_writers(self.img_path) # wandb self.use_wandb = args["wandb_project_name"] != "" if self.use_wandb: wandb.init(project=args["wandb_project_name"]) wandb.run.name = self.model_name wandb.run.save() wandb.watch(list(self.models.values())) print("Model path is:", self.model_path, self.img_path) # multilabel training for supervision self.multilabel_supervision = args["multilabel_supervision"] self.shouldFinetune = args["ft_freq"] > 0 self.finetuneSkip = 1 if not self.multilabel_supervision else 5 transform = mu.get_transforms(args) if not args['test']: self.train_loader = mu.get_dataset_loaders(args, transform, 'train') self.val_loader = mu.get_dataset_loaders(args, transform, 'val') if args['test']: test_transform = mu.get_test_transforms(args) self.test_loader = mu.get_dataset_loaders(args, test_transform, 'test', test_split=args['test_split']) self.num_classes = args["num_classes"] self.l2_norm = True self.temp = args["temp"] if self.l2_norm else 1.0 self.common_dim = 128 self.cpc_projections = nn.ModuleDict({m: nn.Sequential() for m in self.modes}) self.denormalize = denorm() self.val_criterion_base = nn.CrossEntropyLoss() self.val_criterion = lambda x, y: self.val_criterion_base(x, y.float().argmax(dim=1)) self.criteria = { mu.CPCLoss: self.val_criterion, mu.CooperativeLoss: nn.L1Loss(), mu.SupervisionLoss: nn.CrossEntropyLoss() if not self.multilabel_supervision else mu.BinaryFocalLossWithLogits(), mu.HierarchicalLoss: mu.BinaryFocalLossWithLogits(), mu.WeighedHierarchicalLoss: {m: m3d.WeighedLoss(num_losses=2, device=self.device) for m in self.modes}, } self.CooperativeLossLabel = mu.CooperativeLoss print('Modes being used:', self.modes) self.compiled_features = {m: self.get_modality_feature_extractor( self.models[m].final_feature_size, self.models[m].last_size, m) for m in self.modes} self.interModeDotHandler = su.InterModeDotHandler(last_size=None) self.B0 = self.B1 = self.args["batch_size"] self.standard_grid_mask = { m: masku.process_mask( masku.get_standard_grid_mask( self.B0, self.B1, self.args["pred_step"], self.models[m].last_size, device=self.device ) ) for m in self.modes } self.standard_instance_mask = masku.process_mask( masku.get_standard_instance_mask(self.B0, self.B1, self.args["pred_step"], device=self.device) ) self.standard_video_level_mask = masku.process_mask( torch.eye(self.B0, device=self.device).reshape(self.B0, 1, self.B0, 1) ) self.modeSyncers = nn.ModuleDict() self.mode_pairs = [(m0, m1) for m0 in self.modes for m1 in self.modes if m0 < m1] self.sync_wt = self.args["msync_wt"] for (m0, m1) in self.mode_pairs: num_seq = self.args["num_seq"] mode_align_args = { "losses": self.losses, "mode_0_params": self.get_mode_params(m0), "mode_1_params": self.get_mode_params(m1), "dim_layer_1": 64, "instance_mask": None, } # Have to explicitly send these to the GPU as they're present in a dict modality_syncer = ModalitySyncer if self.model_type == mu.ModelSupervised: mode_align_args['instance_mask'] = self.standard_video_level_mask if self.attention: modality_syncer = AttentionModalitySyncer else: modality_syncer = SupervisedModalitySyncer else: instance_mask_m0_m1 = masku.process_mask( masku.get_standard_instance_mask(self.B0, self.B1, num_seq, self.device) ) mode_align_args['instance_mask'] = instance_mask_m0_m1 self.modeSyncers[self.get_tuple_name(m0, m1)] = modality_syncer(mode_align_args).to(self.device) print("[NOTE] Losses used: ", self.losses) self.cosSimHandler = su.CosSimHandler() self.dot_wt = args["dot_wt"] # Use a smaller learning rate if the backbone is already trained degradeBackboneLR = 1.0 if args["tune_bb"] > 0: degradeBackboneLR = args["tune_bb"] backboneLr = { 'params': [p for k in self.models.keys() for p in self.models[k].parameters()], 'lr': args["lr"] * degradeBackboneLR } miscLr = { 'params': [p for model in list(self.modeSyncers.values()) for p in model.parameters()], 'lr': args["lr"] } self.optimizer = optim.Adam( [miscLr, backboneLr], lr=args["lr"], weight_decay=args["wd"] ) patience = 10 self.lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau( self.optimizer, verbose=True, patience=patience, min_lr=1e-5 ) self.model_finetuner = ftu.QuickSupervisedModelTrainer(self.num_classes, self.modes) self.iteration = 0 self.accuracyKList = [1, 3] self.init_knowledge_distillation() self.init_hierarchical() def init_hierarchical(self): self.hierarchical = self.args['hierarchical'] def init_knowledge_distillation(self): self.kd_weight = 0.1 self.temperature = 2.5 self.distill = self.args['distill'] if self.distill: self.student_modes = self.args['student_modes'] else: self.student_modes = self.modes for mode in self.modes: if mode not in self.student_modes: self.models[mode].eval() # Freeze the models if they are not students for param in self.models[mode].parameters(): param.requires_grad = False @staticmethod def get_tuple_name(m0, m1): return "{}|{}".format(m0[0] + m0[-1], m1[0] + m1[-1]) def get_mode_params(self, mode): if mode.split('-')[0] in [mu.ImgMode, mu.AudioMode]: return mu.ModeParams( mode, self.models[mode].param['feature_size'], self.models[mode].last_size, self.models[mode].param['feature_size'] ) else: assert False, "Incorrect mode: {}".format(mode) def get_feature_pair_score(self, pred_features, gt_features): """ (pred/gt)features: [B, N, D, S, S] Special case for a few instances would be with S=1 Returns 6D pair score tensor """ B1, N1, D1, S1, S1 = pred_features.shape B2, N2, D2, S2, S2 = gt_features.shape assert (D1, S1) == (D2, S2), \ "Mismatch between pred and gt features: {}, {}".format(pred_features.shape, gt_features.shape) # dot product D dimension in pred-GT pair, get a 6d tensor. First 3 dims are from pred, last 3 dims are from GT. preds = pred_features.permute(0, 1, 3, 4, 2).contiguous().view(B1 * N1 * S1 * S1, D1) / self.temp gts = gt_features.permute(0, 1, 3, 4, 2).contiguous().view(B2 * N2 * S2 * S2, D2).transpose(0, 1) / self.temp # Get the corresponding scores of each region in the matrix with each other region i.e. # total last_size ** 4 combinations. Note that we have pred_step ** 2 such pairs as well score = torch.matmul(preds, gts).view(B1, N1, S1*S1, B2, N2, S2*S2) return score def log_visuals(self, input_seq, mode): if input_seq.size(0) > 5: input_seq = input_seq[:5] ic = 3 if mode.split('-')[0] in [mu.AudioMode]: denormed_img = vutils.make_grid(input_seq) else: if mode.split('-')[0] not in [mu.ImgMode, mu.AudioMode]: assert input_seq.shape[2] in [1, 2, 3, 17], "Invalid shape: {}".format(input_seq.shape) input_seq = torch.abs(input_seq) input_seq = input_seq.sum(dim=2, keepdim=True) input_seq = input_seq / 0.25 input_seq[input_seq > 1] = 1.0 input_seq[input_seq != input_seq] = 0.0 ic = 1 img_dim = input_seq.shape[-1] assert img_dim in [64, 128, 224], "imgs_dim: {}, input_seq: {}".format(img_dim, input_seq.shape) grid_img = vutils.make_grid( input_seq.transpose(2, 3).contiguous().view(-1, ic, img_dim, img_dim), nrow=self.args["num_seq"] * self.args["seq_len"] ) if mode.startswith("imgs"): denormed_img = self.denormalize(grid_img) else: denormed_img = grid_img self.writer_train.add_image('input_seq/{}'.format(mode), denormed_img, self.iteration) if self.use_wandb: wandb.log({'input_seq/{}'.format(mode): [wandb.Image(denormed_img)]}, step=self.iteration) def log_metrics(self, losses_dict, stats, writer, prefix): for loss in self.losses: for mode in losses_dict[loss].keys(): val = losses_dict[loss][mode].val if hasattr(losses_dict[loss][mode], 'val') else losses_dict[loss][mode] writer.add_scalar( prefix + '/losses/' + loss + '/' + str(mode), val, self.iteration ) if self.use_wandb: wandb.log({prefix + '/losses/' + loss + '/' + str(mode): val}, step=self.iteration) for loss in stats.keys(): for mode in stats[loss].keys(): for stat in stats[loss][mode].keys(): val = stats[loss][mode][stat].val if hasattr(stats[loss][mode][stat], 'val') else stats[loss][mode][stat] writer.add_scalar( prefix + '/stats/' + loss + '/' + str(mode) + '/' + str(stat), val, self.iteration ) if self.use_wandb: wandb.log({prefix + '/stats/' + loss + '/' + str(mode) + '/' + str(stat): val}, step=self.iteration) def perform_self_supervised_forward_passes(self, data, feature_dict): NS = self.args["pred_step"] pred_features, gt_all_features, agg_features, probabilities = {}, {}, {}, {} flat_scores = {} if self.shouldFinetune: feature_dict['Y'].append(data['labels'][::self.finetuneSkip]) for mode in self.modes: if not mode in data.keys(): continue B = data[mode].shape[0] input_seq = data[mode].to(self.device) # assert input_seq.shape[0] == self.args["batch_size"] SQ = self.models[mode].last_size ** 2 pred_features[mode], gt_features, gt_all_features[mode], probs, X = \ self.models[mode](input_seq, ret_rep=True) gt_all_features[mode] = self.cpc_projections[mode](gt_all_features[mode]) pred_features[mode] = self.cpc_projections[mode](pred_features[mode]) probabilities[mode] = probs # score is a 6d tensor: [B, P, SQ, B', N', SQ] score_ = self.get_feature_pair_score(pred_features[mode], gt_features) flat_scores[mode] = score_.view(B * NS * SQ, -1) if self.shouldFinetune: feature_dict['X'][mode].append(X.reshape(X.shape[0], -1)[::self.finetuneSkip].detach().cpu()) del input_seq return pred_features, gt_all_features, agg_features, flat_scores, probabilities, feature_dict def update_supervised_loss_stats(self, logit, supervised_target, stats, loss_dict, mode, eval=False): B = supervised_target.shape[0] if self.multilabel_supervision: if eval: # Intermediate counters for per-class TP, TN, FP, FN tp, tn, fp, fn, top1_single, top3_single, all_single = calc_per_class_multilabel_counts(torch.sigmoid(logit), supervised_target) counter = dict(tp=tp, tn=tn, fp=fp, fn=fn, top1_single=top1_single, top3_single=top3_single, all_single=all_single) if not 'multilabel_counts' in stats[mu.SupervisionLoss][mode].keys(): stats[mu.SupervisionLoss][mode]['multilabel_counts'] = counter else: stats[mu.SupervisionLoss][mode]['multilabel_counts']['tp'] += counter['tp'] stats[mu.SupervisionLoss][mode]['multilabel_counts']['tn'] += counter['tn'] stats[mu.SupervisionLoss][mode]['multilabel_counts']['fp'] += counter['fp'] stats[mu.SupervisionLoss][mode]['multilabel_counts']['fn'] += counter['fn'] stats[mu.SupervisionLoss][mode]['multilabel_counts']['top1_single'] += counter['top1_single'] stats[mu.SupervisionLoss][mode]['multilabel_counts']['top3_single'] += counter['top3_single'] stats[mu.SupervisionLoss][mode]['multilabel_counts']['all_single'] += counter['all_single'] else: # Compute and log top-k accuracy topKs = calc_topk_accuracy(logit, supervised_target, self.accuracyKList) for i in range(len(self.accuracyKList)): stats[mu.SupervisionLoss][mode]["acc" + str(self.accuracyKList[i])].update(topKs[i].item(), B) # Compute supervision loss if not self.multilabel_supervision: supervised_target = supervised_target.view(-1) else: supervised_target = supervised_target.float() loss_dict[mu.SupervisionLoss][mode] = \ self.criteria[mu.SupervisionLoss](logit, supervised_target) def update_supervised_hierarchical_loss_stats(self, logits, targets, stats, loss_dict, mode, eval=False): B = targets['video'].shape[0] # Compute and log top-k accuracy for video level topKs = calc_topk_accuracy(logits['main'], targets['video'], self.accuracyKList) for i in range(len(self.accuracyKList)): stats[mu.SupervisionLoss][mode]["acc" + str(self.accuracyKList[i])].update(topKs[i].item(), B) # Compute supervision hierarchical loss loss_dict[mu.SupervisionLoss][mode] = \ self.criteria[mu.SupervisionLoss](logits['main'], targets['video'].view(-1)) loss_dict[mu.HierarchicalLoss][mode] = \ self.criteria[mu.HierarchicalLoss](logits['side'], targets['atomic'].float()) * 10.0 if mu.WeighedHierarchicalLoss in self.losses: loss_dict[mu.WeighedHierarchicalLoss][mode] = self.criteria[mu.WeighedHierarchicalLoss][mode]( [loss_dict[mu.SupervisionLoss][mode], loss_dict[mu.HierarchicalLoss][mode]] ) def update_self_supervised_metrics(self, gt_all_features, flat_scores, probabilities, stats, data, eval=False): NS, N = self.args["pred_step"], self.args["num_seq"] loss_dict = {k: {} for k in self.losses} for mode in flat_scores.keys(): B = data[mode].shape[0] SQ = self.models[mode].last_size ** 2 target_flattened = self.standard_grid_mask[mode].view(self.B0 * NS * SQ, self.B1 * NS * SQ)[:B * NS * SQ, :B * NS * SQ] # CPC loss if mu.CPCLoss in self.losses: score_flat = flat_scores[mode] target = target_flattened target_lbl = target.float().argmax(dim=1) # Compute and log performance metrics topKs = calc_topk_accuracy(score_flat, target_lbl, self.accuracyKList) for i in range(len(self.accuracyKList)): stats[mu.CPCLoss][mode]["acc" + str(self.accuracyKList[i])].update(topKs[i].item(), B) # Compute CPC loss for independent model training loss_dict[mu.CPCLoss][mode] = self.criteria[mu.CPCLoss](score_flat, target) # Supervision loss if mu.SupervisionLoss in self.losses: probability = probabilities[mode] supervised_target = data['labels'].to(self.device) self.update_supervised_loss_stats(probability, supervised_target, stats, loss_dict, mode, eval) if mu.CooperativeLoss in self.losses: for (m0, m1) in self.mode_pairs: if (m0 not in flat_scores.keys()) or (m1 not in flat_scores.keys()): continue tupName = self.get_tuple_name(m0, m1) # Cdot related losses comp_gt_all0 = self.compiled_features[m0](gt_all_features[m0]).unsqueeze(3).unsqueeze(3) comp_gt_all1 = self.compiled_features[m1](gt_all_features[m1]).unsqueeze(3).unsqueeze(3) cdot0 = self.interModeDotHandler.get_cluster_dots(comp_gt_all0) cdot1 = self.interModeDotHandler.get_cluster_dots(comp_gt_all1) B, NS, B2, NS = cdot0.shape assert cdot0.shape == cdot1.shape == (B, NS, B2, NS), \ "Invalid shapes: {}, {}, {}".format(cdot0.shape, cdot1.shape, (B, NS, B2, NS)) cos_sim_dot_loss = self.criteria[self.CooperativeLossLabel](cdot0, cdot1) loss_dict[self.CooperativeLossLabel][tupName] = self.dot_wt * cos_sim_dot_loss # Modality sync loss sync_loss, mode_stats = self.modeSyncers[tupName](gt_all_features[m0], gt_all_features[m1]) # stats: dict modeLoss -> specificStat for modeLoss in mode_stats.keys(): for stat in mode_stats[modeLoss].keys(): stats[modeLoss][tupName][stat].update(mode_stats[modeLoss][stat].item(), B) loss_dict[mu.ModeSim][tupName] = self.sync_wt * sync_loss return loss_dict, stats @staticmethod def categorical_cross_entropy(logits, b): la = torch.nn.functional.log_softmax(logits, dim=1) return -(b * la).sum(dim=1).mean() def kd_loss_criterion(self, results, labels): """ Compute the knowledge-distillation (KD) loss given outputs, labels. :param results: Expect the dictionary returned by forward() :param labels: GT label for the batch """ w = self.kd_weight t = self.temperature gt_loss = self.criteria[mu.SupervisionLoss](results['outs'], labels) kd_loss = 0.0 for v in results["teacher_outs"]: kd_loss += self.categorical_cross_entropy( results["outs"] / t, torch.nn.functional.softmax(v / t, dim=1) ) kd_loss /= len(results["teacher_outs"]) # Weigh kd_loss with t^2 to preserve scale of gradients final_loss = (kd_loss * w * t * t) + (gt_loss * (1 - w)) return { "loss": final_loss, "gt_loss": gt_loss, "kd_loss": kd_loss } def update_distillation_loss_stats(self, logits, supervised_target, loss_dict): for mode in self.student_modes: results = { 'outs': logits[mode]['main'], 'teacher_outs': [logits[m]['main'] for m in self.modes if m != mode] } losses = self.kd_loss_criterion(results, supervised_target.view(-1)) loss_dict[mu.DistillLoss][mode] = losses['kd_loss'] def get_supervised_forward_pass_results(self, data): results = {'feature': {}, 'logits': {}, 'grid': {}, 'attn': {}} for mode in self.modes: input_seq = data[mode].to(self.device) feature, main_logit, side_logit, grid, attn = self.models[mode](input_seq) results['feature'][mode], results['grid'][mode], results['attn'][mode] = \ feature, grid, attn results['logits'][mode] = {'main': main_logit, 'side': side_logit} del input_seq return results def perform_supervised_forward_passes(self, data, feature_dict): if self.shouldFinetune: key = 'video_labels' if 'video_labels' in data else 'labels' feature_dict['Y'].append(data[key][::self.finetuneSkip]) results = self.get_supervised_forward_pass_results(data) features, attentions, logits = results['grid'], results['attn'], results['logits'] for mode in self.modes: if self.shouldFinetune: feature = results['feature'][mode] feature_dict['X'][mode].append( feature.reshape(feature.shape[0], -1)[::self.finetuneSkip].detach().cpu()) # features: B x D; clip level feature return features, logits, attentions, feature_dict def update_supervised_metrics(self, features, logits, stats, attentions, data, eval=False): B, NS, N = self.args["batch_size"], self.args["pred_step"], self.args["num_seq"] loss_dict = defaultdict(lambda: {}) for mode in self.modes: # Hierarchical loss - normal or auto-weighed if self.hierarchical: logit = logits[mode] targets = { 'video': data['video_labels'].to(self.device), 'atomic': data['atomic_labels'].to(self.device), } self.update_supervised_hierarchical_loss_stats(logit, targets, stats, loss_dict, mode, eval) elif mu.SupervisionLoss in self.losses: # Supervision loss only if hierarchical loss is not present logit = logits[mode]['main'] supervised_target = data['labels'].to(self.device) self.update_supervised_loss_stats(logit, supervised_target, stats, loss_dict, mode, eval) if mu.DistillLoss in self.losses: supervised_target = data['labels'].to(self.device) self.update_distillation_loss_stats(logits, supervised_target, loss_dict) if mu.AlignLoss in self.losses: for (m0, m1) in self.mode_pairs: # In the supervised setting, we receive B x N x D and B x D' features (block, clip level respectively) # Currently we receive only B x D' x s x s i.e. clip level features tupName = self.get_tuple_name(m0, m1) # Modality sync loss sync_loss, mode_stats, attns = self.modeSyncers[tupName](features[m0], features[m1]) if attns: attentions['{}_in_{}'.format(m0, tupName)] = attns['0'] attentions['{}_in_{}'.format(m1, tupName)] = attns['1'] # stats: dict modeLoss -> specificStat for modeLoss in mode_stats.keys(): for stat in mode_stats[modeLoss].keys(): stats[modeLoss][tupName][stat].update(mode_stats[modeLoss][stat].item(), B) loss_dict[mu.AlignLoss][tupName] = self.sync_wt * sync_loss return loss_dict, stats def pretty_print_stats(self, stats): grouped_stats = {} for k, v in stats.items(): a, b = k.split('/')[:2] middle = (a, b) if middle not in grouped_stats: grouped_stats[middle] = [] grouped_stats[middle].append((k, v)) for v in grouped_stats.values(): print(sorted(v)) def perform_self_supervised_pass(self, data, feature_dict, stats, eval): _, gt_all_features, agg_features, flat_scores, probabilities, feature_dict = \ self.perform_self_supervised_forward_passes(data, feature_dict) loss_dict, stats = \ self.update_self_supervised_metrics(gt_all_features, flat_scores, probabilities, stats, data, eval) return loss_dict, stats, feature_dict, {} def perform_supervised_pass(self, data, feature_dict, stats, eval): features, logits, attentions, feature_dict = self.perform_supervised_forward_passes(data, feature_dict) loss_dict, stats = self.update_supervised_metrics(features, logits, stats, attentions, data, eval) etc = {'attn': attentions} if self.hierarchical: etc['atomic_labels'] = data['atomic_labels'].cpu().detach() for m, v in logits.items(): etc['atomic_preds_{}'.format(m)] = v['side'].cpu().detach() video_labels = 'video_labels' if self.hierarchical else 'labels' if eval: etc['video_labels'] = data[video_labels].cpu().detach() for m, v in logits.items(): etc['video_preds_{}'.format(m)] = v['main'].cpu().detach() return loss_dict, stats, feature_dict, etc def perform_pass(self, data, feature_dict, stats, eval=False): if self.model_type == mu.ModelSSL: return self.perform_self_supervised_pass(data, feature_dict, stats, eval) elif self.model_type == mu.ModelSupervised: return self.perform_supervised_pass(data, feature_dict, stats, eval) def aggregate_finetune_set(self, feature_dict): if self.shouldFinetune: feature_dict['X'] = {k: torch.cat(v) for k, v in feature_dict['X'].items()} feature_dict['Y'] = torch.cat(feature_dict['Y']).reshape(-1).detach() return feature_dict def compute_atomic_action_stats(self, etcs, stats): def torch_to_numpy(y_pred, y_true): y_pred = torch.sigmoid(y_pred) return y_pred.cpu().detach().numpy(), y_true.cpu().detach().long().numpy() def map_score_avg(aps): return aps[aps == aps].mean() def map_score_weighted(aps, y_true): aps[aps != aps] = 0 unique, support = np.unique(np.concatenate([np.nonzero(t)[0] for t in y_true]), return_counts=True) counts = np.zeros(448) counts[unique] = support print('Num missing classes:', (counts/counts.sum() < 1e-8).sum()) return np.average(aps, weights=counts) def map_score_all(y_pred, y_true): y_pred, y_true = torch_to_numpy(y_pred, y_true) aps = sklearn.metrics.average_precision_score(y_true, y_pred, average=None) return map_score_avg(aps), map_score_weighted(aps, y_true) for m in self.modes: avg, wgt = map_score_all(etcs['atomic_preds_{}'.format(m)], etcs['atomic_labels']) stats['map/avg/{}'.format(m[0] + m[-1])] = avg stats['map/weighted/{}'.format(m[0] + m[-1])] = wgt def train_epoch(self, epoch): self.train() print("Model path is:", self.model_path) for mode in self.models.keys(): if mode in self.student_modes: self.models[mode].train() for mode in self.modeSyncers.keys(): self.modeSyncers[mode].train() losses_dict, stats = mu.init_loggers(self.losses) B = self.args["batch_size"] train = {'X': {m: [] for m in self.modes}, 'Y': []} tq = tqdm(self.train_loader, desc="Train: Ep {}".format(epoch), position=0) self.optimizer.zero_grad() etcs, overall_stats = {}, {} for idx, data in enumerate(tq): loss_dict, stats, train, etc = self.perform_pass(data, train, stats) loss = torch.tensor(0.0).to(self.device) # Only include losses which are part of self.losses i.e. not super, hierarchical if we're using weighed loss for l in loss_dict.keys(): for v in loss_dict[l].keys(): losses_dict[l][v].update(loss_dict[l][v].item(), B) if l in self.losses: loss += loss_dict[l][v] loss.backward() if idx % self.grad_step_interval: self.optimizer.step() self.optimizer.zero_grad() overall_stats = mu.get_stats_dict(losses_dict, stats) tq_stats = mu.shorten_stats(overall_stats) tq.set_postfix(tq_stats) del loss # Perform logging if self.iteration % self.vis_log_freq == 0: # Log attention if 'attn' in etc: self.addAttnGrid(etc['attn']) # Log images self.addImgGrid(data) for mode in self.modes: if mode in data.keys(): # Log visuals of the complete input seq self.log_visuals(data[mode], mode) # Don't need attn anymore if 'attn' in etc: del etc['attn'] for k, v in etc.items(): if k not in etcs: etcs[k] = [] etcs[k].append(v) if idx % self.args["print_freq"] == 0: self.log_metrics(losses_dict, stats, self.writer_train, prefix='local') self.iteration += 1 for k in etcs.keys(): etcs[k] = torch.cat(etcs[k]) if self.hierarchical: self.compute_atomic_action_stats(etcs, overall_stats) print("Overall train stats:") self.pretty_print_stats(overall_stats) # log to wandb if self.use_wandb: wandb.log({'train/' + k: v for k, v in overall_stats.items()}, step=self.iteration) train = self.aggregate_finetune_set(train) return losses_dict, stats, train def eval_mode(self): self.eval() for mode in self.models.keys(): if mode in self.student_modes: self.models[mode].eval() self.models[mode].eval_mode() for mode in self.modeSyncers.keys(): self.modeSyncers[mode].eval() def validate_epoch(self, epoch): self.eval_mode() losses_dict, stats = mu.init_loggers(self.losses) overall_loss = AverageMeter() B = self.args["batch_size"] tq_stats = {} val = {'X': {m: [] for m in self.modes}, 'Y': []} etcs, overall_stats = {}, {} with torch.no_grad(): tq = tqdm(self.val_loader, desc="Val: Ep {}".format(epoch), position=0) for idx, data in enumerate(tq): loss_dict, stats, val, etc = self.perform_pass(data, val, stats, eval=True) # Perform logging - Handle val separately # if self.iteration % self.vis_log_freq == 0: # # Log attention # if 'attn' in etc: # self.addAttnGrid(etc['attn']) # # Log images # self.addImgGrid(data) # for mode in self.modes: # self.log_visuals(data[mode], mode) loss = torch.tensor(0.0).to(self.device) for l in loss_dict.keys(): for v in loss_dict[l].keys(): losses_dict[l][v].update(loss_dict[l][v].item(), B) if l in self.losses: loss += loss_dict[l][v] overall_loss.update(loss.item(), B) # Don't need attn anymore if 'attn' in etc: del etc['attn'] for k, v in etc.items(): if k not in etcs: etcs[k] = [] etcs[k].append(v) overall_stats = mu.get_stats_dict(losses_dict, stats) tq_stats = mu.shorten_stats(overall_stats) tq.set_postfix(tq_stats) for k in etcs.keys(): etcs[k] = torch.cat(etcs[k]) if self.hierarchical: self.compute_atomic_action_stats(etcs, overall_stats) # compute validation metrics mu.compute_val_metrics(overall_stats) for loss in stats.keys(): for mode in stats[loss].keys(): mu.compute_val_metrics(stats[loss][mode], prefix='{}_{}'.format(loss, mode)) # log to wandb if self.use_wandb: wandb.log({'val/' + k: v for k, v in overall_stats.items()}, step=self.iteration) print("Overall val stats:") self.pretty_print_stats(overall_stats) val = self.aggregate_finetune_set(val) return overall_loss, losses_dict, stats, val def test(self): self.eval_mode() losses_dict, stats = mu.init_loggers(self.losses) overall_loss = AverageMeter() B = self.args["batch_size"] tq_stats = {} val = {'X': {m: [] for m in self.modes}, 'Y': []} etcs, overall_stats = {}, {} with torch.no_grad(): tq = tqdm(self.test_loader, desc="Test:", position=0) for idx, data in enumerate(tq): for k in data.keys(): data[k] = data[k].squeeze(0) loss_dict, stats, val, etc = self.perform_pass(data, val, stats, eval=True) loss = torch.tensor(0.0).to(self.device) for l in loss_dict.keys(): for v in loss_dict[l].keys(): losses_dict[l][v].update(loss_dict[l][v].item(), B) if l in self.losses: loss += loss_dict[l][v] overall_loss.update(loss.item(), B) # Don't need attn anymore if 'attn' in etc: del etc['attn'] for k, v in etc.items(): if k not in etcs: etcs[k] = [] etcs[k].append(v) overall_stats = mu.get_stats_dict(losses_dict, stats) tq_stats = mu.shorten_stats(overall_stats) tq.set_postfix(tq_stats) for k in etcs.keys(): etcs[k] = torch.cat(etcs[k]) if self.hierarchical: self.compute_atomic_action_stats(etcs, overall_stats) # compute validation metrics mu.compute_val_metrics(overall_stats) for loss in stats.keys(): for mode in stats[loss].keys(): mu.compute_val_metrics(stats[loss][mode], prefix='{}_{}'.format(loss, mode)) # log to wandb if self.use_wandb: wandb.log({'val/' + k: v for k, v in overall_stats.items()}, step=self.iteration) print("Overall val stats:") self.pretty_print_stats(overall_stats) val = self.aggregate_finetune_set(val) return overall_loss, losses_dict, stats, val def train_module(self): best_acc = {m: 0.0 for m in self.modes} for epoch in range(self.args["start_epoch"], self.args["epochs"]): train_losses, train_stats, trainD = self.train_epoch(epoch) eval_epoch = epoch % self.args["eval_freq"] == 0 if eval_epoch: ovr_loss, val_losses, val_stats, valD = self.validate_epoch(epoch) self.lr_scheduler.step(ovr_loss.avg) # Log fine-tune performance # FIXME (haofeng): This below doesn't work with multi label supervision if self.shouldFinetune and not self.multilabel_supervision: if (epoch % self.args["ft_freq"] == 0) and eval_epoch: self.model_finetuner.evaluate_classification(trainD, valD) if not self.args["debug"]: train_clustering_dict = self.model_finetuner.evaluate_clustering(trainD, tag='train') # val_clustering_dict = self.model_finetuner.evaluate_clustering(valD, tag='val') if self.use_wandb: for n, d in zip(['train'], [train_clustering_dict]): # , val_clustering_dict]) for k0, d0 in d.items(): wandb.log({'cluster/{}_{}_{}'.format(n, k0, k1): v for k1, v in d0.items()}, step=self.iteration) # save curve self.log_metrics(train_losses, train_stats, self.writer_train, prefix='global') if eval_epoch: self.log_metrics(val_losses, val_stats, self.writer_val, prefix='global') # save check_point for each mode individually for modality in self.modes: loss = mu.CPCLoss if loss not in self.losses: loss = mu.SupervisionLoss is_best = val_stats[loss][modality][1].avg > best_acc[modality] best_acc[modality] = max(val_stats[loss][modality][1].avg, best_acc[modality]) state = { 'epoch': epoch + 1, 'mode': modality, 'net': self.args["net"], 'state_dict': self.models[modality].state_dict(), 'best_acc': best_acc[modality], 'optimizer': self.optimizer.state_dict(), 'iteration': self.iteration } for (m0, m1) in self.mode_pairs: if modality not in [m0, m1]: tupName = self.get_tuple_name(m0, m1) state['mode_syncer_{}'.format(tupName)] = self.modeSyncers[tupName].state_dict() save_checkpoint( state=state, mode=modality, is_best=is_best, filename=os.path.join( self.model_path, 'mode_' + modality + '_epoch%s.pth.tar' % str(epoch + 1) ), gap=3, keep_all=False ) print('Training from ep %d to ep %d finished' % (self.args["start_epoch"], self.args["epochs"])) total_stats = { 'train': { 'losses': train_losses, 'stats': train_stats, }, } if eval_epoch: total_stats['val'] = { 'losses': val_losses, 'stats': val_stats, } return total_stats def get_backbone_for_modality(args, mode): tmp_args = deepcopy(args) tmp_args.mode = mode tmp_args_dict = deepcopy(vars(tmp_args)) model = None print('Current model being used is: {}'.format(args.model)) if mode == mu.AudioMode: model = m3d.AudioVGGEncoder(tmp_args_dict) else: if args.model == mu.ModelSSL: model = DpcRnn(tmp_args_dict) elif args.model == mu.ModelSupervised: model = SupervisedDpcRnn(tmp_args_dict) else: assert False, "Invalid model type: {}".format(args.model) if args.restore_ckpts[mode] is not None: print(mode, args.restore_ckpts[mode]) # First try to load it hoping it's stored without the dataParallel print('Model saved in dataParallel form') model = m3d.get_parallel_model(model) model = mu.load_model(model, args.restore_ckpts[mode]) else: model = m3d.get_parallel_model(model) # Freeze the required layers if args.train_what == 'last': for name, param in model.resnet.named_parameters(): param.requires_grad = False if args.test: for param in model.parameters(): param.requires_grad = False print('\n=========Check Grad: {}============'.format(mode)) param_list = ['-'.join(name.split('.')[:2]) for name, param in model.named_parameters() if not param.requires_grad] print(set(param_list)) print('=================================\n') return model.to(args.device) def run_multi_modal_training(args): torch.manual_seed(0) np.random.seed(0) # Update the batch size according to the number of GPUs if torch.cuda.is_available(): args.batch_size *= torch.cuda.device_count() args.num_workers *= int(np.sqrt(2 * torch.cuda.device_count())) args.num_classes = mu.get_num_classes(args.dataset) args.device = torch.device('cuda') if torch.cuda.is_available() else torch.device("cpu") # FIXME: support multiple views from the same modality args.modes = get_modality_list(args.modalities) args.student_modes = get_modality_list(args.students) args.restore_ckpts = get_modality_restore_ckpts(args) args.old_lr = None args.img_path, args.model_path = mu.set_multi_modal_path(args) models = {} for mode in args.modes: models[mode] = get_backbone_for_modality(args, mode) # Restore from an earlier checkpoint args_dict = deepcopy(vars(args)) args_dict["models"] = models args_dict["data_sources"] = '_'.join(args_dict["modes"]) + "_labels" model_trainer = MultiModalModelTrainer(args_dict) model_trainer = model_trainer.to(args.device) stats = None if args.test: stats = model_trainer.test() else: stats = model_trainer.train_module() return model_trainer, stats if __name__ == '__main__': parser = mu.get_multi_modal_model_train_args() args = parser.parse_args() run_multi_modal_training(args)
[ "wandb.run.save", "model_utils.compute_val_metrics", "numpy.random.seed", "torch.eye", "utils.calc_topk_accuracy", "model_3d.DpcRnn", "model_3d.ImageFetCombiner", "torch.cat", "sim_utils.CorrSimHandler", "torch.cuda.device_count", "collections.defaultdict", "sim_utils.AlignSimHandler", "torch.nn.ModuleDict", "torch.nn.init.constant_", "model_3d.AudioVGGEncoder", "model_utils.get_num_classes", "sim_utils.InterModeDotHandler", "torch.device", "torch.no_grad", "sys.path.append", "sim_utils.DenseCorrSimHandler", "torch.nn.init.kaiming_normal_", "utils.AverageMeter", "model_utils.get_transforms", "model_utils.set_multi_modal_path", "torch.optim.lr_scheduler.ReduceLROnPlateau", "mask_utils.get_standard_instance_mask", "sim_utils.DenseCosSimHandler", "model_3d.NonLinearProjection", "torch.nn.functional.log_softmax", "sklearn.metrics.average_precision_score", "model_utils.get_multi_modal_model_train_args", "torch.matmul", "model_utils.shorten_stats", "model_utils.load_model", "copy.deepcopy", "tqdm.tqdm", "numpy.average", "mask_utils.get_standard_grid_mask", "model_utils.get_writers", "torch.manual_seed", "model_3d.get_parallel_model", "model_utils.init_loggers", "utils.denorm", "model_3d.WeighedLoss", "torch.optim.Adam", "torch.cuda.is_available", "finetune_utils.QuickSupervisedModelTrainer", "model_utils.get_test_transforms", "warnings.filterwarnings", "torch.nn.Sequential", "model_utils.get_dataset_loaders", "torch.nn.L1Loss", "model_utils.get_stats_dict", "torch.nn.CrossEntropyLoss", "numpy.zeros", "torch.nn.functional.softmax", "torchvision.utils.make_grid", "model_3d.SupervisedDpcRnn", "torch.sigmoid", "sim_utils.CosSimHandler", "wandb.init", "wandb.Image", "model_utils.BinaryFocalLossWithLogits", "numpy.nonzero", "model_3d.AttentionProjection", "torch.tensor", "torch.abs", "model_utils.ModeParams", "numpy.sqrt" ]
[((126, 184), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning'}), "('ignore', category=RuntimeWarning)\n", (149, 184), False, 'import warnings\n'), ((480, 510), 'sys.path.append', 'sys.path.append', (['"""../backbone"""'], {}), "('../backbone')\n", (495, 510), False, 'import sys\n'), ((642, 669), 'sys.path.append', 'sys.path.append', (['"""../utils"""'], {}), "('../utils')\n", (657, 669), False, 'import sys\n'), ((47676, 47690), 'copy.deepcopy', 'deepcopy', (['args'], {}), '(args)\n', (47684, 47690), False, 'from copy import deepcopy\n'), ((49220, 49240), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (49237, 49240), False, 'import torch\n'), ((49245, 49262), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (49259, 49262), True, 'import numpy as np\n'), ((49331, 49356), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (49354, 49356), False, 'import torch\n'), ((49507, 49539), 'model_utils.get_num_classes', 'mu.get_num_classes', (['args.dataset'], {}), '(args.dataset)\n', (49525, 49539), True, 'import model_utils as mu\n'), ((49922, 49951), 'model_utils.set_multi_modal_path', 'mu.set_multi_modal_path', (['args'], {}), '(args)\n', (49945, 49951), True, 'import model_utils as mu\n'), ((50553, 50590), 'model_utils.get_multi_modal_model_train_args', 'mu.get_multi_modal_model_train_args', ([], {}), '()\n', (50588, 50590), True, 'import model_utils as mu\n'), ((2308, 2323), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (2321, 2323), True, 'import torch.nn as nn\n'), ((2355, 2370), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (2368, 2370), True, 'import torch.nn as nn\n'), ((4359, 4434), 'model_3d.NonLinearProjection', 'm3d.NonLinearProjection', (["args['mode_0_params'].img_fet_dim", 'self.common_dim'], {}), "(args['mode_0_params'].img_fet_dim, self.common_dim)\n", (4382, 4434), True, 'import model_3d as m3d\n'), ((4466, 4541), 'model_3d.NonLinearProjection', 'm3d.NonLinearProjection', (["args['mode_1_params'].img_fet_dim", 'self.common_dim'], {}), "(args['mode_1_params'].img_fet_dim, self.common_dim)\n", (4489, 4541), True, 'import model_3d as m3d\n'), ((5315, 5460), 'model_3d.AttentionProjection', 'm3d.AttentionProjection', (["args['mode_0_params'].img_fet_dim", "(args['mode_0_params'].img_fet_segments, args['mode_0_params'].img_fet_segments\n )"], {}), "(args['mode_0_params'].img_fet_dim, (args[\n 'mode_0_params'].img_fet_segments, args['mode_0_params'].img_fet_segments))\n", (5338, 5460), True, 'import model_3d as m3d\n'), ((5515, 5660), 'model_3d.AttentionProjection', 'm3d.AttentionProjection', (["args['mode_1_params'].img_fet_dim", "(args['mode_1_params'].img_fet_segments, args['mode_1_params'].img_fet_segments\n )"], {}), "(args['mode_1_params'].img_fet_dim, (args[\n 'mode_1_params'].img_fet_segments, args['mode_1_params'].img_fet_segments))\n", (5538, 5660), True, 'import model_3d as m3d\n'), ((8450, 8479), 'torch.nn.ModuleDict', 'nn.ModuleDict', (["args['models']"], {}), "(args['models'])\n", (8463, 8479), True, 'import torch.nn as nn\n'), ((9088, 9117), 'model_utils.get_writers', 'mu.get_writers', (['self.img_path'], {}), '(self.img_path)\n', (9102, 9117), True, 'import model_utils as mu\n'), ((9730, 9753), 'model_utils.get_transforms', 'mu.get_transforms', (['args'], {}), '(args)\n', (9747, 9753), True, 'import model_utils as mu\n'), ((10420, 10428), 'utils.denorm', 'denorm', ([], {}), '()\n', (10426, 10428), False, 'from utils import AverageMeter, AccuracyTable, ConfusionMeter, save_checkpoint, denorm, calc_topk_accuracy, calc_per_class_multilabel_counts\n'), ((10464, 10485), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (10483, 10485), True, 'import torch.nn as nn\n'), ((11335, 11373), 'sim_utils.InterModeDotHandler', 'su.InterModeDotHandler', ([], {'last_size': 'None'}), '(last_size=None)\n', (11357, 11373), True, 'import sim_utils as su\n'), ((12151, 12166), 'torch.nn.ModuleDict', 'nn.ModuleDict', ([], {}), '()\n', (12164, 12166), True, 'import torch.nn as nn\n'), ((13562, 13580), 'sim_utils.CosSimHandler', 'su.CosSimHandler', ([], {}), '()\n', (13578, 13580), True, 'import sim_utils as su\n'), ((14179, 14251), 'torch.optim.Adam', 'optim.Adam', (['[miscLr, backboneLr]'], {'lr': "args['lr']", 'weight_decay': "args['wd']"}), "([miscLr, backboneLr], lr=args['lr'], weight_decay=args['wd'])\n", (14189, 14251), True, 'import torch.optim as optim\n'), ((14349, 14453), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'optim.lr_scheduler.ReduceLROnPlateau', (['self.optimizer'], {'verbose': '(True)', 'patience': 'patience', 'min_lr': '(1e-05)'}), '(self.optimizer, verbose=True, patience\n =patience, min_lr=1e-05)\n', (14385, 14453), True, 'import torch.optim as optim\n'), ((14502, 14563), 'finetune_utils.QuickSupervisedModelTrainer', 'ftu.QuickSupervisedModelTrainer', (['self.num_classes', 'self.modes'], {}), '(self.num_classes, self.modes)\n', (14533, 14563), True, 'import finetune_utils as ftu\n'), ((23482, 23554), 'utils.calc_topk_accuracy', 'calc_topk_accuracy', (["logits['main']", "targets['video']", 'self.accuracyKList'], {}), "(logits['main'], targets['video'], self.accuracyKList)\n", (23500, 23554), False, 'from utils import AverageMeter, AccuracyTable, ConfusionMeter, save_checkpoint, denorm, calc_topk_accuracy, calc_per_class_multilabel_counts\n'), ((27464, 27510), 'torch.nn.functional.log_softmax', 'torch.nn.functional.log_softmax', (['logits'], {'dim': '(1)'}), '(logits, dim=1)\n', (27495, 27510), False, 'import torch\n'), ((30454, 30478), 'collections.defaultdict', 'defaultdict', (['(lambda : {})'], {}), '(lambda : {})\n', (30465, 30478), False, 'from collections import defaultdict\n'), ((36357, 36385), 'model_utils.init_loggers', 'mu.init_loggers', (['self.losses'], {}), '(self.losses)\n', (36372, 36385), True, 'import model_utils as mu\n'), ((39303, 39331), 'model_utils.init_loggers', 'mu.init_loggers', (['self.losses'], {}), '(self.losses)\n', (39318, 39331), True, 'import model_utils as mu\n'), ((39355, 39369), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (39367, 39369), False, 'from utils import AverageMeter, AccuracyTable, ConfusionMeter, save_checkpoint, denorm, calc_topk_accuracy, calc_per_class_multilabel_counts\n'), ((41249, 41286), 'model_utils.compute_val_metrics', 'mu.compute_val_metrics', (['overall_stats'], {}), '(overall_stats)\n', (41271, 41286), True, 'import model_utils as mu\n'), ((41866, 41894), 'model_utils.init_loggers', 'mu.init_loggers', (['self.losses'], {}), '(self.losses)\n', (41881, 41894), True, 'import model_utils as mu\n'), ((41918, 41932), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (41930, 41932), False, 'from utils import AverageMeter, AccuracyTable, ConfusionMeter, save_checkpoint, denorm, calc_topk_accuracy, calc_per_class_multilabel_counts\n'), ((43440, 43477), 'model_utils.compute_val_metrics', 'mu.compute_val_metrics', (['overall_stats'], {}), '(overall_stats)\n', (43462, 43477), True, 'import model_utils as mu\n'), ((47888, 47922), 'model_3d.AudioVGGEncoder', 'm3d.AudioVGGEncoder', (['tmp_args_dict'], {}), '(tmp_args_dict)\n', (47907, 47922), True, 'import model_3d as m3d\n'), ((48429, 48458), 'model_3d.get_parallel_model', 'm3d.get_parallel_model', (['model'], {}), '(model)\n', (48451, 48458), True, 'import model_3d as m3d\n'), ((48475, 48521), 'model_utils.load_model', 'mu.load_model', (['model', 'args.restore_ckpts[mode]'], {}), '(model, args.restore_ckpts[mode])\n', (48488, 48521), True, 'import model_utils as mu\n'), ((48548, 48577), 'model_3d.get_parallel_model', 'm3d.get_parallel_model', (['model'], {}), '(model)\n', (48570, 48577), True, 'import model_3d as m3d\n'), ((49385, 49410), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (49408, 49410), False, 'import torch\n'), ((49582, 49607), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (49605, 49607), False, 'import torch\n'), ((49558, 49578), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (49570, 49578), False, 'import torch\n'), ((49613, 49632), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (49625, 49632), False, 'import torch\n'), ((1526, 1601), 'model_3d.ImageFetCombiner', 'm3d.ImageFetCombiner', (['mode_params.img_fet_dim', 'mode_params.img_fet_segments'], {}), '(mode_params.img_fet_dim, mode_params.img_fet_segments)\n', (1546, 1601), True, 'import model_3d as m3d\n'), ((8102, 8153), 'model_3d.ImageFetCombiner', 'm3d.ImageFetCombiner', (['final_feature_size', 'last_size'], {}), '(final_feature_size, last_size)\n', (8122, 8153), True, 'import model_3d as m3d\n'), ((9232, 9278), 'wandb.init', 'wandb.init', ([], {'project': "args['wandb_project_name']"}), "(project=args['wandb_project_name'])\n", (9242, 9278), False, 'import wandb\n'), ((9336, 9352), 'wandb.run.save', 'wandb.run.save', ([], {}), '()\n', (9350, 9352), False, 'import wandb\n'), ((9815, 9863), 'model_utils.get_dataset_loaders', 'mu.get_dataset_loaders', (['args', 'transform', '"""train"""'], {}), "(args, transform, 'train')\n", (9837, 9863), True, 'import model_utils as mu\n'), ((9894, 9940), 'model_utils.get_dataset_loaders', 'mu.get_dataset_loaders', (['args', 'transform', '"""val"""'], {}), "(args, transform, 'val')\n", (9916, 9940), True, 'import model_utils as mu\n'), ((9996, 10024), 'model_utils.get_test_transforms', 'mu.get_test_transforms', (['args'], {}), '(args)\n', (10018, 10024), True, 'import model_utils as mu\n'), ((10056, 10144), 'model_utils.get_dataset_loaders', 'mu.get_dataset_loaders', (['args', 'test_transform', '"""test"""'], {'test_split': "args['test_split']"}), "(args, test_transform, 'test', test_split=args[\n 'test_split'])\n", (10078, 10144), True, 'import model_utils as mu\n'), ((10683, 10694), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (10692, 10694), True, 'import torch.nn as nn\n'), ((10867, 10897), 'model_utils.BinaryFocalLossWithLogits', 'mu.BinaryFocalLossWithLogits', ([], {}), '()\n', (10895, 10897), True, 'import model_utils as mu\n'), ((11864, 11962), 'mask_utils.get_standard_instance_mask', 'masku.get_standard_instance_mask', (['self.B0', 'self.B1', "self.args['pred_step']"], {'device': 'self.device'}), "(self.B0, self.B1, self.args['pred_step'],\n device=self.device)\n", (11896, 11962), True, 'import mask_utils as masku\n'), ((15606, 15741), 'model_utils.ModeParams', 'mu.ModeParams', (['mode', "self.models[mode].param['feature_size']", 'self.models[mode].last_size', "self.models[mode].param['feature_size']"], {}), "(mode, self.models[mode].param['feature_size'], self.models[\n mode].last_size, self.models[mode].param['feature_size'])\n", (15619, 15741), True, 'import model_utils as mu\n'), ((17220, 17247), 'torchvision.utils.make_grid', 'vutils.make_grid', (['input_seq'], {}), '(input_seq)\n', (17236, 17247), True, 'import torchvision.utils as vutils\n'), ((22698, 22762), 'utils.calc_topk_accuracy', 'calc_topk_accuracy', (['logit', 'supervised_target', 'self.accuracyKList'], {}), '(logit, supervised_target, self.accuracyKList)\n', (22716, 22762), False, 'from utils import AverageMeter, AccuracyTable, ConfusionMeter, save_checkpoint, denorm, calc_topk_accuracy, calc_per_class_multilabel_counts\n'), ((34921, 34942), 'torch.sigmoid', 'torch.sigmoid', (['y_pred'], {}), '(y_pred)\n', (34934, 34942), False, 'import torch\n'), ((35316, 35329), 'numpy.zeros', 'np.zeros', (['(448)'], {}), '(448)\n', (35324, 35329), True, 'import numpy as np\n'), ((35464, 35495), 'numpy.average', 'np.average', (['aps'], {'weights': 'counts'}), '(aps, weights=counts)\n', (35474, 35495), True, 'import numpy as np\n'), ((35618, 35687), 'sklearn.metrics.average_precision_score', 'sklearn.metrics.average_precision_score', (['y_true', 'y_pred'], {'average': 'None'}), '(y_true, y_pred, average=None)\n', (35657, 35687), False, 'import sklearn\n'), ((37370, 37407), 'model_utils.get_stats_dict', 'mu.get_stats_dict', (['losses_dict', 'stats'], {}), '(losses_dict, stats)\n', (37387, 37407), True, 'import model_utils as mu\n'), ((37431, 37462), 'model_utils.shorten_stats', 'mu.shorten_stats', (['overall_stats'], {}), '(overall_stats)\n', (37447, 37462), True, 'import model_utils as mu\n'), ((38465, 38483), 'torch.cat', 'torch.cat', (['etcs[k]'], {}), '(etcs[k])\n', (38474, 38483), False, 'import torch\n'), ((39539, 39554), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (39552, 39554), False, 'import torch\n'), ((41087, 41105), 'torch.cat', 'torch.cat', (['etcs[k]'], {}), '(etcs[k])\n', (41096, 41105), False, 'import torch\n'), ((42102, 42117), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (42115, 42117), False, 'import torch\n'), ((42136, 42184), 'tqdm.tqdm', 'tqdm', (['self.test_loader'], {'desc': '"""Test:"""', 'position': '(0)'}), "(self.test_loader, desc='Test:', position=0)\n", (42140, 42184), False, 'from tqdm import tqdm\n'), ((43278, 43296), 'torch.cat', 'torch.cat', (['etcs[k]'], {}), '(etcs[k])\n', (43287, 43296), False, 'import torch\n'), ((47991, 48012), 'model_3d.DpcRnn', 'DpcRnn', (['tmp_args_dict'], {}), '(tmp_args_dict)\n', (47997, 48012), False, 'from model_3d import DpcRnn, SupervisedDpcRnn\n'), ((2506, 2544), 'sim_utils.AlignSimHandler', 'su.AlignSimHandler', (['self.instance_mask'], {}), '(self.instance_mask)\n', (2524, 2544), True, 'import sim_utils as su\n'), ((2577, 2595), 'sim_utils.CosSimHandler', 'su.CosSimHandler', ([], {}), '()\n', (2593, 2595), True, 'import sim_utils as su\n'), ((2626, 2645), 'sim_utils.CorrSimHandler', 'su.CorrSimHandler', ([], {}), '()\n', (2643, 2645), True, 'import sim_utils as su\n'), ((2681, 2723), 'sim_utils.DenseCorrSimHandler', 'su.DenseCorrSimHandler', (['self.instance_mask'], {}), '(self.instance_mask)\n', (2703, 2723), True, 'import sim_utils as su\n'), ((2761, 2802), 'sim_utils.DenseCosSimHandler', 'su.DenseCosSimHandler', (['self.instance_mask'], {}), '(self.instance_mask)\n', (2782, 2802), True, 'import sim_utils as su\n'), ((2952, 3022), 'torch.nn.init.kaiming_normal_', 'nn.init.kaiming_normal_', (['m.weight'], {'mode': '"""fan_out"""', 'nonlinearity': '"""relu"""'}), "(m.weight, mode='fan_out', nonlinearity='relu')\n", (2975, 3022), True, 'import torch.nn as nn\n'), ((3239, 3256), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (3251, 3256), False, 'import torch\n'), ((8658, 8683), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (8681, 8683), False, 'import torch\n'), ((10354, 10369), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (10367, 10369), True, 'import torch.nn as nn\n'), ((10728, 10749), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (10747, 10749), True, 'import torch.nn as nn\n'), ((10802, 10832), 'model_utils.BinaryFocalLossWithLogits', 'mu.BinaryFocalLossWithLogits', ([], {}), '()\n', (10830, 10832), True, 'import model_utils as mu\n'), ((10943, 10992), 'model_3d.WeighedLoss', 'm3d.WeighedLoss', ([], {'num_losses': '(2)', 'device': 'self.device'}), '(num_losses=2, device=self.device)\n', (10958, 10992), True, 'import model_3d as m3d\n'), ((11515, 11636), 'mask_utils.get_standard_grid_mask', 'masku.get_standard_grid_mask', (['self.B0', 'self.B1', "self.args['pred_step']", 'self.models[m].last_size'], {'device': 'self.device'}), "(self.B0, self.B1, self.args['pred_step'], self\n .models[m].last_size, device=self.device)\n", (11543, 11636), True, 'import mask_utils as masku\n'), ((16929, 16953), 'torch.matmul', 'torch.matmul', (['preds', 'gts'], {}), '(preds, gts)\n', (16941, 16953), False, 'import torch\n'), ((17463, 17483), 'torch.abs', 'torch.abs', (['input_seq'], {}), '(input_seq)\n', (17472, 17483), False, 'import torch\n'), ((25094, 25156), 'utils.calc_topk_accuracy', 'calc_topk_accuracy', (['score_flat', 'target_lbl', 'self.accuracyKList'], {}), '(score_flat, target_lbl, self.accuracyKList)\n', (25112, 25156), False, 'from utils import AverageMeter, AccuracyTable, ConfusionMeter, save_checkpoint, denorm, calc_topk_accuracy, calc_per_class_multilabel_counts\n'), ((28128, 28169), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['(v / t)'], {'dim': '(1)'}), '(v / t, dim=1)\n', (28155, 28169), False, 'import torch\n'), ((34636, 34648), 'torch.cat', 'torch.cat', (['v'], {}), '(v)\n', (34645, 34648), False, 'import torch\n'), ((40896, 40933), 'model_utils.get_stats_dict', 'mu.get_stats_dict', (['losses_dict', 'stats'], {}), '(losses_dict, stats)\n', (40913, 40933), True, 'import model_utils as mu\n'), ((40961, 40992), 'model_utils.shorten_stats', 'mu.shorten_stats', (['overall_stats'], {}), '(overall_stats)\n', (40977, 40992), True, 'import model_utils as mu\n'), ((43087, 43124), 'model_utils.get_stats_dict', 'mu.get_stats_dict', (['losses_dict', 'stats'], {}), '(losses_dict, stats)\n', (43104, 43124), True, 'import model_utils as mu\n'), ((43152, 43183), 'model_utils.shorten_stats', 'mu.shorten_stats', (['overall_stats'], {}), '(overall_stats)\n', (43168, 43183), True, 'import model_utils as mu\n'), ((48080, 48111), 'model_3d.SupervisedDpcRnn', 'SupervisedDpcRnn', (['tmp_args_dict'], {}), '(tmp_args_dict)\n', (48096, 48111), False, 'from model_3d import DpcRnn, SupervisedDpcRnn\n'), ((3103, 3133), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.weight', '(1)'], {}), '(m.weight, 1)\n', (3120, 3133), True, 'import torch.nn as nn\n'), ((3150, 3178), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.bias', '(0)'], {}), '(m.bias, 0)\n', (3167, 3178), True, 'import torch.nn as nn\n'), ((12042, 12080), 'torch.eye', 'torch.eye', (['self.B0'], {'device': 'self.device'}), '(self.B0, device=self.device)\n', (12051, 12080), False, 'import torch\n'), ((13209, 13281), 'mask_utils.get_standard_instance_mask', 'masku.get_standard_instance_mask', (['self.B0', 'self.B1', 'num_seq', 'self.device'], {}), '(self.B0, self.B1, num_seq, self.device)\n', (13241, 13281), True, 'import mask_utils as masku\n'), ((21531, 21551), 'torch.sigmoid', 'torch.sigmoid', (['logit'], {}), '(logit)\n', (21544, 21551), False, 'import torch\n'), ((36783, 36800), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (36795, 36800), False, 'import torch\n'), ((49455, 49480), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (49478, 49480), False, 'import torch\n'), ((7064, 7088), 'numpy.sqrt', 'np.sqrt', (['images.shape[0]'], {}), '(images.shape[0])\n', (7071, 7088), True, 'import numpy as np\n'), ((7707, 7731), 'numpy.sqrt', 'np.sqrt', (['images.shape[0]'], {}), '(images.shape[0])\n', (7714, 7731), True, 'import numpy as np\n'), ((18410, 18435), 'wandb.Image', 'wandb.Image', (['denormed_img'], {}), '(denormed_img)\n', (18421, 18435), False, 'import wandb\n'), ((40242, 40259), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (40254, 40259), False, 'import torch\n'), ((42433, 42450), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (42445, 42450), False, 'import torch\n'), ((7265, 7282), 'wandb.Image', 'wandb.Image', (['grid'], {}), '(grid)\n', (7276, 7282), False, 'import wandb\n'), ((7896, 7913), 'wandb.Image', 'wandb.Image', (['grid'], {}), '(grid)\n', (7907, 7913), False, 'import wandb\n'), ((34720, 34748), 'torch.cat', 'torch.cat', (["feature_dict['Y']"], {}), "(feature_dict['Y'])\n", (34729, 34748), False, 'import torch\n'), ((35239, 35252), 'numpy.nonzero', 'np.nonzero', (['t'], {}), '(t)\n', (35249, 35252), True, 'import numpy as np\n')]
# <NAME>/Feb 2022 import numpy as np from numpy import linalg as LA import matplotlib import matplotlib.dates import datetime from alive_progress import alive_bar from floodsystem.datafetcher import fetch_measure_levels from floodsystem.station import MonitoringStation from floodsystem.flood import stations_level_over_threshold from floodsystem.station import inconsistent_typical_range_stations def polyfit(dates,levels,p): #LC Task 2F x = matplotlib.dates.date2num(dates) #converts into days since the year 0001 d0 = x[0] #shift of graph x = x - d0 y = levels try: p_coeff = np.polyfit(x,y,p) poly = np.poly1d(p_coeff) #converts to the right form for numpy to use return poly, d0 #coefficients of polynomial of order p except(LA): return np.poly1d(0), d0 #returns the polynomial expression and shift def risk_definition(risk): #define the boundaries for risks boundaries = (0, 0.8, 1.5, 2) #these can be changed based on results if risk == None: return "unknown" if risk < boundaries[1]: return "low" if risk < boundaries[2]: return "moderate" if risk < boundaries[3]: return "high" else: return "severe" def issue_warnings(stations, p=4, dt=1): stations_by_risk = [] risk_of_towns = {} first_deriv_weight, second_deriv_weight = (5, 0.1) #weighting of the derivatives, can be changed count = 0 inconsistent_stations = inconsistent_typical_range_stations(stations) unsafe_stations_name = stations_level_over_threshold(stations, 0.8) #0.8 can be changed as desired unsafe_stations = [station for station in stations for name, level in unsafe_stations_name if station.name == name] with alive_bar(len(stations)) as bar: for station in stations: if station in inconsistent_stations: pass if not station.latest_level_consistent(): inconsistent_stations.append(station) #gets rid of inconsistent stations if station not in unsafe_stations: stations_by_risk.append((station, station.relative_water_level(), risk_definition(station.relative_water_level()))) try: dates, levels = fetch_measure_levels(station.measure_id, dt=datetime.timedelta(days=dt)) #fetched plotting data except (KeyError): inconsistent_stations.append(station) try: levels = np.array(levels) levels = (levels - station.typical_range[0]) / (station.typical_range[1] - station.typical_range[0]) except (TypeError, ValueError): #makes sure bad data doenst break the program inconsistent_stations.append(station) try: poly, d0 = polyfit(dates,levels,p) except (IndexError, ValueError, TypeError): inconsistent_stations.append(station) first_deriv = poly.deriv() second_deriv = poly.deriv(2) risk_value = poly(0) risk_value += first_deriv(0) * first_deriv_weight risk_value += second_deriv(0) * second_deriv_weight # if (risk_value is None) or (station.relative_water_level() is None): inconsistent_stations.append(station) elif risk_value < station.relative_water_level(): risk_value = station.relative_water_level() stations_by_risk.append((station, risk_value, risk_definition(risk_value))) if (station.town not in risk_of_towns.keys()) or (risk_value > risk_of_towns[station.town]): risk_of_towns[station.town] = risk_value else: stations_by_risk.append((station, 0, risk_definition(0))) count = count + 1 bar() if count > 100: break return risk_of_towns
[ "floodsystem.station.inconsistent_typical_range_stations", "floodsystem.flood.stations_level_over_threshold", "numpy.poly1d", "numpy.polyfit", "numpy.array", "datetime.timedelta", "matplotlib.dates.date2num" ]
[((486, 518), 'matplotlib.dates.date2num', 'matplotlib.dates.date2num', (['dates'], {}), '(dates)\n', (511, 518), False, 'import matplotlib\n'), ((1851, 1896), 'floodsystem.station.inconsistent_typical_range_stations', 'inconsistent_typical_range_stations', (['stations'], {}), '(stations)\n', (1886, 1896), False, 'from floodsystem.station import inconsistent_typical_range_stations\n'), ((1924, 1968), 'floodsystem.flood.stations_level_over_threshold', 'stations_level_over_threshold', (['stations', '(0.8)'], {}), '(stations, 0.8)\n', (1953, 1968), False, 'from floodsystem.flood import stations_level_over_threshold\n'), ((758, 777), 'numpy.polyfit', 'np.polyfit', (['x', 'y', 'p'], {}), '(x, y, p)\n', (768, 777), True, 'import numpy as np\n'), ((793, 811), 'numpy.poly1d', 'np.poly1d', (['p_coeff'], {}), '(p_coeff)\n', (802, 811), True, 'import numpy as np\n'), ((1016, 1028), 'numpy.poly1d', 'np.poly1d', (['(0)'], {}), '(0)\n', (1025, 1028), True, 'import numpy as np\n'), ((2897, 2913), 'numpy.array', 'np.array', (['levels'], {}), '(levels)\n', (2905, 2913), True, 'import numpy as np\n'), ((2711, 2738), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'dt'}), '(days=dt)\n', (2729, 2738), False, 'import datetime\n')]
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import numpy.ma as ma import itertools class TPM: """ A collecton of static methods to calculate transition probability matrix of a descrete markov process from an unbalanced panel data """ @staticmethod def f(x): """ simple helper function >>> a = 10 >>> b = [1,2,3] >>> x = (a, b) >>> f(x) [10, 10, 10] :param x: :return: """ if x is None: return return [x[0]]* len(x[1]) @staticmethod def get_bins(array, bins=100): """ Calculate in which *tile a given number of an array is. If bins=100 the function returns an array of percentiles where each number is a percentile >>> import numpy as np >>> array = np.array(range(20)) >>> array [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] >>> get_bins(array, bins=10) [0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9] >>> np.random.shuffle(array) # shuffle the array >>> array [10 14 0 1 12 4 3 17 15 9 7 11 13 8 18 5 16 6 2 19] >>> get_bins(array, bins=10) [5 7 0 0 6 2 1 8 7 4 3 5 6 4 9 2 8 3 1 9] :param array: 1D numpy array. **must not contain NaNs** :param bins: number of states or bins in which the data should be splitted :return: np.array() preserving the order of elements """ if array is None: return assert(isinstance(array, type(np.array((1,))))), "input must be {}, not {}".format(type(np.array((1,))), type(array)) assert(len(array) > bins), "len(array) must be bigger than number of states. Given len(array)= {} , bins= {}".format(len(array), bins) sorted_indx = np.argsort(array) bin_size = len(array)/bins # split array into bins splitted_in_bins = np.array_split(sorted_indx, bins) # convert values in bins into states splitted_in_bins = np.array(list(map(lambda z: TPM.f(z), zip(range(bins), splitted_in_bins)))) # flatten the array with states tiles = [item for sublist in splitted_in_bins for item in sublist] # create a dictionary with information on which state corresponds to which index states_dict = dict(zip(sorted_indx, tiles)) # return an identical to input_array array of states return np.array(list(map(lambda z: states_dict[z], range(len(array))))) @staticmethod def calculate_states(array, n_states=100): """ Enhances a method get_bins by accepting an array with NaN values and ignoring them. It preserves the order of original array and returns NaN on the same place as in input. >>> import numpy as np >>> array = np.array(list(map(lambda x: float(x), range(20)))) [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.] >>> array[np.random.randint(0, len(array), size=int(len(array)*0.2))] = np.NaN [nan 1. 2. nan nan 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. nan 17. 18. 19.] >>> calculate_states(array, n_states=10) [nan 0. 0. nan nan 1. 1. 2. 2. 3. 3. 4. 4. 5. 5. 6. nan 7. 8. 9.] >>> np.random.shuffle(array) [ 8. nan 14. 5. nan nan 10. 13. 9. 18. 1. nan 11. 7. 12. 17. 2. 15. 6. 19.] >>> calculate_states(array, n_states=10) [ 2. nan 5. 1. nan nan 3. 5. 3. 8. 0. nan 4. 2. 4. 7. 0. 6. 1. 9.] :param array: 1D numpy array. :param n_states: number of states or bins in which the data should be splitted :return: np.array() preserving the order of elements """ if array is None: return mask = np.invert(np.array(ma.masked_invalid(array).mask)) shrinked_array = array[np.array(mask)] shrinked_array = TPM.get_bins(shrinked_array, bins=n_states) # expand array back to original size # extremely inefficient code here expanded_array = list() p = 0 for indx in mask: if indx: expanded_array.append(shrinked_array[p]) p += 1 else: expanded_array.append(np.NaN) return np.array(expanded_array) @staticmethod def convert_to_states(array, n_states=100): """ converts a 2D numpy array into an identical 2D numpy array with values being replaced by a corresponding state, where states are calculated in accordance with calculate_states() function. >>> import numpy as np >>> data = list() >>> for i in range(10): >>> a = np.array(list(map(lambda x: float(x), range(10)))) >>> a[np.random.randint(0, len(a), size=int(len(a)*0.2))] = np.NaN >>> data.append(a) >>> array = np.array(data).T >>> print(array) # very primitive unbalanced panel [[ 0. nan nan nan 0. 0. nan 0. 0. 0.] [ 1. 1. nan 1. 1. nan 1. 1. 1. 1.] [nan 2. 2. 2. 2. 2. 2. 2. 2. 2.] [ 3. 3. 3. 3. 3. nan nan 3. nan 3.] [nan 4. 4. 4. 4. 4. 4. 4. 4. 4.] [ 5. 5. 5. 5. 5. 5. 5. nan 5. 5.] [ 6. 6. 6. nan 6. 6. 6. 6. nan nan] [ 7. 7. 7. 7. nan 7. 7. 7. 7. 7.] [ 8. 8. 8. 8. nan 8. 8. nan 8. 8.] [ 9. 9. 9. 9. 9. 9. 9. 9. 9. 9.]] >>> array = convert_to_states(array, n_states=5) >>> print(array) # resulting convertion into 5 states [[ 0. nan nan nan 0. 0. nan 0. 0. 0.] [ 0. 0. nan 0. 0. nan 0. 0. 0. 0.] [nan 0. 0. 0. 1. 0. 0. 1. 1. 1.] [ 1. 1. 0. 1. 1. nan nan 1. nan 1.] [nan 1. 1. 1. 2. 1. 1. 2. 1. 2.] [ 1. 2. 1. 2. 2. 1. 1. nan 2. 2.] [ 2. 2. 2. nan 3. 2. 2. 2. nan nan] [ 2. 3. 2. 2. nan 2. 2. 3. 2. 3.] [ 3. 3. 3. 3. nan 3. 3. nan 3. 3.] [ 4. 4. 4. 4. 4. 4. 4. 4. 4. 4.]] >>> data = list() >>> for i in range(10): # generate unbalanced panel >>> a = np.array(list(map(lambda x: float(x), range(10)))) >>> a[np.random.randint(0, len(a), size=int(len(a)*0.2))] = np.NaN >>> np.random.shuffle(a) >>> data.append(a) >>> array = np.array(data).T >>> print(array) # randomly shuffled unbalanced panel [[ 9. 6. 6. 2. 2. 1. nan nan 9. 7.] [nan 7. nan 8. nan 4. 5. 8. 8. 9.] [ 0. 1. 7. nan 8. 7. nan 6. 4. 0.] [ 3. nan 0. nan 4. nan 2. 4. 0. 1.] [ 7. 4. 4. 1. 0. 3. 8. 9. nan 2.] [ 8. 3. 8. 7. 6. 2. 0. 0. nan nan] [nan 9. 9. 9. 9. 0. 6. 1. 2. nan] [ 5. 2. 3. 5. nan 5. 9. 3. 1. 5.] [ 4. nan 2. 6. 7. nan 3. 7. 6. 4.] [ 1. 8. 1. 3. 3. 9. 7. 2. 3. 3.]] >>> array = convert_to_states(array, n_states=5) >>> print(array) # resulting convertion into 5 states [[ 4. 2. 2. 0. 0. 0. nan nan 4. 3.] [nan 2. nan 3. nan 2. 1. 3. 3. 4.] [ 0. 0. 3. nan 3. 3. nan 2. 2. 0.] [ 1. nan 0. nan 1. nan 0. 2. 0. 0.] [ 2. 1. 2. 0. 0. 1. 3. 4. nan 1.] [ 3. 1. 3. 2. 2. 1. 0. 0. nan nan] [nan 4. 4. 4. 4. 0. 2. 0. 1. nan] [ 2. 0. 1. 1. nan 2. 4. 1. 0. 2.] [ 1. nan 1. 2. 2. nan 1. 3. 2. 2.] [ 0. 3. 0. 1. 1. 4. 2. 1. 1. 1.]] :param array: 2D numpy array. :param n_states: number of states or bins in which the data should be splitted :return: np.array() of states being calculated along columns, preserving np.NaNs """ if array is None: return assert(isinstance(array, type(np.array((2, 2))))), "input must be {}, not {}".format(type(np.array((2, 2))), type(array)) assert(len(array.shape) == 2), "array must be 2 dimentional, not {}".format(array.shape) return np.apply_along_axis(TPM.calculate_states, 0, array, n_states=n_states) @staticmethod def calculate_tpm(array, n_states=100, markov_order=1): """ Calculate a transition probability matrix of a descrete markov process given an unbalanced panel. The input array is treated as an unbalanced panel data. For example each row is a firm and each entry is a growth rate of this firm in a given period of time (columns). *np.nan* means a missing entry. The function: 1. calculates states for each entry in a given array. For example, if the number of states is equal to 100, the function calculates in which percentile a given entry is. 2. omits all transitions from a missing entry and to a missing entry. For example, *nan -> 0.* (see array[0, 0] & array[0,1] in the code below) or *5. -> nan* (see array[1, 0] & array[1,1] in the code below) 3. calculates frequencies of transitions from one state to another and returns it as a transition probability matrix >>> data = list() >>> for i in range(10): # generate unbalanced panel >>> a = np.array(list(map(lambda x: float(x), range(10)))) >>> a[np.random.randint(0, len(a), size=int(len(a)*0.2))] = np.NaN >>> np.random.shuffle(a) >>> data.append(a) >>> array = np.array(data).T >>> print(array) # randomly shuffled unbalanced panel [[nan 0. 1. 5. 9. 5. nan 8. 0. 4.] [ 5. nan 8. 9. 8. 0. 7. 9. 8. 0.] [ 8. 4. 9. 8. nan 3. 3. 1. 3. 1.] [ 9. 7. 7. nan 6. 8. 9. nan nan nan] [nan 2. nan nan 1. 4. 4. 3. nan 6.] [ 4. 5. 4. 7. 3. 9. 8. 5. 9. 7.] [ 6. 8. 6. 1. 4. nan 5. 4. 1. 3.] [ 3. 3. 0. 4. nan 1. 6. 7. 7. 8.] [ 7. 6. 3. 3. 5. 2. 2. 6. 4. nan] [ 1. 9. nan 6. 7. 7. nan nan 6. 9.]] >>> print(array.shape) (10, 10) >>> tpm = calculate_tpm(array, n_states=5) >>> tpm [[0.14285714 0.42857143 0.28571429 0. 0.14285714] [0.46153846 0.15384615 0.15384615 0. 0.23076923] [0.14285714 0.28571429 0.28571429 0.21428571 0.07142857] [0.25 0.25 0.25 0. 0.25 ] [0. 0. 0.16666667 0.83333333 0. ]] >>> print(tpm.shape) (5, 5) :param array: 2D numpy array representing an unbalanced panel data :param n_states: number of states or bins in which the data should be splitted :param markov_order: order of the markov process :return: np.array() containing transition probability matrix """ if array is None: return assert(isinstance(array, type(np.array((2, 2))))), "input must be {}, not {}".format(type(np.array((2, 2))), type(array)) assert(len(array.shape) == 2), "array must be 2 dimentional, not {}".format(array.shape) # convert values into markov process states states_matrix = TPM.convert_to_states(array, n_states=n_states) # calculate frequencies all_possible_jumps = np.zeros(shape=(n_states, n_states)) for index in range(states_matrix.shape[1]-2): # collect all possible jumps g = states_matrix[:, index:index+2] # filter all rows with NaN g = g[~np.isnan(g).any(axis=1)] unique_pairs, count_pairs = np.unique(g, axis=0, return_counts=True) #unique_pairs = tuple(map(lambda y: tuple([int(y[0]), int(y[1])]), unique_pairs)) # inefficient code here for indx, key in enumerate(unique_pairs): all_possible_jumps[int(key[0]), int(key[1])] += count_pairs[indx] sum_rows = np.sum(all_possible_jumps, axis=1) # divide each row on its sum return np.divide(all_possible_jumps.T, sum_rows).T if __name__ == "__main__": # test case 1 get_bins print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<") print("What get_bins() function is doing?") array = np.array(range(20)) print(array) r = TPM.get_bins(array, bins=10) print(r) np.random.shuffle(array) print(r) r = TPM.get_bins(array, bins=10) print(r) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") print() # test case 2 calculates_states print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<") print("What calculate_states() function is doing?") array = np.array(list(map(lambda x: float(x), range(20)))) print(array) array[np.random.randint(0, len(array), size=int(len(array)*0.2))] = np.NaN print(array) r = TPM.calculate_states(array, n_states=10) print(r) np.random.shuffle(array) print(array) r = TPM.calculate_states(array, n_states=10) print(r) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") print() # test case 3 convert_to_states # artificially create an unbalanced panel print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<") print("What convert_to_states() function is doing?") data = list() for i in range(10): a = np.array(list(map(lambda x: float(x), range(10)))) a[np.random.randint(0, len(a), size=int(len(a)*0.2))] = np.NaN np.random.shuffle(a) data.append(a) array = np.array(data).T print(array) print(array.shape) states_matrix = TPM.convert_to_states(array, n_states=5) print(states_matrix) print(states_matrix.shape) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") print() # test case 4 calculate_tpm # artificially create an unbalanced panel print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<") print("What calculate_tpm() function is doing?") data = list() for i in range(10): a = np.array(list(map(lambda x: float(x), range(10)))) a[np.random.randint(0, len(a), size=int(len(a)*0.2))] = np.NaN np.random.shuffle(a) data.append(a) array = np.array(data).T print(array) print(array.shape) tpm_matrix = TPM.calculate_tpm(array, n_states=5) print(tpm_matrix) print(tpm_matrix.shape) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") print()
[ "numpy.divide", "numpy.sum", "numpy.unique", "numpy.zeros", "numpy.ma.masked_invalid", "numpy.isnan", "numpy.argsort", "numpy.apply_along_axis", "numpy.array", "numpy.array_split", "numpy.random.shuffle" ]
[((12699, 12723), 'numpy.random.shuffle', 'np.random.shuffle', (['array'], {}), '(array)\n', (12716, 12723), True, 'import numpy as np\n'), ((13262, 13286), 'numpy.random.shuffle', 'np.random.shuffle', (['array'], {}), '(array)\n', (13279, 13286), True, 'import numpy as np\n'), ((1869, 1886), 'numpy.argsort', 'np.argsort', (['array'], {}), '(array)\n', (1879, 1886), True, 'import numpy as np\n'), ((1981, 2014), 'numpy.array_split', 'np.array_split', (['sorted_indx', 'bins'], {}), '(sorted_indx, bins)\n', (1995, 2014), True, 'import numpy as np\n'), ((4355, 4379), 'numpy.array', 'np.array', (['expanded_array'], {}), '(expanded_array)\n', (4363, 4379), True, 'import numpy as np\n'), ((8359, 8429), 'numpy.apply_along_axis', 'np.apply_along_axis', (['TPM.calculate_states', '(0)', 'array'], {'n_states': 'n_states'}), '(TPM.calculate_states, 0, array, n_states=n_states)\n', (8378, 8429), True, 'import numpy as np\n'), ((11657, 11693), 'numpy.zeros', 'np.zeros', ([], {'shape': '(n_states, n_states)'}), '(shape=(n_states, n_states))\n', (11665, 11693), True, 'import numpy as np\n'), ((12297, 12331), 'numpy.sum', 'np.sum', (['all_possible_jumps'], {'axis': '(1)'}), '(all_possible_jumps, axis=1)\n', (12303, 12331), True, 'import numpy as np\n'), ((13829, 13849), 'numpy.random.shuffle', 'np.random.shuffle', (['a'], {}), '(a)\n', (13846, 13849), True, 'import numpy as np\n'), ((13887, 13901), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (13895, 13901), True, 'import numpy as np\n'), ((14518, 14538), 'numpy.random.shuffle', 'np.random.shuffle', (['a'], {}), '(a)\n', (14535, 14538), True, 'import numpy as np\n'), ((14576, 14590), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (14584, 14590), True, 'import numpy as np\n'), ((3919, 3933), 'numpy.array', 'np.array', (['mask'], {}), '(mask)\n', (3927, 3933), True, 'import numpy as np\n'), ((11966, 12006), 'numpy.unique', 'np.unique', (['g'], {'axis': '(0)', 'return_counts': '(True)'}), '(g, axis=0, return_counts=True)\n', (11975, 12006), True, 'import numpy as np\n'), ((12386, 12427), 'numpy.divide', 'np.divide', (['all_possible_jumps.T', 'sum_rows'], {}), '(all_possible_jumps.T, sum_rows)\n', (12395, 12427), True, 'import numpy as np\n'), ((1585, 1599), 'numpy.array', 'np.array', (['(1,)'], {}), '((1,))\n', (1593, 1599), True, 'import numpy as np\n'), ((1643, 1657), 'numpy.array', 'np.array', (['(1,)'], {}), '((1,))\n', (1651, 1657), True, 'import numpy as np\n'), ((8120, 8136), 'numpy.array', 'np.array', (['(2, 2)'], {}), '((2, 2))\n', (8128, 8136), True, 'import numpy as np\n'), ((8180, 8196), 'numpy.array', 'np.array', (['(2, 2)'], {}), '((2, 2))\n', (8188, 8196), True, 'import numpy as np\n'), ((11245, 11261), 'numpy.array', 'np.array', (['(2, 2)'], {}), '((2, 2))\n', (11253, 11261), True, 'import numpy as np\n'), ((11305, 11321), 'numpy.array', 'np.array', (['(2, 2)'], {}), '((2, 2))\n', (11313, 11321), True, 'import numpy as np\n'), ((3855, 3879), 'numpy.ma.masked_invalid', 'ma.masked_invalid', (['array'], {}), '(array)\n', (3872, 3879), True, 'import numpy.ma as ma\n'), ((11900, 11911), 'numpy.isnan', 'np.isnan', (['g'], {}), '(g)\n', (11908, 11911), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Xtreme RGB Colourspace ====================== Defines the *Xtreme RGB* colourspace: - :attr:`XTREME_RGB_COLOURSPACE`. See Also -------- `RGB Colourspaces IPython Notebook <http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/models/rgb.ipynb>`_ # noqa References ---------- .. [1] http://www.hutchcolor.com/profiles/XtremeRGB.zip (Last accessed 12 April 2014) """ from __future__ import division, unicode_literals import numpy as np from colour.colorimetry import ILLUMINANTS from colour.models import RGB_Colourspace, normalised_primary_matrix __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers' __license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = '<EMAIL>' __status__ = 'Production' __all__ = ['XTREME_RGB_PRIMARIES', 'XTREME_RGB_WHITEPOINT', 'XTREME_RGB_TO_XYZ_MATRIX', 'XYZ_TO_XTREME_RGB_MATRIX', 'XTREME_RGB_TRANSFER_FUNCTION', 'XTREME_RGB_INVERSE_TRANSFER_FUNCTION', 'XTREME_RGB_COLOURSPACE'] XTREME_RGB_PRIMARIES = np.array( [[1, 0], [0, 1], [0, 0]]) """ *Xtreme RGB* colourspace primaries. XTREME_RGB_PRIMARIES : ndarray, (3, 2) """ XTREME_RGB_WHITEPOINT = ILLUMINANTS.get( 'CIE 1931 2 Degree Standard Observer').get('D50') """ *Xtreme RGB* colourspace whitepoint. XTREME_RGB_WHITEPOINT : tuple """ XTREME_RGB_TO_XYZ_MATRIX = normalised_primary_matrix(XTREME_RGB_PRIMARIES, XTREME_RGB_WHITEPOINT) """ *Xtreme RGB* colourspace to *CIE XYZ* colourspace matrix. XTREME_RGB_TO_XYZ_MATRIX : array_like, (3, 3) """ XYZ_TO_XTREME_RGB_MATRIX = np.linalg.inv(XTREME_RGB_TO_XYZ_MATRIX) """ *CIE XYZ* colourspace to *Xtreme RGB* colourspace matrix. XYZ_TO_XTREME_RGB_MATRIX : array_like, (3, 3) """ XTREME_RGB_TRANSFER_FUNCTION = lambda x: x ** (1 / 2.2) """ Transfer function from linear to *Xtreme RGB* colourspace. XTREME_RGB_TRANSFER_FUNCTION : object """ XTREME_RGB_INVERSE_TRANSFER_FUNCTION = lambda x: x ** 2.2 """ Inverse transfer function from *Xtreme RGB* colourspace to linear. XTREME_RGB_INVERSE_TRANSFER_FUNCTION : object """ XTREME_RGB_COLOURSPACE = RGB_Colourspace( 'Xtreme RGB', XTREME_RGB_PRIMARIES, XTREME_RGB_WHITEPOINT, XTREME_RGB_TO_XYZ_MATRIX, XYZ_TO_XTREME_RGB_MATRIX, XTREME_RGB_TRANSFER_FUNCTION, XTREME_RGB_INVERSE_TRANSFER_FUNCTION) """ *Xtreme RGB* colourspace. XTREME_RGB_COLOURSPACE : RGB_Colourspace """
[ "colour.models.normalised_primary_matrix", "colour.models.RGB_Colourspace", "colour.colorimetry.ILLUMINANTS.get", "numpy.linalg.inv", "numpy.array" ]
[((1215, 1249), 'numpy.array', 'np.array', (['[[1, 0], [0, 1], [0, 0]]'], {}), '([[1, 0], [0, 1], [0, 0]])\n', (1223, 1249), True, 'import numpy as np\n'), ((1549, 1619), 'colour.models.normalised_primary_matrix', 'normalised_primary_matrix', (['XTREME_RGB_PRIMARIES', 'XTREME_RGB_WHITEPOINT'], {}), '(XTREME_RGB_PRIMARIES, XTREME_RGB_WHITEPOINT)\n', (1574, 1619), False, 'from colour.models import RGB_Colourspace, normalised_primary_matrix\n'), ((1814, 1853), 'numpy.linalg.inv', 'np.linalg.inv', (['XTREME_RGB_TO_XYZ_MATRIX'], {}), '(XTREME_RGB_TO_XYZ_MATRIX)\n', (1827, 1853), True, 'import numpy as np\n'), ((2337, 2539), 'colour.models.RGB_Colourspace', 'RGB_Colourspace', (['"""Xtreme RGB"""', 'XTREME_RGB_PRIMARIES', 'XTREME_RGB_WHITEPOINT', 'XTREME_RGB_TO_XYZ_MATRIX', 'XYZ_TO_XTREME_RGB_MATRIX', 'XTREME_RGB_TRANSFER_FUNCTION', 'XTREME_RGB_INVERSE_TRANSFER_FUNCTION'], {}), "('Xtreme RGB', XTREME_RGB_PRIMARIES, XTREME_RGB_WHITEPOINT,\n XTREME_RGB_TO_XYZ_MATRIX, XYZ_TO_XTREME_RGB_MATRIX,\n XTREME_RGB_TRANSFER_FUNCTION, XTREME_RGB_INVERSE_TRANSFER_FUNCTION)\n", (2352, 2539), False, 'from colour.models import RGB_Colourspace, normalised_primary_matrix\n'), ((1374, 1428), 'colour.colorimetry.ILLUMINANTS.get', 'ILLUMINANTS.get', (['"""CIE 1931 2 Degree Standard Observer"""'], {}), "('CIE 1931 2 Degree Standard Observer')\n", (1389, 1428), False, 'from colour.colorimetry import ILLUMINANTS\n')]
import numpy as np import pickle as pkl import os import pandas as pd # Creates a dictionary, path_dict, with all of the required path information for the following # functions including save directory and finding the s2p-output # Parameters: # fdir - the path to the original recording file # fname - the name of the original recording file # threshold_scaling_values - the corresponding threshold_scaling value used # by the automatic script def define_paths(fdir, fname): path_dict = {} # define paths for loading s2p data path_dict['s2p_dir'] = os.path.join(fdir, 'suite2p', 'plane0') path_dict['s2p_F_path'] = os.path.join(path_dict['s2p_dir'], 'F.npy') path_dict['s2p_Fneu_path'] = os.path.join(path_dict['s2p_dir'], 'Fneu.npy') path_dict['s2p_iscell_path'] = os.path.join(path_dict['s2p_dir'], 'iscell.npy') path_dict['s2p_ops_path'] = os.path.join(path_dict['s2p_dir'], 'ops.npy') # define savepaths for converted output data path_dict['csv_savepath'] = os.path.join(fdir, f'{fname}_s2p_data.csv') path_dict['npy_savepath'] = os.path.join(fdir, f'{fname}_s2p_neuropil_corrected_signals.npy') return path_dict #Takes the path information from path_dict and uses it to load and save the files #they direct towards def load_s2p_data(path_dict): s2p_data_dict = {} # load s2p data s2p_data_dict['F_data'] = np.load(path_dict['s2p_F_path'], allow_pickle=True) s2p_data_dict['Fneu_data'] = np.load(path_dict['s2p_Fneu_path'], allow_pickle=True) s2p_data_dict['iscell_data'] = np.load(path_dict['s2p_iscell_path'], allow_pickle=True) s2p_data_dict['ops_data'] = np.load(path_dict['s2p_ops_path'], allow_pickle=True).item() return s2p_data_dict #Calls the previous two and finally saves the converted files as csv and npy files def csv_npy_save(fdir, fname): path_dict = define_paths(fdir, fname) s2p_data_dict = load_s2p_data(path_dict) npil_corr_signals = s2p_data_dict['F_data'] - s2p_data_dict['ops_data']['neucoeff'] * s2p_data_dict['Fneu_data'] iscell_npil_corr_data = npil_corr_signals[s2p_data_dict['iscell_data'][:,0].astype('bool'),:] # save cell activity data as a csv with ROIs on y axis and samples on x axis np.save(path_dict['npy_savepath'], iscell_npil_corr_data) # this saves the user-curated neuropil corrected signals as an npy file pd.DataFrame(data=iscell_npil_corr_data).to_csv(path_dict['csv_savepath'], index=False, header=False) # this saves the same data as a csv file
[ "pandas.DataFrame", "numpy.load", "numpy.save", "os.path.join" ]
[((635, 674), 'os.path.join', 'os.path.join', (['fdir', '"""suite2p"""', '"""plane0"""'], {}), "(fdir, 'suite2p', 'plane0')\n", (647, 674), False, 'import os\n'), ((706, 749), 'os.path.join', 'os.path.join', (["path_dict['s2p_dir']", '"""F.npy"""'], {}), "(path_dict['s2p_dir'], 'F.npy')\n", (718, 749), False, 'import os\n'), ((783, 829), 'os.path.join', 'os.path.join', (["path_dict['s2p_dir']", '"""Fneu.npy"""'], {}), "(path_dict['s2p_dir'], 'Fneu.npy')\n", (795, 829), False, 'import os\n'), ((865, 913), 'os.path.join', 'os.path.join', (["path_dict['s2p_dir']", '"""iscell.npy"""'], {}), "(path_dict['s2p_dir'], 'iscell.npy')\n", (877, 913), False, 'import os\n'), ((946, 991), 'os.path.join', 'os.path.join', (["path_dict['s2p_dir']", '"""ops.npy"""'], {}), "(path_dict['s2p_dir'], 'ops.npy')\n", (958, 991), False, 'import os\n'), ((1074, 1117), 'os.path.join', 'os.path.join', (['fdir', 'f"""{fname}_s2p_data.csv"""'], {}), "(fdir, f'{fname}_s2p_data.csv')\n", (1086, 1117), False, 'import os\n'), ((1150, 1215), 'os.path.join', 'os.path.join', (['fdir', 'f"""{fname}_s2p_neuropil_corrected_signals.npy"""'], {}), "(fdir, f'{fname}_s2p_neuropil_corrected_signals.npy')\n", (1162, 1215), False, 'import os\n'), ((1454, 1505), 'numpy.load', 'np.load', (["path_dict['s2p_F_path']"], {'allow_pickle': '(True)'}), "(path_dict['s2p_F_path'], allow_pickle=True)\n", (1461, 1505), True, 'import numpy as np\n'), ((1539, 1593), 'numpy.load', 'np.load', (["path_dict['s2p_Fneu_path']"], {'allow_pickle': '(True)'}), "(path_dict['s2p_Fneu_path'], allow_pickle=True)\n", (1546, 1593), True, 'import numpy as np\n'), ((1629, 1685), 'numpy.load', 'np.load', (["path_dict['s2p_iscell_path']"], {'allow_pickle': '(True)'}), "(path_dict['s2p_iscell_path'], allow_pickle=True)\n", (1636, 1685), True, 'import numpy as np\n'), ((2318, 2375), 'numpy.save', 'np.save', (["path_dict['npy_savepath']", 'iscell_npil_corr_data'], {}), "(path_dict['npy_savepath'], iscell_npil_corr_data)\n", (2325, 2375), True, 'import numpy as np\n'), ((1718, 1771), 'numpy.load', 'np.load', (["path_dict['s2p_ops_path']"], {'allow_pickle': '(True)'}), "(path_dict['s2p_ops_path'], allow_pickle=True)\n", (1725, 1771), True, 'import numpy as np\n'), ((2452, 2492), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'iscell_npil_corr_data'}), '(data=iscell_npil_corr_data)\n', (2464, 2492), True, 'import pandas as pd\n')]
from typing import Optional, Tuple import numpy as np from sklearn import datasets from torch.utils.data import DataLoader, Dataset import torch # import torch.multiprocessing as multiprocessing # multiprocessing.set_start_method("spawn") # class DensityDataset: # def __init__(self, data, dtype=np.float32): # self.data = data # self.dtype = dtype # def __len__(self): # return len(self.data) # def __getitem__(self, idx: int) -> np.ndarray: # data = self.data[idx] # return np.np.ndarray(data, dtype=self.dtype) def add_dataset_args(parser): parser.add_argument( "--seed", type=int, default=123, help="number of data points for training", ) parser.add_argument( "--dataset", type=str, default="noisysine", help="Dataset to be used for visualization", ) parser.add_argument( "--n_samples", type=int, default=5_000, help="number of data points for training", ) parser.add_argument( "--noise", type=float, default=0.1, help="number of data points for training", ) parser.add_argument( "--n_train", type=int, default=2_000, help="number of data points for training", ) parser.add_argument( "--n_valid", type=int, default=1_000, help="number of data points for training", ) return parser class DensityDataset(Dataset): def __init__(self, n_samples: int = 10_000, noise: float = 0.1, seed: int = 123): self.n_samples = n_samples self.seed = seed self.noise = noise self.reset() def __len__(self): return len(self.data) def __getitem__(self, idx: int) -> torch.Tensor: data = self.data[idx] return data def reset(self): self._create_data() def _create_data(self): raise NotImplementedError class GenericDataset(DensityDataset): def __init__(self, data): self.data = data def get_data( N: int = 30, input_noise: float = 0.15, output_noise: float = 0.15, N_test: int = 400, ) -> Tuple[np.ndnp.ndarray, np.ndnp.ndarray, np.ndnp.ndarray]: np.random.seed(0) X = np.linspace(-1, 1, N) Y = X + 0.2 * np.power(X, 3.0) + 0.5 * np.power(0.5 + X, 2.0) * np.sin(4.0 * X) Y += output_noise * np.random.randn(N) Y -= np.mean(Y) Y /= np.std(Y) X += input_noise * np.random.randn(N) assert X.shape == (N,) assert Y.shape == (N,) X_test = np.linspace(-1.2, 1.2, N_test) return X[:, None], Y[:, None], X_test[:, None] class SCurveDataset(DensityDataset): def _create_data(self): data, _ = datasets.make_s_curve( n_samples=self.n_samples, noise=self.noise, random_state=self.seed ) data = data[:, [0, 2]] self.data = data class BlobsDataset(DensityDataset): def _create_data(self): data, _ = datasets.make_blobs(n_samples=self.n_samples, random_state=self.seed) self.data = data class MoonsDataset(DensityDataset): def _create_data(self): data, _ = datasets.make_moons( n_samples=self.n_samples, noise=self.noise, random_state=self.seed ) self.data = data class SwissRollDataset(DensityDataset): def _create_data(self): data, _ = datasets.make_swiss_roll( n_samples=self.n_samples, noise=self.noise, random_state=self.seed ) data = data[:, [0, 2]] self.data = data class NoisySineDataset(DensityDataset): def _create_data(self): rng = np.random.RandomState(seed=self.seed) x = np.abs(2 * rng.randn(1, self.n_samples)) y = np.sin(x) + 0.25 * rng.randn(1, self.n_samples) self.data = np.vstack((x, y)).T class CheckBoard(DensityDataset): def _create_data(self): rng = np.random.RandomState(self.seed) x1 = rng.rand(self.n_samples) * 4 - 2 x2_ = rng.rand(self.n_samples) - rng.randint(0, 2, self.n_samples) * 2 x2 = x2_ + (np.floor(x1) % 2) data = np.concatenate([x1[:, None], x2[:, None]], 1) * 2 self.data = data + 0.001 * rng.randn(*data.shape)
[ "numpy.random.seed", "numpy.concatenate", "numpy.random.randn", "numpy.std", "numpy.power", "numpy.floor", "sklearn.datasets.make_blobs", "numpy.random.RandomState", "sklearn.datasets.make_moons", "sklearn.datasets.make_swiss_roll", "numpy.mean", "numpy.sin", "numpy.linspace", "sklearn.datasets.make_s_curve", "numpy.vstack" ]
[((2267, 2284), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2281, 2284), True, 'import numpy as np\n'), ((2293, 2314), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'N'], {}), '(-1, 1, N)\n', (2304, 2314), True, 'import numpy as np\n'), ((2451, 2461), 'numpy.mean', 'np.mean', (['Y'], {}), '(Y)\n', (2458, 2461), True, 'import numpy as np\n'), ((2471, 2480), 'numpy.std', 'np.std', (['Y'], {}), '(Y)\n', (2477, 2480), True, 'import numpy as np\n'), ((2593, 2623), 'numpy.linspace', 'np.linspace', (['(-1.2)', '(1.2)', 'N_test'], {}), '(-1.2, 1.2, N_test)\n', (2604, 2623), True, 'import numpy as np\n'), ((2423, 2441), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (2438, 2441), True, 'import numpy as np\n'), ((2505, 2523), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (2520, 2523), True, 'import numpy as np\n'), ((2761, 2854), 'sklearn.datasets.make_s_curve', 'datasets.make_s_curve', ([], {'n_samples': 'self.n_samples', 'noise': 'self.noise', 'random_state': 'self.seed'}), '(n_samples=self.n_samples, noise=self.noise,\n random_state=self.seed)\n', (2782, 2854), False, 'from sklearn import datasets\n'), ((3013, 3082), 'sklearn.datasets.make_blobs', 'datasets.make_blobs', ([], {'n_samples': 'self.n_samples', 'random_state': 'self.seed'}), '(n_samples=self.n_samples, random_state=self.seed)\n', (3032, 3082), False, 'from sklearn import datasets\n'), ((3192, 3283), 'sklearn.datasets.make_moons', 'datasets.make_moons', ([], {'n_samples': 'self.n_samples', 'noise': 'self.noise', 'random_state': 'self.seed'}), '(n_samples=self.n_samples, noise=self.noise,\n random_state=self.seed)\n', (3211, 3283), False, 'from sklearn import datasets\n'), ((3415, 3511), 'sklearn.datasets.make_swiss_roll', 'datasets.make_swiss_roll', ([], {'n_samples': 'self.n_samples', 'noise': 'self.noise', 'random_state': 'self.seed'}), '(n_samples=self.n_samples, noise=self.noise,\n random_state=self.seed)\n', (3439, 3511), False, 'from sklearn import datasets\n'), ((3671, 3708), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': 'self.seed'}), '(seed=self.seed)\n', (3692, 3708), True, 'import numpy as np\n'), ((3940, 3972), 'numpy.random.RandomState', 'np.random.RandomState', (['self.seed'], {}), '(self.seed)\n', (3961, 3972), True, 'import numpy as np\n'), ((2383, 2398), 'numpy.sin', 'np.sin', (['(4.0 * X)'], {}), '(4.0 * X)\n', (2389, 2398), True, 'import numpy as np\n'), ((3774, 3783), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (3780, 3783), True, 'import numpy as np\n'), ((3842, 3859), 'numpy.vstack', 'np.vstack', (['(x, y)'], {}), '((x, y))\n', (3851, 3859), True, 'import numpy as np\n'), ((4151, 4196), 'numpy.concatenate', 'np.concatenate', (['[x1[:, None], x2[:, None]]', '(1)'], {}), '([x1[:, None], x2[:, None]], 1)\n', (4165, 4196), True, 'import numpy as np\n'), ((2333, 2349), 'numpy.power', 'np.power', (['X', '(3.0)'], {}), '(X, 3.0)\n', (2341, 2349), True, 'import numpy as np\n'), ((2358, 2380), 'numpy.power', 'np.power', (['(0.5 + X)', '(2.0)'], {}), '(0.5 + X, 2.0)\n', (2366, 2380), True, 'import numpy as np\n'), ((4118, 4130), 'numpy.floor', 'np.floor', (['x1'], {}), '(x1)\n', (4126, 4130), True, 'import numpy as np\n')]
""" 2-layer controller. """ from aw_nas import utils, assert_rollout_type from aw_nas.utils import DistributedDataParallel from aw_nas.controller.base import BaseController from aw_nas.btcs.layer2.search_space import ( Layer2Rollout, Layer2DiffRollout, DenseMicroRollout, DenseMicroDiffRollout, StagewiseMacroRollout, StagewiseMacroDiffRollout, SinkConnectMacroDiffRollout, ) from collections import OrderedDict import numpy as np import os import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim try: # from torch.nn.SyncBatchNorm import convert_sync_batch_norm as convert_sync_bn from torch.nn import SyncBatchNorm convert_sync_bn = SyncBatchNorm.convert_sync_batchnorm except ImportError: convert_sync_bn = lambda m: m class Layer2Optimizer(optim.Optimizer): def __init__(self, params, **opt_cfg): super(Layer2Optimizer, self).__init__([torch.tensor([])], defaults={}) macro_opt_type = opt_cfg["macro"].pop("type") micro_opt_type = opt_cfg["micro"].pop("type") # currently width alphas & macro-alpha share the same optimizer self.macro_optimizer = getattr(optim, macro_opt_type)( nn.ParameterList(params[0:2]), **opt_cfg["macro"] ) # after adding width-alphas, as 2nd self.micro_optimizer = getattr(optim, micro_opt_type)( nn.ParameterList(params[2:]), **opt_cfg["micro"] ) def step(self): self.macro_optimizer.step() self.micro_optimizer.step() torch.optim.layer2 = Layer2Optimizer # add patch the torch optim class Layer2DiffController(BaseController, nn.Module): NAME = "layer2-differentiable" def __init__( self, search_space, rollout_type, mode="eval", device="cuda", macro_controller_type="random_sample", macro_controller_cfg={}, micro_controller_type="random_sample", micro_controller_cfg={}, inspect_hessian_every=-1, save_alphas_every=-1, multiprocess=False, schedule_cfg=None, ): super(Layer2DiffController, self).__init__( search_space, rollout_type, schedule_cfg=schedule_cfg ) nn.Module.__init__(self) self.search_space = search_space self.rollout_type = rollout_type self.device = device self.to(self.device) self.inspect_hessian_every = inspect_hessian_every self.inspect_hessian = False self.save_alphas_every = save_alphas_every self.save_alphas = False self.saved_dict = { "macro": [], "micro": [], "width": [], } self.multiprocess = multiprocess # the macro/micro controllers if macro_controller_type == "macro-stagewise-diff": self.macro_controller = MacroStagewiseDiffController( self.search_space.macro_search_space, macro_controller_type, device=self.device, multiprocess=self.multiprocess, **macro_controller_cfg, ) elif macro_controller_type == "macro-sink-connect-diff": self.macro_controller = MacroSinkConnectDiffController( self.search_space.macro_search_space, macro_controller_type, device=self.device, multiprocess=self.multiprocess, **macro_controller_cfg, ) else: raise NotImplementedError() if micro_controller_type == "micro-dense-diff": self.micro_controller = MicroDenseDiffController( self.search_space.micro_search_space, micro_controller_type, device=self.device, multiprocess=self.multiprocess, **micro_controller_cfg, ) else: raise NotImplementedError() object.__setattr__(self, "parallel_model", self) self._parallelize() def _parallelize(self): if self.multiprocess: net = convert_sync_bn(self).to(self.device) object.__setattr__( self, "parallel_model", DistributedDataParallel( self, (self.device,), find_unused_parameters=True ), ) def on_epoch_start(self, epoch): super(Layer2DiffController, self).on_epoch_start(epoch) if self.inspect_hessian_every >= 0 and epoch % self.inspect_hessian_every == 0: self.inspect_hessian = True if self.save_alphas_every >= 0 and epoch % self.save_alphas_every == 0: self.save_alphas = True # save alphas every epoch if self.save_alphas: self.saved_dict["macro"].append( [alpha.data.cpu() for alpha in self.macro_controller.cg_alphas] ) self.saved_dict["micro"].append( [alpha.data.cpu() for alpha in self.micro_controller.cg_alphas] ) self.saved_dict["width"].append( [ width_alpha.cpu() for width_alpha in self.macro_controller.width_alphas ] ) self.macro_controller.on_epoch_start(epoch) self.micro_controller.on_epoch_start(epoch) def set_device(self, device): self.device = device self.to(device) def set_mode(self, mode): super(Layer2DiffController, self).set_mode(mode) if mode == "train": nn.Module.train(self) elif mode == "eval": nn.Module.eval(self) else: raise Exception("Unrecognized mode: {}".format(mode)) def parameters(self, recurse=False): # FIXME: normal nn.module.parameters() use recurse=True to acquire all params param_list = nn.ParameterList([]) param_list.extend(self.macro_controller.parameters()) param_list.extend(self.micro_controller.parameters()) return param_list def _entropy_loss(self): return ( self.macro_controller._entropy_loss() + self.micro_controller._entropy_loss() ) def sample(self, n=1, batch_size=1): if self.multiprocess: return self.parallel_model.forward(n=n, batch_size=batch_size) else: return self.forward(n=n, batch_size=batch_size) def forward(self, n=1, batch_size=1): rollouts = [] macro_rollouts = self.macro_controller.forward(n=n, batch_size=batch_size) micro_rollouts = self.micro_controller.forward(n=n, batch_size=batch_size) for i in range(n): rollouts.append( Layer2DiffRollout( macro_rollouts[i], micro_rollouts[i], self.search_space ) ) return rollouts def gradient(self, loss, return_grads=True, zero_grads=True): if zero_grads: self.zero_grad() if self.inspect_hessian: for name, param in self.named_parameters(): max_eig = utils.torch_utils.max_eig_of_hessian(loss, param) self.logger.info("Max eigenvalue of Hessian of %s: %f", name, max_eig) _loss = loss + self._entropy_loss() _loss.backward() if return_grads: return utils.get_numpy(_loss), [ (k, v.grad.clone()) for k, v in self.named_parameters() ] return utils.get_numpy(_loss) def step_current_gradient(self, optimizer): self.macro_controller.step_current_gradient(optimizer.macro_optimizer) self.micro_controller.step_current_gradient(optimizer.micro_optimizer) def step_gradient(self, gradients, optimizer): self.macro_controller.step_gradient(gradients[0], optimizer.macro_optimizer) self.micro_controller.step_gradient(gradients[1], optimizer.micro_optimizer) def step(self, rollouts, optimizer, perf_name): macro_rollouts = [r.macro for r in rollouts] micro_rollouts = [r.micro for r in rollouts] macro_loss = self.macro_controller.step( macro_rollouts, optimizer.macro_optimizer, perf_name ) micro_loss = self.micro_controller.step( micro_rollouts, optimizer.micro_optimizer, perf_name ) return macro_loss, micro_loss def summary(self, rollouts, log=False, log_prefix="", step=None): macro_rollouts = [r.macro for r in rollouts] micro_rollouts = [r.micro for r in rollouts] self.macro_controller.summary( macro_rollouts, log=log, log_prefix=log_prefix, step=None ) self.micro_controller.summary( micro_rollouts, log=log, log_prefix=log_prefix, step=None ) def save(self, path): """Save the parameters to disk.""" torch.save({"epoch": self.epoch, "state_dict": self.state_dict()}, path) self.logger.info("Saved controller network to %s", path) """save alphas""" if self.save_alphas_every is not None: # os.path.dirname means the parent path of the `PATH` torch.save( self.saved_dict, os.path.join(os.path.dirname(os.path.dirname(path)), "alphas.pth"), ) def load(self, path): """Load the parameters from disk.""" checkpoint = torch.load(path, map_location=torch.device("cpu")) self.load_state_dict(checkpoint["state_dict"]) self.on_epoch_start(checkpoint["epoch"]) self.logger.info("Loaded controller network from %s", path) # since the layer2controller.parameters() is a list of [macro_parameters(), micro_parameters()], we need to override the zero_grad() since it used model.parameters() def zero_grad(self): for param in self.parameters(): for p in param: if p.grad is not None: p.grad.detach_() p.grad.zero_() @classmethod def supported_rollout_types(cls): return ["layer2", "layer2-differentiable"] class GetArchMacro(torch.autograd.Function): @staticmethod def forward( ctx, search_space, op_weights, device, i_stage, ): stage_conn = torch.zeros( ( search_space.stage_node_nums[i_stage], search_space.stage_node_nums[i_stage], ) ).to(device) stage_conn[search_space.idxes[i_stage]] = op_weights ctx.save_for_backward( torch.as_tensor(op_weights), torch.as_tensor(search_space.idxes[i_stage]) ) return stage_conn @staticmethod def backward(ctx, grad_output): op_weights, idxes = ctx.saved_tensors op_weights_grad = grad_output[idxes[0], idxes[1]] return None, op_weights_grad, None, None, None class MacroStagewiseDiffController(BaseController, nn.Module): NAME = "macro-stagewise-diff" SCHEDULABLE_ATTRS = [ "gumbel_temperature", "entropy_coeff", "force_uniform", "width_gumbel_temperature", "width_entropy_coeff", ] def __init__( self, search_space, rollout_type, mode="eval", device="cuda", use_prob=False, gumbel_hard=False, gumbel_temperature=1.0, use_sigmoid=False, use_edge_normalization=False, entropy_coeff=0.01, max_grad_norm=None, force_uniform=False, full_init=False, # use all-one initialization and big flops reg progressive_pruning_th=None, multiprocess=False, per_stage_width=True, # default use per stage width width_entropy_coeff=0.01, width_gumbel_temperature=1.0, schedule_cfg=None, ): super(MacroStagewiseDiffController, self).__init__( search_space, rollout_type, schedule_cfg=schedule_cfg ) nn.Module.__init__(self) self.device = device # sampling self.use_prob = use_prob self.gumbel_hard = gumbel_hard self.gumbel_temperature = gumbel_temperature self.use_sigmoid = use_sigmoid # use_prob / use_sigmoid should not the True at the same time # if both false use plain gumbel softmax assert not (use_prob and use_sigmoid) # edge normalization self.use_edge_normalization = use_edge_normalization # training self.entropy_coeff = entropy_coeff self.max_grad_norm = max_grad_norm self.force_uniform = force_uniform self.progressive_pruning_th = progressive_pruning_th self.width_choice = self.search_space.width_choice self.multiprocess = multiprocess self.per_stage_width = per_stage_width self.width_gumbel_temperature = width_gumbel_temperature self.width_entropy_coeff = width_entropy_coeff # generate parameters self.full_init = full_init if not self.full_init: init_value = 1.0e-3 else: init_value = 1.0 self.cg_alphas = nn.ParameterList( [ nn.Parameter( init_value * torch.randn(sum(self.search_space.num_possible_edges)) ) ] ) # width choices [#cells , #width_choice] if self.width_choice is not None: if not self.per_stage_width: self.width_alphas = nn.ParameterList( [ nn.Parameter( init_value * torch.randn( len(self.search_space.cell_layout), len(self.width_choice), ) ) ] ) else: self.width_alphas = nn.ParameterList( [ nn.Parameter( init_value * torch.randn( len(self.search_space.stage_node_nums), len(self.width_choice), ) ) ] ) self.stage_num_alphas = ( self.search_space.num_possible_edges ) # used for competible with sink-connecting ss if self.use_edge_normalization: raise NotImplementedError("MacroDiffController does not support edge-norm") else: self.cg_betas = None self.get_arch = GetArchMacro() self.to(self.device) def set_mode(self, mode): super(MacroStagewiseDiffController, self).set_mode(mode) if mode == "train": nn.Module.train(self) elif mode == "eval": nn.Module.eval(self) else: raise Exception("Unrecognized mode: {}".format(mode)) def set_device(self, device): self.device = device self.to(device) def progressive_pruning(self): for alpha in self.cg_alphas: # inpalce replace alphas that smaller than the pruning threshold, no grad alpha.data = alpha * (alpha.gt(self.progressive_pruning_th).float()) def forward(self, n=1, batch_size=1): return self.sample(n=n, batch_size=batch_size) def sample(self, n=1, batch_size=1): if self.progressive_pruning_th is not None: self.progressive_pruning() width_arch, width_logits = self.sample_width(n=n, batch_size=batch_size) rollouts = [] for i_sample in range(n): # op_weights.shape: [num_edges, [batch_size,] num_ops] # edge_norms.shape: [num_edges] do not have batch_size. op_weights_list = [] edge_norms_list = [] sampled_list = [] logits_list = [] for alphas in self.cg_alphas: if ( self.progressive_pruning_th is not None and self.progressive_pruning_th > 0 ): alphas = alphas.clamp(self.progressive_pruning_th, 1.0e4) else: pass if self.force_uniform: # cg_alpha parameters will not be in the graph # NOTE: `force_uniform` config does not affects edge_norms (betas), # if one wants a force_uniform search, keep `use_edge_normalization=False` alphas = torch.zeros_like(alphas) if batch_size > 1: expanded_alpha = ( alphas.reshape([alphas.shape[0], 1, alphas.shape[1]]) .repeat([1, batch_size, 1]) .reshape([-1, alphas.shape[-1]]) ) else: expanded_alpha = alphas if self.use_prob: sampled = F.softmax( expanded_alpha / self.gumbel_temperature, dim=-1 ) elif self.use_sigmoid: sampled = utils.relaxed_bernoulli_sample( expanded_alpha, self.gumbel_temperature ) else: # gumbel sampling sampled, _ = utils.gumbel_softmax( expanded_alpha, self.gumbel_temperature, hard=False ) if self.gumbel_hard: op_weights = utils.straight_through(sampled) else: op_weights = sampled if batch_size > 1: sampled = sampled.reshape([-1, batch_size, op_weights.shape[-1]]) op_weights = op_weights.reshape( [-1, batch_size, op_weights.shape[-1]] ) op_weights_list.append(op_weights) sampled_list.append(utils.get_numpy(sampled)) # logits_list.append(utils.get_numpy(alphas)) logits_list.append(alphas) stage_conns = [] split_op_weights = torch.split(op_weights, self.stage_num_alphas) for i_stage in range(self.search_space.stage_num): stage_conn = self.get_arch.apply( self.search_space, split_op_weights[i_stage], self.device, i_stage, ) stage_conns.append(stage_conn) rollouts.append( StagewiseMacroDiffRollout( arch=stage_conns, sampled=sampled_list, logits=logits_list, width_arch=width_arch[i_sample], width_logits=width_logits[i_sample], search_space=self.search_space, ) ) return rollouts def sample_width(self, n=1, batch_size=1): assert batch_size == 1, "sample_width should not have batch size > 1" width_sampled_list = [] width_logits_list = [] width_op_weights_list = [] for _ in range(n): # sample the width alphas for width_alphas in self.width_alphas: if self.force_uniform: # cg_alpha parameters will not be in the graph # NOTE: `force_uniform` config does not affects edge_norms (betas), # if one wants a force_uniform search, keep `use_edge_normalization=False` width_alphas = torch.zeros_like(width_alphas) if batch_size > 1: expanded_width_alpha = ( width_alphas.reshape( [width_alphas.shape[0], 1, width_alphas.shape[1]] ) .repeat([1, batch_size, 1]) .reshape([-1, width_alphas.shape[-1]]) ) else: expanded_width_alpha = width_alphas if self.use_prob: width_sampled = F.softmax( expanded_width_alpha / self.width_gumbel_temperature, dim=-1 ) elif self.use_sigmoid: width_sampled = utils.relaxed_bernoulli_sample( expanded_width_alpha, self.width_gumbel_temperature ) else: # gumbel sampling width_sampled, _ = utils.gumbel_softmax( expanded_width_alpha, self.width_gumbel_temperature, hard=False ) if self.gumbel_hard: width_op_weights = utils.straight_through(width_sampled) else: width_op_weights = width_sampled if batch_size > 1: width_sampled = width_sampled.reshape( [-1, batch_size, width_op_weights.shape[-1]] ) width_op_weights = width_op_weights.reshape( [-1, batch_size, width_op_weights.shape[-1]] ) if not self.per_stage_width: width_op_weights_full = width_op_weights width_sampled_full = width_sampled width_alphas_full = width_alphas else: # the last stage has one more node node_list = self.search_space.stage_node_nums.copy() # let the 1st stage num_node -1 # to let all reduction cell uses the width-alphas of next stage node_list[0] = node_list[0] - 1 width_op_weights_full = torch.cat( [ width_op_weights[idx_stage].repeat(num_nodes - 1, 1) for idx_stage, num_nodes in enumerate(node_list) ] ) width_sampled_full = torch.cat( [ width_sampled[idx_stage].repeat(num_nodes - 1, 1) for idx_stage, num_nodes in enumerate(node_list) ] ) width_alphas_full = torch.cat( [ width_alphas[idx_stage].repeat(num_nodes - 1, 1) for idx_stage, num_nodes in enumerate(node_list) ] ) width_op_weights_list.append(width_op_weights_full) width_sampled_list.append(utils.get_numpy(width_sampled_full)) # logits_list.append(utils.get_numpy(alphas)) width_logits_list.append(width_alphas_full) return width_op_weights_list, width_logits_list def save(self, path): """Save the parameters to disk.""" torch.save({"epoch": self.epoch, "state_dict": self.state_dict()}, path) self.logger.info("Saved controller network to %s", path) def load(self, path): """Load the parameters from disk.""" checkpoint = torch.load(path, map_location=torch.device("cpu")) self.load_state_dict(checkpoint["state_dict"]) self.on_epoch_start(checkpoint["epoch"]) self.logger.info("Loaded controller network from %s", path) def _entropy_loss(self): ent_loss = 0.0 if self.entropy_coeff > 0: alphas = self.cg_alphas[0].split( [i - 1 for i in self.search_space.stage_node_nums] ) probs = [F.softmax(alpha, dim=-1) for alpha in self.cg_alphas] ent_loss = ( self.entropy_coeff * sum(-(torch.log(prob) * prob).sum() for prob in probs) + ent_loss ) if self.width_entropy_coeff > 0: width_alphas = self.width_alphas probs = [F.softmax(alpha, dim=-1) for alpha in self.width_alphas] ent_loss = ( self.width_entropy_coeff * sum(-(torch.log(prob) * prob).sum() for prob in probs) + ent_loss ) return ent_loss def gradient(self, loss, return_grads=True, zero_grads=True): raise NotImplementedError( "the grad function is implemented in the layer2diffcontroller.gradient()" ) def step_current_gradient(self, optimizer): if self.max_grad_norm is not None: torch.nn.utils.clip_grad_norm_(self.parameters(), self.max_grad_norm) optimizer.step() def step_gradient(self, gradients, optimizer): self.zero_grad() named_params = dict(self.named_parameters()) for k, grad in gradients: named_params[k].grad = grad # clip the gradients if self.max_grad_norm is not None: torch.nn.utils.clip_grad_norm_(self.parameters(), self.max_grad_norm) # apply the gradients optimizer.step() def step(self, rollouts, optimizer, perf_name): # very memory inefficient self.zero_grad() losses = [r.get_perf(perf_name) for r in rollouts] optimizer.step() [l.backward() for l in losses] return np.mean([l.detach().cpu().numpy() for l in losses]) def __getstate__(self): state = super(MacroStagewiseDiffController, self).__getstate__().copy() del state["get_arch"] return state def __setstate__(self, state): super(MacroStagewiseDiffController, self).__setstate__(state) self.get_arch = GetArchMacro() def summary(self, rollouts, log=False, log_prefix="", step=None): num = len(rollouts) logits_list = [ [utils.get_numpy(logits) for logits in r.logits] for r in rollouts ] _ss = self.search_space if self.gumbel_hard: cg_logprobs = [0.0 for _ in range(_ss.num_cell_groups)] cg_entros = [0.0 for _ in range(_ss.num_cell_groups)] for rollout, logits in zip(rollouts, logits_list): for cg_idx, (vec, cg_logits) in enumerate(zip(rollout.arch, logits)): prob = utils.softmax(cg_logits) logprob = np.log(prob) if self.gumbel_hard: inds = np.argmax(utils.get_numpy(vec.op_weights), axis=-1) cg_logprobs[cg_idx] += np.sum(logprob[range(len(inds)), inds]) cg_entros[cg_idx] += -(prob * logprob).sum() # mean across rollouts if self.gumbel_hard: cg_logprobs = [s / num for s in cg_logprobs] total_logprob = sum(cg_logprobs) cg_logprobs_str = ",".join(["{:.2f}".format(n) for n in cg_logprobs]) cg_entros = [s / num for s in cg_entros] total_entro = sum(cg_entros) cg_entro_str = ",".join(["{:.2f}".format(n) for n in cg_entros]) if log: # maybe log the summary self.logger.info( "%s%d rollouts: %s ENTROPY: %2f (%s)", log_prefix, num, "-LOG_PROB: %.2f (%s) ;" % (-total_logprob, cg_logprobs_str) if self.gumbel_hard else "", total_entro, cg_entro_str, ) if step is not None and not self.writer.is_none(): if self.gumbel_hard: self.writer.add_scalar("log_prob", total_logprob, step) self.writer.add_scalar("entropy", total_entro, step) stats = [ (n + " ENTRO", entro) for n, entro in zip(_ss.cell_group_names, cg_entros) ] if self.gumbel_hard: stats += [ (n + " LOGPROB", logprob) for n, logprob in zip(_ss.cell_group_names, cg_logprobs) ] return OrderedDict(stats) @classmethod def supported_rollout_types(cls): return ["macro-stagewise", "macro-stagewise-diff", "macro-sink-connect-diff"] class GetArchMacroSinkConnect(torch.autograd.Function): @staticmethod def forward( ctx, search_space, op_weights, device, i_stage, ): stage_conn = torch.zeros( ( search_space.stage_node_nums[i_stage], search_space.stage_node_nums[i_stage], ) ).to(device) stage_conn[np.arange(len(op_weights)) + 1, np.arange(len(op_weights))] = 1 stage_conn[-1, : len(op_weights)] = op_weights ctx.save_for_backward( torch.as_tensor(op_weights), torch.as_tensor(search_space.idxes[i_stage]) ) return stage_conn @staticmethod def backward(ctx, grad_output): op_weights, idxes = ctx.saved_tensors op_weights_grad = grad_output[-1, : len(op_weights)] return None, op_weights_grad, None, None, None class MacroSinkConnectDiffController(MacroStagewiseDiffController): NAME = "macro-sink-connect-diff" # The TF_NAS-like macro search space(sink-based connecting) # during each stage, before the reduction node, a `sinking point` aggregate the output of each node's output with softmax # noted that cg-alpha here should denote whether connected or not def __init__(self, *args, **kwargs): super(MacroSinkConnectDiffController, self).__init__(*args, **kwargs) if not self.full_init: self.cg_alphas = nn.ParameterList( [ nn.Parameter( 1e-3 * torch.randn( sum([n - 1 for n in self.search_space.stage_node_nums]) ) ) ] ) else: self.cg_alphas = nn.ParameterList( [ nn.Parameter( torch.ones( sum([n - 1 for n in self.search_space.stage_node_nums]) ) ) ] ) assert ( self.use_sigmoid == False ) # sink-connecting should introduce competition in edges self.get_arch = GetArchMacroSinkConnect() self.stage_num_alphas = [n - 1 for n in self.search_space.stage_node_nums] self.to(self.device) # move the newly generated cg_alphas to cuda # The only difference with MacroStageWiseDiffController's sample is that the arch is packed into `sink-connect-diff-rollout` def sample(self, n=1, batch_size=1): # if use progressive pruning if self.progressive_pruning_th is not None: self.progressive_pruning() width_arch, width_logits = self.sample_width(n=n, batch_size=batch_size) rollouts = [] for i_sample in range(n): # op_weights.shape: [num_edges, [batch_size,] num_ops] # edge_norms.shape: [num_edges] do not have batch_size. op_weights_list = [] edge_norms_list = [] sampled_list = [] logits_list = [] for alphas in self.cg_alphas: splits = [i - 1 for i in self.search_space.stage_node_nums] op_weights = [] sampleds = [] for alpha in alphas.split(splits): if ( self.force_uniform ): # cg_alpha parameters will not be in the graph # NOTE: `force_uniform` config does not affects edge_norms (betas), # if one wants a force_uniform search, keep `use_edge_normalization=False` alpha = torch.zeros_like(alpha) if batch_size > 1: expanded_alpha = ( alpha.reshape([alpha.shape[0], 1, alpha.shape[1]]) .repeat([1, batch_size, 1]) .reshape([-1, alpha.shape[-1]]) ) else: expanded_alpha = alpha if self.use_prob: sampled = F.softmax( expanded_alpha / self.gumbel_temperature, dim=-1 ) elif self.use_sigmoid: sampled = utils.relaxed_bernoulli_sample( expanded_alpha, self.gumbel_temperature ) else: # gumbel sampling sampled, _ = utils.gumbel_softmax( expanded_alpha, self.gumbel_temperature, hard=False ) if self.gumbel_hard: op_weight = utils.straight_through(sampled) else: op_weight = sampled if batch_size > 1: sampled = sampled.reshape([-1, batch_size, op_weight.shape[-1]]) op_weight = op_weight.reshape( [-1, batch_size, op_weight.shape[-1]] ) op_weights.append(op_weight) sampleds.append(sampled) op_weights = torch.cat(op_weights) sampleds = torch.cat(sampleds) op_weights_list.append(op_weights) sampled_list.append(utils.get_numpy(sampleds)) logits_list.append(alphas) stage_conns = [] split_op_weights = torch.split(op_weights, self.stage_num_alphas) for i_stage in range(self.search_space.stage_num): stage_conn = self.get_arch.apply( self.search_space, split_op_weights[i_stage], self.device, i_stage, ) stage_conns.append(stage_conn) rollouts.append( SinkConnectMacroDiffRollout( arch=stage_conns, sampled=sampled_list, logits=logits_list, width_arch=width_arch[i_sample], width_logits=width_logits[i_sample], search_space=self.search_space, ) ) return rollouts def __setstate__(self, state): super(MacroSinkConnectDiffController, self).__setstate__(state) self.get_arch = GetArchMacroSinkConnect() class GetArchMicro(torch.autograd.Function): @staticmethod def forward(ctx, search_space, op_weights, device): empty_arch = torch.zeros( ( search_space._num_nodes, search_space._num_nodes, search_space.num_op_choices, ) ).to(device) empty_arch[search_space.idx] = op_weights ctx.save_for_backward( torch.as_tensor(op_weights), torch.as_tensor(search_space.idx) ) return empty_arch @staticmethod def backward(ctx, grad_output): op_weights, idxes = ctx.saved_tensors op_weights_grad = grad_output[idxes[0], idxes[1]] return None, op_weights_grad, None class MicroDenseDiffController(BaseController, nn.Module): NAME = "micro-dense-diff" SCHEDULABLE_ATTRS = ["gumbel_temperature", "entropy_coeff", "force_uniform"] def __init__( self, search_space, rollout_type, mode="eval", device="cuda", use_prob=False, gumbel_hard=False, gumbel_temperature=1.0, use_sigmoid=True, use_edge_normalization=False, entropy_coeff=0.01, max_grad_norm=None, force_uniform=False, full_init=False, progressive_pruning_th=None, multiprocess=False, schedule_cfg=None, ): super(MicroDenseDiffController, self).__init__( search_space, rollout_type, schedule_cfg=schedule_cfg ) nn.Module.__init__(self) self.device = device # sampling self.use_prob = use_prob self.use_sigmoid = use_sigmoid self.gumbel_hard = gumbel_hard self.gumbel_temperature = gumbel_temperature assert not (use_prob and use_sigmoid) # edge normalization self.use_edge_normalization = use_edge_normalization # training self.entropy_coeff = entropy_coeff self.max_grad_norm = max_grad_norm self.force_uniform = force_uniform self.full_init = full_init self.progressive_pruning_th = progressive_pruning_th self.multiprocess = multiprocess _num_init_nodes = self.search_space.num_init_nodes _num_edges_list = [ sum( _num_init_nodes + i for i in range(self.search_space.get_num_steps(i_cg)) ) for i_cg in range(self.search_space.num_cell_groups) ] if not self.full_init: self.cg_alphas = nn.ParameterList( [ nn.Parameter( 1e-3 * torch.randn( _num_edges, len(self.search_space.cell_shared_primitives[i_cg]), ) ) # shape: [num_edges, num_ops] for i_cg, _num_edges in enumerate(_num_edges_list) ] ) else: self.cg_alphas = nn.ParameterList( [ nn.Parameter( 1 * torch.ones( _num_edges, len(self.search_space.cell_shared_primitives[i_cg]), ) ) # shape: [num_edges, num_ops] for i_cg, _num_edges in enumerate(_num_edges_list) ] ) if self.use_edge_normalization: raise NotImplementedError("MicroDenseController does not support edge-norm") else: self.cg_betas = None self.get_arch = GetArchMicro() self.to(self.device) def set_mode(self, mode): super(MicroDenseDiffController, self).set_mode(mode) if mode == "train": nn.Module.train(self) elif mode == "eval": nn.Module.eval(self) else: raise Exception("Unrecognized mode: {}".format(mode)) def set_device(self, device): self.device = device self.to(device) def progressive_pruning(self): for alpha in self.cg_alphas: # inpalce replace alphas that smaller than the pruning threshold, no grad alpha.data = alpha * (alpha.gt(self.progressive_pruning_th).float()) def forward(self, n=1, batch_size=1): # pylint: disable=arguments-differ return self.sample(n=n, batch_size=batch_size) def sample(self, n=1, batch_size=1): if self.progressive_pruning_th is not None: self.progressive_pruning() rollouts = [] for _ in range(n): # op_weights.shape: [num_edges, [batch_size,] num_ops] # edge_norms.shape: [num_edges] do not have batch_size. op_weights_list = [] edge_norms_list = [] sampled_list = [] logits_list = [] for alphas in self.cg_alphas: if self.force_uniform: # cg_alpha parameters will not be in the graph # NOTE: `force_uniform` config does not affects edge_norms (betas), # if one wants a force_uniform search, keep `use_edge_normalization=False` alphas = torch.zeros_like(alphas) if batch_size > 1: expanded_alpha = ( alphas.reshape([alphas.shape[0], 1, alphas.shape[1]]) .repeat([1, batch_size, 1]) .reshape([-1, alphas.shape[-1]]) ) else: expanded_alpha = alphas if self.use_prob: # probability as sample sampled = F.softmax( expanded_alpha / self.gumbel_temperature, dim=-1 ) elif self.use_sigmoid: sampled = utils.relaxed_bernoulli_sample( expanded_alpha, self.gumbel_temperature ) else: # gumbel sampling sampled, _ = utils.gumbel_softmax( expanded_alpha, self.gumbel_temperature, hard=False ) if self.gumbel_hard: op_weights = utils.straight_through(sampled) else: op_weights = sampled if batch_size > 1: sampled = sampled.reshape([-1, batch_size, op_weights.shape[-1]]) op_weights = op_weights.reshape( [-1, batch_size, op_weights.shape[-1]] ) op_weights_list.append(op_weights) sampled_list.append(utils.get_numpy(sampled)) # logits_list.append(utils.get_numpy(alphas)) logits_list.append((alphas)) if self.use_edge_normalization: raise NotImplementedError else: arch_list = [] logits_arch_list = [] for op_weights in op_weights_list: arch = self.get_arch.apply( self.search_space, op_weights, self.device ) arch_list.append(arch) for logits in logits_list: logits_arch = self.get_arch.apply( self.search_space, logits, self.device ) logits_arch_list.append(logits_arch) rollouts.append( DenseMicroDiffRollout( arch_list, sampled_list, logits_list, logits_arch_list, search_space=self.search_space, ) ) return rollouts def save(self, path): """Save the parameters to disk.""" torch.save({"epoch": self.epoch, "state_dict": self.state_dict()}, path) self.logger.info("Saved controller network to %s", path) def load(self, path): """Load the parameters from disk.""" checkpoint = torch.load(path, map_location=torch.device("cpu")) self.load_state_dict(checkpoint["state_dict"]) self.on_epoch_start(checkpoint["epoch"]) self.logger.info("Loaded controller network from %s", path) def _entropy_loss(self): if self.entropy_coeff > 0: probs = [F.softmax(alpha, dim=-1) for alpha in self.cg_alphas] return self.entropy_coeff * sum( -(torch.log(prob) * prob).sum() for prob in probs ) return 0.0 def gradient(self, loss, return_grads=True, zero_grads=True): raise NotImplementedError( "the grad function is implemented in the layer2diffcontroller.gradient()" ) def step_current_gradient(self, optimizer): if self.max_grad_norm is not None: torch.nn.utils.clip_grad_norm_(self.parameters(), self.max_grad_norm) optimizer.step() def step_gradient(self, gradients, optimizer): self.zero_grad() named_params = dict(self.named_parameters()) for k, grad in gradients: named_params[k].grad = grad # clip the gradients if self.max_grad_norm is not None: torch.nn.utils.clip_grad_norm_(self.parameters(), self.max_grad_norm) # apply the gradients optimizer.step() def step(self, rollouts, optimizer, perf_name): # very memory inefficient self.zero_grad() losses = [r.get_perf(perf_name) for r in rollouts] optimizer.step() [l.backward() for l in losses] return np.mean([l.detach().cpu().numpy() for l in losses]) def __getstate__(self): state = super(MicroDenseDiffController, self).__getstate__().copy() del state["get_arch"] return state def __setstate__(self, state): super(MicroDenseDiffController, self).__setstate__(state) self.get_arch = GetArchMicro() def summary(self, rollouts, log=False, log_prefix="", step=None): num = len(rollouts) logits_list = [ [utils.get_numpy(logits) for logits in r.logits] for r in rollouts ] _ss = self.search_space if self.gumbel_hard: cg_logprobs = [0.0 for _ in range(_ss.num_cell_groups)] cg_entros = [0.0 for _ in range(_ss.num_cell_groups)] for rollout, logits in zip(rollouts, logits_list): for cg_idx, (vec, cg_logits) in enumerate(zip(rollout.arch, logits)): prob = utils.softmax(cg_logits) logprob = np.log(prob) if self.gumbel_hard: inds = np.argmax(utils.get_numpy(vec), axis=-1) cg_logprobs[cg_idx] += np.sum(logprob[range(len(inds)), inds]) cg_entros[cg_idx] += -(prob * logprob).sum() # mean across rollouts if self.gumbel_hard: cg_logprobs = [s / num for s in cg_logprobs] total_logprob = sum(cg_logprobs) cg_logprobs_str = ",".join(["{:.2f}".format(n) for n in cg_logprobs]) cg_entros = [s / num for s in cg_entros] total_entro = sum(cg_entros) cg_entro_str = ",".join(["{:.2f}".format(n) for n in cg_entros]) if log: # maybe log the summary self.logger.info( "%s%d rollouts: %s ENTROPY: %2f (%s)", log_prefix, num, "-LOG_PROB: %.2f (%s) ;" % (-total_logprob, cg_logprobs_str) if self.gumbel_hard else "", total_entro, cg_entro_str, ) if step is not None and not self.writer.is_none(): if self.gumbel_hard: self.writer.add_scalar("log_prob", total_logprob, step) self.writer.add_scalar("entropy", total_entro, step) stats = [ (n + " ENTRO", entro) for n, entro in zip(_ss.cell_group_names, cg_entros) ] if self.gumbel_hard: stats += [ (n + " LOGPROB", logprob) for n, logprob in zip(_ss.cell_group_names, cg_logprobs) ] return OrderedDict(stats) @classmethod def supported_rollout_types(cls): return ["micro-dense", "micro-dense-diff"]
[ "aw_nas.utils.gumbel_softmax", "aw_nas.utils.get_numpy", "torch.cat", "torch.device", "aw_nas.btcs.layer2.search_space.SinkConnectMacroDiffRollout", "aw_nas.btcs.layer2.search_space.Layer2DiffRollout", "aw_nas.utils.torch_utils.max_eig_of_hessian", "os.path.dirname", "torch.nn.ParameterList", "torch.zeros", "torch.log", "torch.zeros_like", "torch.split", "torch.nn.Module.__init__", "aw_nas.utils.softmax", "torch.nn.Module.eval", "aw_nas.utils.relaxed_bernoulli_sample", "torch.nn.Module.train", "numpy.log", "aw_nas.btcs.layer2.search_space.StagewiseMacroDiffRollout", "aw_nas.utils.DistributedDataParallel", "torch.nn.functional.softmax", "aw_nas.utils.straight_through", "aw_nas.btcs.layer2.search_space.DenseMicroDiffRollout", "collections.OrderedDict", "torch.as_tensor", "torch.tensor" ]
[((2257, 2281), 'torch.nn.Module.__init__', 'nn.Module.__init__', (['self'], {}), '(self)\n', (2275, 2281), True, 'import torch.nn as nn\n'), ((5941, 5961), 'torch.nn.ParameterList', 'nn.ParameterList', (['[]'], {}), '([])\n', (5957, 5961), True, 'import torch.nn as nn\n'), ((7560, 7582), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['_loss'], {}), '(_loss)\n', (7575, 7582), False, 'from aw_nas import utils, assert_rollout_type\n'), ((12062, 12086), 'torch.nn.Module.__init__', 'nn.Module.__init__', (['self'], {}), '(self)\n', (12080, 12086), True, 'import torch.nn as nn\n'), ((28177, 28195), 'collections.OrderedDict', 'OrderedDict', (['stats'], {}), '(stats)\n', (28188, 28195), False, 'from collections import OrderedDict\n'), ((36406, 36430), 'torch.nn.Module.__init__', 'nn.Module.__init__', (['self'], {}), '(self)\n', (36424, 36430), True, 'import torch.nn as nn\n'), ((47194, 47212), 'collections.OrderedDict', 'OrderedDict', (['stats'], {}), '(stats)\n', (47205, 47212), False, 'from collections import OrderedDict\n'), ((1229, 1258), 'torch.nn.ParameterList', 'nn.ParameterList', (['params[0:2]'], {}), '(params[0:2])\n', (1245, 1258), True, 'import torch.nn as nn\n'), ((1401, 1429), 'torch.nn.ParameterList', 'nn.ParameterList', (['params[2:]'], {}), '(params[2:])\n', (1417, 1429), True, 'import torch.nn as nn\n'), ((5628, 5649), 'torch.nn.Module.train', 'nn.Module.train', (['self'], {}), '(self)\n', (5643, 5649), True, 'import torch.nn as nn\n'), ((10655, 10682), 'torch.as_tensor', 'torch.as_tensor', (['op_weights'], {}), '(op_weights)\n', (10670, 10682), False, 'import torch\n'), ((10684, 10728), 'torch.as_tensor', 'torch.as_tensor', (['search_space.idxes[i_stage]'], {}), '(search_space.idxes[i_stage])\n', (10699, 10728), False, 'import torch\n'), ((14935, 14956), 'torch.nn.Module.train', 'nn.Module.train', (['self'], {}), '(self)\n', (14950, 14956), True, 'import torch.nn as nn\n'), ((28900, 28927), 'torch.as_tensor', 'torch.as_tensor', (['op_weights'], {}), '(op_weights)\n', (28915, 28927), False, 'import torch\n'), ((28929, 28973), 'torch.as_tensor', 'torch.as_tensor', (['search_space.idxes[i_stage]'], {}), '(search_space.idxes[i_stage])\n', (28944, 28973), False, 'import torch\n'), ((35315, 35342), 'torch.as_tensor', 'torch.as_tensor', (['op_weights'], {}), '(op_weights)\n', (35330, 35342), False, 'import torch\n'), ((35344, 35377), 'torch.as_tensor', 'torch.as_tensor', (['search_space.idx'], {}), '(search_space.idx)\n', (35359, 35377), False, 'import torch\n'), ((38731, 38752), 'torch.nn.Module.train', 'nn.Module.train', (['self'], {}), '(self)\n', (38746, 38752), True, 'import torch.nn as nn\n'), ((942, 958), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (954, 958), False, 'import torch\n'), ((4283, 4357), 'aw_nas.utils.DistributedDataParallel', 'DistributedDataParallel', (['self', '(self.device,)'], {'find_unused_parameters': '(True)'}), '(self, (self.device,), find_unused_parameters=True)\n', (4306, 4357), False, 'from aw_nas.utils import DistributedDataParallel\n'), ((5691, 5711), 'torch.nn.Module.eval', 'nn.Module.eval', (['self'], {}), '(self)\n', (5705, 5711), True, 'import torch.nn as nn\n'), ((6795, 6869), 'aw_nas.btcs.layer2.search_space.Layer2DiffRollout', 'Layer2DiffRollout', (['macro_rollouts[i]', 'micro_rollouts[i]', 'self.search_space'], {}), '(macro_rollouts[i], micro_rollouts[i], self.search_space)\n', (6812, 6869), False, 'from aw_nas.btcs.layer2.search_space import Layer2Rollout, Layer2DiffRollout, DenseMicroRollout, DenseMicroDiffRollout, StagewiseMacroRollout, StagewiseMacroDiffRollout, SinkConnectMacroDiffRollout\n'), ((7182, 7231), 'aw_nas.utils.torch_utils.max_eig_of_hessian', 'utils.torch_utils.max_eig_of_hessian', (['loss', 'param'], {}), '(loss, param)\n', (7218, 7231), False, 'from aw_nas import utils, assert_rollout_type\n'), ((7433, 7455), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['_loss'], {}), '(_loss)\n', (7448, 7455), False, 'from aw_nas import utils, assert_rollout_type\n'), ((9506, 9525), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (9518, 9525), False, 'import torch\n'), ((10379, 10475), 'torch.zeros', 'torch.zeros', (['(search_space.stage_node_nums[i_stage], search_space.stage_node_nums[i_stage])'], {}), '((search_space.stage_node_nums[i_stage], search_space.\n stage_node_nums[i_stage]))\n', (10390, 10475), False, 'import torch\n'), ((14998, 15018), 'torch.nn.Module.eval', 'nn.Module.eval', (['self'], {}), '(self)\n', (15012, 15018), True, 'import torch.nn as nn\n'), ((18339, 18385), 'torch.split', 'torch.split', (['op_weights', 'self.stage_num_alphas'], {}), '(op_weights, self.stage_num_alphas)\n', (18350, 18385), False, 'import torch\n'), ((18791, 18988), 'aw_nas.btcs.layer2.search_space.StagewiseMacroDiffRollout', 'StagewiseMacroDiffRollout', ([], {'arch': 'stage_conns', 'sampled': 'sampled_list', 'logits': 'logits_list', 'width_arch': 'width_arch[i_sample]', 'width_logits': 'width_logits[i_sample]', 'search_space': 'self.search_space'}), '(arch=stage_conns, sampled=sampled_list, logits=\n logits_list, width_arch=width_arch[i_sample], width_logits=width_logits\n [i_sample], search_space=self.search_space)\n', (18816, 18988), False, 'from aw_nas.btcs.layer2.search_space import Layer2Rollout, Layer2DiffRollout, DenseMicroRollout, DenseMicroDiffRollout, StagewiseMacroRollout, StagewiseMacroDiffRollout, SinkConnectMacroDiffRollout\n'), ((22943, 22978), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['width_sampled_full'], {}), '(width_sampled_full)\n', (22958, 22978), False, 'from aw_nas import utils, assert_rollout_type\n'), ((23490, 23509), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (23502, 23509), False, 'import torch\n'), ((23919, 23943), 'torch.nn.functional.softmax', 'F.softmax', (['alpha'], {'dim': '(-1)'}), '(alpha, dim=-1)\n', (23928, 23943), True, 'import torch.nn.functional as F\n'), ((24254, 24278), 'torch.nn.functional.softmax', 'F.softmax', (['alpha'], {'dim': '(-1)'}), '(alpha, dim=-1)\n', (24263, 24278), True, 'import torch.nn.functional as F\n'), ((26062, 26085), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['logits'], {}), '(logits)\n', (26077, 26085), False, 'from aw_nas import utils, assert_rollout_type\n'), ((26493, 26517), 'aw_nas.utils.softmax', 'utils.softmax', (['cg_logits'], {}), '(cg_logits)\n', (26506, 26517), False, 'from aw_nas import utils, assert_rollout_type\n'), ((26544, 26556), 'numpy.log', 'np.log', (['prob'], {}), '(prob)\n', (26550, 26556), True, 'import numpy as np\n'), ((28547, 28643), 'torch.zeros', 'torch.zeros', (['(search_space.stage_node_nums[i_stage], search_space.stage_node_nums[i_stage])'], {}), '((search_space.stage_node_nums[i_stage], search_space.\n stage_node_nums[i_stage]))\n', (28558, 28643), False, 'import torch\n'), ((33617, 33638), 'torch.cat', 'torch.cat', (['op_weights'], {}), '(op_weights)\n', (33626, 33638), False, 'import torch\n'), ((33666, 33685), 'torch.cat', 'torch.cat', (['sampleds'], {}), '(sampleds)\n', (33675, 33685), False, 'import torch\n'), ((33913, 33959), 'torch.split', 'torch.split', (['op_weights', 'self.stage_num_alphas'], {}), '(op_weights, self.stage_num_alphas)\n', (33924, 33959), False, 'import torch\n'), ((34365, 34564), 'aw_nas.btcs.layer2.search_space.SinkConnectMacroDiffRollout', 'SinkConnectMacroDiffRollout', ([], {'arch': 'stage_conns', 'sampled': 'sampled_list', 'logits': 'logits_list', 'width_arch': 'width_arch[i_sample]', 'width_logits': 'width_logits[i_sample]', 'search_space': 'self.search_space'}), '(arch=stage_conns, sampled=sampled_list, logits=\n logits_list, width_arch=width_arch[i_sample], width_logits=width_logits\n [i_sample], search_space=self.search_space)\n', (34392, 34564), False, 'from aw_nas.btcs.layer2.search_space import Layer2Rollout, Layer2DiffRollout, DenseMicroRollout, DenseMicroDiffRollout, StagewiseMacroRollout, StagewiseMacroDiffRollout, SinkConnectMacroDiffRollout\n'), ((35033, 35130), 'torch.zeros', 'torch.zeros', (['(search_space._num_nodes, search_space._num_nodes, search_space.num_op_choices)'], {}), '((search_space._num_nodes, search_space._num_nodes, search_space\n .num_op_choices))\n', (35044, 35130), False, 'import torch\n'), ((38794, 38814), 'torch.nn.Module.eval', 'nn.Module.eval', (['self'], {}), '(self)\n', (38808, 38814), True, 'import torch.nn as nn\n'), ((42469, 42582), 'aw_nas.btcs.layer2.search_space.DenseMicroDiffRollout', 'DenseMicroDiffRollout', (['arch_list', 'sampled_list', 'logits_list', 'logits_arch_list'], {'search_space': 'self.search_space'}), '(arch_list, sampled_list, logits_list,\n logits_arch_list, search_space=self.search_space)\n', (42490, 42582), False, 'from aw_nas.btcs.layer2.search_space import Layer2Rollout, Layer2DiffRollout, DenseMicroRollout, DenseMicroDiffRollout, StagewiseMacroRollout, StagewiseMacroDiffRollout, SinkConnectMacroDiffRollout\n'), ((43075, 43094), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (43087, 43094), False, 'import torch\n'), ((43354, 43378), 'torch.nn.functional.softmax', 'F.softmax', (['alpha'], {'dim': '(-1)'}), '(alpha, dim=-1)\n', (43363, 43378), True, 'import torch.nn.functional as F\n'), ((45090, 45113), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['logits'], {}), '(logits)\n', (45105, 45113), False, 'from aw_nas import utils, assert_rollout_type\n'), ((45521, 45545), 'aw_nas.utils.softmax', 'utils.softmax', (['cg_logits'], {}), '(cg_logits)\n', (45534, 45545), False, 'from aw_nas import utils, assert_rollout_type\n'), ((45572, 45584), 'numpy.log', 'np.log', (['prob'], {}), '(prob)\n', (45578, 45584), True, 'import numpy as np\n'), ((16680, 16704), 'torch.zeros_like', 'torch.zeros_like', (['alphas'], {}), '(alphas)\n', (16696, 16704), False, 'import torch\n'), ((17119, 17178), 'torch.nn.functional.softmax', 'F.softmax', (['(expanded_alpha / self.gumbel_temperature)'], {'dim': '(-1)'}), '(expanded_alpha / self.gumbel_temperature, dim=-1)\n', (17128, 17178), True, 'import torch.nn.functional as F\n'), ((17696, 17727), 'aw_nas.utils.straight_through', 'utils.straight_through', (['sampled'], {}), '(sampled)\n', (17718, 17727), False, 'from aw_nas import utils, assert_rollout_type\n'), ((18139, 18163), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['sampled'], {}), '(sampled)\n', (18154, 18163), False, 'from aw_nas import utils, assert_rollout_type\n'), ((19803, 19833), 'torch.zeros_like', 'torch.zeros_like', (['width_alphas'], {}), '(width_alphas)\n', (19819, 19833), False, 'import torch\n'), ((20351, 20422), 'torch.nn.functional.softmax', 'F.softmax', (['(expanded_width_alpha / self.width_gumbel_temperature)'], {'dim': '(-1)'}), '(expanded_width_alpha / self.width_gumbel_temperature, dim=-1)\n', (20360, 20422), True, 'import torch.nn.functional as F\n'), ((20982, 21019), 'aw_nas.utils.straight_through', 'utils.straight_through', (['width_sampled'], {}), '(width_sampled)\n', (21004, 21019), False, 'from aw_nas import utils, assert_rollout_type\n'), ((33774, 33799), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['sampleds'], {}), '(sampleds)\n', (33789, 33799), False, 'from aw_nas import utils, assert_rollout_type\n'), ((40141, 40165), 'torch.zeros_like', 'torch.zeros_like', (['alphas'], {}), '(alphas)\n', (40157, 40165), False, 'import torch\n'), ((40625, 40684), 'torch.nn.functional.softmax', 'F.softmax', (['(expanded_alpha / self.gumbel_temperature)'], {'dim': '(-1)'}), '(expanded_alpha / self.gumbel_temperature, dim=-1)\n', (40634, 40684), True, 'import torch.nn.functional as F\n'), ((41202, 41233), 'aw_nas.utils.straight_through', 'utils.straight_through', (['sampled'], {}), '(sampled)\n', (41224, 41233), False, 'from aw_nas import utils, assert_rollout_type\n'), ((41645, 41669), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['sampled'], {}), '(sampled)\n', (41660, 41669), False, 'from aw_nas import utils, assert_rollout_type\n'), ((9329, 9350), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (9344, 9350), False, 'import os\n'), ((17294, 17365), 'aw_nas.utils.relaxed_bernoulli_sample', 'utils.relaxed_bernoulli_sample', (['expanded_alpha', 'self.gumbel_temperature'], {}), '(expanded_alpha, self.gumbel_temperature)\n', (17324, 17365), False, 'from aw_nas import utils, assert_rollout_type\n'), ((17505, 17578), 'aw_nas.utils.gumbel_softmax', 'utils.gumbel_softmax', (['expanded_alpha', 'self.gumbel_temperature'], {'hard': '(False)'}), '(expanded_alpha, self.gumbel_temperature, hard=False)\n', (17525, 17578), False, 'from aw_nas import utils, assert_rollout_type\n'), ((20544, 20632), 'aw_nas.utils.relaxed_bernoulli_sample', 'utils.relaxed_bernoulli_sample', (['expanded_width_alpha', 'self.width_gumbel_temperature'], {}), '(expanded_width_alpha, self.\n width_gumbel_temperature)\n', (20574, 20632), False, 'from aw_nas import utils, assert_rollout_type\n'), ((20773, 20862), 'aw_nas.utils.gumbel_softmax', 'utils.gumbel_softmax', (['expanded_width_alpha', 'self.width_gumbel_temperature'], {'hard': '(False)'}), '(expanded_width_alpha, self.width_gumbel_temperature,\n hard=False)\n', (20793, 20862), False, 'from aw_nas import utils, assert_rollout_type\n'), ((26631, 26662), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['vec.op_weights'], {}), '(vec.op_weights)\n', (26646, 26662), False, 'from aw_nas import utils, assert_rollout_type\n'), ((32012, 32035), 'torch.zeros_like', 'torch.zeros_like', (['alpha'], {}), '(alpha)\n', (32028, 32035), False, 'import torch\n'), ((32486, 32545), 'torch.nn.functional.softmax', 'F.softmax', (['(expanded_alpha / self.gumbel_temperature)'], {'dim': '(-1)'}), '(expanded_alpha / self.gumbel_temperature, dim=-1)\n', (32495, 32545), True, 'import torch.nn.functional as F\n'), ((33114, 33145), 'aw_nas.utils.straight_through', 'utils.straight_through', (['sampled'], {}), '(sampled)\n', (33136, 33145), False, 'from aw_nas import utils, assert_rollout_type\n'), ((40800, 40871), 'aw_nas.utils.relaxed_bernoulli_sample', 'utils.relaxed_bernoulli_sample', (['expanded_alpha', 'self.gumbel_temperature'], {}), '(expanded_alpha, self.gumbel_temperature)\n', (40830, 40871), False, 'from aw_nas import utils, assert_rollout_type\n'), ((41011, 41084), 'aw_nas.utils.gumbel_softmax', 'utils.gumbel_softmax', (['expanded_alpha', 'self.gumbel_temperature'], {'hard': '(False)'}), '(expanded_alpha, self.gumbel_temperature, hard=False)\n', (41031, 41084), False, 'from aw_nas import utils, assert_rollout_type\n'), ((45659, 45679), 'aw_nas.utils.get_numpy', 'utils.get_numpy', (['vec'], {}), '(vec)\n', (45674, 45679), False, 'from aw_nas import utils, assert_rollout_type\n'), ((32677, 32748), 'aw_nas.utils.relaxed_bernoulli_sample', 'utils.relaxed_bernoulli_sample', (['expanded_alpha', 'self.gumbel_temperature'], {}), '(expanded_alpha, self.gumbel_temperature)\n', (32707, 32748), False, 'from aw_nas import utils, assert_rollout_type\n'), ((32908, 32981), 'aw_nas.utils.gumbel_softmax', 'utils.gumbel_softmax', (['expanded_alpha', 'self.gumbel_temperature'], {'hard': '(False)'}), '(expanded_alpha, self.gumbel_temperature, hard=False)\n', (32928, 32981), False, 'from aw_nas import utils, assert_rollout_type\n'), ((43471, 43486), 'torch.log', 'torch.log', (['prob'], {}), '(prob)\n', (43480, 43486), False, 'import torch\n'), ((24057, 24072), 'torch.log', 'torch.log', (['prob'], {}), '(prob)\n', (24066, 24072), False, 'import torch\n'), ((24401, 24416), 'torch.log', 'torch.log', (['prob'], {}), '(prob)\n', (24410, 24416), False, 'import torch\n')]
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 os from nose.tools import nottest import numpy as np import tvm from tvm.contrib import graph_runtime, util from tvm import relay import tvm.micro as micro from tvm.relay.testing import resnet # Use the host emulated micro device, because it's simpler and faster to test. DEVICE_TYPE = "host" BINUTIL_PREFIX = "" HOST_SESSION = micro.Session(DEVICE_TYPE, BINUTIL_PREFIX) # TODO(weberlo): Add example program to test scalar double/int TVMValue serialization. def test_add(): """Test a program which performs addition.""" shape = (1024,) dtype = "float32" # Construct TVM expression. tvm_shape = tvm.convert(shape) A = tvm.placeholder(tvm_shape, name="A", dtype=dtype) B = tvm.placeholder(tvm_shape, name="B", dtype=dtype) C = tvm.compute(A.shape, lambda *i: A(*i) + B(*i), name="C") s = tvm.create_schedule(C.op) func_name = "fadd" c_mod = tvm.build(s, [A, B, C], target="c", name=func_name) with HOST_SESSION as sess: micro_mod = sess.create_micro_mod(c_mod) micro_func = micro_mod[func_name] ctx = tvm.micro_dev(0) a = tvm.nd.array(np.random.uniform(size=shape).astype(dtype), ctx) b = tvm.nd.array(np.random.uniform(size=shape).astype(dtype), ctx) c = tvm.nd.array(np.zeros(shape, dtype=dtype), ctx) micro_func(a, b, c) tvm.testing.assert_allclose( c.asnumpy(), a.asnumpy() + b.asnumpy()) def test_workspace_add(): """Test a program which uses a workspace.""" shape = (1024,) dtype = "float32" # Construct TVM expression. tvm_shape = tvm.convert(shape) A = tvm.placeholder(tvm_shape, name="A", dtype=dtype) B = tvm.placeholder(tvm_shape, name="B", dtype=dtype) B = tvm.compute(A.shape, lambda *i: A(*i) + 1, name="B") C = tvm.compute(A.shape, lambda *i: B(*i) + 1, name="C") s = tvm.create_schedule(C.op) func_name = "fadd_two_workspace" c_mod = tvm.build(s, [A, C], target="c", name=func_name) with HOST_SESSION as sess: micro_mod = sess.create_micro_mod(c_mod) micro_func = micro_mod[func_name] ctx = tvm.micro_dev(0) a = tvm.nd.array(np.random.uniform(size=shape).astype(dtype), ctx) c = tvm.nd.array(np.zeros(shape, dtype=dtype), ctx) micro_func(a, c) tvm.testing.assert_allclose( c.asnumpy(), a.asnumpy() + 2.0) def test_graph_runtime(): """Test a program which uses the graph runtime.""" shape = (1024,) dtype = "float32" # Construct Relay program. x = relay.var("x", relay.TensorType(shape=shape, dtype=dtype)) xx = relay.multiply(x, x) z = relay.add(xx, relay.const(1.0)) func = relay.Function([x], z) with HOST_SESSION as sess: mod, params = sess.build(func) mod.set_input(**params) x_in = np.random.uniform(size=shape[0]).astype(dtype) mod.run(x=x_in) result = mod.get_output(0).asnumpy() tvm.testing.assert_allclose( result, x_in * x_in + 1.0) def test_resnet_random(): """Test ResNet18 inference with random weights and inputs.""" resnet_func, params = resnet.get_workload(num_classes=10, num_layers=18, image_shape=(3, 32, 32)) # Remove the final softmax layer, because uTVM does not currently support it. resnet_func_no_sm = relay.Function(resnet_func.params, resnet_func.body.args[0], resnet_func.ret_type) with HOST_SESSION as sess: # TODO(weberlo): Use `resnet_func` once we have libc support. mod, params = sess.build(resnet_func_no_sm, params=params) mod.set_input(**params) # Generate random input. data = np.random.uniform(size=mod.get_input(0).shape) mod.run(data=data) result = mod.get_output(0).asnumpy() # We gave a random input, so all we want is a result with some nonzero # entries. assert result.sum() != 0.0 # TODO(weberlo): Enable this test or move the code somewhere else. @nottest def test_resnet_pretrained(): """Test classification with a pretrained ResNet18 model.""" import mxnet as mx from mxnet.gluon.model_zoo.vision import get_model from mxnet.gluon.utils import download from PIL import Image # TODO(weberlo) there's a significant amount of overlap between here and # `tutorials/frontend/from_mxnet.py`. Should refactor. dtype = "float32" # Fetch a mapping from class IDs to human-readable labels. synset_url = "".join(["https://gist.githubusercontent.com/zhreshold/", "4d0b62f3d01426887599d4f7ede23ee5/raw/", "596b27d23537e5a1b5751d2b0481ef172f58b539/", "imagenet1000_clsid_to_human.txt"]) synset_name = "synset.txt" download(synset_url, synset_name) with open(synset_name) as f: synset = eval(f.read()) # Read raw image and preprocess into the format ResNet can work on. img_name = "cat.png" download("https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true", img_name) image = Image.open(img_name).resize((224, 224)) image = np.array(image) - np.array([123., 117., 104.]) image /= np.array([58.395, 57.12, 57.375]) image = image.transpose((2, 0, 1)) image = image[np.newaxis, :] image = tvm.nd.array(image.astype(dtype)) block = get_model("resnet18_v1", pretrained=True) func, params = relay.frontend.from_mxnet(block, shape={"data": image.shape}) with HOST_SESSION as sess: mod, params = sess.build(func, params=params) # Set model weights. mod.set_input(**params) # Execute with `image` as the input. mod.run(data=image) # Get outputs. tvm_output = mod.get_output(0) prediction_idx = np.argmax(tvm_output.asnumpy()[0]) prediction = synset[prediction_idx] assert prediction == "tiger cat" if __name__ == "__main__": test_add() test_workspace_add() test_graph_runtime() test_resnet_random()
[ "tvm.convert", "tvm.create_schedule", "tvm.relay.Function", "tvm.testing.assert_allclose", "mxnet.gluon.utils.download", "tvm.relay.multiply", "tvm.relay.frontend.from_mxnet", "mxnet.gluon.model_zoo.vision.get_model", "tvm.relay.const", "numpy.random.uniform", "tvm.relay.testing.resnet.get_workload", "tvm.placeholder", "numpy.zeros", "tvm.relay.TensorType", "tvm.build", "PIL.Image.open", "numpy.array", "tvm.micro.Session", "tvm.micro_dev" ]
[((1123, 1165), 'tvm.micro.Session', 'micro.Session', (['DEVICE_TYPE', 'BINUTIL_PREFIX'], {}), '(DEVICE_TYPE, BINUTIL_PREFIX)\n', (1136, 1165), True, 'import tvm.micro as micro\n'), ((1412, 1430), 'tvm.convert', 'tvm.convert', (['shape'], {}), '(shape)\n', (1423, 1430), False, 'import tvm\n'), ((1439, 1488), 'tvm.placeholder', 'tvm.placeholder', (['tvm_shape'], {'name': '"""A"""', 'dtype': 'dtype'}), "(tvm_shape, name='A', dtype=dtype)\n", (1454, 1488), False, 'import tvm\n'), ((1497, 1546), 'tvm.placeholder', 'tvm.placeholder', (['tvm_shape'], {'name': '"""B"""', 'dtype': 'dtype'}), "(tvm_shape, name='B', dtype=dtype)\n", (1512, 1546), False, 'import tvm\n'), ((1620, 1645), 'tvm.create_schedule', 'tvm.create_schedule', (['C.op'], {}), '(C.op)\n', (1639, 1645), False, 'import tvm\n'), ((1682, 1733), 'tvm.build', 'tvm.build', (['s', '[A, B, C]'], {'target': '"""c"""', 'name': 'func_name'}), "(s, [A, B, C], target='c', name=func_name)\n", (1691, 1733), False, 'import tvm\n'), ((2388, 2406), 'tvm.convert', 'tvm.convert', (['shape'], {}), '(shape)\n', (2399, 2406), False, 'import tvm\n'), ((2415, 2464), 'tvm.placeholder', 'tvm.placeholder', (['tvm_shape'], {'name': '"""A"""', 'dtype': 'dtype'}), "(tvm_shape, name='A', dtype=dtype)\n", (2430, 2464), False, 'import tvm\n'), ((2473, 2522), 'tvm.placeholder', 'tvm.placeholder', (['tvm_shape'], {'name': '"""B"""', 'dtype': 'dtype'}), "(tvm_shape, name='B', dtype=dtype)\n", (2488, 2522), False, 'import tvm\n'), ((2653, 2678), 'tvm.create_schedule', 'tvm.create_schedule', (['C.op'], {}), '(C.op)\n', (2672, 2678), False, 'import tvm\n'), ((2729, 2777), 'tvm.build', 'tvm.build', (['s', '[A, C]'], {'target': '"""c"""', 'name': 'func_name'}), "(s, [A, C], target='c', name=func_name)\n", (2738, 2777), False, 'import tvm\n'), ((3411, 3431), 'tvm.relay.multiply', 'relay.multiply', (['x', 'x'], {}), '(x, x)\n', (3425, 3431), False, 'from tvm import relay\n'), ((3483, 3505), 'tvm.relay.Function', 'relay.Function', (['[x]', 'z'], {}), '([x], z)\n', (3497, 3505), False, 'from tvm import relay\n'), ((3942, 4017), 'tvm.relay.testing.resnet.get_workload', 'resnet.get_workload', ([], {'num_classes': '(10)', 'num_layers': '(18)', 'image_shape': '(3, 32, 32)'}), '(num_classes=10, num_layers=18, image_shape=(3, 32, 32))\n', (3961, 4017), False, 'from tvm.relay.testing import resnet\n'), ((4216, 4303), 'tvm.relay.Function', 'relay.Function', (['resnet_func.params', 'resnet_func.body.args[0]', 'resnet_func.ret_type'], {}), '(resnet_func.params, resnet_func.body.args[0], resnet_func.\n ret_type)\n', (4230, 4303), False, 'from tvm import relay\n'), ((5731, 5764), 'mxnet.gluon.utils.download', 'download', (['synset_url', 'synset_name'], {}), '(synset_url, synset_name)\n', (5739, 5764), False, 'from mxnet.gluon.utils import download\n'), ((5932, 6024), 'mxnet.gluon.utils.download', 'download', (['"""https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true"""', 'img_name'], {}), "('https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true',\n img_name)\n", (5940, 6024), False, 'from mxnet.gluon.utils import download\n'), ((6158, 6191), 'numpy.array', 'np.array', (['[58.395, 57.12, 57.375]'], {}), '([58.395, 57.12, 57.375])\n', (6166, 6191), True, 'import numpy as np\n'), ((6323, 6364), 'mxnet.gluon.model_zoo.vision.get_model', 'get_model', (['"""resnet18_v1"""'], {'pretrained': '(True)'}), "('resnet18_v1', pretrained=True)\n", (6332, 6364), False, 'from mxnet.gluon.model_zoo.vision import get_model\n'), ((6384, 6445), 'tvm.relay.frontend.from_mxnet', 'relay.frontend.from_mxnet', (['block'], {'shape': "{'data': image.shape}"}), "(block, shape={'data': image.shape})\n", (6409, 6445), False, 'from tvm import relay\n'), ((1871, 1887), 'tvm.micro_dev', 'tvm.micro_dev', (['(0)'], {}), '(0)\n', (1884, 1887), False, 'import tvm\n'), ((2915, 2931), 'tvm.micro_dev', 'tvm.micro_dev', (['(0)'], {}), '(0)\n', (2928, 2931), False, 'import tvm\n'), ((3358, 3400), 'tvm.relay.TensorType', 'relay.TensorType', ([], {'shape': 'shape', 'dtype': 'dtype'}), '(shape=shape, dtype=dtype)\n', (3374, 3400), False, 'from tvm import relay\n'), ((3454, 3470), 'tvm.relay.const', 'relay.const', (['(1.0)'], {}), '(1.0)\n', (3465, 3470), False, 'from tvm import relay\n'), ((3750, 3804), 'tvm.testing.assert_allclose', 'tvm.testing.assert_allclose', (['result', '(x_in * x_in + 1.0)'], {}), '(result, x_in * x_in + 1.0)\n', (3777, 3804), False, 'import tvm\n'), ((6098, 6113), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (6106, 6113), True, 'import numpy as np\n'), ((6116, 6147), 'numpy.array', 'np.array', (['[123.0, 117.0, 104.0]'], {}), '([123.0, 117.0, 104.0])\n', (6124, 6147), True, 'import numpy as np\n'), ((2063, 2091), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (2071, 2091), True, 'import numpy as np\n'), ((3032, 3060), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (3040, 3060), True, 'import numpy as np\n'), ((6046, 6066), 'PIL.Image.open', 'Image.open', (['img_name'], {}), '(img_name)\n', (6056, 6066), False, 'from PIL import Image\n'), ((3625, 3657), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'shape[0]'}), '(size=shape[0])\n', (3642, 3657), True, 'import numpy as np\n'), ((1913, 1942), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'shape'}), '(size=shape)\n', (1930, 1942), True, 'import numpy as np\n'), ((1988, 2017), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'shape'}), '(size=shape)\n', (2005, 2017), True, 'import numpy as np\n'), ((2957, 2986), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'shape'}), '(size=shape)\n', (2974, 2986), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from timeit import Timer a = np.array([1, 2, 3, 4]) print(a + 1) 2**a b = np.ones(4) + 1 a - b a * b j = np.arange(5) 2**(j + 1) - j c = np.ones((3, 3)) # NOT matrix multiplication! print(c * c) print(c.dot(c)) a = np.arange(10) b = a[0::2] c = a[1::2] print(b,c) print(b + c) a = list(range(10)) b = a[0::2] c = a[1::2] print(b,c) print([b[i] + c[i] for i in range(len(b))]) iterable = (2**x for x in range(5)) a = np.fromiter(iterable, int) print(a) iterable = (2^(3*x) for x in range(5)) a = np.fromiter(iterable, int) print(a) print(min(Timer(setup=""" import numpy as np a = np.arange(10) """, stmt=""" b = a[0::2] c = a[1::2] b + c """).repeat(5,1000))) print(min(Timer(setup=""" a = list(range(10)) """, stmt=""" b = a[0::2] c = a[1::2] [b[i] + c[i] for i in range(len(b))] """).repeat(5,1000))) print(min(Timer(setup="import numpy as np\na = np.arange(10000)", stmt="a + 1").repeat(5,1000))) print(min(Timer(setup="l = range(10000)", stmt="[i+1 for i in l]").repeat(5,1000)))
[ "timeit.Timer", "numpy.ones", "numpy.array", "numpy.arange", "numpy.fromiter" ]
[((95, 117), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (103, 117), True, 'import numpy as np\n'), ((171, 183), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (180, 183), True, 'import numpy as np\n'), ((204, 219), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (211, 219), True, 'import numpy as np\n'), ((283, 296), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (292, 296), True, 'import numpy as np\n'), ((486, 512), 'numpy.fromiter', 'np.fromiter', (['iterable', 'int'], {}), '(iterable, int)\n', (497, 512), True, 'import numpy as np\n'), ((566, 592), 'numpy.fromiter', 'np.fromiter', (['iterable', 'int'], {}), '(iterable, int)\n', (577, 592), True, 'import numpy as np\n'), ((140, 150), 'numpy.ones', 'np.ones', (['(4)'], {}), '(4)\n', (147, 150), True, 'import numpy as np\n'), ((613, 719), 'timeit.Timer', 'Timer', ([], {'setup': '"""\nimport numpy as np\na = np.arange(10)\n"""', 'stmt': '"""\nb = a[0::2]\nc = a[1::2]\nb + c\n"""'}), '(setup="""\nimport numpy as np\na = np.arange(10)\n""", stmt=\n """\nb = a[0::2]\nc = a[1::2]\nb + c\n""")\n', (618, 719), False, 'from timeit import Timer\n'), ((743, 863), 'timeit.Timer', 'Timer', ([], {'setup': '"""\na = list(range(10))\n"""', 'stmt': '"""\nb = a[0::2]\nc = a[1::2]\n[b[i] + c[i] for i in range(len(b))]\n"""'}), '(setup="""\na = list(range(10))\n""", stmt=\n """\nb = a[0::2]\nc = a[1::2]\n[b[i] + c[i] for i in range(len(b))]\n""")\n', (748, 863), False, 'from timeit import Timer\n'), ((887, 959), 'timeit.Timer', 'Timer', ([], {'setup': '"""import numpy as np\na = np.arange(10000)"""', 'stmt': '"""a + 1"""'}), '(setup="""import numpy as np\na = np.arange(10000)""", stmt=\'a + 1\')\n', (892, 959), False, 'from timeit import Timer\n'), ((991, 1047), 'timeit.Timer', 'Timer', ([], {'setup': '"""l = range(10000)"""', 'stmt': '"""[i+1 for i in l]"""'}), "(setup='l = range(10000)', stmt='[i+1 for i in l]')\n", (996, 1047), False, 'from timeit import Timer\n')]
import pickle from pathlib import Path import numpy as np from second.core import box_np_ops from second.data.dataset import Dataset, get_dataset_class from second.data.kitti_dataset import KittiDataset import second.data.nuscenes_dataset as nuds from second.utils.progress_bar import progress_bar_iter as prog_bar from concurrent.futures import ProcessPoolExecutor def create_groundtruth_database(dataset_class_name, data_path, info_path=None, used_classes=None, database_save_path=None, db_info_save_path=None, relative_path=True, add_rgb=False, lidar_only=False, bev_only=False, coors_range=None): dataset = get_dataset_class(dataset_class_name)( info_path=info_path, root_path=data_path, ) root_path = Path(data_path) if database_save_path is None: database_save_path = root_path / 'gt_database' else: database_save_path = Path(database_save_path) if db_info_save_path is None: db_info_save_path = root_path / "dbinfos_train.pkl" database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} group_counter = 0 for j in prog_bar(list(range(len(dataset)))): image_idx = j sensor_data = dataset.get_sensor_data(j) if "image_idx" in sensor_data["metadata"]: image_idx = sensor_data["metadata"]["image_idx"] points = sensor_data["lidar"]["points"] annos = sensor_data["lidar"]["annotations"] gt_boxes = annos["boxes"] names = annos["names"] group_dict = {} group_ids = np.full([gt_boxes.shape[0]], -1, dtype=np.int64) if "group_ids" in annos: group_ids = annos["group_ids"] else: group_ids = np.arange(gt_boxes.shape[0], dtype=np.int64) difficulty = np.zeros(gt_boxes.shape[0], dtype=np.int32) if "difficulty" in annos: difficulty = annos["difficulty"] num_obj = gt_boxes.shape[0] point_indices = box_np_ops.points_in_rbbox(points, gt_boxes) for i in range(num_obj): filename = f"{image_idx}_{names[i]}_{i}.bin" filepath = database_save_path / filename gt_points = points[point_indices[:, i]] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) if (used_classes is None) or names[i] in used_classes: if relative_path: db_path = str(database_save_path.stem + "/" + filename) else: db_path = str(filepath) db_info = { "name": names[i], "path": db_path, "image_idx": image_idx, "gt_idx": i, "box3d_lidar": gt_boxes[i], "num_points_in_gt": gt_points.shape[0], "difficulty": difficulty[i], # "group_id": -1, # "bbox": bboxes[i], } local_group_id = group_ids[i] # if local_group_id >= 0: if local_group_id not in group_dict: group_dict[local_group_id] = group_counter group_counter += 1 db_info["group_id"] = group_dict[local_group_id] if "score" in annos: db_info["score"] = annos["score"][i] if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print(f"load {len(v)} {k} database infos") with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) def create_groundtruth_database_with_sweep_info(dataset_class_name, data_path, info_path=None, used_classes=None, database_save_path=None, db_info_save_path=None, relative_path=True, add_rgb=False, lidar_only=False, bev_only=False, coors_range=None): dataset = get_dataset_class(dataset_class_name)( info_path=info_path, root_path=data_path, ) root_path = Path(data_path) if database_save_path is None: database_save_path = root_path / 'gt_database_with_sweep_info' else: database_save_path = Path(database_save_path) if db_info_save_path is None: db_info_save_path = root_path / "dbinfos_train_with_sweep_info.pkl" database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} group_counter = 0 for j in prog_bar(list(range(len(dataset)))): image_idx = j sensor_data = dataset.get_sensor_data(j) if "image_idx" in sensor_data["metadata"]: image_idx = sensor_data["metadata"]["image_idx"] assert("sweep_points_list" in sensor_data["lidar"]) sweep_points_list = sensor_data["lidar"]["sweep_points_list"] assert("sweep_annotations" in sensor_data["lidar"]) sweep_gt_boxes_list = sensor_data["lidar"]["sweep_annotations"]["boxes_list"] sweep_gt_tokens_list = sensor_data["lidar"]["sweep_annotations"]["tokens_list"] sweep_gt_names_list = sensor_data["lidar"]["sweep_annotations"]["names_list"] # we focus on the objects in the first frame # and find the bounding box index of the same object in every frame points = sensor_data["lidar"]["points"] annos = sensor_data["lidar"]["annotations"] names = annos["names"] gt_boxes = annos["boxes"] attrs = annos["attrs"] tokens = sweep_gt_tokens_list[0] # sanity check with redundancy assert(len(sweep_gt_boxes_list) == len(sweep_gt_tokens_list) == len(sweep_gt_names_list)) assert(len(gt_boxes) == len(attrs) == len(tokens)) assert(np.all(names == sweep_gt_names_list[0])) assert(np.all(gt_boxes == sweep_gt_boxes_list[0])) # on every frame, we mask points inside each bounding box # but we are not looking at every bounding box sweep_point_indices_list = [] for sweep_points, sweep_gt_boxes in zip(sweep_points_list, sweep_gt_boxes_list): sweep_point_indices_list.append(box_np_ops.points_in_rbbox(sweep_points, sweep_gt_boxes)) # crop point cloud based on boxes in the current frame point_indices = box_np_ops.points_in_rbbox(points, gt_boxes) # group_dict = {} group_ids = np.full([gt_boxes.shape[0]], -1, dtype=np.int64) if "group_ids" in annos: group_ids = annos["group_ids"] else: group_ids = np.arange(gt_boxes.shape[0], dtype=np.int64) # difficulty = np.zeros(gt_boxes.shape[0], dtype=np.int32) if "difficulty" in annos: difficulty = annos["difficulty"] num_obj = gt_boxes.shape[0] for i in range(num_obj): filename = f"{image_idx}_{names[i]}_{i}.bin" filepath = database_save_path / filename # only use non-key frame boxes when the object is moving if attrs[i] in ['vehicle.moving', 'cycle.with_rider', 'pedestrian.moving']: gt_points_list = [] for t in range(len(sweep_points_list)): # fast pass for most frames if i < len(sweep_gt_tokens_list[t]) and sweep_gt_tokens_list[t][i] == tokens[i]: box_idx = i else: I = np.flatnonzero(tokens[i] == sweep_gt_tokens_list[t]) if len(I) == 0: continue elif len(I) == 1: box_idx = I[0] else: raise ValueError('Identical object tokens') gt_points_list.append(sweep_points_list[t][sweep_point_indices_list[t][:, box_idx]]) gt_points = np.concatenate(gt_points_list, axis=0)[:, [0, 1, 2, 4]] else: gt_points = points[point_indices[:, i]] # offset points based on the bounding box in the current frame gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) if (used_classes is None) or names[i] in used_classes: if relative_path: db_path = str(database_save_path.stem + "/" + filename) else: db_path = str(filepath) db_info = { "name": names[i], "path": db_path, "image_idx": image_idx, "gt_idx": i, "box3d_lidar": gt_boxes[i], "num_points_in_gt": gt_points.shape[0], "difficulty": difficulty[i] } local_group_id = group_ids[i] if local_group_id not in group_dict: group_dict[local_group_id] = group_counter group_counter += 1 db_info["group_id"] = group_dict[local_group_id] if "score" in annos: db_info["score"] = annos["score"][i] if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print(f"load {len(v)} {k} database infos") with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f)
[ "numpy.full", "pickle.dump", "numpy.concatenate", "numpy.flatnonzero", "numpy.zeros", "second.core.box_np_ops.points_in_rbbox", "pathlib.Path", "numpy.arange", "second.data.dataset.get_dataset_class", "numpy.all" ]
[((1058, 1073), 'pathlib.Path', 'Path', (['data_path'], {}), '(data_path)\n', (1062, 1073), False, 'from pathlib import Path\n'), ((4946, 4961), 'pathlib.Path', 'Path', (['data_path'], {}), '(data_path)\n', (4950, 4961), False, 'from pathlib import Path\n'), ((939, 976), 'second.data.dataset.get_dataset_class', 'get_dataset_class', (['dataset_class_name'], {}), '(dataset_class_name)\n', (956, 976), False, 'from second.data.dataset import Dataset, get_dataset_class\n'), ((1203, 1227), 'pathlib.Path', 'Path', (['database_save_path'], {}), '(database_save_path)\n', (1207, 1227), False, 'from pathlib import Path\n'), ((1869, 1917), 'numpy.full', 'np.full', (['[gt_boxes.shape[0]]', '(-1)'], {'dtype': 'np.int64'}), '([gt_boxes.shape[0]], -1, dtype=np.int64)\n', (1876, 1917), True, 'import numpy as np\n'), ((2098, 2141), 'numpy.zeros', 'np.zeros', (['gt_boxes.shape[0]'], {'dtype': 'np.int32'}), '(gt_boxes.shape[0], dtype=np.int32)\n', (2106, 2141), True, 'import numpy as np\n'), ((2282, 2326), 'second.core.box_np_ops.points_in_rbbox', 'box_np_ops.points_in_rbbox', (['points', 'gt_boxes'], {}), '(points, gt_boxes)\n', (2308, 2326), False, 'from second.core import box_np_ops\n'), ((4052, 4080), 'pickle.dump', 'pickle.dump', (['all_db_infos', 'f'], {}), '(all_db_infos, f)\n', (4063, 4080), False, 'import pickle\n'), ((4827, 4864), 'second.data.dataset.get_dataset_class', 'get_dataset_class', (['dataset_class_name'], {}), '(dataset_class_name)\n', (4844, 4864), False, 'from second.data.dataset import Dataset, get_dataset_class\n'), ((5107, 5131), 'pathlib.Path', 'Path', (['database_save_path'], {}), '(database_save_path)\n', (5111, 5131), False, 'from pathlib import Path\n'), ((6609, 6648), 'numpy.all', 'np.all', (['(names == sweep_gt_names_list[0])'], {}), '(names == sweep_gt_names_list[0])\n', (6615, 6648), True, 'import numpy as np\n'), ((6665, 6707), 'numpy.all', 'np.all', (['(gt_boxes == sweep_gt_boxes_list[0])'], {}), '(gt_boxes == sweep_gt_boxes_list[0])\n', (6671, 6707), True, 'import numpy as np\n'), ((7149, 7193), 'second.core.box_np_ops.points_in_rbbox', 'box_np_ops.points_in_rbbox', (['points', 'gt_boxes'], {}), '(points, gt_boxes)\n', (7175, 7193), False, 'from second.core import box_np_ops\n'), ((7250, 7298), 'numpy.full', 'np.full', (['[gt_boxes.shape[0]]', '(-1)'], {'dtype': 'np.int64'}), '([gt_boxes.shape[0]], -1, dtype=np.int64)\n', (7257, 7298), True, 'import numpy as np\n'), ((7490, 7533), 'numpy.zeros', 'np.zeros', (['gt_boxes.shape[0]'], {'dtype': 'np.int32'}), '(gt_boxes.shape[0], dtype=np.int32)\n', (7498, 7533), True, 'import numpy as np\n'), ((10285, 10313), 'pickle.dump', 'pickle.dump', (['all_db_infos', 'f'], {}), '(all_db_infos, f)\n', (10296, 10313), False, 'import pickle\n'), ((2032, 2076), 'numpy.arange', 'np.arange', (['gt_boxes.shape[0]'], {'dtype': 'np.int64'}), '(gt_boxes.shape[0], dtype=np.int64)\n', (2041, 2076), True, 'import numpy as np\n'), ((7413, 7457), 'numpy.arange', 'np.arange', (['gt_boxes.shape[0]'], {'dtype': 'np.int64'}), '(gt_boxes.shape[0], dtype=np.int64)\n', (7422, 7457), True, 'import numpy as np\n'), ((7003, 7059), 'second.core.box_np_ops.points_in_rbbox', 'box_np_ops.points_in_rbbox', (['sweep_points', 'sweep_gt_boxes'], {}), '(sweep_points, sweep_gt_boxes)\n', (7029, 7059), False, 'from second.core import box_np_ops\n'), ((8661, 8699), 'numpy.concatenate', 'np.concatenate', (['gt_points_list'], {'axis': '(0)'}), '(gt_points_list, axis=0)\n', (8675, 8699), True, 'import numpy as np\n'), ((8294, 8346), 'numpy.flatnonzero', 'np.flatnonzero', (['(tokens[i] == sweep_gt_tokens_list[t])'], {}), '(tokens[i] == sweep_gt_tokens_list[t])\n', (8308, 8346), True, 'import numpy as np\n')]
# -*- encoding: utf-8 -*- """Script for analyzing data from the simulated primary and follow-up experiments.""" # Allow importing modules from parent directory. import sys sys.path.append('..') from fdr import lsu, tst, qvalue from fwer import bonferroni, sidak, hochberg, holm_bonferroni from permutation import tfr_permutation_test import numpy as np from repeat import fwer_replicability as repl from util import grid_model_counts as counts """Load the simulated datasets.""" fpath = '/home/puolival/multipy_data' fname_primary = fpath + '/primary.npy' fname_followup = fname_primary.replace('primary', 'follow-up') print('Loading simulated datasets ..') primary_data, followup_data = (np.load(fname_primary), np.load(fname_followup)) print('Done.') # Extract p-values pvals_pri, pvals_fol = (primary_data.flat[0]['pvals'], followup_data.flat[0]['pvals']) # Extract raw data for permutation testing rvs_a_pri, rvs_b_pri = (primary_data.flat[0]['rvs_a'], primary_data.flat[0]['rvs_b']) rvs_a_fol, rvs_b_fol = (followup_data.flat[0]['rvs_a'], followup_data.flat[0]['rvs_b']) """Define analysis parameters.""" n_iterations, n_effect_sizes, nl, _ = np.shape(pvals_pri) emph_primary = 0.1 alpha = 0.05 method = qvalue sl = 30 # TODO: save to .npy file. """Compute reproducibility rates.""" rr = np.zeros([n_iterations, n_effect_sizes]) for ind in np.ndindex(n_iterations, n_effect_sizes): print('Analysis iteration %3d' % (1+ind[0])) replicable = repl(pvals_pri[ind].flatten(), pvals_fol[ind].flatten(), emph_primary, method, alpha) replicable = np.reshape(replicable, [nl, nl]) rr[ind] = counts(replicable, nl, sl)[0] """Save data to disk.""" output_fpath = fpath output_fname = output_fpath + ('/result-%s.npy' % method.__name__) np.save(output_fname, {'rr': rr}) print('Results saved to disk.')
[ "sys.path.append", "numpy.ndindex", "numpy.save", "numpy.load", "numpy.zeros", "util.grid_model_counts", "numpy.shape", "numpy.reshape" ]
[((173, 194), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (188, 194), False, 'import sys\n'), ((1262, 1281), 'numpy.shape', 'np.shape', (['pvals_pri'], {}), '(pvals_pri)\n', (1270, 1281), True, 'import numpy as np\n'), ((1408, 1448), 'numpy.zeros', 'np.zeros', (['[n_iterations, n_effect_sizes]'], {}), '([n_iterations, n_effect_sizes])\n', (1416, 1448), True, 'import numpy as np\n'), ((1461, 1501), 'numpy.ndindex', 'np.ndindex', (['n_iterations', 'n_effect_sizes'], {}), '(n_iterations, n_effect_sizes)\n', (1471, 1501), True, 'import numpy as np\n'), ((1886, 1919), 'numpy.save', 'np.save', (['output_fname', "{'rr': rr}"], {}), "(output_fname, {'rr': rr})\n", (1893, 1919), True, 'import numpy as np\n'), ((696, 718), 'numpy.load', 'np.load', (['fname_primary'], {}), '(fname_primary)\n', (703, 718), True, 'import numpy as np\n'), ((751, 774), 'numpy.load', 'np.load', (['fname_followup'], {}), '(fname_followup)\n', (758, 774), True, 'import numpy as np\n'), ((1694, 1726), 'numpy.reshape', 'np.reshape', (['replicable', '[nl, nl]'], {}), '(replicable, [nl, nl])\n', (1704, 1726), True, 'import numpy as np\n'), ((1741, 1767), 'util.grid_model_counts', 'counts', (['replicable', 'nl', 'sl'], {}), '(replicable, nl, sl)\n', (1747, 1767), True, 'from util import grid_model_counts as counts\n')]
from collections import defaultdict, Counter, OrderedDict, namedtuple, deque from typing import List, Dict, Any, Tuple, Iterable, Set, Optional import numpy as np import tensorflow as tf from dpu_utils.tfutils import unsorted_segment_logsumexp, pick_indices_from_probs from dpu_utils.mlutils.vocabulary import Vocabulary from dpu_utils.tfmodels import AsyncGGNN from .model import Model, ModelTestResult, write_to_minibatch BIG_NUMBER = 1e7 SMALL_NUMBER = 1e-7 # These are special non-terminal symbols that are expanded to literals, either from # a small dict that we collect during training, or by copying from the context. ROOT_NONTERMINAL = 'Expression' VARIABLE_NONTERMINAL = 'Variable' LITERAL_NONTERMINALS = ['IntLiteral', 'CharLiteral', 'StringLiteral'] LAST_USED_TOKEN_NAME = '<LAST TOK>' EXPANSION_LABELED_EDGE_TYPE_NAMES = ["Child"] EXPANSION_UNLABELED_EDGE_TYPE_NAMES = ["Parent", "NextUse", "NextToken", "NextSibling", "NextSubtree", "InheritedToSynthesised"] class MissingProductionException(Exception): pass ExpansionInformation = namedtuple("ExpansionInformation", ["node_to_type", "node_to_label", "node_to_prod_id", "node_to_children", "node_to_parent", "node_to_synthesised_attr_node", "node_to_inherited_attr_node", "variable_to_last_use_id", "node_to_representation", "node_to_labeled_incoming_edges", "node_to_unlabeled_incoming_edges", "context_token_representations", "context_token_mask", "context_tokens", "literal_production_choice_normalizer", "nodes_to_expand", "expansion_logprob", "num_expansions", ]) def clone_list_defaultdict(dict_to_clone) -> defaultdict: return defaultdict(list, {key: list(value) for (key, value) in dict_to_clone.items()}) def clone_expansion_info(expansion_info: ExpansionInformation, increment_expansion_counter: bool=False) -> ExpansionInformation: """Create a clone of the expansion information with fresh copies of all (morally) mutable components.""" return ExpansionInformation(node_to_type=dict(expansion_info.node_to_type), node_to_label=dict(expansion_info.node_to_label), node_to_prod_id=dict(expansion_info.node_to_prod_id), node_to_children=clone_list_defaultdict(expansion_info.node_to_children), node_to_parent=dict(expansion_info.node_to_parent), node_to_synthesised_attr_node=dict(expansion_info.node_to_synthesised_attr_node), node_to_inherited_attr_node=dict(expansion_info.node_to_inherited_attr_node), variable_to_last_use_id=dict(expansion_info.variable_to_last_use_id), node_to_representation=dict(expansion_info.node_to_representation), node_to_labeled_incoming_edges=dict(expansion_info.node_to_labeled_incoming_edges), node_to_unlabeled_incoming_edges=dict(expansion_info.node_to_unlabeled_incoming_edges), context_token_representations=expansion_info.context_token_representations, context_token_mask=expansion_info.context_token_mask, context_tokens=expansion_info.context_tokens, literal_production_choice_normalizer=expansion_info.literal_production_choice_normalizer, nodes_to_expand=deque(expansion_info.nodes_to_expand), expansion_logprob=[expansion_info.expansion_logprob[0]], num_expansions=expansion_info.num_expansions + (1 if increment_expansion_counter else 0)) def get_tokens_from_expansion(expansion_info: ExpansionInformation, root_node: int) -> List[str]: def dfs(node: int) -> List[str]: children = expansion_info.node_to_children.get(node) if children is None: return [expansion_info.node_to_label[node]] else: return [tok for child in children for tok in dfs(child)] return dfs(root_node) def raw_rhs_to_tuple(symbol_to_kind, symbol_to_label, rhs_ids: Iterable[int]) -> Tuple: rhs = [] for rhs_node_id in rhs_ids: rhs_node_kind = symbol_to_kind[str(rhs_node_id)] if rhs_node_kind == "Token": rhs.append(symbol_to_label[str(rhs_node_id)]) else: rhs.append(rhs_node_kind) return tuple(rhs) def get_restricted_edge_types(hyperparameters: Dict[str, Any]): expansion_labeled_edge_types = OrderedDict( (name, edge_id) for (edge_id, name) in enumerate(n for n in EXPANSION_LABELED_EDGE_TYPE_NAMES if n not in hyperparameters.get('exclude_edge_types', []))) expansion_unlabeled_edge_types = OrderedDict( (name, edge_id) for (edge_id, name) in enumerate(n for n in EXPANSION_UNLABELED_EDGE_TYPE_NAMES if n not in hyperparameters.get('exclude_edge_types', []))) return expansion_labeled_edge_types, expansion_unlabeled_edge_types class NAGDecoder(object): """ Class implementing Neural Attribute Grammar decoding. It is important to note that the training code (batched) and testing code (non-batched, to ease beam search) are fairly independent. At train time, we know the target values for all nodes in the graph, and hence can compute representations for all nodes in one go (using a standard AsyncGNN). We then read out the representation for all nodes at which we make predictions, pass them through a layer to obtain logits for these, and then use cross-entropy loss to optimize them. At test time, we need to deal with a dynamic structure of the graph. To handle this, we query the NN step-wise, using three kinds of operations: * Context + Initialization: This produces the representation of the first few nodes in the expansion graph (i.e., corresponding to the last variable / token / root node). * Message passing: This does one-step propagation in the AysncGNN (exposed as operation 'eg_step_propagation_result'), producing the representation of one new node. * Predict expansion: Project a node representation to a decision how to expand it (exposed as ops 'eg_*production_choice_probs'). All the construction of edges, sampling, beam search, etc. is handled in pure Python. In comments and documentation in this class, shape annotations are often provided, in which abbreviations are used: - B ~ "Batch size": Number of NAG graphs in the current batch (corresponds to number of contexts). - GP ~ "Grammar Productions": Number of NAG graph nodes at which we need to choose a production from the grammar. - VP ~ "Variable Productions": Number of NAG graph nodes at which we need to choose a variable from the context. - LP ~ "Literal Productions": Number of NAG graph nodes at which we need to choose a literal from the context. - D ~ "Dimension": Dimension of the node representations in the core (async) GNN. Hyperparameter "eg_hidden_size". """ @staticmethod def get_default_hyperparameters() -> Dict[str, Any]: defaults = { 'eg_token_vocab_size': 100, 'eg_literal_vocab_size': 10, 'eg_max_variable_choices': 10, 'eg_propagation_substeps': 50, 'eg_hidden_size': 64, 'eg_edge_label_size': 16, 'exclude_edge_types': [], 'eg_graph_rnn_cell': 'GRU', # GRU or RNN 'eg_graph_rnn_activation': 'tanh', # tanh, ReLU 'eg_use_edge_bias': False, 'eg_use_vars_for_production_choice': True, # Use mean-pooled variable representation as input for production choice 'eg_update_last_variable_use_representation': True, 'eg_use_literal_copying': True, 'eg_use_context_attention': True, 'eg_max_context_tokens': 500, } return defaults def __init__(self, context_model: Model): # We simply share all internal data structures with the context model, so store it: self.__context_model = context_model pass @property def hyperparameters(self): return self.__context_model.hyperparameters @property def metadata(self): return self.__context_model.metadata @property def parameters(self): return self.__context_model.parameters @property def placeholders(self): return self.__context_model.placeholders @property def ops(self): return self.__context_model.ops @property def sess(self): return self.__context_model.sess def train_log(self, msg) -> None: return self.__context_model.train_log(msg) def test_log(self, msg) -> None: return self.__context_model.test_log(msg) # ---------- Constructing the core model ---------- def make_parameters(self): # Use an OrderedDict so that we can rely on the iteration order later. self.__expansion_labeled_edge_types, self.__expansion_unlabeled_edge_types = \ get_restricted_edge_types(self.hyperparameters) eg_token_vocab_size = len(self.metadata['eg_token_vocab']) eg_hidden_size = self.hyperparameters['eg_hidden_size'] eg_edge_label_size = self.hyperparameters['eg_edge_label_size'] self.parameters['eg_token_embeddings'] = \ tf.get_variable(name='eg_token_embeddings', shape=[eg_token_vocab_size, eg_hidden_size], initializer=tf.random_normal_initializer(), ) # TODO: Should be more generic than being fixed to the number productions... if eg_edge_label_size > 0: self.parameters['eg_edge_label_embeddings'] = \ tf.get_variable(name='eg_edge_label_embeddings', shape=[len(self.metadata['eg_edge_label_vocab']), eg_edge_label_size], initializer=tf.random_normal_initializer(), ) def make_placeholders(self, is_train: bool) -> None: self.placeholders['eg_node_token_ids'] = tf.placeholder(tf.int32, [None], name="eg_node_token_ids") # List of lists of lists of (embeddings of) labels of edges L_{r,s,e}: Labels of edges of type # e propagating in step s. # Restrictions: len(L_{s,e}) = len(S_{s,e}) [see __make_train_placeholders] self.placeholders['eg_edge_label_ids'] = \ [[tf.placeholder(dtype=tf.int32, shape=[None], name="eg_edge_label_step%i_typ%i" % (step, edge_typ)) for edge_typ in range(len(self.__expansion_labeled_edge_types))] for step in range(self.hyperparameters['eg_propagation_substeps'])] if is_train: self.__make_train_placeholders() else: self.__make_test_placeholders() def __make_train_placeholders(self): eg_edge_type_num = len(self.__expansion_labeled_edge_types) + len(self.__expansion_unlabeled_edge_types) # Initial nodes I: Node IDs that will have no (active) incoming edges. self.placeholders['eg_initial_node_ids'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_initial_node_ids") # Sending nodes S_{s,e}: Source node ids of edges of type e propagating in step s. # Restrictions: If v in S_{s,e}, then v in R_{s'} for s' < s or v in I. self.placeholders['eg_sending_node_ids'] = \ [[tf.placeholder(dtype=tf.int32, shape=[None], name="eg_sending_node_ids_step%i_edgetyp%i" % (step, edge_typ)) for edge_typ in range(eg_edge_type_num)] for step in range(self.hyperparameters['eg_propagation_substeps'])] # Normalised edge target nodes T_{s}: Targets of edges propagating in step s, normalised to a # continuous range starting from 0. This is used for aggregating messages from the sending nodes. self.placeholders['eg_msg_target_node_ids'] = \ [tf.placeholder(dtype=tf.int32, shape=[None], name="eg_msg_targets_nodes_step%i" % (step,)) for step in range(self.hyperparameters['eg_propagation_substeps'])] # Receiving nodes R_{s}: Target node ids of aggregated messages in propagation step s. # Restrictions: If v in R_{s}, v not in R_{s'} for all s' != s and v not in I self.placeholders['eg_receiving_node_ids'] = \ [tf.placeholder(dtype=tf.int32, shape=[None], name="eg_receiving_nodes_step%i" % (step,)) for step in range(self.hyperparameters['eg_propagation_substeps'])] # Number of receiving nodes N_{s} # Restrictions: N_{s} = len(R_{s}) self.placeholders['eg_receiving_node_nums'] = \ tf.placeholder(dtype=tf.int32, shape=[self.hyperparameters['eg_propagation_substeps']], name="eg_receiving_nodes_nums") self.placeholders['eg_production_nodes'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_production_nodes") if self.hyperparameters['eg_use_vars_for_production_choice']: self.placeholders['eg_production_var_last_use_node_ids'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_production_var_last_use_node_ids") self.placeholders['eg_production_var_last_use_node_ids_target_ids'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_production_var_last_use_node_ids_target_ids") self.placeholders['eg_production_node_choices'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_production_node_choices") if self.hyperparameters['eg_use_context_attention']: self.placeholders['eg_production_to_context_id'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_production_to_context_id") self.placeholders['eg_varproduction_nodes'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name='eg_varproduction_nodes') self.placeholders['eg_varproduction_options_nodes'] = \ tf.placeholder(dtype=tf.int32, shape=[None, self.hyperparameters['eg_max_variable_choices']], name='eg_varproduction_options_nodes') self.placeholders['eg_varproduction_options_mask'] = \ tf.placeholder(dtype=tf.float32, shape=[None, self.hyperparameters['eg_max_variable_choices']], name='eg_varproduction_options_mask') self.placeholders['eg_varproduction_node_choices'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name='eg_varproduction_node_choices') self.placeholders['eg_litproduction_nodes'] = {} self.placeholders['eg_litproduction_node_choices'] = {} self.placeholders['eg_litproduction_to_context_id'] = {} self.placeholders['eg_litproduction_choice_normalizer'] = {} for literal_kind in LITERAL_NONTERMINALS: self.placeholders['eg_litproduction_nodes'][literal_kind] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_litproduction_nodes_%s" % literal_kind) self.placeholders['eg_litproduction_node_choices'][literal_kind] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_litproduction_node_choices_%s" % literal_kind) if self.hyperparameters['eg_use_literal_copying']: self.placeholders['eg_litproduction_to_context_id'][literal_kind] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_litproduction_to_context_id_%s" % literal_kind) self.placeholders['eg_litproduction_choice_normalizer'][literal_kind] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_litproduction_choice_normalizer_%s" % literal_kind) def __make_test_placeholders(self): eg_h_dim = self.hyperparameters['eg_hidden_size'] self.placeholders['eg_production_node_representation'] = \ tf.placeholder(dtype=tf.float32, shape=[eg_h_dim], name="eg_production_node_representation") if self.hyperparameters['eg_use_vars_for_production_choice']: self.placeholders['eg_production_var_representations'] = \ tf.placeholder(dtype=tf.float32, shape=[None, eg_h_dim], name="eg_production_var_representations") if self.hyperparameters["eg_use_literal_copying"] or self.hyperparameters['eg_use_context_attention']: self.placeholders['context_token_representations'] = \ tf.placeholder(dtype=tf.float32, shape=[self.hyperparameters['eg_max_context_tokens'], eg_h_dim], name='context_token_representations') self.placeholders['eg_varproduction_node_representation'] = \ tf.placeholder(dtype=tf.float32, shape=[eg_h_dim], name="eg_varproduction_node_representation") self.placeholders['eg_num_variable_choices'] = \ tf.placeholder(dtype=tf.int32, shape=[], name='eg_num_variable_choices') self.placeholders['eg_varproduction_options_representations'] = \ tf.placeholder(dtype=tf.float32, shape=[None, eg_h_dim], name="eg_varproduction_options_representations") self.placeholders['eg_litproduction_node_representation'] = \ tf.placeholder(dtype=tf.float32, shape=[eg_h_dim], name="eg_litproduction_node_representation") if self.hyperparameters['eg_use_literal_copying']: self.placeholders['eg_litproduction_choice_normalizer'] = \ tf.placeholder(dtype=tf.int32, shape=[None], name="eg_litproduction_choice_normalizer") # Used for one-step message propagation of expansion graph: eg_edge_type_num = len(self.__expansion_labeled_edge_types) + len(self.__expansion_unlabeled_edge_types) self.placeholders['eg_msg_source_representations'] = \ [tf.placeholder(dtype=tf.float32, shape=[None, eg_h_dim], name="eg_msg_source_representations_etyp%i" % (edge_typ,)) for edge_typ in range(eg_edge_type_num)] self.placeholders['eg_msg_target_label_id'] =\ tf.placeholder(dtype=tf.int32, shape=[], name='eg_msg_target_label_id') def make_model(self, is_train: bool=True): if is_train: self.__make_train_model() else: self.__make_test_model() def __embed_edge_labels(self, num_eg_substeps: int) -> List[List[tf.Tensor]]: edge_labels = [] for step in range(num_eg_substeps): step_edge_labels = [] for edge_typ in range(len(self.__expansion_labeled_edge_types)): if self.hyperparameters['eg_edge_label_size'] > 0: edge_label_embeddings = \ tf.nn.embedding_lookup(self.parameters['eg_edge_label_embeddings'], self.placeholders['eg_edge_label_ids'][step][edge_typ]) else: edge_label_embeddings = \ tf.zeros(shape=[tf.shape(self.placeholders['eg_edge_label_ids'][step][edge_typ])[0], 0]) step_edge_labels.append(edge_label_embeddings) edge_labels.append(step_edge_labels) return edge_labels def __make_train_model(self): # Pick CG representation where possible, and use embedding otherwise: eg_node_label_embeddings = \ tf.nn.embedding_lookup(self.parameters['eg_token_embeddings'], self.placeholders['eg_node_token_ids']) eg_initial_node_representations = \ tf.where(condition=self.ops['eg_node_representation_use_from_context'], x=self.ops['eg_node_representations_from_context'], y=eg_node_label_embeddings) # ----- (3) Compute representations of expansion graph using an async GNN submodel: eg_h_dim = self.hyperparameters['eg_hidden_size'] eg_hypers = {name.replace("eg_", "", 1): value for (name, value) in self.hyperparameters.items() if name.startswith("eg_")} eg_hypers['propagation_rounds'] = 1 eg_hypers['num_labeled_edge_types'] = len(self.__expansion_labeled_edge_types) eg_hypers['num_unlabeled_edge_types'] = len(self.__expansion_unlabeled_edge_types) with tf.variable_scope("ExpansionGraph"): eg_model = AsyncGGNN(eg_hypers) # Note that we only use a single async schedule here, so every argument is wrapped in # [] to use the generic code supporting many schedules: eg_node_representations = \ eg_model.async_ggnn_layer( eg_initial_node_representations, [self.placeholders['eg_initial_node_ids']], [self.placeholders['eg_sending_node_ids']], [self.__embed_edge_labels(self.hyperparameters['eg_propagation_substeps'])], [self.placeholders['eg_msg_target_node_ids']], [self.placeholders['eg_receiving_node_ids']], [self.placeholders['eg_receiving_node_nums']]) # ----- (4) Finally, try to predict the right productions: # === Grammar productions: eg_production_node_representations = \ tf.gather(params=eg_node_representations, indices=self.placeholders['eg_production_nodes']) # Shape [num_choice_nodes, D] if self.hyperparameters['eg_use_vars_for_production_choice']: variable_representations_at_prod_choice = \ tf.gather(params=eg_node_representations, indices=self.placeholders['eg_production_var_last_use_node_ids']) variable_representations_at_prod_choice = \ tf.unsorted_segment_mean( data=variable_representations_at_prod_choice, segment_ids=self.placeholders['eg_production_var_last_use_node_ids_target_ids'], num_segments=tf.shape(eg_production_node_representations)[0]) else: variable_representations_at_prod_choice = None eg_production_choice_logits = \ self.__make_production_choice_logits_model( eg_production_node_representations, variable_representations_at_prod_choice, self.ops.get('context_token_representations'), self.placeholders.get('context_token_mask'), self.placeholders.get('eg_production_to_context_id')) # === Variable productions eg_varproduction_node_representations = \ tf.gather(params=eg_node_representations, indices=self.placeholders['eg_varproduction_nodes']) # Shape: [VP, D] eg_varproduction_options_nodes_flat = \ tf.reshape(self.placeholders['eg_varproduction_options_nodes'], shape=[-1]) # Shape [VP * eg_max_variable_choices] eg_varproduction_options_representations = \ tf.reshape(tf.gather(params=eg_node_representations, indices=eg_varproduction_options_nodes_flat ), # Shape: [VP * eg_max_variable_choices, D] shape=[-1, self.hyperparameters['eg_max_variable_choices'], eg_h_dim] ) # Shape: [VP, eg_max_variable_choices, D] eg_varproduction_choice_logits = \ self.__make_variable_choice_logits_model( eg_varproduction_node_representations, eg_varproduction_options_representations, ) # Shape: [VP, eg_max_variable_choices] # Mask out unused choice options out: eg_varproduction_choice_logits += \ (1.0 - self.placeholders['eg_varproduction_options_mask']) * -BIG_NUMBER # === Literal productions literal_logits = {} for literal_kind in LITERAL_NONTERMINALS: eg_litproduction_representation = \ tf.gather(params=eg_node_representations, indices=self.placeholders['eg_litproduction_nodes'][literal_kind] ) # Shape: [LP, D] eg_litproduction_to_context_id, eg_litproduction_choice_normalizer = None, None if self.hyperparameters['eg_use_literal_copying']: eg_litproduction_to_context_id = \ self.placeholders['eg_litproduction_to_context_id'][literal_kind] eg_litproduction_choice_normalizer = \ self.placeholders['eg_litproduction_choice_normalizer'][literal_kind] literal_logits[literal_kind] = \ self.__make_literal_choice_logits_model( literal_kind, eg_litproduction_representation, self.ops.get('context_token_representations'), self.placeholders.get('context_token_mask'), eg_litproduction_to_context_id, eg_litproduction_choice_normalizer, ) # (5) Compute loss: raw_prod_loss = \ tf.nn.sparse_softmax_cross_entropy_with_logits( logits=eg_production_choice_logits, labels=self.placeholders['eg_production_node_choices']) raw_var_loss = \ tf.nn.sparse_softmax_cross_entropy_with_logits( logits=eg_varproduction_choice_logits, labels=self.placeholders['eg_varproduction_node_choices']) # Normalize all losses by number of actual decisions made, which differ from batch to batch. # Can't use tf.reduce_mean because these can be empty, and reduce_mean gives NaN for those: prod_loss = tf.reduce_sum(raw_prod_loss) / (tf.cast(tf.size(raw_prod_loss), dtype=tf.float32) + SMALL_NUMBER) var_loss = tf.reduce_sum(raw_var_loss) / (tf.cast(tf.size(raw_var_loss), dtype=tf.float32) + SMALL_NUMBER) if len(LITERAL_NONTERMINALS) > 0: raw_lit_loss = [tf.nn.sparse_softmax_cross_entropy_with_logits( logits=literal_logits[literal_kind], labels=self.placeholders['eg_litproduction_node_choices'][literal_kind]) for literal_kind in LITERAL_NONTERMINALS] raw_lit_loss = tf.concat(raw_lit_loss, axis=0) lit_loss = tf.reduce_sum(raw_lit_loss) / (tf.cast(tf.size(raw_lit_loss), dtype=tf.float32) + SMALL_NUMBER) else: raw_lit_loss = [0.0] lit_loss = 0.0 self.ops['loss'] = prod_loss + var_loss + lit_loss # TODO: If we want to batch this per sample, then we need an extra placeholder that maps productions/variables to # samples and use unsorted_segment_sum to gather together all the logprobs from all productions. self.ops['log_probs'] = -tf.reduce_sum(raw_prod_loss) - tf.reduce_sum(raw_var_loss) - tf.reduce_sum(raw_lit_loss) def __make_test_model(self): # Almost everywhere, we need to add extra dimensions to account for the fact that in training, # we need to handle several samples in one batch, whereas we don't do that during test: context_token_representations = self.placeholders.get('context_token_representations') context_token_masks = self.placeholders.get('context_token_mask') if context_token_representations is not None: context_token_representations = tf.expand_dims(context_token_representations, axis=0) # === Grammar productions: if self.hyperparameters['eg_use_vars_for_production_choice']: pooled_variable_representations_at_prod_choice = \ tf.reduce_mean(self.placeholders['eg_production_var_representations'], axis=0) pooled_variable_representations_at_prod_choice = \ tf.expand_dims(pooled_variable_representations_at_prod_choice, axis=0) else: pooled_variable_representations_at_prod_choice = None eg_production_choice_logits = \ self.__make_production_choice_logits_model( tf.expand_dims(self.placeholders['eg_production_node_representation'], axis=0), pooled_variable_representations_at_prod_choice, context_token_representations, context_token_masks, production_to_context_id=tf.constant([0], dtype=tf.int32)) self.ops['eg_production_choice_probs'] = tf.nn.softmax(eg_production_choice_logits)[0] # === Variable productions eg_varproduction_choice_logits = \ self.__make_variable_choice_logits_model( tf.expand_dims(self.placeholders['eg_varproduction_node_representation'], axis=0), tf.expand_dims(self.placeholders['eg_varproduction_options_representations'], axis=0), ) eg_varproduction_choice_logits = tf.squeeze(eg_varproduction_choice_logits, axis=0) self.ops['eg_varproduction_choice_probs'] = tf.nn.softmax(eg_varproduction_choice_logits, dim=-1) # === Literal productions self.ops['eg_litproduction_choice_probs'] = {} for literal_kind in LITERAL_NONTERMINALS: literal_logits = \ self.__make_literal_choice_logits_model( literal_kind, tf.expand_dims(self.placeholders['eg_litproduction_node_representation'], axis=0), context_token_representations, context_token_masks, tf.constant([0], dtype=tf.int32), self.placeholders.get('eg_litproduction_choice_normalizer'), ) self.ops['eg_litproduction_choice_probs'][literal_kind] = \ tf.nn.softmax(literal_logits, axis=-1)[0] # Expose one-step message propagation in expansion graph: eg_hypers = {name.replace("eg_", "", 1): value for (name, value) in self.hyperparameters.items() if name.startswith("eg_")} eg_hypers['propagation_rounds'] = 1 eg_hypers['num_labeled_edge_types'] = len(self.__expansion_labeled_edge_types) eg_hypers['num_unlabeled_edge_types'] = len(self.__expansion_unlabeled_edge_types) with tf.variable_scope("ExpansionGraph"): eg_model = AsyncGGNN(eg_hypers) # First, embed edge labels. We only need the first step: edge_labels = self.__embed_edge_labels(1)[0] all_sending_representations = \ tf.concat(self.placeholders['eg_msg_source_representations'], axis=0) msg_target_ids = tf.zeros([tf.shape(all_sending_representations)[0]], dtype=tf.int32) receiving_node_num = tf.constant(1, dtype=tf.int32) # Get node label embedding: target_node_label_embeddings =\ tf.nn.embedding_lookup( self.parameters['eg_token_embeddings'], tf.expand_dims(self.placeholders['eg_msg_target_label_id'], axis=0), ) # Shape [1, eg_h_dim] with tf.variable_scope("async_ggnn/prop_round0"): self.ops['eg_step_propagation_result'] = \ eg_model.propagate_one_step(self.placeholders['eg_msg_source_representations'], edge_labels, msg_target_ids, receiving_node_num, target_node_label_embeddings)[0] def __make_production_choice_logits_model( self, production_node_representations: tf.Tensor, variable_representations_at_prod_choice: Optional[tf.Tensor], context_representations: Optional[tf.Tensor], context_representations_mask: Optional[tf.Tensor], production_to_context_id: Optional[tf.Tensor], ) -> tf.Tensor: """ Args: production_node_representations: Representations of nodes at which we choose grammar productions. Shape: [GP, D] variable_representations_at_prod_choice: [Optional] Representations of the current values of variables at nodes at which we choose grammar productions. Shape: [GP, D] context_representations: [Optional] Representations of nodes in context. Shape: [B, eg_max_context_tokens, D] context_representations_mask: [Optional] 0/1 mask marking which entries in context_representations are meaningful. Shape: [B, eg_max_context_tokens] production_to_context_id: [Optional] Map from entries in production_node_representations to the context. Shape: [GP] Returns: Logits for the choices of grammar production rules in the current batch. Shape: [GP, eg_production_num] """ eg_production_choice_inputs = [production_node_representations] if self.hyperparameters['eg_use_vars_for_production_choice']: eg_production_choice_inputs.append(variable_representations_at_prod_choice) if self.hyperparameters.get('eg_use_context_attention', False): context_token_representations = \ tf.gather(params=context_representations, indices=production_to_context_id) # Shape [GP, eg_max_context_tokens, D] attention_scores = \ tf.matmul(a=tf.expand_dims(production_node_representations, axis=1), # Shape [GP, 1, D] b=context_token_representations, # Shape [GP, eg_max_context_tokens, D] transpose_b=True) # Shape [GP, 1, eg_max_context_tokens] attention_scores = tf.squeeze(attention_scores, axis=1) # Shape [GP, eg_max_context_tokens] context_masks = tf.gather(params=context_representations_mask, indices=production_to_context_id) context_masks = (1 - context_masks) * -BIG_NUMBER attention_scores += context_masks attention_weight = tf.nn.softmax(attention_scores) weighted_context_token_representations = \ context_token_representations * tf.expand_dims(attention_weight, axis=-1) # Shape [num_choice_nodes, eg_max_context_tokens, D] context_representations = \ tf.reduce_sum(weighted_context_token_representations, axis=1) # Shape [num_choice_nodes, D] eg_production_choice_inputs.append(context_representations) eg_production_choice_input = tf.concat(eg_production_choice_inputs, axis=1) return tf.layers.dense(eg_production_choice_input, units=self.metadata['eg_production_num'], activation=None, kernel_initializer=tf.glorot_uniform_initializer(), name="grammar_choice_representation_to_logits", ) def __make_variable_choice_logits_model( self, varchoice_node_representation: tf.Tensor, varchoice_options_representations: tf.Tensor) -> tf.Tensor: """ Args: varchoice_node_representation: Representations of nodes at which we choose variables. Shape: [VP, D] varchoice_options_representations: Representations of variables that we can choose at each choice node. Shape: [VP, num_variable_choices, D] Returns: Logits for the choices of variables in the current batch. Shape: [VP, num_variable_choices] """ varchoice_options_inner_prod = \ tf.einsum('sd,svd->sv', varchoice_node_representation, varchoice_options_representations) # Shape: [VP, num_variable_choices] varchoice_node_representation_repeated = \ tf.tile(tf.expand_dims(varchoice_node_representation, axis=-2), multiples=[1, tf.shape(varchoice_options_representations)[1], 1], ) # Shape: [VP, num_variable_choices, D] varchoice_final_options_representations = \ tf.concat([varchoice_node_representation_repeated, varchoice_options_representations, tf.expand_dims(varchoice_options_inner_prod, axis=-1)], axis=-1) # Shape: [VP, num_variable_choices, 2*D + 1] varchoice_logits = \ tf.layers.dense(varchoice_final_options_representations, units=1, use_bias=False, activation=None, kernel_initializer=tf.glorot_uniform_initializer(), name="varchoice_representation_to_logits", ) # Shape: [VP, num_variable_choices, 1] return tf.squeeze(varchoice_logits, axis=-1) # Shape: [VP, num_variable_choices] def __make_literal_choice_logits_model( self, literal_kind: str, litproduction_node_representations: tf.Tensor, context_representations: Optional[tf.Tensor], context_representations_mask: Optional[tf.Tensor], litproduction_to_context_id: Optional[tf.Tensor], litproduction_choice_normalizer: Optional[tf.Tensor] ) -> tf.Tensor: """ Args: literal_kind: Kind of literal we are generating. litproduction_node_representations: Representations of nodes at which we choose literals. Shape: [LP, D] context_representations: [Optional] Representations of nodes in context. Shape: [B, eg_max_context_tokens, D] context_representations_mask: [Optional] 0/1 mask marking which entries in context_representations are meaningful. Shape: [B, eg_max_context_tokens] litproduction_to_context_id: [Optional] Map from entries in litproduction_node_representations to the context. Shape: [LP] litproduction_choice_normalizer: [Optional] If copying from the context tokens, some of them may refer to the same token (potentially one present in the vocab). This tensor allows normalisation in these cases, by assigning the same ID to all occurrences of the same token (usually the first one). Shape: [LP, eg_max_context_tokens + literal_vocab_size] Returns: Logits for the choices of literal production rules in the current batch. Shape: If using copying: [LP, literal_vocab_size + eg_max_context_tokens] Otherwise: [LP, literal_vocab_size] """ literal_logits = \ tf.layers.dense(litproduction_node_representations, units=len(self.metadata["eg_literal_vocabs"][literal_kind]), activation=None, kernel_initializer=tf.glorot_uniform_initializer(), name="%s_literal_choice_representation_to_logits" % literal_kind, ) # Shape [LP, lit_vocab_size] if not self.hyperparameters['eg_use_literal_copying']: return literal_logits # Do dot product with the context tokens: context_token_representations = \ tf.gather(params=context_representations, indices=litproduction_to_context_id) # Shape [LP, eg_max_context_tokens, D] copy_scores = \ tf.matmul(a=tf.expand_dims(litproduction_node_representations, axis=1), # Shape [LP, 1, D] b=context_token_representations, # Shape [LP, eg_max_context_tokens, D] transpose_b=True) # Shape [LP, 1, eg_max_context_tokens] copy_scores = tf.squeeze(copy_scores, axis=1) # Shape [LP, eg_max_context_tokens] context_masks = tf.gather(params=context_representations_mask, indices=litproduction_to_context_id) context_masks = (1 - context_masks) * -BIG_NUMBER # Mask out unused context tokens copy_scores += context_masks vocab_choices_and_copy_scores = \ tf.concat([literal_logits, copy_scores], axis=1) # Shape [num_choice_nodes, literal_vocab_size + eg_max_context_tokens] # Now collapse logits relating to the same token (e.g., by showing up several times in context): normalized_vocab_choices_and_copy_logits = \ unsorted_segment_logsumexp(scores=tf.reshape(vocab_choices_and_copy_scores, shape=[-1]), segment_ids=litproduction_choice_normalizer, num_segments=tf.shape(litproduction_choice_normalizer)[0]) num_literal_options = len(self.metadata["eg_literal_vocabs"][literal_kind]) num_literal_options += self.hyperparameters['eg_max_context_tokens'] return tf.reshape(normalized_vocab_choices_and_copy_logits, shape=[-1, num_literal_options]) # ---------- Data loading (raw data to learning-ready data) ---------- @staticmethod def init_metadata(raw_metadata: Dict[str, Any]) -> None: raw_metadata['eg_token_counter'] = Counter() raw_metadata['eg_literal_counters'] = defaultdict(Counter) raw_metadata['eg_production_vocab'] = defaultdict(set) @staticmethod def load_metadata_from_sample(raw_sample: Dict[str, Any], raw_metadata: Dict[str, Any]) -> None: symbol_id_to_kind = raw_sample['SymbolKinds'] symbol_id_to_label = raw_sample['SymbolLabels'] for symbol_label in symbol_id_to_label.values(): raw_metadata['eg_token_counter'][symbol_label] += 1 for (node_id, symbol_kind) in symbol_id_to_kind.items(): raw_metadata['eg_token_counter'][symbol_kind] += 1 if symbol_kind in LITERAL_NONTERMINALS: literal = symbol_id_to_label[node_id] raw_metadata['eg_literal_counters'][symbol_kind][literal] += 1 last_token_before_hole = raw_sample['ContextGraph']['NodeLabels'][str(raw_sample['LastTokenBeforeHole'])] raw_metadata['eg_token_counter'][last_token_before_hole] += 1 for (lhs_id, rhs_ids) in raw_sample['Productions'].items(): lhs_kind = symbol_id_to_kind[str(lhs_id)] rhs = raw_rhs_to_tuple(symbol_id_to_kind, symbol_id_to_label, rhs_ids) raw_metadata['eg_production_vocab'][lhs_kind].add(rhs) def finalise_metadata(self, raw_metadata_list: List[Dict[str, Any]], final_metadata: Dict[str, Any]) -> None: # First, merge all needed information: merged_token_counter = Counter() merged_literal_counters = {literal_kind: Counter() for literal_kind in LITERAL_NONTERMINALS} merged_production_vocab = defaultdict(set) for raw_metadata in raw_metadata_list: merged_token_counter += raw_metadata['eg_token_counter'] for literal_kind in LITERAL_NONTERMINALS: merged_literal_counters[literal_kind] += raw_metadata['eg_literal_counters'][literal_kind] for lhs, rhs_options in raw_metadata['eg_production_vocab'].items(): merged_production_vocab[lhs].update(rhs_options) final_metadata['eg_token_vocab'] = \ Vocabulary.create_vocabulary(merged_token_counter, max_size=self.hyperparameters['eg_token_vocab_size']) final_metadata["eg_literal_vocabs"] = {} for literal_kind in LITERAL_NONTERMINALS: final_metadata["eg_literal_vocabs"][literal_kind] = \ Vocabulary.create_vocabulary(merged_literal_counters[literal_kind], count_threshold=0, max_size=self.hyperparameters['eg_literal_vocab_size']) next_production_id = 0 eg_production_vocab = defaultdict(dict) next_edge_label_id = 0 eg_edge_label_vocab = defaultdict(dict) for lhs, rhs_options in sorted(merged_production_vocab.items(), key=lambda t: t[0]): final_metadata['eg_token_vocab'].add_or_get_id(lhs) for rhs in sorted(rhs_options): production_id = eg_production_vocab[lhs].get(rhs) if production_id is None: production_id = next_production_id eg_production_vocab[lhs][rhs] = production_id next_production_id += 1 for (rhs_symbol_index, symbol) in enumerate(rhs): final_metadata['eg_token_vocab'].add_or_get_id(symbol) eg_edge_label_vocab[(production_id, rhs_symbol_index)] = next_edge_label_id next_edge_label_id += 1 final_metadata["eg_production_vocab"] = eg_production_vocab final_metadata["eg_edge_label_vocab"] = eg_edge_label_vocab final_metadata['eg_production_num'] = next_production_id self.train_log("Imputed grammar:") for lhs, rhs_options in eg_production_vocab.items(): for rhs, idx in sorted(rhs_options.items(), key=lambda v: v[1]): self.train_log(" %s -[%02i]-> %s" % (str(lhs), idx, " ".join(rhs))) self.train_log("Known literals:") for literal_kind in LITERAL_NONTERMINALS: self.train_log(" %s: %s" % (literal_kind, sorted(final_metadata['eg_literal_vocabs'][literal_kind].token_to_id.keys()))) @staticmethod def __load_expansiongraph_data_from_sample(hyperparameters: Dict[str, Any], metadata: Dict[str, Any], raw_sample: Dict[str, Any], result_holder: Dict[str, Any], is_train: bool) -> None: result_holder['eg_node_labels'] = [] # "Downwards" version of a node (depends on parents & pred's). Keys are IDs from symbol expansion record: node_to_inherited_id = {} # type: Dict[int, int] # "Upwards" version of a node (depends on children). Keys are IDs from symbol expansion record: node_to_synthesised_id = {} # type: Dict[int, int] # Maps variable name to the id of the node where it was last used. Keys are variable names, values are from fresh space next to symbol expansion record: last_used_node_id = {} # type: Dict[str, int] # First, we create node ids for the bits of the context graph that we want to re-use # and populate the intermediate data structures with them: prod_root_node = min(int(v) for v in raw_sample['Productions'].keys()) node_to_inherited_id[prod_root_node] = 0 result_holder['eg_node_labels'].append(metadata['eg_token_vocab'].get_id_or_unk(ROOT_NONTERMINAL)) last_used_node_id[LAST_USED_TOKEN_NAME] = -1 node_to_synthesised_id[last_used_node_id[LAST_USED_TOKEN_NAME]] = 1 result_holder['eg_node_labels'].append(metadata['eg_token_vocab'].get_id_or_unk( raw_sample['ContextGraph']['NodeLabels'][str(raw_sample['LastTokenBeforeHole'])])) if not is_train: result_holder['eg_variable_eg_node_ids'] = {} result_holder['eg_last_token_eg_node_id'] = node_to_synthesised_id[last_used_node_id[LAST_USED_TOKEN_NAME]] for var, cg_graph_var_node_id in raw_sample['LastUseOfVariablesInScope'].items(): eg_var_node_id = len(result_holder['eg_node_labels']) result_holder['eg_node_labels'].append(metadata['eg_token_vocab'].get_id_or_unk(var)) last_used_node_id[var] = -len(last_used_node_id) - 1 node_to_synthesised_id[last_used_node_id[var]] = eg_var_node_id if not is_train: result_holder['eg_variable_eg_node_ids'][var] = eg_var_node_id if is_train: NAGDecoder.__load_expansiongraph_training_data_from_sample(hyperparameters, metadata, raw_sample, prod_root_node, node_to_inherited_id, node_to_synthesised_id, last_used_node_id, result_holder) else: def collect_tokens(node: int) -> List[str]: node_tokens = [] children = raw_sample['Productions'].get(str(node)) or [] for child_id in children: if str(child_id) not in raw_sample['Productions']: child_label = raw_sample['SymbolLabels'].get(str(child_id)) or raw_sample['SymbolKinds'][str(child_id)] node_tokens.append(child_label) else: node_tokens.extend(collect_tokens(child_id)) return node_tokens result_holder['eg_tokens'] = collect_tokens(prod_root_node) result_holder['eg_root_node'] = node_to_inherited_id[prod_root_node] def compute_incoming_edges(self, nonterminal_nodes: Set[str], expansion_info: ExpansionInformation, node_id: int) -> None: assert (node_id not in expansion_info.node_to_unlabeled_incoming_edges) incoming_labeled_edges = defaultdict(list) # type: Dict[str, List[Tuple[int, int]]] incoming_unlabeled_edges = defaultdict(list) # type: Dict[str, List[int]] is_inherited_attr_node = node_id in expansion_info.node_to_synthesised_attr_node if is_inherited_attr_node: node_type = expansion_info.node_to_type[node_id] node_label = expansion_info.node_to_label[node_id] node_parent = expansion_info.node_to_parent[node_id] prod_id = expansion_info.node_to_prod_id[node_parent] this_node_child_index = expansion_info.node_to_children[node_parent].index(node_id) child_edge_label = self.metadata['eg_edge_label_vocab'][(prod_id, this_node_child_index)] incoming_labeled_edges['Child'].append((node_parent, child_edge_label)) if node_type == VARIABLE_NONTERMINAL: incoming_unlabeled_edges['NextUse'].append( expansion_info.node_to_synthesised_attr_node[expansion_info.variable_to_last_use_id[node_label]]) if node_type not in nonterminal_nodes: incoming_unlabeled_edges['NextToken'].append(expansion_info.node_to_synthesised_attr_node[ expansion_info.variable_to_last_use_id[ LAST_USED_TOKEN_NAME]]) node_siblings = expansion_info.node_to_children[node_parent] node_child_idx = node_siblings.index(node_id) if node_child_idx > 0: incoming_unlabeled_edges['NextSibling'].append( expansion_info.node_to_synthesised_attr_node[node_siblings[node_child_idx - 1]]) incoming_unlabeled_edges['NextSubtree'].append(expansion_info.node_to_synthesised_attr_node[ expansion_info.variable_to_last_use_id[ LAST_USED_TOKEN_NAME]]) else: inherited_node = expansion_info.node_to_inherited_attr_node[node_id] for child_node in expansion_info.node_to_children[inherited_node]: incoming_unlabeled_edges['Parent'].append(expansion_info.node_to_synthesised_attr_node[child_node]) incoming_unlabeled_edges['InheritedToSynthesised'].append(inherited_node) expansion_info.node_to_labeled_incoming_edges[node_id] = incoming_labeled_edges expansion_info.node_to_unlabeled_incoming_edges[node_id] = incoming_unlabeled_edges @staticmethod def __load_expansiongraph_training_data_from_sample( hyperparameters: Dict[str, Any], metadata: Dict[str, Any], raw_sample: Dict[str, Any], prod_root_node: int, node_to_inherited_id: Dict[int, int], node_to_synthesised_id: Dict[int, int], last_used_node_id: Dict[str, int], result_holder: Dict[str, Any]) -> None: # Shortcuts and temp data we use during construction: symbol_to_kind = raw_sample['SymbolKinds'] # type: Dict[str, str] symbol_to_prod = raw_sample['Productions'] # type: Dict[str, List[int]] symbol_to_label = raw_sample['SymbolLabels'] # type: Dict[str, str] variables_in_scope = list(sorted(raw_sample['LastUseOfVariablesInScope'].keys())) # type: List[str] # These are the things we'll use in the end: eg_node_id_to_prod_id = [] # type: List[Tuple[int, int]] # Pairs of (node id, chosen production id) eg_node_id_to_varchoice = [] # type: List[Tuple[int, List[int], int]] # Triples of (node id, [id of last var use], index of correct var) eg_node_id_to_literal_choice = defaultdict(list) # type: Dict[str, List[Tuple[int, int]]] # Maps literal kind to pairs of (node id, chosen literal id) eg_prod_node_to_var_last_uses = {} # type: Dict[int, np.ndarray] # Dict from production node id to [id of last var use] eg_schedule = [] # type: List[Dict[str, List[Tuple[int, int, Optional[int]]]]] # edge type name to edges of that type in each expansion step. # We will use these to pick literals: eg_literal_tok_to_idx = {} if hyperparameters['eg_use_literal_copying']: eg_literal_choice_normalizer_maps = {} # For each literal kind, we compute a "normalizer map", which we use to identify # choices that correspond to the same literal (e.g., when using a literal several # times in context) for literal_kind in LITERAL_NONTERMINALS: # Collect all choices (vocab + things we can copy from): literal_vocab = metadata['eg_literal_vocabs'][literal_kind] literal_choices = \ literal_vocab.id_to_token \ + result_holder['context_nonkeyword_tokens'][:hyperparameters['eg_max_context_tokens']] first_tok_occurrences = {} num_choices = hyperparameters['eg_max_context_tokens'] + len(literal_vocab) normalizer_map = np.arange(num_choices, dtype=np.int16) for (token_idx, token) in enumerate(literal_choices): first_occ = first_tok_occurrences.get(token) if first_occ is not None: normalizer_map[token_idx] = first_occ else: first_tok_occurrences[token] = token_idx eg_literal_tok_to_idx[literal_kind] = first_tok_occurrences eg_literal_choice_normalizer_maps[literal_kind] = normalizer_map result_holder['eg_literal_choice_normalizer_maps'] = eg_literal_choice_normalizer_maps else: for literal_kind in LITERAL_NONTERMINALS: eg_literal_tok_to_idx[literal_kind] = metadata['eg_literal_vocabs'][literal_kind].token_to_id # Map prods onto internal numbering and compute propagation schedule: def declare_new_node(sym_exp_node_id: int, is_synthesised: bool) -> int: new_node_id = len(result_holder['eg_node_labels']) node_label = symbol_to_label.get(str(sym_exp_node_id)) or symbol_to_kind[str(sym_exp_node_id)] result_holder['eg_node_labels'].append(metadata['eg_token_vocab'].get_id_or_unk(node_label)) if is_synthesised: node_to_synthesised_id[sym_exp_node_id] = new_node_id else: node_to_inherited_id[sym_exp_node_id] = new_node_id return new_node_id def expand_node(node_id: int) -> None: rhs_node_ids = symbol_to_prod.get(str(node_id)) if rhs_node_ids is None: # In the case that we have no children, the downwards and upwards version of our node are the same: node_to_synthesised_id[node_id] = node_to_inherited_id[node_id] return declare_new_node(node_id, is_synthesised=True) # Figure out which production id this one is is and store it away: rhs = raw_rhs_to_tuple(symbol_to_kind, symbol_to_label, rhs_node_ids) known_lhs_productions = metadata['eg_production_vocab'][symbol_to_kind[str(node_id)]] if rhs not in known_lhs_productions: raise MissingProductionException("%s -> %s" % (symbol_to_kind[str(node_id)], rhs)) prod_id = known_lhs_productions[rhs] eg_node_id_to_prod_id.append((node_to_inherited_id[node_id], prod_id)) if hyperparameters['eg_use_vars_for_production_choice']: eg_prod_node_to_var_last_uses[node_to_inherited_id[node_id]] = \ np.array([node_to_synthesised_id[last_used_node_id[varchoice]] for varchoice in variables_in_scope], dtype=np.int16) # print("Expanding %i using rule %i %s -> %s" % (node_to_inherited_id[node_id], prod_id, # symbol_to_label.get(str(node_id)) or symbol_to_kind[str(node_id)], # tuple([symbol_to_kind[str(rhs_node_id)] for rhs_node_id in rhs_node_ids]))) # Visit all children, in left-to-right order, descending into them if needed last_sibling = None parent_inwards_edges = defaultdict(list) # type: Dict[str, List[Tuple[int, int, Optional[int]]]] parent_inwards_edges['InheritedToSynthesised'].append((node_to_inherited_id[node_id], node_to_synthesised_id[node_id], None)) for (rhs_symbol_idx, child_id) in enumerate(rhs_node_ids): child_inherited_id = declare_new_node(child_id, is_synthesised=False) child_inwards_edges = defaultdict(list) # type: Dict[str, List[Tuple[int, int, Optional[int]]]] child_edge_label_id = metadata['eg_edge_label_vocab'][(prod_id, rhs_symbol_idx)] child_inwards_edges['Child'].append((node_to_inherited_id[node_id], child_inherited_id, child_edge_label_id)) # Connection from left sibling, and prepare to be connected to the right sibling: if last_sibling is not None: child_inwards_edges['NextSibling'].append((node_to_synthesised_id[last_sibling], child_inherited_id, None)) last_sibling = child_id # Connection from the last generated leaf ("next action" in "A syntactic neural model for general-purpose code generation", Yin & Neubig '17): child_inwards_edges['NextSubtree'].append((node_to_synthesised_id[last_used_node_id[LAST_USED_TOKEN_NAME]], child_inherited_id, None)) # Check if we are terminal (token) node and add appropriate edges if that's the case: if str(child_id) not in symbol_to_prod: child_inwards_edges['NextToken'].append((node_to_synthesised_id[last_used_node_id[LAST_USED_TOKEN_NAME]], child_inherited_id, None)) last_used_node_id[LAST_USED_TOKEN_NAME] = child_id # If we are a variable or literal, we also need to store information to train to make the right choice: child_kind = symbol_to_kind[str(child_id)] if child_kind == VARIABLE_NONTERMINAL: var_name = symbol_to_label[str(child_id)] # print(" Chose variable %s" % var_name) last_var_use_id = last_used_node_id[var_name] cur_variable_to_last_use_ids = [node_to_synthesised_id[last_used_node_id[varchoice]] for varchoice in variables_in_scope] varchoice_id = variables_in_scope.index(var_name) eg_node_id_to_varchoice.append((node_to_inherited_id[node_id], cur_variable_to_last_use_ids, varchoice_id)) child_inwards_edges['NextUse'].append((node_to_synthesised_id[last_var_use_id], child_inherited_id, None)) if hyperparameters['eg_update_last_variable_use_representation']: last_used_node_id[var_name] = child_id elif child_kind in LITERAL_NONTERMINALS: literal = symbol_to_label[str(child_id)] # print(" Chose literal %s" % literal) literal_id = eg_literal_tok_to_idx[child_kind].get(literal) # In the case that a literal is not in the vocab and not in the context, the above will return None, # so map that explicitly to the id for UNK: if literal_id is None: literal_id = metadata['eg_literal_vocabs'][child_kind].get_id_or_unk(literal) eg_node_id_to_literal_choice[child_kind].append((node_to_inherited_id[node_id], literal_id)) # Store the edges leading to new node, recurse into it, and mark its upwards connection for later: eg_schedule.append(child_inwards_edges) expand_node(child_id) parent_inwards_edges['Parent'].append((node_to_synthesised_id[child_id], node_to_synthesised_id[node_id], None)) eg_schedule.append(parent_inwards_edges) expand_node(prod_root_node) expansion_labeled_edge_types, expansion_unlabeled_edge_types = get_restricted_edge_types(hyperparameters) def split_schedule_step(step: Dict[str, List[Tuple[int, int, Optional[int]]]]) -> List[List[Tuple[int, int]]]: total_edge_types = len(expansion_labeled_edge_types) + len(expansion_unlabeled_edge_types) step_by_edge = [[] for _ in range(total_edge_types)] # type: List[List[Tuple[int, int]]] for (label, edges) in step.items(): edges = [(v, w) for (v, w, _) in edges] # Strip off (optional) label: if label in expansion_labeled_edge_types: step_by_edge[expansion_labeled_edge_types[label]] = edges elif label in expansion_unlabeled_edge_types: step_by_edge[len(expansion_labeled_edge_types) + expansion_unlabeled_edge_types[label]] = edges return step_by_edge def edge_labels_from_schedule_step(step: Dict[str, List[Tuple[int, int, Optional[int]]]]) -> List[List[int]]: labels_by_edge = [[] for _ in range(len(expansion_labeled_edge_types))] # type: List[List[int]] for (label, edges) in step.items(): if label in expansion_labeled_edge_types: label_ids = [l for (_, _, l) in edges] # Keep only edge label labels_by_edge[expansion_labeled_edge_types[label]] = label_ids return labels_by_edge # print("Schedule:") # initialised_nodes = set() # initialised_nodes = initialised_nodes | result_holder['eg_node_id_to_cg_node_id'].keys() # for step_id, expansion_step in enumerate(eg_schedule): # print(" Step %i" % step_id) # initialised_this_step = set() # for edge_type in EXPANSION_UNLABELED_EDGE_TYPE_NAMES + EXPANSION_LABELED_EDGE_TYPE_NAMES: # for (v, w, _) in expansion_step[edge_type]: # assert v in initialised_nodes # assert w not in initialised_nodes # initialised_this_step.add(w) # for newly_computed_node in initialised_this_step: # node_label_id = result_holder['eg_node_labels'][newly_computed_node] # print(" Node Label for %i: %i (reversed %s)" # % (newly_computed_node, node_label_id, metadata['eg_token_vocab'].id_to_token[node_label_id])) # for edge_type in EXPANSION_UNLABELED_EDGE_TYPE_NAMES + EXPANSION_LABELED_EDGE_TYPE_NAMES: # edges = expansion_step[edge_type] # if len(edges) > 0: # initialised_nodes = initialised_nodes | initialised_this_step # print(" %s edges: [%s]" % (edge_type, # ", ".join("(%s -[%s]> %s)" % (v, l, w) for (v, w, l) in edges))) # print("Variable choices:\n %s" % (str(eg_node_id_to_varchoice))) # print("Literal choices: \n %s" % (str(eg_node_id_to_literal_choice))) if hyperparameters['eg_use_vars_for_production_choice']: result_holder['eg_production_node_id_to_var_last_use_node_ids'] = eg_prod_node_to_var_last_uses result_holder['eg_node_id_to_prod_id'] = np.array(eg_node_id_to_prod_id, dtype=np.int16) result_holder['eg_node_id_to_varchoice'] = eg_node_id_to_varchoice result_holder['eg_node_id_to_literal_choice'] = {} for literal_kind in LITERAL_NONTERMINALS: literal_choice_data = eg_node_id_to_literal_choice.get(literal_kind) if literal_choice_data is None: literal_choice_data = np.empty(shape=[0, 2], dtype=np.uint16) else: literal_choice_data = np.array(literal_choice_data, dtype=np.uint16) result_holder['eg_node_id_to_literal_choice'][literal_kind] = literal_choice_data result_holder['eg_schedule'] = [split_schedule_step(step) for step in eg_schedule] result_holder['eg_edge_label_ids'] = [edge_labels_from_schedule_step(step) for step in eg_schedule] @staticmethod def load_data_from_sample(hyperparameters: Dict[str, Any], metadata: Dict[str, Any], raw_sample: Dict[str, Any], result_holder: Dict[str, Any], is_train: bool=True) -> bool: try: NAGDecoder.__load_expansiongraph_data_from_sample(hyperparameters, metadata, raw_sample=raw_sample, result_holder=result_holder, is_train=is_train) if "eg_schedule" in result_holder and len(result_holder['eg_schedule']) >= hyperparameters['eg_propagation_substeps']: print("Dropping example using %i propagation steps in schedule" % (len(result_holder['eg_schedule']),)) return False except MissingProductionException as e: print("Dropping example using unknown production rule %s" % (str(e),)) return False except Exception as e: print("Dropping example because an error happened %s" % (str(e),)) return False return True # ---------- Minibatch construction ---------- def init_minibatch(self, batch_data: Dict[str, Any]) -> None: total_edge_types = len(self.__expansion_labeled_edge_types) + len(self.__expansion_unlabeled_edge_types) batch_data['eg_node_offset'] = 0 batch_data['next_step_target_node_id'] = [0 for _ in range(self.hyperparameters['eg_propagation_substeps'])] batch_data['eg_node_token_ids'] = [] batch_data['eg_initial_node_ids'] = [] batch_data['eg_sending_node_ids'] = [[[] for _ in range(total_edge_types)] for _ in range(self.hyperparameters['eg_propagation_substeps'])] batch_data['eg_edge_label_ids'] = [[[] for _ in range(len(self.__expansion_labeled_edge_types))] for _ in range(self.hyperparameters['eg_propagation_substeps'])] batch_data['eg_msg_target_node_ids'] = [[[] for _ in range(total_edge_types)] for _ in range(self.hyperparameters['eg_propagation_substeps'])] batch_data['eg_receiving_node_ids'] = [[] for _ in range(self.hyperparameters['eg_propagation_substeps'])] batch_data['eg_receiving_node_nums'] = [0 for _ in range(self.hyperparameters['eg_propagation_substeps'])] batch_data['eg_production_nodes'] = [] if self.hyperparameters['eg_use_vars_for_production_choice']: batch_data['eg_prod_idx_offset'] = 0 batch_data['eg_production_var_last_use_node_ids'] = [] batch_data['eg_production_var_last_use_node_ids_target_ids'] = [] batch_data['eg_production_node_choices'] = [] if self.hyperparameters.get('eg_use_context_attention', False): batch_data['eg_production_to_context_id'] = [] batch_data['eg_varproduction_nodes'] = [] batch_data['eg_varproduction_options_nodes'] = [] batch_data['eg_varproduction_options_mask'] = [] batch_data['eg_varproduction_node_choices'] = [] batch_data['eg_litproduction_nodes'] = {literal_kind: [] for literal_kind in LITERAL_NONTERMINALS} batch_data['eg_litproduction_node_choices'] = {literal_kind: [] for literal_kind in LITERAL_NONTERMINALS} batch_data['eg_litproduction_to_context_id'] = {literal_kind: [] for literal_kind in LITERAL_NONTERMINALS} batch_data['eg_litproduction_choice_normalizer'] = {literal_kind: [] for literal_kind in LITERAL_NONTERMINALS} def __extend_minibatch_by_expansion_graph_train_from_sample(self, batch_data: Dict[str, Any], sample: Dict[str, Any]) -> None: this_sample_id = batch_data['samples_in_batch'] - 1 # Counter already incremented when we get called total_edge_types = len(self.__expansion_labeled_edge_types) + len(self.__expansion_unlabeled_edge_types) for (step_num, schedule_step) in enumerate(sample['eg_schedule']): eg_node_id_to_step_target_id = OrderedDict() for edge_type in range(total_edge_types): for (source, target) in schedule_step[edge_type]: batch_data['eg_sending_node_ids'][step_num][edge_type].append(source + batch_data['eg_node_offset']) step_target_id = eg_node_id_to_step_target_id.get(target) if step_target_id is None: step_target_id = batch_data['next_step_target_node_id'][step_num] batch_data['next_step_target_node_id'][step_num] += 1 eg_node_id_to_step_target_id[target] = step_target_id batch_data['eg_msg_target_node_ids'][step_num][edge_type].append(step_target_id) for edge_type in range(len(self.__expansion_labeled_edge_types)): batch_data['eg_edge_label_ids'][step_num][edge_type].extend(sample['eg_edge_label_ids'][step_num][edge_type]) for eg_target_node_id in eg_node_id_to_step_target_id.keys(): batch_data['eg_receiving_node_ids'][step_num].append(eg_target_node_id + batch_data['eg_node_offset']) batch_data['eg_receiving_node_nums'][step_num] += len(eg_node_id_to_step_target_id) # ----- Data related to the production choices: batch_data['eg_production_nodes'].extend(sample['eg_node_id_to_prod_id'][:, 0] + batch_data['eg_node_offset']) batch_data['eg_production_node_choices'].extend(sample['eg_node_id_to_prod_id'][:, 1]) if self.hyperparameters['eg_use_context_attention']: batch_data['eg_production_to_context_id'].extend([this_sample_id] * sample['eg_node_id_to_prod_id'].shape[0]) if self.hyperparameters['eg_use_vars_for_production_choice']: for (prod_index, prod_node_id) in enumerate(sample['eg_node_id_to_prod_id'][:, 0]): var_last_uses_at_prod_node_id = sample['eg_production_node_id_to_var_last_use_node_ids'][prod_node_id] batch_data['eg_production_var_last_use_node_ids'].extend(var_last_uses_at_prod_node_id + batch_data['eg_node_offset']) overall_prod_index = prod_index + batch_data['eg_prod_idx_offset'] batch_data['eg_production_var_last_use_node_ids_target_ids'].extend([overall_prod_index] * len(var_last_uses_at_prod_node_id)) for (eg_varproduction_node_id, eg_varproduction_options_node_ids, chosen_id) in sample['eg_node_id_to_varchoice']: batch_data['eg_varproduction_nodes'].append(eg_varproduction_node_id + batch_data['eg_node_offset']) # Restrict to number of choices that we want to allow, make sure we keep the correct one: eg_varproduction_correct_node_id = eg_varproduction_options_node_ids[chosen_id] eg_varproduction_distractor_node_ids = eg_varproduction_options_node_ids[:chosen_id] + eg_varproduction_options_node_ids[chosen_id + 1:] np.random.shuffle(eg_varproduction_distractor_node_ids) eg_varproduction_options_node_ids = [eg_varproduction_correct_node_id] eg_varproduction_options_node_ids.extend(eg_varproduction_distractor_node_ids[:self.hyperparameters['eg_max_variable_choices'] - 1]) num_of_options = len(eg_varproduction_options_node_ids) if num_of_options == 0: raise Exception("Sample is choosing a variable from an empty set.") num_padding = self.hyperparameters['eg_max_variable_choices'] - num_of_options eg_varproduction_options_mask = [1.] * num_of_options + [0.] * num_padding eg_varproduction_options_node_ids = np.array(eg_varproduction_options_node_ids + [0] * num_padding) batch_data['eg_varproduction_options_nodes'].append(eg_varproduction_options_node_ids + batch_data['eg_node_offset']) batch_data['eg_varproduction_options_mask'].append(eg_varproduction_options_mask) batch_data['eg_varproduction_node_choices'].append(0) # We've reordered so that the correct choice is always first for literal_kind in LITERAL_NONTERMINALS: # Shape [num_choice_nodes, 2], with (v, c) meaning that at eg node v, we want to choose literal c: literal_choices = sample['eg_node_id_to_literal_choice'][literal_kind] if self.hyperparameters['eg_use_literal_copying']: # Prepare normalizer. We'll use an unsorted_segment_sum on the model side, and that only operates on a flattened shape # So here, we repeat the normalizer an appropriate number of times, but shifting by the number of choices normalizer_map = sample['eg_literal_choice_normalizer_maps'][literal_kind] num_choices_so_far = sum(choice_nodes.shape[0] for choice_nodes in batch_data['eg_litproduction_nodes'][literal_kind]) num_choices_this_sample = literal_choices.shape[0] repeated_normalizer_map = np.tile(np.expand_dims(normalizer_map, axis=0), reps=[num_choices_this_sample, 1]) flattened_normalizer_offsets = np.repeat((np.arange(num_choices_this_sample) + num_choices_so_far) * len(normalizer_map), repeats=len(normalizer_map)) normalizer_offsets = np.reshape(flattened_normalizer_offsets, [-1, len(normalizer_map)]) batch_data['eg_litproduction_choice_normalizer'][literal_kind].append( np.reshape(repeated_normalizer_map + normalizer_offsets, -1)) batch_data['eg_litproduction_to_context_id'][literal_kind].append([this_sample_id] * literal_choices.shape[0]) batch_data['eg_litproduction_nodes'][literal_kind].append(literal_choices[:, 0] + batch_data['eg_node_offset']) batch_data['eg_litproduction_node_choices'][literal_kind].append(literal_choices[:, 1]) def extend_minibatch_by_sample(self, batch_data: Dict[str, Any], sample: Dict[str, Any]) -> None: batch_data['eg_node_token_ids'].extend(sample['eg_node_labels']) self.__extend_minibatch_by_expansion_graph_train_from_sample(batch_data, sample) batch_data['eg_node_offset'] += len(sample['eg_node_labels']) if self.hyperparameters['eg_use_vars_for_production_choice']: batch_data['eg_prod_idx_offset'] += len(sample['eg_node_id_to_prod_id'][:, 0]) def finalise_minibatch(self, batch_data: Dict[str, Any], minibatch: Dict[tf.Tensor, Any]) -> None: total_edge_types = len(self.__expansion_labeled_edge_types) + len(self.__expansion_unlabeled_edge_types) flat_batch_keys = ['eg_node_token_ids', 'eg_initial_node_ids', 'eg_receiving_node_nums', 'eg_production_nodes', 'eg_production_node_choices', 'eg_varproduction_nodes', 'eg_varproduction_options_nodes', 'eg_varproduction_options_mask', 'eg_varproduction_node_choices'] if self.hyperparameters['eg_use_vars_for_production_choice']: flat_batch_keys.extend(['eg_production_var_last_use_node_ids', 'eg_production_var_last_use_node_ids_target_ids', ]) if self.hyperparameters['eg_use_context_attention']: flat_batch_keys.append('eg_production_to_context_id') for key in flat_batch_keys: write_to_minibatch(minibatch, self.placeholders[key], batch_data[key]) for step in range(self.hyperparameters['eg_propagation_substeps']): write_to_minibatch(minibatch, self.placeholders['eg_msg_target_node_ids'][step], np.concatenate(batch_data['eg_msg_target_node_ids'][step])) write_to_minibatch(minibatch, self.placeholders['eg_receiving_node_ids'][step], batch_data['eg_receiving_node_ids'][step]) for edge_type_idx in range(total_edge_types): write_to_minibatch(minibatch, self.placeholders['eg_sending_node_ids'][step][edge_type_idx], batch_data['eg_sending_node_ids'][step][edge_type_idx]) for edge_type_idx in range(len(self.__expansion_labeled_edge_types)): write_to_minibatch(minibatch, self.placeholders['eg_edge_label_ids'][step][edge_type_idx], batch_data['eg_edge_label_ids'][step][edge_type_idx]) for literal_kind in LITERAL_NONTERMINALS: write_to_minibatch(minibatch, self.placeholders['eg_litproduction_nodes'][literal_kind], np.concatenate(batch_data['eg_litproduction_nodes'][literal_kind], axis=0)) write_to_minibatch(minibatch, self.placeholders['eg_litproduction_node_choices'][literal_kind], np.concatenate(batch_data['eg_litproduction_node_choices'][literal_kind], axis=0)) if self.hyperparameters['eg_use_literal_copying']: write_to_minibatch(minibatch, self.placeholders['eg_litproduction_to_context_id'][literal_kind], np.concatenate(batch_data['eg_litproduction_to_context_id'][literal_kind], axis=0)) write_to_minibatch(minibatch, self.placeholders['eg_litproduction_choice_normalizer'][literal_kind], np.concatenate(batch_data['eg_litproduction_choice_normalizer'][literal_kind], axis=0)) # ---------- Test-time code ---------- def generate_suggestions_for_one_sample(self, test_sample: Dict[str, Any], raw_sample, sample_idx, initial_eg_node_representations: tf.Tensor, beam_size: int=3, max_decoding_steps: int=100, context_tokens: Optional[List[str]]=None, context_token_representations: Optional[tf.Tensor]=None, context_token_mask: Optional[np.ndarray]=None, ) -> ModelTestResult: production_id_to_production = {} # type: Dict[int, Tuple[str, Iterable[str]]] for (nonterminal, nonterminal_rules) in self.metadata['eg_production_vocab'].items(): for (expansion, prod_id) in nonterminal_rules.items(): production_id_to_production[prod_id] = (nonterminal, expansion) max_used_eg_node_id = initial_eg_node_representations.shape[0] def declare_new_node(expansion_info: ExpansionInformation, parent_node: int, node_type: str) -> int: nonlocal max_used_eg_node_id new_node_id = max_used_eg_node_id new_synthesised_node_id = max_used_eg_node_id + 1 max_used_eg_node_id += 2 expansion_info.node_to_parent[new_node_id] = parent_node expansion_info.node_to_children[parent_node].append(new_node_id) expansion_info.node_to_type[new_node_id] = node_type expansion_info.node_to_label[new_node_id] = node_type expansion_info.node_to_label[new_synthesised_node_id] = node_type expansion_info.node_to_synthesised_attr_node[new_node_id] = new_synthesised_node_id expansion_info.node_to_inherited_attr_node[new_synthesised_node_id] = new_node_id return new_node_id def get_node_attributes(expansion_info: ExpansionInformation, node_id: int) -> tf.Tensor: """ Return attributes associated with node, either from cache in expansion information or by calling the model to compute a representation according to the edge information in the expansion_info. """ node_attributes = expansion_info.node_to_representation.get(node_id) if node_attributes is None: node_label = expansion_info.node_to_label[node_id] if node_label == VARIABLE_NONTERMINAL: node_label = ROOT_NONTERMINAL if node_id not in expansion_info.node_to_unlabeled_incoming_edges: self.compute_incoming_edges(self.metadata['eg_production_vocab'].keys(), expansion_info, node_id) msg_prop_data = {self.placeholders['eg_msg_target_label_id']: self.metadata['eg_token_vocab'].get_id_or_unk(node_label)} for labeled_edge_typ in self.__expansion_labeled_edge_types.keys(): source_node_ids = [v for (v, _) in expansion_info.node_to_labeled_incoming_edges[node_id][labeled_edge_typ]] edge_labels = [l for (_, l) in expansion_info.node_to_labeled_incoming_edges[node_id][labeled_edge_typ]] if len(source_node_ids) == 0: sender_repr = np.empty(shape=[0, self.hyperparameters['eg_hidden_size']]) else: sender_repr = [get_node_attributes(expansion_info, source_node_id) for source_node_id in source_node_ids] labeled_edge_typ_idx = self.__expansion_labeled_edge_types[labeled_edge_typ] msg_prop_data[self.placeholders['eg_msg_source_representations'][labeled_edge_typ_idx]] = sender_repr msg_prop_data[self.placeholders['eg_edge_label_ids'][0][labeled_edge_typ_idx]] = edge_labels for unlabeled_edge_typ in self.__expansion_unlabeled_edge_types.keys(): source_node_ids = expansion_info.node_to_unlabeled_incoming_edges[node_id][unlabeled_edge_typ] if len(source_node_ids) == 0: sender_repr = np.empty(shape=[0, self.hyperparameters['eg_hidden_size']]) else: sender_repr = [get_node_attributes(expansion_info, source_node_id) for source_node_id in source_node_ids] shifted_edge_type_id = len(self.__expansion_labeled_edge_types) + self.__expansion_unlabeled_edge_types[unlabeled_edge_typ] msg_prop_data[self.placeholders['eg_msg_source_representations'][shifted_edge_type_id]] = sender_repr # print("Computing attributes for %i (label %s) with following edges:" % (node_id, node_label)) # for labeled_edge_type in EXPANSION_LABELED_EDGE_TYPE_NAMES + EXPANSION_UNLABELED_EDGE_TYPE_NAMES: # edges = expansion_info.node_to_labeled_incoming_edges[node_id][labeled_edge_type] # if len(edges) > 0: # print(" %s edges: [%s]" % (labeled_edge_type, # ", ".join("(%s, %s)" % (w, node_id) for w in edges))) node_attributes = self.sess.run(self.ops['eg_step_propagation_result'], feed_dict=msg_prop_data) expansion_info.node_to_representation[node_id] = node_attributes return node_attributes def sample_productions(expansion_info: ExpansionInformation, node_to_expand: int) -> List[Tuple[Iterable[str], int, float]]: prod_query_data = {} write_to_minibatch(prod_query_data, self.placeholders['eg_production_node_representation'], get_node_attributes(expansion_info, node_to_expand)) if self.hyperparameters['eg_use_vars_for_production_choice']: vars_in_scope = list(expansion_info.variable_to_last_use_id.keys()) vars_in_scope.remove(LAST_USED_TOKEN_NAME) vars_in_scope_representations = [get_node_attributes(expansion_info, expansion_info.variable_to_last_use_id[var]) for var in vars_in_scope] write_to_minibatch(prod_query_data, self.placeholders['eg_production_var_representations'], vars_in_scope_representations) if self.hyperparameters['eg_use_literal_copying'] or self.hyperparameters['eg_use_context_attention']: write_to_minibatch(prod_query_data, self.placeholders['context_token_representations'], expansion_info.context_token_representations) write_to_minibatch(prod_query_data, self.placeholders['context_token_mask'], expansion_info.context_token_mask) production_probs = self.sess.run(self.ops['eg_production_choice_probs'], feed_dict=prod_query_data) result = [] # print("### Prod probs: %s" % (str(production_probs),)) for picked_production_index in pick_indices_from_probs(production_probs, beam_size): prod_lhs, prod_rhs = production_id_to_production[picked_production_index] # TODO: This should be ensured by appropriate masking in the model if prod_lhs == expansion_info.node_to_type[node_to_expand]: assert prod_lhs == expansion_info.node_to_type[node_to_expand] result.append((prod_rhs, picked_production_index, production_probs[picked_production_index])) return result def sample_variable(expansion_info: ExpansionInformation, node_id: int) -> List[Tuple[str, float]]: vars_in_scope = list(expansion_info.variable_to_last_use_id.keys()) vars_in_scope.remove(LAST_USED_TOKEN_NAME) vars_in_scope_representations = [get_node_attributes(expansion_info, expansion_info.variable_to_last_use_id[var]) for var in vars_in_scope] var_query_data = {self.placeholders['eg_num_variable_choices']: len(vars_in_scope)} write_to_minibatch(var_query_data, self.placeholders['eg_varproduction_options_representations'], vars_in_scope_representations) # We choose the variable name based on the information of the /parent/ node: parent_node = expansion_info.node_to_parent[node_id] write_to_minibatch(var_query_data, self.placeholders['eg_varproduction_node_representation'], get_node_attributes(expansion_info, parent_node)) var_probs = self.sess.run(self.ops['eg_varproduction_choice_probs'], feed_dict=var_query_data) result = [] # print("### Var probs: %s" % (str(var_probs),)) for picked_var_index in pick_indices_from_probs(var_probs, beam_size): result.append((vars_in_scope[picked_var_index], var_probs[picked_var_index])) return result def sample_literal(expansion_info: ExpansionInformation, node_id: int) -> List[Tuple[str, float]]: literal_kind_to_sample = expansion_info.node_to_type[node_id] lit_query_data = {} # We choose the literal based on the information of the /parent/ node: parent_node = expansion_info.node_to_parent[node_id] write_to_minibatch(lit_query_data, self.placeholders['eg_litproduction_node_representation'], get_node_attributes(expansion_info, parent_node)) if self.hyperparameters["eg_use_literal_copying"]: write_to_minibatch(lit_query_data, self.placeholders['context_token_representations'], expansion_info.context_token_representations) write_to_minibatch(lit_query_data, self.placeholders['context_token_mask'], expansion_info.context_token_mask) write_to_minibatch(lit_query_data, self.placeholders['eg_litproduction_choice_normalizer'], expansion_info.literal_production_choice_normalizer[literal_kind_to_sample]) lit_probs = self.sess.run(self.ops['eg_litproduction_choice_probs'][literal_kind_to_sample], feed_dict=lit_query_data) result = [] # print("### Var probs: %s" % (str(lit_probs),)) literal_vocab = self.metadata["eg_literal_vocabs"][literal_kind_to_sample] literal_vocab_size = len(literal_vocab) for picked_lit_index in pick_indices_from_probs(lit_probs, beam_size): if picked_lit_index < literal_vocab_size: result.append((literal_vocab.id_to_token[picked_lit_index], lit_probs[picked_lit_index])) else: result.append((expansion_info.context_tokens[picked_lit_index - literal_vocab_size], lit_probs[picked_lit_index])) return result def expand_node(expansion_info: ExpansionInformation) -> List[ExpansionInformation]: if len(expansion_info.nodes_to_expand) == 0: return [expansion_info] if expansion_info.num_expansions > max_decoding_steps: return [] node_to_expand = expansion_info.nodes_to_expand.popleft() type_to_expand = expansion_info.node_to_type[node_to_expand] expansions = [] if type_to_expand in self.metadata['eg_production_vocab']: # Case production from grammar for (prod_rhs, prod_id, prod_probability) in sample_productions(expansion_info, node_to_expand): picked_rhs_expansion_info = clone_expansion_info(expansion_info, increment_expansion_counter=True) picked_rhs_expansion_info.node_to_prod_id[node_to_expand] = prod_id picked_rhs_expansion_info.expansion_logprob[0] = picked_rhs_expansion_info.expansion_logprob[0] + np.log(prod_probability) # print("Expanding %i using rule %s -> %s with prob %.3f in %s (tree prob %.3f)." # % (node_to_expand, type_to_expand, prod_rhs, prod_probability, # " ".join(get_tokens_from_expansion(expansion_info, root_node)), # np.exp(expansion_info.expansion_logprob[0]))) # Declare all children for child_node_type in prod_rhs: child_node_id = declare_new_node(picked_rhs_expansion_info, node_to_expand, child_node_type) # print(" Child %i (type %s)" % (child_node_id, child_node_type)) # Mark the children as expansions. As we do depth-first, push them to front of the queue; and as # extendleft reverses the order and we do left-to-right, reverse that reversal: picked_rhs_expansion_info.nodes_to_expand.extendleft(reversed(picked_rhs_expansion_info.node_to_children[node_to_expand])) expansions.append(picked_rhs_expansion_info) elif type_to_expand == VARIABLE_NONTERMINAL: # Case choose variable name. if len(expansion_info.variable_to_last_use_id.keys()) > 1: # Only continue if at least one var is in scope (not just LAST_USED_TOKEN_NAME) for (child_label, var_probability) in sample_variable(expansion_info, node_to_expand): # print("Expanding %i by using variable %s with prob %.3f in %s (tree prob %.3f)." # % (node_to_expand, child_label, var_probability, # " ".join(get_tokens_from_expansion(expansion_info, root_node)), # np.exp(expansion_info.expansion_logprob[0]))) child_expansion_info = clone_expansion_info(expansion_info) child_expansion_info.node_to_synthesised_attr_node[node_to_expand] = node_to_expand # synthesised and inherited are the same for leafs child_expansion_info.node_to_label[node_to_expand] = child_label self.compute_incoming_edges(self.metadata['eg_production_vocab'].keys(), child_expansion_info, node_to_expand) # This needs to be done now before we update the variable-to-last-use info child_expansion_info.expansion_logprob[0] = child_expansion_info.expansion_logprob[0] + np.log(var_probability) if self.hyperparameters['eg_update_last_variable_use_representation']: child_expansion_info.variable_to_last_use_id[child_label] = node_to_expand child_expansion_info.variable_to_last_use_id[LAST_USED_TOKEN_NAME] = node_to_expand expansions.append(child_expansion_info) elif type_to_expand in LITERAL_NONTERMINALS: for (picked_literal, literal_probability) in sample_literal(expansion_info, node_to_expand): # print("Expanding %i by using literal %s with prob %.3f in %s (tree prob %.3f)." # % (node_to_expand, picked_literal, literal_probability, # " ".join(get_tokens_from_expansion(expansion_info, root_node)), # np.exp(expansion_info.expansion_logprob[0]))) picked_literal_expansion_info = clone_expansion_info(expansion_info) picked_literal_expansion_info.node_to_synthesised_attr_node[node_to_expand] = node_to_expand # synthesised and inherited are the same for leafs picked_literal_expansion_info.node_to_label[node_to_expand] = picked_literal self.compute_incoming_edges(self.metadata['eg_production_vocab'].keys(), picked_literal_expansion_info, node_to_expand) picked_literal_expansion_info.expansion_logprob[0] = picked_literal_expansion_info.expansion_logprob[0] + np.log(literal_probability) picked_literal_expansion_info.variable_to_last_use_id[LAST_USED_TOKEN_NAME] = node_to_expand expansions.append(picked_literal_expansion_info) else: # Case node is a terminal: Do nothing # print("Handling leaf node %i (label %s)" % (node_to_expand, expansion_info.node_to_label[node_to_expand])) expansion_info.node_to_synthesised_attr_node[node_to_expand] = node_to_expand # synthesised and inherited are the same for leafs self.compute_incoming_edges(self.metadata['eg_production_vocab'].keys(), expansion_info, node_to_expand) # This needs to be done now before we update the variable-to-last-use info expansion_info.variable_to_last_use_id[LAST_USED_TOKEN_NAME] = node_to_expand expansions = [expansion_info] return expansions if self.hyperparameters['eg_use_literal_copying']: literal_production_choice_normalizer = {} for literal_kind in LITERAL_NONTERMINALS: # Collect all choices (vocab + things we can copy from): literal_vocab = self.metadata['eg_literal_vocabs'][literal_kind] literal_choices = literal_vocab.id_to_token + context_tokens first_tok_occurrences = {} num_choices = len(literal_vocab) + self.hyperparameters['eg_max_context_tokens'] normalizer_map = np.arange(num_choices, dtype=np.int16) for (token_idx, token) in enumerate(literal_choices): first_occ = first_tok_occurrences.get(token) if first_occ is not None: normalizer_map[token_idx] = first_occ else: first_tok_occurrences[token] = token_idx literal_production_choice_normalizer[literal_kind] = normalizer_map else: literal_production_choice_normalizer = None root_node = test_sample['eg_root_node'] initial_variable_to_last_use_id = test_sample['eg_variable_eg_node_ids'] initial_variable_to_last_use_id[LAST_USED_TOKEN_NAME] = test_sample['eg_last_token_eg_node_id'] initial_node_to_representation = {node_id: initial_eg_node_representations[node_id] for node_id in initial_variable_to_last_use_id.values()} initial_node_to_representation[root_node] = initial_eg_node_representations[root_node] initial_info = ExpansionInformation(node_to_type={root_node: ROOT_NONTERMINAL}, node_to_label={root_node: ROOT_NONTERMINAL}, node_to_prod_id={}, node_to_children=defaultdict(list), node_to_parent={}, node_to_synthesised_attr_node={node_id: node_id for node_id in initial_node_to_representation.keys()}, node_to_inherited_attr_node={}, variable_to_last_use_id=initial_variable_to_last_use_id, node_to_representation=initial_node_to_representation, node_to_labeled_incoming_edges={root_node: defaultdict(list)}, node_to_unlabeled_incoming_edges={root_node: defaultdict(list)}, context_token_representations=context_token_representations, context_token_mask=context_token_mask, context_tokens=context_tokens, literal_production_choice_normalizer=literal_production_choice_normalizer, nodes_to_expand=deque([root_node]), expansion_logprob=[0.0], num_expansions=0) beams = [initial_info] while any(len(b.nodes_to_expand) > 0 for b in beams): new_beams = [new_beam for beam in beams for new_beam in expand_node(beam)] beams = sorted(new_beams, key=lambda b: -b.expansion_logprob[0])[:beam_size] # Pick top K beams self.test_log("Sample Number: " + str(sample_idx)) self.test_log(raw_sample["Filename"]) self.test_log(raw_sample['HoleSpan'] + " " + raw_sample['HoleLineSpan']) self.test_log(str(raw_sample['HoleTokensBefore']) + " " + str(raw_sample['HoleTokensAfter'])) self.test_log("Groundtruth: %s" % (" ".join(test_sample['eg_tokens']),)) all_predictions = [] # type: List[Tuple[List[str], float]] for (k, beam_info) in enumerate(beams): kth_result = get_tokens_from_expansion(beam_info, root_node) all_predictions.append((kth_result, np.exp(beam_info.expansion_logprob[0]))) self.test_log(" @%i Prob. %.3f: %s" % (k+1, np.exp(beam_info.expansion_logprob[0]), " ".join(kth_result))) if len(beams) == 0: self.test_log("No beams finished!") return ModelTestResult(test_sample['eg_tokens'], all_predictions)
[ "tensorflow.einsum", "tensorflow.reduce_sum", "numpy.empty", "tensorflow.reshape", "collections.defaultdict", "numpy.arange", "numpy.exp", "collections.deque", "tensorflow.nn.softmax", "tensorflow.size", "tensorflow.gather", "tensorflow.concat", "tensorflow.variable_scope", "tensorflow.placeholder", "numpy.reshape", "tensorflow.squeeze", "collections.Counter", "numpy.random.shuffle", "tensorflow.nn.embedding_lookup", "tensorflow.reduce_mean", "tensorflow.constant", "tensorflow.random_normal_initializer", "tensorflow.where", "tensorflow.expand_dims", "numpy.concatenate", "tensorflow.glorot_uniform_initializer", "numpy.log", "numpy.expand_dims", "tensorflow.shape", "numpy.array", "collections.namedtuple", "collections.OrderedDict", "dpu_utils.tfutils.pick_indices_from_probs", "dpu_utils.mlutils.vocabulary.Vocabulary.create_vocabulary", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "dpu_utils.tfmodels.AsyncGGNN" ]
[((1096, 1608), 'collections.namedtuple', 'namedtuple', (['"""ExpansionInformation"""', "['node_to_type', 'node_to_label', 'node_to_prod_id', 'node_to_children',\n 'node_to_parent', 'node_to_synthesised_attr_node',\n 'node_to_inherited_attr_node', 'variable_to_last_use_id',\n 'node_to_representation', 'node_to_labeled_incoming_edges',\n 'node_to_unlabeled_incoming_edges', 'context_token_representations',\n 'context_token_mask', 'context_tokens',\n 'literal_production_choice_normalizer', 'nodes_to_expand',\n 'expansion_logprob', 'num_expansions']"], {}), "('ExpansionInformation', ['node_to_type', 'node_to_label',\n 'node_to_prod_id', 'node_to_children', 'node_to_parent',\n 'node_to_synthesised_attr_node', 'node_to_inherited_attr_node',\n 'variable_to_last_use_id', 'node_to_representation',\n 'node_to_labeled_incoming_edges', 'node_to_unlabeled_incoming_edges',\n 'context_token_representations', 'context_token_mask', 'context_tokens',\n 'literal_production_choice_normalizer', 'nodes_to_expand',\n 'expansion_logprob', 'num_expansions'])\n", (1106, 1608), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((11015, 11073), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""eg_node_token_ids"""'}), "(tf.int32, [None], name='eg_node_token_ids')\n", (11029, 11073), True, 'import tensorflow as tf\n'), ((12232, 12304), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_initial_node_ids"""'}), "(dtype=tf.int32, shape=[None], name='eg_initial_node_ids')\n", (12246, 12304), True, 'import tensorflow as tf\n'), ((13983, 14107), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': "[self.hyperparameters['eg_propagation_substeps']]", 'name': '"""eg_receiving_nodes_nums"""'}), "(dtype=tf.int32, shape=[self.hyperparameters[\n 'eg_propagation_substeps']], name='eg_receiving_nodes_nums')\n", (13997, 14107), True, 'import tensorflow as tf\n'), ((14223, 14295), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_production_nodes"""'}), "(dtype=tf.int32, shape=[None], name='eg_production_nodes')\n", (14237, 14295), True, 'import tensorflow as tf\n'), ((14942, 15021), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_production_node_choices"""'}), "(dtype=tf.int32, shape=[None], name='eg_production_node_choices')\n", (14956, 15021), True, 'import tensorflow as tf\n'), ((15315, 15390), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_varproduction_nodes"""'}), "(dtype=tf.int32, shape=[None], name='eg_varproduction_nodes')\n", (15329, 15390), True, 'import tensorflow as tf\n'), ((15468, 15605), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': "[None, self.hyperparameters['eg_max_variable_choices']]", 'name': '"""eg_varproduction_options_nodes"""'}), "(dtype=tf.int32, shape=[None, self.hyperparameters[\n 'eg_max_variable_choices']], name='eg_varproduction_options_nodes')\n", (15482, 15605), True, 'import tensorflow as tf\n'), ((15730, 15868), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': "[None, self.hyperparameters['eg_max_variable_choices']]", 'name': '"""eg_varproduction_options_mask"""'}), "(dtype=tf.float32, shape=[None, self.hyperparameters[\n 'eg_max_variable_choices']], name='eg_varproduction_options_mask')\n", (15744, 15868), True, 'import tensorflow as tf\n'), ((15993, 16080), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_varproduction_node_choices"""'}), "(dtype=tf.int32, shape=[None], name=\n 'eg_varproduction_node_choices')\n", (16007, 16080), True, 'import tensorflow as tf\n'), ((17746, 17843), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[eg_h_dim]', 'name': '"""eg_production_node_representation"""'}), "(dtype=tf.float32, shape=[eg_h_dim], name=\n 'eg_production_node_representation')\n", (17760, 17843), True, 'import tensorflow as tf\n'), ((18688, 18788), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[eg_h_dim]', 'name': '"""eg_varproduction_node_representation"""'}), "(dtype=tf.float32, shape=[eg_h_dim], name=\n 'eg_varproduction_node_representation')\n", (18702, 18788), True, 'import tensorflow as tf\n'), ((18907, 18979), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[]', 'name': '"""eg_num_variable_choices"""'}), "(dtype=tf.int32, shape=[], name='eg_num_variable_choices')\n", (18921, 18979), True, 'import tensorflow as tf\n'), ((19066, 19176), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, eg_h_dim]', 'name': '"""eg_varproduction_options_representations"""'}), "(dtype=tf.float32, shape=[None, eg_h_dim], name=\n 'eg_varproduction_options_representations')\n", (19080, 19176), True, 'import tensorflow as tf\n'), ((19309, 19409), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[eg_h_dim]', 'name': '"""eg_litproduction_node_representation"""'}), "(dtype=tf.float32, shape=[eg_h_dim], name=\n 'eg_litproduction_node_representation')\n", (19323, 19409), True, 'import tensorflow as tf\n'), ((20308, 20379), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[]', 'name': '"""eg_msg_target_label_id"""'}), "(dtype=tf.int32, shape=[], name='eg_msg_target_label_id')\n", (20322, 20379), True, 'import tensorflow as tf\n'), ((21631, 21738), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (["self.parameters['eg_token_embeddings']", "self.placeholders['eg_node_token_ids']"], {}), "(self.parameters['eg_token_embeddings'], self.\n placeholders['eg_node_token_ids'])\n", (21653, 21738), True, 'import tensorflow as tf\n'), ((21825, 21986), 'tensorflow.where', 'tf.where', ([], {'condition': "self.ops['eg_node_representation_use_from_context']", 'x': "self.ops['eg_node_representations_from_context']", 'y': 'eg_node_label_embeddings'}), "(condition=self.ops['eg_node_representation_use_from_context'], x=\n self.ops['eg_node_representations_from_context'], y=\n eg_node_label_embeddings)\n", (21833, 21986), True, 'import tensorflow as tf\n'), ((23550, 23646), 'tensorflow.gather', 'tf.gather', ([], {'params': 'eg_node_representations', 'indices': "self.placeholders['eg_production_nodes']"}), "(params=eg_node_representations, indices=self.placeholders[\n 'eg_production_nodes'])\n", (23559, 23646), True, 'import tensorflow as tf\n'), ((24890, 24989), 'tensorflow.gather', 'tf.gather', ([], {'params': 'eg_node_representations', 'indices': "self.placeholders['eg_varproduction_nodes']"}), "(params=eg_node_representations, indices=self.placeholders[\n 'eg_varproduction_nodes'])\n", (24899, 24989), True, 'import tensorflow as tf\n'), ((25085, 25160), 'tensorflow.reshape', 'tf.reshape', (["self.placeholders['eg_varproduction_options_nodes']"], {'shape': '[-1]'}), "(self.placeholders['eg_varproduction_options_nodes'], shape=[-1])\n", (25095, 25160), True, 'import tensorflow as tf\n'), ((27416, 27564), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'eg_production_choice_logits', 'labels': "self.placeholders['eg_production_node_choices']"}), "(logits=\n eg_production_choice_logits, labels=self.placeholders[\n 'eg_production_node_choices'])\n", (27462, 27564), True, 'import tensorflow as tf\n'), ((27625, 27779), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'eg_varproduction_choice_logits', 'labels': "self.placeholders['eg_varproduction_node_choices']"}), "(logits=\n eg_varproduction_choice_logits, labels=self.placeholders[\n 'eg_varproduction_node_choices'])\n", (27671, 27779), True, 'import tensorflow as tf\n'), ((31214, 31264), 'tensorflow.squeeze', 'tf.squeeze', (['eg_varproduction_choice_logits'], {'axis': '(0)'}), '(eg_varproduction_choice_logits, axis=0)\n', (31224, 31264), True, 'import tensorflow as tf\n'), ((31317, 31370), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['eg_varproduction_choice_logits'], {'dim': '(-1)'}), '(eg_varproduction_choice_logits, dim=-1)\n', (31330, 31370), True, 'import tensorflow as tf\n'), ((37122, 37168), 'tensorflow.concat', 'tf.concat', (['eg_production_choice_inputs'], {'axis': '(1)'}), '(eg_production_choice_inputs, axis=1)\n', (37131, 37168), True, 'import tensorflow as tf\n'), ((38272, 38365), 'tensorflow.einsum', 'tf.einsum', (['"""sd,svd->sv"""', 'varchoice_node_representation', 'varchoice_options_representations'], {}), "('sd,svd->sv', varchoice_node_representation,\n varchoice_options_representations)\n", (38281, 38365), True, 'import tensorflow as tf\n'), ((39569, 39606), 'tensorflow.squeeze', 'tf.squeeze', (['varchoice_logits'], {'axis': '(-1)'}), '(varchoice_logits, axis=-1)\n', (39579, 39606), True, 'import tensorflow as tf\n'), ((42134, 42212), 'tensorflow.gather', 'tf.gather', ([], {'params': 'context_representations', 'indices': 'litproduction_to_context_id'}), '(params=context_representations, indices=litproduction_to_context_id)\n', (42143, 42212), True, 'import tensorflow as tf\n'), ((42601, 42632), 'tensorflow.squeeze', 'tf.squeeze', (['copy_scores'], {'axis': '(1)'}), '(copy_scores, axis=1)\n', (42611, 42632), True, 'import tensorflow as tf\n'), ((42695, 42783), 'tensorflow.gather', 'tf.gather', ([], {'params': 'context_representations_mask', 'indices': 'litproduction_to_context_id'}), '(params=context_representations_mask, indices=\n litproduction_to_context_id)\n', (42704, 42783), True, 'import tensorflow as tf\n'), ((42997, 43045), 'tensorflow.concat', 'tf.concat', (['[literal_logits, copy_scores]'], {'axis': '(1)'}), '([literal_logits, copy_scores], axis=1)\n', (43006, 43045), True, 'import tensorflow as tf\n'), ((43760, 43849), 'tensorflow.reshape', 'tf.reshape', (['normalized_vocab_choices_and_copy_logits'], {'shape': '[-1, num_literal_options]'}), '(normalized_vocab_choices_and_copy_logits, shape=[-1,\n num_literal_options])\n', (43770, 43849), True, 'import tensorflow as tf\n'), ((44070, 44079), 'collections.Counter', 'Counter', ([], {}), '()\n', (44077, 44079), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((44126, 44146), 'collections.defaultdict', 'defaultdict', (['Counter'], {}), '(Counter)\n', (44137, 44146), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((44193, 44209), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (44204, 44209), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((45525, 45534), 'collections.Counter', 'Counter', ([], {}), '()\n', (45532, 45534), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((45670, 45686), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (45681, 45686), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((46168, 46277), 'dpu_utils.mlutils.vocabulary.Vocabulary.create_vocabulary', 'Vocabulary.create_vocabulary', (['merged_token_counter'], {'max_size': "self.hyperparameters['eg_token_vocab_size']"}), "(merged_token_counter, max_size=self.\n hyperparameters['eg_token_vocab_size'])\n", (46196, 46277), False, 'from dpu_utils.mlutils.vocabulary import Vocabulary\n'), ((46791, 46808), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (46802, 46808), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((46870, 46887), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (46881, 46887), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((52121, 52138), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (52132, 52138), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((52216, 52233), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (52227, 52233), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((55835, 55852), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (55846, 55852), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((67964, 68011), 'numpy.array', 'np.array', (['eg_node_id_to_prod_id'], {'dtype': 'np.int16'}), '(eg_node_id_to_prod_id, dtype=np.int16)\n', (67972, 68011), True, 'import numpy as np\n'), ((3929, 3966), 'collections.deque', 'deque', (['expansion_info.nodes_to_expand'], {}), '(expansion_info.nodes_to_expand)\n', (3934, 3966), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((13125, 13220), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': "('eg_msg_targets_nodes_step%i' % (step,))"}), "(dtype=tf.int32, shape=[None], name=\n 'eg_msg_targets_nodes_step%i' % (step,))\n", (13139, 13220), True, 'import tensorflow as tf\n'), ((13603, 13696), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': "('eg_receiving_nodes_step%i' % (step,))"}), "(dtype=tf.int32, shape=[None], name=\n 'eg_receiving_nodes_step%i' % (step,))\n", (13617, 13696), True, 'import tensorflow as tf\n'), ((14456, 14549), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_production_var_last_use_node_ids"""'}), "(dtype=tf.int32, shape=[None], name=\n 'eg_production_var_last_use_node_ids')\n", (14470, 14549), True, 'import tensorflow as tf\n'), ((14707, 14811), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_production_var_last_use_node_ids_target_ids"""'}), "(dtype=tf.int32, shape=[None], name=\n 'eg_production_var_last_use_node_ids_target_ids')\n", (14721, 14811), True, 'import tensorflow as tf\n'), ((15165, 15250), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_production_to_context_id"""'}), "(dtype=tf.int32, shape=[None], name='eg_production_to_context_id'\n )\n", (15179, 15250), True, 'import tensorflow as tf\n'), ((16525, 16623), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': "('eg_litproduction_nodes_%s' % literal_kind)"}), "(dtype=tf.int32, shape=[None], name=\n 'eg_litproduction_nodes_%s' % literal_kind)\n", (16539, 16623), True, 'import tensorflow as tf\n'), ((16778, 16883), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': "('eg_litproduction_node_choices_%s' % literal_kind)"}), "(dtype=tf.int32, shape=[None], name=\n 'eg_litproduction_node_choices_%s' % literal_kind)\n", (16792, 16883), True, 'import tensorflow as tf\n'), ((18051, 18154), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, eg_h_dim]', 'name': '"""eg_production_var_representations"""'}), "(dtype=tf.float32, shape=[None, eg_h_dim], name=\n 'eg_production_var_representations')\n", (18065, 18154), True, 'import tensorflow as tf\n'), ((18407, 18547), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': "[self.hyperparameters['eg_max_context_tokens'], eg_h_dim]", 'name': '"""context_token_representations"""'}), "(dtype=tf.float32, shape=[self.hyperparameters[\n 'eg_max_context_tokens'], eg_h_dim], name='context_token_representations')\n", (18421, 18547), True, 'import tensorflow as tf\n'), ((19606, 19698), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': '"""eg_litproduction_choice_normalizer"""'}), "(dtype=tf.int32, shape=[None], name=\n 'eg_litproduction_choice_normalizer')\n", (19620, 19698), True, 'import tensorflow as tf\n'), ((20014, 20134), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, eg_h_dim]', 'name': "('eg_msg_source_representations_etyp%i' % (edge_typ,))"}), "(dtype=tf.float32, shape=[None, eg_h_dim], name=\n 'eg_msg_source_representations_etyp%i' % (edge_typ,))\n", (20028, 20134), True, 'import tensorflow as tf\n'), ((22579, 22614), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""ExpansionGraph"""'], {}), "('ExpansionGraph')\n", (22596, 22614), True, 'import tensorflow as tf\n'), ((22639, 22659), 'dpu_utils.tfmodels.AsyncGGNN', 'AsyncGGNN', (['eg_hypers'], {}), '(eg_hypers)\n', (22648, 22659), False, 'from dpu_utils.tfmodels import AsyncGGNN\n'), ((23838, 23950), 'tensorflow.gather', 'tf.gather', ([], {'params': 'eg_node_representations', 'indices': "self.placeholders['eg_production_var_last_use_node_ids']"}), "(params=eg_node_representations, indices=self.placeholders[\n 'eg_production_var_last_use_node_ids'])\n", (23847, 23950), True, 'import tensorflow as tf\n'), ((25300, 25391), 'tensorflow.gather', 'tf.gather', ([], {'params': 'eg_node_representations', 'indices': 'eg_varproduction_options_nodes_flat'}), '(params=eg_node_representations, indices=\n eg_varproduction_options_nodes_flat)\n', (25309, 25391), True, 'import tensorflow as tf\n'), ((26280, 26393), 'tensorflow.gather', 'tf.gather', ([], {'params': 'eg_node_representations', 'indices': "self.placeholders['eg_litproduction_nodes'][literal_kind]"}), "(params=eg_node_representations, indices=self.placeholders[\n 'eg_litproduction_nodes'][literal_kind])\n", (26289, 26393), True, 'import tensorflow as tf\n'), ((28025, 28053), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['raw_prod_loss'], {}), '(raw_prod_loss)\n', (28038, 28053), True, 'import tensorflow as tf\n'), ((28142, 28169), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['raw_var_loss'], {}), '(raw_var_loss)\n', (28155, 28169), True, 'import tensorflow as tf\n'), ((28627, 28658), 'tensorflow.concat', 'tf.concat', (['raw_lit_loss'], {'axis': '(0)'}), '(raw_lit_loss, axis=0)\n', (28636, 28658), True, 'import tensorflow as tf\n'), ((29234, 29261), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['raw_lit_loss'], {}), '(raw_lit_loss)\n', (29247, 29261), True, 'import tensorflow as tf\n'), ((29762, 29815), 'tensorflow.expand_dims', 'tf.expand_dims', (['context_token_representations'], {'axis': '(0)'}), '(context_token_representations, axis=0)\n', (29776, 29815), True, 'import tensorflow as tf\n'), ((30001, 30079), 'tensorflow.reduce_mean', 'tf.reduce_mean', (["self.placeholders['eg_production_var_representations']"], {'axis': '(0)'}), "(self.placeholders['eg_production_var_representations'], axis=0)\n", (30015, 30079), True, 'import tensorflow as tf\n'), ((30159, 30229), 'tensorflow.expand_dims', 'tf.expand_dims', (['pooled_variable_representations_at_prod_choice'], {'axis': '(0)'}), '(pooled_variable_representations_at_prod_choice, axis=0)\n', (30173, 30229), True, 'import tensorflow as tf\n'), ((30422, 30500), 'tensorflow.expand_dims', 'tf.expand_dims', (["self.placeholders['eg_production_node_representation']"], {'axis': '(0)'}), "(self.placeholders['eg_production_node_representation'], axis=0)\n", (30436, 30500), True, 'import tensorflow as tf\n'), ((30774, 30816), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['eg_production_choice_logits'], {}), '(eg_production_choice_logits)\n', (30787, 30816), True, 'import tensorflow as tf\n'), ((30969, 31054), 'tensorflow.expand_dims', 'tf.expand_dims', (["self.placeholders['eg_varproduction_node_representation']"], {'axis': '(0)'}), "(self.placeholders['eg_varproduction_node_representation'],\n axis=0)\n", (30983, 31054), True, 'import tensorflow as tf\n'), ((31068, 31158), 'tensorflow.expand_dims', 'tf.expand_dims', (["self.placeholders['eg_varproduction_options_representations']"], {'axis': '(0)'}), "(self.placeholders['eg_varproduction_options_representations'\n ], axis=0)\n", (31082, 31158), True, 'import tensorflow as tf\n'), ((32591, 32626), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""ExpansionGraph"""'], {}), "('ExpansionGraph')\n", (32608, 32626), True, 'import tensorflow as tf\n'), ((32651, 32671), 'dpu_utils.tfmodels.AsyncGGNN', 'AsyncGGNN', (['eg_hypers'], {}), '(eg_hypers)\n', (32660, 32671), False, 'from dpu_utils.tfmodels import AsyncGGNN\n'), ((32860, 32929), 'tensorflow.concat', 'tf.concat', (["self.placeholders['eg_msg_source_representations']"], {'axis': '(0)'}), "(self.placeholders['eg_msg_source_representations'], axis=0)\n", (32869, 32929), True, 'import tensorflow as tf\n'), ((33061, 33091), 'tensorflow.constant', 'tf.constant', (['(1)'], {'dtype': 'tf.int32'}), '(1, dtype=tf.int32)\n', (33072, 33091), True, 'import tensorflow as tf\n'), ((35656, 35731), 'tensorflow.gather', 'tf.gather', ([], {'params': 'context_representations', 'indices': 'production_to_context_id'}), '(params=context_representations, indices=production_to_context_id)\n', (35665, 35731), True, 'import tensorflow as tf\n'), ((36242, 36278), 'tensorflow.squeeze', 'tf.squeeze', (['attention_scores'], {'axis': '(1)'}), '(attention_scores, axis=1)\n', (36252, 36278), True, 'import tensorflow as tf\n'), ((36361, 36446), 'tensorflow.gather', 'tf.gather', ([], {'params': 'context_representations_mask', 'indices': 'production_to_context_id'}), '(params=context_representations_mask, indices=production_to_context_id\n )\n', (36370, 36446), True, 'import tensorflow as tf\n'), ((36620, 36651), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['attention_scores'], {}), '(attention_scores)\n', (36633, 36651), True, 'import tensorflow as tf\n'), ((36907, 36968), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['weighted_context_token_representations'], {'axis': '(1)'}), '(weighted_context_token_representations, axis=1)\n', (36920, 36968), True, 'import tensorflow as tf\n'), ((38514, 38568), 'tensorflow.expand_dims', 'tf.expand_dims', (['varchoice_node_representation'], {'axis': '(-2)'}), '(varchoice_node_representation, axis=-2)\n', (38528, 38568), True, 'import tensorflow as tf\n'), ((45584, 45593), 'collections.Counter', 'Counter', ([], {}), '()\n', (45591, 45593), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((46496, 46642), 'dpu_utils.mlutils.vocabulary.Vocabulary.create_vocabulary', 'Vocabulary.create_vocabulary', (['merged_literal_counters[literal_kind]'], {'count_threshold': '(0)', 'max_size': "self.hyperparameters['eg_literal_vocab_size']"}), "(merged_literal_counters[literal_kind],\n count_threshold=0, max_size=self.hyperparameters['eg_literal_vocab_size'])\n", (46524, 46642), False, 'from dpu_utils.mlutils.vocabulary import Vocabulary\n'), ((60443, 60460), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (60454, 60460), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((72879, 72892), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (72890, 72892), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((75793, 75848), 'numpy.random.shuffle', 'np.random.shuffle', (['eg_varproduction_distractor_node_ids'], {}), '(eg_varproduction_distractor_node_ids)\n', (75810, 75848), True, 'import numpy as np\n'), ((76491, 76554), 'numpy.array', 'np.array', (['(eg_varproduction_options_node_ids + [0] * num_padding)'], {}), '(eg_varproduction_options_node_ids + [0] * num_padding)\n', (76499, 76554), True, 'import numpy as np\n'), ((90086, 90138), 'dpu_utils.tfutils.pick_indices_from_probs', 'pick_indices_from_probs', (['production_probs', 'beam_size'], {}), '(production_probs, beam_size)\n', (90109, 90138), False, 'from dpu_utils.tfutils import unsorted_segment_logsumexp, pick_indices_from_probs\n'), ((91830, 91875), 'dpu_utils.tfutils.pick_indices_from_probs', 'pick_indices_from_probs', (['var_probs', 'beam_size'], {}), '(var_probs, beam_size)\n', (91853, 91875), False, 'from dpu_utils.tfutils import unsorted_segment_logsumexp, pick_indices_from_probs\n'), ((93681, 93726), 'dpu_utils.tfutils.pick_indices_from_probs', 'pick_indices_from_probs', (['lit_probs', 'beam_size'], {}), '(lit_probs, beam_size)\n', (93704, 93726), False, 'from dpu_utils.tfutils import unsorted_segment_logsumexp, pick_indices_from_probs\n'), ((10387, 10417), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {}), '()\n', (10415, 10417), True, 'import tensorflow as tf\n'), ((11491, 11594), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': "('eg_edge_label_step%i_typ%i' % (step, edge_typ))"}), "(dtype=tf.int32, shape=[None], name=\n 'eg_edge_label_step%i_typ%i' % (step, edge_typ))\n", (11505, 11594), True, 'import tensorflow as tf\n'), ((12544, 12657), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': "('eg_sending_node_ids_step%i_edgetyp%i' % (step, edge_typ))"}), "(dtype=tf.int32, shape=[None], name=\n 'eg_sending_node_ids_step%i_edgetyp%i' % (step, edge_typ))\n", (12558, 12657), True, 'import tensorflow as tf\n'), ((17110, 17216), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': "('eg_litproduction_to_context_id_%s' % literal_kind)"}), "(dtype=tf.int32, shape=[None], name=\n 'eg_litproduction_to_context_id_%s' % literal_kind)\n", (17124, 17216), True, 'import tensorflow as tf\n'), ((17392, 17502), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None]', 'name': "('eg_litproduction_choice_normalizer_%s' % literal_kind)"}), "(dtype=tf.int32, shape=[None], name=\n 'eg_litproduction_choice_normalizer_%s' % literal_kind)\n", (17406, 17502), True, 'import tensorflow as tf\n'), ((28308, 28474), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'literal_logits[literal_kind]', 'labels': "self.placeholders['eg_litproduction_node_choices'][literal_kind]"}), "(logits=literal_logits[\n literal_kind], labels=self.placeholders['eg_litproduction_node_choices'\n ][literal_kind])\n", (28354, 28474), True, 'import tensorflow as tf\n'), ((28682, 28709), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['raw_lit_loss'], {}), '(raw_lit_loss)\n', (28695, 28709), True, 'import tensorflow as tf\n'), ((29204, 29231), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['raw_var_loss'], {}), '(raw_var_loss)\n', (29217, 29231), True, 'import tensorflow as tf\n'), ((30691, 30723), 'tensorflow.constant', 'tf.constant', (['[0]'], {'dtype': 'tf.int32'}), '([0], dtype=tf.int32)\n', (30702, 30723), True, 'import tensorflow as tf\n'), ((31653, 31738), 'tensorflow.expand_dims', 'tf.expand_dims', (["self.placeholders['eg_litproduction_node_representation']"], {'axis': '(0)'}), "(self.placeholders['eg_litproduction_node_representation'],\n axis=0)\n", (31667, 31738), True, 'import tensorflow as tf\n'), ((31848, 31880), 'tensorflow.constant', 'tf.constant', (['[0]'], {'dtype': 'tf.int32'}), '([0], dtype=tf.int32)\n', (31859, 31880), True, 'import tensorflow as tf\n'), ((32073, 32111), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['literal_logits'], {'axis': '(-1)'}), '(literal_logits, axis=-1)\n', (32086, 32111), True, 'import tensorflow as tf\n'), ((33296, 33363), 'tensorflow.expand_dims', 'tf.expand_dims', (["self.placeholders['eg_msg_target_label_id']"], {'axis': '(0)'}), "(self.placeholders['eg_msg_target_label_id'], axis=0)\n", (33310, 33363), True, 'import tensorflow as tf\n'), ((33428, 33471), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""async_ggnn/prop_round0"""'], {}), "('async_ggnn/prop_round0')\n", (33445, 33471), True, 'import tensorflow as tf\n'), ((36755, 36796), 'tensorflow.expand_dims', 'tf.expand_dims', (['attention_weight'], {'axis': '(-1)'}), '(attention_weight, axis=-1)\n', (36769, 36796), True, 'import tensorflow as tf\n'), ((37399, 37430), 'tensorflow.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (37428, 37430), True, 'import tensorflow as tf\n'), ((38976, 39029), 'tensorflow.expand_dims', 'tf.expand_dims', (['varchoice_options_inner_prod'], {'axis': '(-1)'}), '(varchoice_options_inner_prod, axis=-1)\n', (38990, 39029), True, 'import tensorflow as tf\n'), ((39380, 39411), 'tensorflow.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (39409, 39411), True, 'import tensorflow as tf\n'), ((41744, 41775), 'tensorflow.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (41773, 41775), True, 'import tensorflow as tf\n'), ((42324, 42382), 'tensorflow.expand_dims', 'tf.expand_dims', (['litproduction_node_representations'], {'axis': '(1)'}), '(litproduction_node_representations, axis=1)\n', (42338, 42382), True, 'import tensorflow as tf\n'), ((43345, 43398), 'tensorflow.reshape', 'tf.reshape', (['vocab_choices_and_copy_scores'], {'shape': '[-1]'}), '(vocab_choices_and_copy_scores, shape=[-1])\n', (43355, 43398), True, 'import tensorflow as tf\n'), ((57208, 57246), 'numpy.arange', 'np.arange', (['num_choices'], {'dtype': 'np.int16'}), '(num_choices, dtype=np.int16)\n', (57217, 57246), True, 'import numpy as np\n'), ((59803, 59923), 'numpy.array', 'np.array', (['[node_to_synthesised_id[last_used_node_id[varchoice]] for varchoice in\n variables_in_scope]'], {'dtype': 'np.int16'}), '([node_to_synthesised_id[last_used_node_id[varchoice]] for\n varchoice in variables_in_scope], dtype=np.int16)\n', (59811, 59923), True, 'import numpy as np\n'), ((60985, 61002), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (60996, 61002), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((68359, 68398), 'numpy.empty', 'np.empty', ([], {'shape': '[0, 2]', 'dtype': 'np.uint16'}), '(shape=[0, 2], dtype=np.uint16)\n', (68367, 68398), True, 'import numpy as np\n'), ((68455, 68501), 'numpy.array', 'np.array', (['literal_choice_data'], {'dtype': 'np.uint16'}), '(literal_choice_data, dtype=np.uint16)\n', (68463, 68501), True, 'import numpy as np\n'), ((80639, 80697), 'numpy.concatenate', 'np.concatenate', (["batch_data['eg_msg_target_node_ids'][step]"], {}), "(batch_data['eg_msg_target_node_ids'][step])\n", (80653, 80697), True, 'import numpy as np\n'), ((81717, 81791), 'numpy.concatenate', 'np.concatenate', (["batch_data['eg_litproduction_nodes'][literal_kind]"], {'axis': '(0)'}), "(batch_data['eg_litproduction_nodes'][literal_kind], axis=0)\n", (81731, 81791), True, 'import numpy as np\n'), ((81963, 82048), 'numpy.concatenate', 'np.concatenate', (["batch_data['eg_litproduction_node_choices'][literal_kind]"], {'axis': '(0)'}), "(batch_data['eg_litproduction_node_choices'][literal_kind],\n axis=0)\n", (81977, 82048), True, 'import numpy as np\n'), ((100676, 100714), 'numpy.arange', 'np.arange', (['num_choices'], {'dtype': 'np.int16'}), '(num_choices, dtype=np.int16)\n', (100685, 100714), True, 'import numpy as np\n'), ((102026, 102043), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (102037, 102043), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((103189, 103207), 'collections.deque', 'deque', (['[root_node]'], {}), '([root_node])\n', (103194, 103207), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((10842, 10872), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {}), '()\n', (10870, 10872), True, 'import tensorflow as tf\n'), ((20938, 21066), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (["self.parameters['eg_edge_label_embeddings']", "self.placeholders['eg_edge_label_ids'][step][edge_typ]"], {}), "(self.parameters['eg_edge_label_embeddings'], self.\n placeholders['eg_edge_label_ids'][step][edge_typ])\n", (20960, 21066), True, 'import tensorflow as tf\n'), ((28065, 28087), 'tensorflow.size', 'tf.size', (['raw_prod_loss'], {}), '(raw_prod_loss)\n', (28072, 28087), True, 'import tensorflow as tf\n'), ((28181, 28202), 'tensorflow.size', 'tf.size', (['raw_var_loss'], {}), '(raw_var_loss)\n', (28188, 28202), True, 'import tensorflow as tf\n'), ((29173, 29201), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['raw_prod_loss'], {}), '(raw_prod_loss)\n', (29186, 29201), True, 'import tensorflow as tf\n'), ((35884, 35939), 'tensorflow.expand_dims', 'tf.expand_dims', (['production_node_representations'], {'axis': '(1)'}), '(production_node_representations, axis=1)\n', (35898, 35939), True, 'import tensorflow as tf\n'), ((43536, 43577), 'tensorflow.shape', 'tf.shape', (['litproduction_choice_normalizer'], {}), '(litproduction_choice_normalizer)\n', (43544, 43577), True, 'import tensorflow as tf\n'), ((77816, 77854), 'numpy.expand_dims', 'np.expand_dims', (['normalizer_map'], {'axis': '(0)'}), '(normalizer_map, axis=0)\n', (77830, 77854), True, 'import numpy as np\n'), ((78377, 78437), 'numpy.reshape', 'np.reshape', (['(repeated_normalizer_map + normalizer_offsets)', '(-1)'], {}), '(repeated_normalizer_map + normalizer_offsets, -1)\n', (78387, 78437), True, 'import numpy as np\n'), ((82292, 82378), 'numpy.concatenate', 'np.concatenate', (["batch_data['eg_litproduction_to_context_id'][literal_kind]"], {'axis': '(0)'}), "(batch_data['eg_litproduction_to_context_id'][literal_kind],\n axis=0)\n", (82306, 82378), True, 'import numpy as np\n'), ((82563, 82654), 'numpy.concatenate', 'np.concatenate', (["batch_data['eg_litproduction_choice_normalizer'][literal_kind]"], {'axis': '(0)'}), "(batch_data['eg_litproduction_choice_normalizer'][\n literal_kind], axis=0)\n", (82577, 82654), True, 'import numpy as np\n'), ((102618, 102635), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (102629, 102635), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((102727, 102744), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (102738, 102744), False, 'from collections import defaultdict, Counter, OrderedDict, namedtuple, deque\n'), ((104289, 104327), 'numpy.exp', 'np.exp', (['beam_info.expansion_logprob[0]'], {}), '(beam_info.expansion_logprob[0])\n', (104295, 104327), True, 'import numpy as np\n'), ((24270, 24314), 'tensorflow.shape', 'tf.shape', (['eg_production_node_representations'], {}), '(eg_production_node_representations)\n', (24278, 24314), True, 'import tensorflow as tf\n'), ((28721, 28742), 'tensorflow.size', 'tf.size', (['raw_lit_loss'], {}), '(raw_lit_loss)\n', (28728, 28742), True, 'import tensorflow as tf\n'), ((32969, 33006), 'tensorflow.shape', 'tf.shape', (['all_sending_representations'], {}), '(all_sending_representations)\n', (32977, 33006), True, 'import tensorflow as tf\n'), ((38635, 38678), 'tensorflow.shape', 'tf.shape', (['varchoice_options_representations'], {}), '(varchoice_options_representations)\n', (38643, 38678), True, 'import tensorflow as tf\n'), ((86185, 86244), 'numpy.empty', 'np.empty', ([], {'shape': "[0, self.hyperparameters['eg_hidden_size']]"}), "(shape=[0, self.hyperparameters['eg_hidden_size']])\n", (86193, 86244), True, 'import numpy as np\n'), ((87024, 87083), 'numpy.empty', 'np.empty', ([], {'shape': "[0, self.hyperparameters['eg_hidden_size']]"}), "(shape=[0, self.hyperparameters['eg_hidden_size']])\n", (87032, 87083), True, 'import numpy as np\n'), ((95092, 95116), 'numpy.log', 'np.log', (['prod_probability'], {}), '(prod_probability)\n', (95098, 95116), True, 'import numpy as np\n'), ((104387, 104425), 'numpy.exp', 'np.exp', (['beam_info.expansion_logprob[0]'], {}), '(beam_info.expansion_logprob[0])\n', (104393, 104425), True, 'import numpy as np\n'), ((77999, 78033), 'numpy.arange', 'np.arange', (['num_choices_this_sample'], {}), '(num_choices_this_sample)\n', (78008, 78033), True, 'import numpy as np\n'), ((97600, 97623), 'numpy.log', 'np.log', (['var_probability'], {}), '(var_probability)\n', (97606, 97623), True, 'import numpy as np\n'), ((99183, 99210), 'numpy.log', 'np.log', (['literal_probability'], {}), '(literal_probability)\n', (99189, 99210), True, 'import numpy as np\n'), ((21217, 21281), 'tensorflow.shape', 'tf.shape', (["self.placeholders['eg_edge_label_ids'][step][edge_typ]"], {}), "(self.placeholders['eg_edge_label_ids'][step][edge_typ])\n", (21225, 21281), True, 'import tensorflow as tf\n')]
from glob import glob import zipfile import shutil import os import json import numpy as np import nibabel as nib import matplotlib.pyplot as plt """ find all zip files, unzip one by one for each unzipped content: get patient ID according to zip filename save T1 weighted nifit as format "mri5726_NACC626353" zipname followed by patient ID Note: request MRIs from NACC are all 3T """ def read_json(jsonfile): with open(jsonfile) as f: return json.load(f) def get_Series(json_files): pool = [] for jsonfile in json_files: data = read_json(jsonfile) if 'SeriesDescription' not in data: pool.append('unknown') else: pool.append(data['SeriesDescription']) return pool def get_zipname(path): return path.split('/')[-1].strip('ni.zip') def unzip_folder(path): target_path = '/data/datasets/NACC15RAW/'+get_zipname(path)+'/' with zipfile.ZipFile(path, 'r') as zip_ref: zip_ref.extractall(target_path) # print('unzip ' + target_path + ' done!') return target_path def delete_folder(path): shutil.rmtree(path) # print('delete ' + path + ' done!') def find_json(path): pool = [] for root, dirs, files in os.walk(path): for file in files: if file.endswith('.json'): pool.append(os.path.join(root, file)) return pool def find_nifti(path): pool = [] for root, dirs, files in os.walk(path): for file in files: if file.endswith('.nii'): pool.append(os.path.join(root, file)) return pool def condition_series(serie): if 'T1' in serie or 't1' in serie: return True if 'MPRAGE' in serie or 'mprage' in serie or 'mp-rage' in serie or 'MP-RAGE' in serie: return True if 'T2' in serie or 't2' in serie: return False if 'FLAIR' in serie or 'flair' in serie or 'Flair' in serie: return False if 'Localizer' in serie or 'localizer' in serie: return False if 'DTI' in serie: return False if 'calibration' in serie: return False return True def save_image(niftifile, serie): image = nib.load(niftifile).get_data().squeeze() if len(image.shape) != 3: return if min(image.shape) < 80: return if not condition_series(serie): return x, y, z = image.shape zipname = niftifile.split('/')[4] print(zipname, image.shape) save_path = '/data/datasets/NACC15RAW/images/'+zipname+'/' if not os.path.exists(save_path): os.mkdir(save_path) imagename = serie + '##' + niftifile.split('/')[-1].replace('.nii', '.jpg') plt.subplot(131) plt.imshow(image[x//2, :, :], cmap='gray') plt.subplot(132) plt.imshow(image[:, y//2, :], cmap='gray') plt.subplot(133) plt.imshow(image[:, :, z//2], cmap='gray') plt.savefig(save_path+imagename) plt.close() def process(zipfile): target_path = unzip_folder(zipfile) json_files = find_json(target_path) series = get_Series(json_files) for i, jsonfile in enumerate(json_files): niftifile = jsonfile.replace('.json', '.nii') serie = series[i] try: save_image(niftifile, serie) except: pass delete_folder(target_path) def process_json(zipfile, ET, RT, FA, SS): target_path = unzip_folder(zipfile) json_files = find_json(target_path) series = get_Series(json_files) for i, jsonfile in enumerate(json_files): if condition_series(series[i]): jf = read_json(jsonfile) if 'MRAcquisitionType' not in jf or jf['MRAcquisitionType'] != '3D': continue if 'EchoTime' not in jf or float(jf['EchoTime']) > 0.1: continue if 'RepetitionTime' not in jf or float(jf['RepetitionTime']) > 0.1: continue if 'FlipAngle' not in jf: continue if 'ScanningSequence' not in jf: continue ET.append(float(jf['EchoTime'])) RT.append(float(jf['RepetitionTime'])) FA.append(float(jf['FlipAngle'])) SS.append(jf['ScanningSequence']) print(series[i], "has echo time", jf['EchoTime'], '**** RepTime', jf['RepetitionTime'], '*** FlipAngle', jf['FlipAngle']) delete_folder(target_path) if __name__ == "__main__": zip_files = glob('/data/datasets/NACC15RAW/mri*.zip') ET, RT, FA, SS = [], [], [], [] for zip_file in zip_files[:100]: process_json(zip_file, ET, RT, FA, SS) ET = np.array(ET) print("ET: ", np.mean(ET), "+/-", np.std(ET)) RT = np.array(RT) print("RT: ", np.mean(RT), "+/-", np.std(RT)) FA = np.array(FA) print("FA: ", np.mean(FA), "+/-", np.std(FA)) print("scaning sequence ", SS)
[ "matplotlib.pyplot.subplot", "os.mkdir", "json.load", "zipfile.ZipFile", "nibabel.load", "numpy.std", "matplotlib.pyplot.imshow", "matplotlib.pyplot.close", "os.walk", "os.path.exists", "numpy.mean", "numpy.array", "glob.glob", "shutil.rmtree", "os.path.join", "matplotlib.pyplot.savefig" ]
[((1100, 1119), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (1113, 1119), False, 'import shutil\n'), ((1226, 1239), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (1233, 1239), False, 'import os\n'), ((1443, 1456), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (1450, 1456), False, 'import os\n'), ((2663, 2679), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(131)'], {}), '(131)\n', (2674, 2679), True, 'import matplotlib.pyplot as plt\n'), ((2684, 2728), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image[x // 2, :, :]'], {'cmap': '"""gray"""'}), "(image[x // 2, :, :], cmap='gray')\n", (2694, 2728), True, 'import matplotlib.pyplot as plt\n'), ((2731, 2747), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(132)'], {}), '(132)\n', (2742, 2747), True, 'import matplotlib.pyplot as plt\n'), ((2752, 2796), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image[:, y // 2, :]'], {'cmap': '"""gray"""'}), "(image[:, y // 2, :], cmap='gray')\n", (2762, 2796), True, 'import matplotlib.pyplot as plt\n'), ((2799, 2815), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(133)'], {}), '(133)\n', (2810, 2815), True, 'import matplotlib.pyplot as plt\n'), ((2820, 2864), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image[:, :, z // 2]'], {'cmap': '"""gray"""'}), "(image[:, :, z // 2], cmap='gray')\n", (2830, 2864), True, 'import matplotlib.pyplot as plt\n'), ((2867, 2901), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(save_path + imagename)'], {}), '(save_path + imagename)\n', (2878, 2901), True, 'import matplotlib.pyplot as plt\n'), ((2904, 2915), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2913, 2915), True, 'import matplotlib.pyplot as plt\n'), ((4337, 4378), 'glob.glob', 'glob', (['"""/data/datasets/NACC15RAW/mri*.zip"""'], {}), "('/data/datasets/NACC15RAW/mri*.zip')\n", (4341, 4378), False, 'from glob import glob\n'), ((4508, 4520), 'numpy.array', 'np.array', (['ET'], {}), '(ET)\n', (4516, 4520), True, 'import numpy as np\n'), ((4580, 4592), 'numpy.array', 'np.array', (['RT'], {}), '(RT)\n', (4588, 4592), True, 'import numpy as np\n'), ((4652, 4664), 'numpy.array', 'np.array', (['FA'], {}), '(FA)\n', (4660, 4664), True, 'import numpy as np\n'), ((465, 477), 'json.load', 'json.load', (['f'], {}), '(f)\n', (474, 477), False, 'import json\n'), ((921, 947), 'zipfile.ZipFile', 'zipfile.ZipFile', (['path', '"""r"""'], {}), "(path, 'r')\n", (936, 947), False, 'import zipfile\n'), ((2524, 2549), 'os.path.exists', 'os.path.exists', (['save_path'], {}), '(save_path)\n', (2538, 2549), False, 'import os\n'), ((2559, 2578), 'os.mkdir', 'os.mkdir', (['save_path'], {}), '(save_path)\n', (2567, 2578), False, 'import os\n'), ((4539, 4550), 'numpy.mean', 'np.mean', (['ET'], {}), '(ET)\n', (4546, 4550), True, 'import numpy as np\n'), ((4559, 4569), 'numpy.std', 'np.std', (['ET'], {}), '(ET)\n', (4565, 4569), True, 'import numpy as np\n'), ((4611, 4622), 'numpy.mean', 'np.mean', (['RT'], {}), '(RT)\n', (4618, 4622), True, 'import numpy as np\n'), ((4631, 4641), 'numpy.std', 'np.std', (['RT'], {}), '(RT)\n', (4637, 4641), True, 'import numpy as np\n'), ((4683, 4694), 'numpy.mean', 'np.mean', (['FA'], {}), '(FA)\n', (4690, 4694), True, 'import numpy as np\n'), ((4703, 4713), 'numpy.std', 'np.std', (['FA'], {}), '(FA)\n', (4709, 4713), True, 'import numpy as np\n'), ((1335, 1359), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (1347, 1359), False, 'import os\n'), ((1551, 1575), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (1563, 1575), False, 'import os\n'), ((2172, 2191), 'nibabel.load', 'nib.load', (['niftifile'], {}), '(niftifile)\n', (2180, 2191), True, 'import nibabel as nib\n')]
import numpy as _np import scipy.sparse as _sp from ._basis_utils import _shuffle_sites #################################################### # set of helper functions to implement the partial # # trace of lattice density matrices. They do not # # have any checks and states are assumed to be # # in the non-symmetry reduced basis. # #################################################### def _lattice_partial_trace_pure(psi,sub_sys_A,L,sps,return_rdm="A"): """ This function computes the partial trace of a dense pure state psi over set of sites sub_sys_A and returns reduced DM. Vectorisation available. """ psi_v=_lattice_reshape_pure(psi,sub_sys_A,L,sps) if return_rdm == "A": return _np.squeeze(_np.einsum("...ij,...kj->...ik",psi_v,psi_v.conj())),None elif return_rdm == "B": return None,_np.squeeze(_np.einsum("...ji,...jk->...ik",psi_v.conj(),psi_v)) elif return_rdm == "both": return _np.squeeze(_np.einsum("...ij,...kj->...ik",psi_v,psi_v.conj())),_np.squeeze(_np.einsum("...ji,...jk->...ik",psi_v.conj(),psi_v)) def _lattice_partial_trace_mixed(rho,sub_sys_A,L,sps,return_rdm="A"): """ This function computes the partial trace of a set of dense mixed states rho over set of sites sub_sys_A and returns reduced DM. Vectorisation available. """ rho_v=_lattice_reshape_mixed(rho,sub_sys_A,L,sps) if return_rdm == "A": return _np.einsum("...jlkl->...jk",rho_v),None elif return_rdm == "B": return None,_np.einsum("...ljlk->...jk",rho_v.conj()) elif return_rdm == "both": return _np.einsum("...jlkl->...jk",rho_v),_np.einsum("...ljlk->...jk",rho_v.conj()) def _lattice_partial_trace_sparse_pure(psi,sub_sys_A,L,sps,return_rdm="A"): """ This function computes the partial trace of a sparse pure state psi over set of sites sub_sys_A and returns reduced DM. """ psi=_lattice_reshape_sparse_pure(psi,sub_sys_A,L,sps) if return_rdm == "A": return psi.dot(psi.H),None elif return_rdm == "B": return None,psi.H.dot(psi) elif return_rdm == "both": return psi.dot(psi.H),psi.H.dot(psi) def _lattice_reshape_pure(psi,sub_sys_A,L,sps): """ This function reshapes the dense pure state psi over the Hilbert space defined by sub_sys_A and its complement. Vectorisation available. """ extra_dims = psi.shape[:-1] n_dims = len(extra_dims) sub_sys_B = set(range(L))-set(sub_sys_A) sub_sys_A = tuple(sub_sys_A) sub_sys_B = tuple(sub_sys_B) L_A = len(sub_sys_A) L_B = len(sub_sys_B) Ns_A = (sps**L_A) Ns_B = (sps**L_B) T_tup = sub_sys_A+sub_sys_B psi_v = _shuffle_sites(sps,T_tup,psi) psi_v = psi_v.reshape(extra_dims+(Ns_A,Ns_B)) return psi_v ''' def _lattice_reshape_pure(psi,sub_sys_A,L,sps): """ This function reshapes the dense pure state psi over the Hilbert space defined by sub_sys_A and its complement. Vectorisation available. """ extra_dims = psi.shape[:-1] n_dims = len(extra_dims) sub_sys_B = set(range(L))-set(sub_sys_A) sub_sys_A = tuple(sub_sys_A) sub_sys_B = tuple(sub_sys_B) L_A = len(sub_sys_A) L_B = len(sub_sys_B) Ns_A = (sps**L_A) Ns_B = (sps**L_B) T_tup = sub_sys_A+sub_sys_B T_tup = tuple(range(n_dims)) + tuple(n_dims + s for s in T_tup) R_tup = extra_dims + tuple(sps for i in range(L)) psi_v = psi.reshape(R_tup) # DM where index is given per site as rho_v[i_1,...,i_L,j_1,...j_L] psi_v = psi_v.transpose(T_tup) # take transpose to reshuffle indices psi_v = psi_v.reshape(extra_dims+(Ns_A,Ns_B)) return psi_v ''' def _lattice_reshape_mixed(rho,sub_sys_A,L,sps): """ This function reshapes the dense mixed state psi over the Hilbert space defined by sub_sys_A and its complement. Vectorisation available. """ extra_dims = rho.shape[:-2] n_dims = len(extra_dims) sub_sys_B = set(range(L))-set(sub_sys_A) sub_sys_A = tuple(sub_sys_A) sub_sys_B = tuple(sub_sys_B) L_A = len(sub_sys_A) L_B = len(sub_sys_B) Ns_A = (sps**L_A) Ns_B = (sps**L_B) # T_tup tells numpy how to reshuffle the indices such that when I reshape the array to the # 4-_tensor rho_{ik,jl} i,j are for sub_sys_A and k,l are for sub_sys_B # which means I need (sub_sys_A,sub_sys_B,sub_sys_A+L,sub_sys_B+L) T_tup = sub_sys_A+sub_sys_B T_tup = tuple(T_tup) + tuple(L+s for s in T_tup) rho = rho.reshape(extra_dims+(-1,)) rho_v = _shuffle_sites(sps,T_tup,rho) return rho_v.reshape(extra_dims+(Ns_A,Ns_B,Ns_A,Ns_B)) ''' def _lattice_reshape_mixed(rho,sub_sys_A,L,sps): """ This function reshapes the dense mixed state psi over the Hilbert space defined by sub_sys_A and its complement. Vectorisation available. """ extra_dims = rho.shape[:-2] n_dims = len(extra_dims) sub_sys_B = set(range(L))-set(sub_sys_A) sub_sys_A = tuple(sub_sys_A) sub_sys_B = tuple(sub_sys_B) L_A = len(sub_sys_A) L_B = len(sub_sys_B) Ns_A = (sps**L_A) Ns_B = (sps**L_B) # T_tup tells numpy how to reshuffle the indices such that when I reshape the array to the # 4-_tensor rho_{ik,jl} i,j are for sub_sys_A and k,l are for sub_sys_B # which means I need (sub_sys_A,sub_sys_B,sub_sys_A+L,sub_sys_B+L) T_tup = sub_sys_A+sub_sys_B T_tup = tuple(range(n_dims)) + tuple(s+n_dims for s in T_tup) + tuple(L+n_dims+s for s in T_tup) R_tup = extra_dims + tuple(sps for i in range(2*L)) rho_v = rho.reshape(R_tup) # DM where index is given per site as rho_v[i_1,...,i_L,j_1,...j_L] rho_v = rho_v.transpose(T_tup) # take transpose to reshuffle indices return rho_v.reshape(extra_dims+(Ns_A,Ns_B,Ns_A,Ns_B)) ''' def _lattice_reshape_sparse_pure(psi,sub_sys_A,L,sps): """ This function reshapes the sparse pure state psi over the Hilbert space defined by sub_sys_A and its complement. """ sub_sys_B = set(range(L))-set(sub_sys_A) sub_sys_A = tuple(sub_sys_A) sub_sys_B = tuple(sub_sys_B) L_A = len(sub_sys_A) L_B = len(sub_sys_B) Ns_A = (sps**L_A) Ns_B = (sps**L_B) psi = psi.tocoo() T_tup = sub_sys_A+sub_sys_B # reshuffle indices for the sub-systems. # j = sum( j[i]*(sps**i) for i in range(L)) # this reshuffles the j[i] similar to the transpose operation # on the dense arrays psi_v.transpose(T_tup) if T_tup != tuple(range(L)): indx = _np.zeros(psi.col.shape,dtype=psi.col.dtype) for i_old,i_new in enumerate(T_tup): indx += ((psi.col//(sps**(L-i_new-1))) % sps)*(sps**(L-i_old-1)) else: indx = psi.col # A = _np.array([0,1,2,3,4,5,6,7,8,9,10,11]) # print("make shift way of reshaping array") # print("A = {}".format(A)) # print("A.reshape((3,4)): \n {}".format(A.reshape((3,4)))) # print("rows: A.reshape((3,4))/4: \n {}".format(A.reshape((3,4))/4)) # print("cols: A.reshape((3,4))%4: \n {}".format(A.reshape((3,4))%4)) psi._shape = (Ns_A,Ns_B) psi.row[:] = indx / Ns_B psi.col[:] = indx % Ns_B return psi.tocsr() def _tensor_reshape_pure(psi,sub_sys_A,Ns_l,Ns_r): extra_dims = psi.shape[:-1] if sub_sys_A == "left": return psi.reshape(extra_dims+(Ns_l,Ns_r)) else: n_dims = len(extra_dims) T_tup = tuple(range(n_dims))+(n_dims+1,n_dims) psi_v = psi.reshape(extra_dims+(Ns_l,Ns_r)) return psi_v.transpose(T_tup) def _tensor_reshape_sparse_pure(psi,sub_sys_A,Ns_l,Ns_r): psi = psi.tocoo() # make shift way of reshaping array # j = j_l + Ns_r * j_l # j_l = j / Ns_r # j_r = j % Ns_r if sub_sys_A == "left": psi._shape = (Ns_l,Ns_r) psi.row[:] = psi.col / Ns_r psi.col[:] = psi.col % Ns_r return psi.tocsr() else: psi._shape = (Ns_l,Ns_r) psi.row[:] = psi.col / Ns_r psi.col[:] = psi.col % Ns_r return psi.T.tocsr() def _tensor_reshape_mixed(rho,sub_sys_A,Ns_l,Ns_r): extra_dims = rho.shape[:-2] if sub_sys_A == "left": return rho.reshape(extra_dims+(Ns_l,Ns_r,Ns_l,Ns_r)) else: n_dims = len(extra_dims) T_tup = tuple(range(n_dims))+(n_dims+1,n_dims)+(n_dims+3,n_dims+2) rho_v = rho.reshape(extra_dims+(Ns_l,Ns_r,Ns_l,Ns_r)) return rho_v.transpose(T_tup) def _tensor_partial_trace_pure(psi,sub_sys_A,Ns_l,Ns_r,return_rdm="A"): psi_v = _tensor_reshape_pure(psi,sub_sys_A,Ns_l,Ns_r) if return_rdm == "A": return _np.squeeze(_np.einsum("...ij,...kj->...ik",psi_v,psi_v.conj())),None elif return_rdm == "B": return None,_np.squeeze(_np.einsum("...ji,...jk->...ik",psi_v.conj(),psi_v)) elif return_rdm == "both": return _np.squeeze(_np.einsum("...ij,...kj->...ik",psi_v,psi_v.conj())),_np.squeeze(_np.einsum("...ji,...jk->...ik",psi_v.conj(),psi_v)) def _tensor_partial_trace_sparse_pure(psi,sub_sys_A,Ns_l,Ns_r,return_rdm="A"): psi = _tensor_reshape_sparse_pure(psi,sub_sys_A,Ns_l,Ns_r) if return_rdm == "A": return psi.dot(psi.H),None elif return_rdm == "B": return None,psi.H.dot(psi) elif return_rdm == "both": return psi.dot(psi.H),psi.H.dot(psi) def _tensor_partial_trace_mixed(rho,sub_sys_A,Ns_l,Ns_r,return_rdm="A"): rho_v = _tensor_reshape_mixed(rho,sub_sys_A,Ns_l,Ns_r) if return_rdm == "A": return _np.squeeze(_np.einsum("...ijkj->...ik",rho_v)),None elif return_rdm == "B": return None,_np.squeeze(_np.einsum("...jijk->...ik",rho_v.conj())) elif return_rdm == "both": return _np.squeeze(_np.einsum("...ijkj->...ik",rho_v)),_np.squeeze(_np.einsum("...jijk->...ik",rho_v.conj()))
[ "numpy.zeros", "numpy.einsum" ]
[((6095, 6140), 'numpy.zeros', '_np.zeros', (['psi.col.shape'], {'dtype': 'psi.col.dtype'}), '(psi.col.shape, dtype=psi.col.dtype)\n', (6104, 6140), True, 'import numpy as _np\n'), ((1385, 1420), 'numpy.einsum', '_np.einsum', (['"""...jlkl->...jk"""', 'rho_v'], {}), "('...jlkl->...jk', rho_v)\n", (1395, 1420), True, 'import numpy as _np\n'), ((8788, 8823), 'numpy.einsum', '_np.einsum', (['"""...ijkj->...ik"""', 'rho_v'], {}), "('...ijkj->...ik', rho_v)\n", (8798, 8823), True, 'import numpy as _np\n'), ((1543, 1578), 'numpy.einsum', '_np.einsum', (['"""...jlkl->...jk"""', 'rho_v'], {}), "('...jlkl->...jk', rho_v)\n", (1553, 1578), True, 'import numpy as _np\n'), ((8972, 9007), 'numpy.einsum', '_np.einsum', (['"""...ijkj->...ik"""', 'rho_v'], {}), "('...ijkj->...ik', rho_v)\n", (8982, 9007), True, 'import numpy as _np\n')]
import torch import numpy as np __all__ = ["CosineDistance"] #NOTE: see https://github.com/pytorch/pytorch/issues/8069 #TODO: update acos_safe once PR mentioned in above link is merged and available def _acos_safe(x: torch.Tensor, eps: float=1e-4): slope = np.arccos(1.0 - eps) / eps # TODO: stop doing this allocation once sparse gradients with NaNs (like in # th.where) are handled differently. buf = torch.empty_like(x) good = torch.abs(x) <= 1.0 - eps bad = ~good sign = torch.sign(x[bad]) buf[good] = torch.acos(x[good]) buf[bad] = torch.acos(sign * (1.0 - eps)) - slope * sign * (torch.abs(x[bad]) - 1.0 + eps) return buf ''' def _acos_safe(x: torch.Tensor, eps: float=1e-4): sign = torch.sign(x) slope = np.arccos(1.0 - eps) / eps return torch.where(torch.abs(x) <= 1.0 - eps, torch.acos(x), torch.acos(sign * (1.0 - eps)) - slope * sign * (torch.abs(x) - 1.0 + eps) ) ''' class CosineDistance(torch.nn.CosineSimilarity): def __init__(self, dim: int=1, epsilon: float=1e-4, normalized: bool=True, ): super(CosineDistance, self).__init__(dim=dim, eps=epsilon) self.normalized = normalized self.epsilon = epsilon def forward(self, gt: torch.Tensor, pred: torch.Tensor, weights: torch.Tensor=None, # float tensor mask: torch.Tensor=None, # byte tensor ) -> torch.Tensor: dot = torch.sum(gt * pred, dim=self.dim) if self.normalized\ else super(CosineDistance, self).forward(gt, pred) # return torch.acos(dot) / np.pi #NOTE: (eps) clamping should also fix the nan grad issue (traditional [-1, 1] clamping does not) # return torch.acos(torch.clamp(dot, min=-1.0 + self.epsilon, max=1.0 - self.epsilon)) / np.pi return _acos_safe(dot, eps=self.epsilon) / np.pi
[ "torch.sum", "torch.sign", "torch.abs", "torch.empty_like", "numpy.arccos", "torch.acos" ]
[((422, 441), 'torch.empty_like', 'torch.empty_like', (['x'], {}), '(x)\n', (438, 441), False, 'import torch\n'), ((506, 524), 'torch.sign', 'torch.sign', (['x[bad]'], {}), '(x[bad])\n', (516, 524), False, 'import torch\n'), ((541, 560), 'torch.acos', 'torch.acos', (['x[good]'], {}), '(x[good])\n', (551, 560), False, 'import torch\n'), ((264, 284), 'numpy.arccos', 'np.arccos', (['(1.0 - eps)'], {}), '(1.0 - eps)\n', (273, 284), True, 'import numpy as np\n'), ((453, 465), 'torch.abs', 'torch.abs', (['x'], {}), '(x)\n', (462, 465), False, 'import torch\n'), ((576, 606), 'torch.acos', 'torch.acos', (['(sign * (1.0 - eps))'], {}), '(sign * (1.0 - eps))\n', (586, 606), False, 'import torch\n'), ((1545, 1579), 'torch.sum', 'torch.sum', (['(gt * pred)'], {'dim': 'self.dim'}), '(gt * pred, dim=self.dim)\n', (1554, 1579), False, 'import torch\n'), ((625, 642), 'torch.abs', 'torch.abs', (['x[bad]'], {}), '(x[bad])\n', (634, 642), False, 'import torch\n')]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Copyright (c) 2019, Eurecat / UPF # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the <organization> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @file test_script_mics.py # @author <NAME> # @date 29/07/2019 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import numpy as np from masp import shoebox_room_sim as srs import time import librosa # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # SETUP # Room definition room = np.array([10.2, 7.1, 3.2]) # Desired RT per octave band, and time to truncate the responses rt60 = np.array([1., 0.8, 0.7, 0.6, 0.5]) nBands = len(rt60) # Generate octave bands band_centerfreqs = np.empty(nBands) band_centerfreqs[0] = 125 for nb in range(1, nBands): band_centerfreqs[nb] = 2 * band_centerfreqs[nb-1] # Absorption for approximately achieving the RT60 above - row per band abs_wall = srs.find_abs_coeffs_from_rt(room, rt60)[0] # Critical distance for the room _, d_critical, _ = srs.room_stats(room, abs_wall) # Receiver position rec = np.array([ [4.5, 3.4, 1.5], [2.0, 3.1, 1.4] ]) nRec = rec.shape[0] # Source positions src = np.array([ [6.2, 2.0, 1.8], [7.9, 3.3, 1.75], [5.8, 5.0, 1.9] ]) nSrc = src.shape[0] # Mic orientations and directivities mic_specs = np.array([ [1, 0, 0, 0.5], # cardioid looking to the front [-1, 0, 0, 0.25]]) # hypercardioid looking backwards # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # RUN SIMULATOR # Echogram tic = time.time() maxlim = 1.5 # just stop if the echogram goes beyond that time ( or just set it to max(rt60) ) limits = np.minimum(rt60, maxlim) # Compute echograms # abs_echograms, rec_echograms, echograms = srs.compute_echograms_mic(room, src, rec, abs_wall, limits, mic_specs); abs_echograms = srs.compute_echograms_mic(room, src, rec, abs_wall, limits, mic_specs); # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # RENDERING # In this case all the information (receiver directivity especially) is already # encoded in the echograms, hence they are rendered directly to discrete RIRs fs = 48000 mic_rirs = srs.render_rirs_mic(abs_echograms, band_centerfreqs, fs) toc = time.time() print('Elapsed time is ' + str(toc-tic) + 'seconds.') # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # GENERATE SOUND SCENES # Each source is convolved with the respective mic IR, and summed with # the rest of the sources to create the microphone mixed signals sourcepath = '../../data/milk_cow_blues_4src.wav' src_sigs = librosa.core.load(sourcepath, sr=None, mono=False)[0].T[:,:nSrc] mic_sigs = srs.apply_source_signals_mic(mic_rirs, src_sigs)
[ "numpy.minimum", "masp.shoebox_room_sim.render_rirs_mic", "numpy.empty", "masp.shoebox_room_sim.apply_source_signals_mic", "time.time", "librosa.core.load", "masp.shoebox_room_sim.find_abs_coeffs_from_rt", "numpy.array", "masp.shoebox_room_sim.compute_echograms_mic", "masp.shoebox_room_sim.room_stats" ]
[((2087, 2113), 'numpy.array', 'np.array', (['[10.2, 7.1, 3.2]'], {}), '([10.2, 7.1, 3.2])\n', (2095, 2113), True, 'import numpy as np\n'), ((2187, 2222), 'numpy.array', 'np.array', (['[1.0, 0.8, 0.7, 0.6, 0.5]'], {}), '([1.0, 0.8, 0.7, 0.6, 0.5])\n', (2195, 2222), True, 'import numpy as np\n'), ((2285, 2301), 'numpy.empty', 'np.empty', (['nBands'], {}), '(nBands)\n', (2293, 2301), True, 'import numpy as np\n'), ((2589, 2619), 'masp.shoebox_room_sim.room_stats', 'srs.room_stats', (['room', 'abs_wall'], {}), '(room, abs_wall)\n', (2603, 2619), True, 'from masp import shoebox_room_sim as srs\n'), ((2647, 2691), 'numpy.array', 'np.array', (['[[4.5, 3.4, 1.5], [2.0, 3.1, 1.4]]'], {}), '([[4.5, 3.4, 1.5], [2.0, 3.1, 1.4]])\n', (2655, 2691), True, 'import numpy as np\n'), ((2740, 2802), 'numpy.array', 'np.array', (['[[6.2, 2.0, 1.8], [7.9, 3.3, 1.75], [5.8, 5.0, 1.9]]'], {}), '([[6.2, 2.0, 1.8], [7.9, 3.3, 1.75], [5.8, 5.0, 1.9]])\n', (2748, 2802), True, 'import numpy as np\n'), ((2875, 2919), 'numpy.array', 'np.array', (['[[1, 0, 0, 0.5], [-1, 0, 0, 0.25]]'], {}), '([[1, 0, 0, 0.5], [-1, 0, 0, 0.25]])\n', (2883, 2919), True, 'import numpy as np\n'), ((3135, 3146), 'time.time', 'time.time', ([], {}), '()\n', (3144, 3146), False, 'import time\n'), ((3252, 3276), 'numpy.minimum', 'np.minimum', (['rt60', 'maxlim'], {}), '(rt60, maxlim)\n', (3262, 3276), True, 'import numpy as np\n'), ((3430, 3500), 'masp.shoebox_room_sim.compute_echograms_mic', 'srs.compute_echograms_mic', (['room', 'src', 'rec', 'abs_wall', 'limits', 'mic_specs'], {}), '(room, src, rec, abs_wall, limits, mic_specs)\n', (3455, 3500), True, 'from masp import shoebox_room_sim as srs\n'), ((3780, 3836), 'masp.shoebox_room_sim.render_rirs_mic', 'srs.render_rirs_mic', (['abs_echograms', 'band_centerfreqs', 'fs'], {}), '(abs_echograms, band_centerfreqs, fs)\n', (3799, 3836), True, 'from masp import shoebox_room_sim as srs\n'), ((3844, 3855), 'time.time', 'time.time', ([], {}), '()\n', (3853, 3855), False, 'import time\n'), ((4295, 4343), 'masp.shoebox_room_sim.apply_source_signals_mic', 'srs.apply_source_signals_mic', (['mic_rirs', 'src_sigs'], {}), '(mic_rirs, src_sigs)\n', (4323, 4343), True, 'from masp import shoebox_room_sim as srs\n'), ((2493, 2532), 'masp.shoebox_room_sim.find_abs_coeffs_from_rt', 'srs.find_abs_coeffs_from_rt', (['room', 'rt60'], {}), '(room, rt60)\n', (2520, 2532), True, 'from masp import shoebox_room_sim as srs\n'), ((4218, 4268), 'librosa.core.load', 'librosa.core.load', (['sourcepath'], {'sr': 'None', 'mono': '(False)'}), '(sourcepath, sr=None, mono=False)\n', (4235, 4268), False, 'import librosa\n')]
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import datetime import json import logging import os import random import time from pathlib import Path import cv2 import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, DistributedSampler from torch.utils.data import Dataset import datasets import util.misc as utils from datasets import get_coco_api_from_dataset from datasets.coco import make_coco_transforms from engine import evaluate, train_one_epoch from models import build_model logger = logging.getLogger(__name__) def parse_textds_json(json_path, image_root, profile=False): content = load_json(json_path) d = [] for gt in content['data_list']: img_path = os.path.join(image_root, gt['img_name']) if not os.path.exists(img_path): if profile: logger.warning('image not exists - {} '.format(img_path)) continue polygons = [] texts = [] legibility_list = [] # 清晰文字,默认:true language_list = [] for annotation in gt['annotations']: if len(annotation['polygon']) == 0: # or len(annotation['text']) == 0: continue polygons.append(np.array(annotation['polygon']).reshape(-1, 2)) texts.append(annotation['text']) legibility_list.append(not annotation['illegibility']) language_list.append(annotation['language']) for char_annotation in annotation['chars']: if len(char_annotation['polygon']) == 0 or len(char_annotation['char']) == 0: continue polygons.append(char_annotation['polygon']) texts.append(char_annotation['char']) legibility_list.append(not char_annotation['illegibility']) language_list.append(char_annotation['language']) if len(polygons) > 0: d.append({'img_path': img_path, 'polygons': np.array(polygons), 'texts': texts, 'legibility': legibility_list, 'language': language_list}) return d def load_json(file_path: str): with open(file_path, 'r', encoding='utf8') as f: content = json.load(f) return content class JsonDataset(Dataset): """ """ @classmethod def load_json(cls, json_path, mode='train'): d = [] if isinstance(json_path, list): img_root = [os.path.join(os.path.dirname(p), mode) for p in json_path] for j_path, i_root in zip(json_path, img_root): print(i_root, j_path) d.extend(parse_textds_json(json_path=j_path, image_root=i_root)) else: image_root = os.path.join(os.path.dirname(json_path), mode) d = parse_textds_json(json_path=json_path, image_root=image_root) return d def __init__(self, json_path, mode='train', language='english', rect=False, psize=(640, 640), area_limit=80.0, scale=0.125, auto_fit=False, dict_out=True, profile=False, transforms=None): super().__init__() self.mode = mode self.arbitary_text_mode = not rect self.out_img_size = psize self.auto_fit = auto_fit self.dict_item = dict_out self.min_area = area_limit self.scale = scale self.profile = profile self.data = self.load_json(json_path=json_path, mode=mode) print(f'dataset: {len(self.data)}') self._transforms = transforms def __len__(self): return len(self.data) def __getitem__(self, idx): item = self.data[idx] image_path = item['img_path'] if not os.path.exists(image_path): if self.profile: logger.warning(f'NO Exists - {image_path}') return self.__getitem__(random.randint(0, len(self) - 1)) text_polys = item['polygons'] legibles = item['legibility'] cvimg = cv2.imread(image_path) cvimg = cv2.cvtColor(cvimg, cv2.COLOR_BGR2RGB) if self._transforms is not None: cvimg, text_polys, legibles = self._transforms(cvimg, text_polys, legibles) return cvimg, text_polys, legibles class SimpleJsonDataset(JsonDataset): def __init__(self, json_path, mode='train', language='english', rect=False, psize=(640, 640), area_limit=80.0, scale=0.125, auto_fit=False, dict_out=True, profile=False, transforms=None, target_transforms=None): super().__init__(json_path, mode, language, rect, psize, area_limit, scale, auto_fit, dict_out, profile, transforms) self._target_transforms = target_transforms def __getitem__(self, idx): item = self.data[idx] image_path = item['img_path'] target = {'image_id': torch.tensor(idx, dtype=torch.int64)} if not os.path.exists(image_path): if self.profile: logger.warning(f'NO Exists - {image_path}') return self.__getitem__(random.randint(0, len(self) - 1)) pimg = Image.open(image_path) cvimg = pimg.copy() pimg.close() target['orig_size'] = torch.tensor(pimg.size, dtype=torch.int64) classes = [0 for _ in item['polygons']] iscrowd = [0 for _ in item['polygons']] target['labels'] = torch.tensor(classes, dtype=torch.int64) target['iscrowd'] = torch.tensor(iscrowd) if 'bbox' not in item and 'polygons' in item: polys = item['polygons'] if not isinstance(polys, np.ndarray): polys = np.array(polys) bboxes = [None] * polys.shape[0] for pi, poly in enumerate(polys): x0 = np.min(poly[..., 0]) y0 = np.min(poly[..., 1]) x1 = np.max(poly[..., 0]) y1 = np.max(poly[..., 1]) bboxes[pi] = (x0, y0, x1, y1) target['boxes'] = torch.as_tensor(bboxes, dtype=torch.float32).reshape(-1, 4) if self._transforms: cvimg, item = self._transforms(cvimg, target) return cvimg, item def get_args_parser(): parser = argparse.ArgumentParser('Set transformer detector', add_help=False) parser.add_argument('--lr', default=1e-4, type=float) parser.add_argument('--lr_backbone', default=1e-5, type=float) parser.add_argument('--batch_size', default=2, type=int) parser.add_argument('--weight_decay', default=1e-4, type=float) parser.add_argument('--epochs', default=300, type=int) parser.add_argument('--lr_drop', default=200, type=int) parser.add_argument('--clip_max_norm', default=0.1, type=float, help='gradient clipping max norm') # Model parameters parser.add_argument('--frozen_weights', type=str, default=None, help="Path to the pretrained model. If set, only the mask head will be trained") # * Backbone parser.add_argument('--backbone', default='resnet50', type=str, help="Name of the convolutional backbone to use") parser.add_argument('--dilation', action='store_true', help="If true, we replace stride with dilation in the last convolutional block (DC5)") parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'), help="Type of positional embedding to use on top of the image features") # * Transformer parser.add_argument('--enc_layers', default=6, type=int, help="Number of encoding layers in the transformer") parser.add_argument('--dec_layers', default=6, type=int, help="Number of decoding layers in the transformer") parser.add_argument('--dim_feedforward', default=2048, type=int, help="Intermediate size of the feedforward layers in the transformer blocks") parser.add_argument('--hidden_dim', default=256, type=int, help="Size of the embeddings (dimension of the transformer)") parser.add_argument('--dropout', default=0.1, type=float, help="Dropout applied in the transformer") parser.add_argument('--nheads', default=8, type=int, help="Number of attention heads inside the transformer's attentions") parser.add_argument('--num_queries', default=100, type=int, help="Number of query slots") parser.add_argument('--pre_norm', action='store_true') # * Segmentation parser.add_argument('--masks', action='store_true', help="Train segmentation head if the flag is provided") # Loss parser.add_argument('--no_aux_loss', dest='aux_loss', action='store_false', help="Disables auxiliary decoding losses (loss at each layer)") # * Matcher parser.add_argument('--set_cost_class', default=1, type=float, help="Class coefficient in the matching cost") parser.add_argument('--set_cost_bbox', default=5, type=float, help="L1 box coefficient in the matching cost") parser.add_argument('--set_cost_giou', default=2, type=float, help="giou box coefficient in the matching cost") # * Loss coefficients parser.add_argument('--mask_loss_coef', default=1, type=float) parser.add_argument('--dice_loss_coef', default=1, type=float) parser.add_argument('--bbox_loss_coef', default=5, type=float) parser.add_argument('--giou_loss_coef', default=2, type=float) parser.add_argument('--eos_coef', default=0.1, type=float, help="Relative classification weight of the no-object class") # dataset parameters parser.add_argument('--dataset_file', default='coco') parser.add_argument('--coco_path', type=str) parser.add_argument('--coco_panoptic_path', type=str) parser.add_argument('--remove_difficult', action='store_true') parser.add_argument('--output_dir', default='', help='path where to save, empty for no saving') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=42, type=int) parser.add_argument('--resume', default='', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval', action='store_true') parser.add_argument('--num_workers', default=2, type=int) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') return parser def main(args): utils.init_distributed_mode(args) print("git:\n {}\n".format(utils.get_sha())) if args.frozen_weights is not None: assert args.masks, "Frozen training is meant for segmentation only" print(args) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + utils.get_rank() torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) model, criterion, postprocessors = build_model(args) model.to(device) model_without_ddp = model if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print('number of params:', n_parameters) param_dicts = [ {"params": [p for n, p in model_without_ddp.named_parameters() if "backbone" not in n and p.requires_grad]}, { "params": [p for n, p in model_without_ddp.named_parameters() if "backbone" in n and p.requires_grad], "lr": args.lr_backbone, }, ] optimizer = torch.optim.AdamW(param_dicts, lr=args.lr, weight_decay=args.weight_decay) lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, args.lr_drop) train_json = [ '/content/icpr2018/train.json', '/content/das/train.json', '/content/ctw1500/train.json', ] val_json = [ '/content/icpr2018/val.json', '/content/das/val.json', '/content/ctw1500/val.json', ] dataset_train = SimpleJsonDataset(json_path=train_json, mode='train', transforms=make_coco_transforms('train')) dataset_val = SimpleJsonDataset(json_path=val_json, mode='val', transforms=make_coco_transforms('val')) if args.distributed: sampler_train = DistributedSampler(dataset_train) sampler_val = DistributedSampler(dataset_val, shuffle=False) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) batch_sampler_train = torch.utils.data.BatchSampler( sampler_train, args.batch_size, drop_last=True) data_loader_train = DataLoader(dataset_train, batch_sampler=batch_sampler_train, collate_fn=utils.collate_fn, num_workers=args.num_workers) data_loader_val = DataLoader(dataset_val, args.batch_size, sampler=sampler_val, drop_last=False, collate_fn=utils.collate_fn, num_workers=args.num_workers) if args.dataset_file == "coco_panoptic": # We also evaluate AP during panoptic training, on original coco DS coco_val = datasets.coco.build("val", args) base_ds = get_coco_api_from_dataset(coco_val) else: base_ds = get_coco_api_from_dataset(dataset_val) if args.frozen_weights is not None: checkpoint = torch.load(args.frozen_weights, map_location='cpu') model_without_ddp.detr.load_state_dict(checkpoint['model']) output_dir = Path(args.output_dir) if args.resume: if args.resume.startswith('https'): checkpoint = torch.hub.load_state_dict_from_url( args.resume, map_location='cpu', check_hash=True) else: checkpoint = torch.load(args.resume, map_location='cpu') model_without_ddp.load_state_dict(checkpoint['model']) if not args.eval and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint: optimizer.load_state_dict(checkpoint['optimizer']) lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) args.start_epoch = checkpoint['epoch'] + 1 if args.eval: test_stats, coco_evaluator = evaluate(model, criterion, postprocessors, data_loader_val, base_ds, device, args.output_dir) if args.output_dir: utils.save_on_master(coco_evaluator.coco_eval["bbox"].eval, output_dir / "eval.pth") return print("Start training") start_time = time.time() model.accumulate = 100 for epoch in range(args.start_epoch, args.epochs): if args.distributed: sampler_train.set_epoch(epoch) model.step = epoch * args.batch_size train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, args.clip_max_norm) lr_scheduler.step() if args.output_dir: checkpoint_paths = [output_dir / 'checkpoint.pth'] # extra checkpoint before LR drop and every 100 epochs if (epoch + 1) % args.lr_drop == 0 or (epoch + 1) % 100 == 0: checkpoint_paths.append(output_dir / f'checkpoint{epoch:04}.pth') for checkpoint_path in checkpoint_paths: utils.save_on_master({ 'model': model_without_ddp.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict(), 'epoch': epoch, 'args': args, }, checkpoint_path) # test_stats, coco_evaluator = evaluate( # model, criterion, postprocessors, data_loader_val, base_ds, device, args.output_dir # ) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, # **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and utils.is_main_process(): with (output_dir / "log.txt").open("a") as f: f.write(json.dumps(log_stats) + "\n") # for evaluation logs # if coco_evaluator is not None: # (output_dir / 'eval').mkdir(exist_ok=True) # if "bbox" in coco_evaluator.coco_eval: # filenames = ['latest.pth'] # if epoch % 50 == 0: # filenames.append(f'{epoch:03}.pth') # for name in filenames: # torch.save(coco_evaluator.coco_eval["bbox"].eval, # output_dir / "eval" / name) total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) if __name__ == '__main__': parser = argparse.ArgumentParser('DETR training and evaluation script', parents=[get_args_parser()]) args = parser.parse_args() if args.output_dir: Path(args.output_dir).mkdir(parents=True, exist_ok=True) main(args)
[ "numpy.random.seed", "argparse.ArgumentParser", "torch.optim.lr_scheduler.StepLR", "torch.utils.data.RandomSampler", "torch.optim.AdamW", "json.dumps", "pathlib.Path", "torch.device", "util.misc.is_main_process", "os.path.join", "util.misc.init_distributed_mode", "datasets.coco.build", "torch.utils.data.DataLoader", "cv2.cvtColor", "torch.nn.parallel.DistributedDataParallel", "torch.load", "os.path.exists", "os.path.dirname", "numpy.max", "random.seed", "torch.utils.data.SequentialSampler", "models.build_model", "torch.as_tensor", "torch.hub.load_state_dict_from_url", "util.misc.get_rank", "engine.train_one_epoch", "torch.manual_seed", "util.misc.save_on_master", "numpy.min", "torch.utils.data.BatchSampler", "json.load", "time.time", "PIL.Image.open", "cv2.imread", "torch.utils.data.DistributedSampler", "engine.evaluate", "datasets.coco.make_coco_transforms", "numpy.array", "util.misc.get_sha", "torch.tensor", "logging.getLogger", "datasets.get_coco_api_from_dataset" ]
[((577, 604), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (594, 604), False, 'import logging\n'), ((6230, 6297), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Set transformer detector"""'], {'add_help': '(False)'}), "('Set transformer detector', add_help=False)\n", (6253, 6297), False, 'import argparse\n'), ((10994, 11027), 'util.misc.init_distributed_mode', 'utils.init_distributed_mode', (['args'], {}), '(args)\n', (11021, 11027), True, 'import util.misc as utils\n'), ((11225, 11250), 'torch.device', 'torch.device', (['args.device'], {}), '(args.device)\n', (11237, 11250), False, 'import torch\n'), ((11335, 11358), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (11352, 11358), False, 'import torch\n'), ((11363, 11383), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (11377, 11383), True, 'import numpy as np\n'), ((11388, 11405), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (11399, 11405), False, 'import random\n'), ((11446, 11463), 'models.build_model', 'build_model', (['args'], {}), '(args)\n', (11457, 11463), False, 'from models import build_model\n'), ((12128, 12202), 'torch.optim.AdamW', 'torch.optim.AdamW', (['param_dicts'], {'lr': 'args.lr', 'weight_decay': 'args.weight_decay'}), '(param_dicts, lr=args.lr, weight_decay=args.weight_decay)\n', (12145, 12202), False, 'import torch\n'), ((12256, 12312), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer', 'args.lr_drop'], {}), '(optimizer, args.lr_drop)\n', (12287, 12312), False, 'import torch\n'), ((13137, 13214), 'torch.utils.data.BatchSampler', 'torch.utils.data.BatchSampler', (['sampler_train', 'args.batch_size'], {'drop_last': '(True)'}), '(sampler_train, args.batch_size, drop_last=True)\n', (13166, 13214), False, 'import torch\n'), ((13249, 13373), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_train'], {'batch_sampler': 'batch_sampler_train', 'collate_fn': 'utils.collate_fn', 'num_workers': 'args.num_workers'}), '(dataset_train, batch_sampler=batch_sampler_train, collate_fn=\n utils.collate_fn, num_workers=args.num_workers)\n', (13259, 13373), False, 'from torch.utils.data import DataLoader, DistributedSampler\n'), ((13426, 13568), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_val', 'args.batch_size'], {'sampler': 'sampler_val', 'drop_last': '(False)', 'collate_fn': 'utils.collate_fn', 'num_workers': 'args.num_workers'}), '(dataset_val, args.batch_size, sampler=sampler_val, drop_last=\n False, collate_fn=utils.collate_fn, num_workers=args.num_workers)\n', (13436, 13568), False, 'from torch.utils.data import DataLoader, DistributedSampler\n'), ((14092, 14113), 'pathlib.Path', 'Path', (['args.output_dir'], {}), '(args.output_dir)\n', (14096, 14113), False, 'from pathlib import Path\n'), ((15135, 15146), 'time.time', 'time.time', ([], {}), '()\n', (15144, 15146), False, 'import time\n'), ((769, 809), 'os.path.join', 'os.path.join', (['image_root', "gt['img_name']"], {}), "(image_root, gt['img_name'])\n", (781, 809), False, 'import os\n'), ((2259, 2271), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2268, 2271), False, 'import json\n'), ((4023, 4045), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (4033, 4045), False, 'import cv2\n'), ((4062, 4100), 'cv2.cvtColor', 'cv2.cvtColor', (['cvimg', 'cv2.COLOR_BGR2RGB'], {}), '(cvimg, cv2.COLOR_BGR2RGB)\n', (4074, 4100), False, 'import cv2\n'), ((5138, 5160), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (5148, 5160), False, 'from PIL import Image\n'), ((5240, 5282), 'torch.tensor', 'torch.tensor', (['pimg.size'], {'dtype': 'torch.int64'}), '(pimg.size, dtype=torch.int64)\n', (5252, 5282), False, 'import torch\n'), ((5407, 5447), 'torch.tensor', 'torch.tensor', (['classes'], {'dtype': 'torch.int64'}), '(classes, dtype=torch.int64)\n', (5419, 5447), False, 'import torch\n'), ((5476, 5497), 'torch.tensor', 'torch.tensor', (['iscrowd'], {}), '(iscrowd)\n', (5488, 5497), False, 'import torch\n'), ((11314, 11330), 'util.misc.get_rank', 'utils.get_rank', ([], {}), '()\n', (11328, 11330), True, 'import util.misc as utils\n'), ((11557, 11628), 'torch.nn.parallel.DistributedDataParallel', 'torch.nn.parallel.DistributedDataParallel', (['model'], {'device_ids': '[args.gpu]'}), '(model, device_ids=[args.gpu])\n', (11598, 11628), False, 'import torch\n'), ((12857, 12890), 'torch.utils.data.DistributedSampler', 'DistributedSampler', (['dataset_train'], {}), '(dataset_train)\n', (12875, 12890), False, 'from torch.utils.data import DataLoader, DistributedSampler\n'), ((12913, 12959), 'torch.utils.data.DistributedSampler', 'DistributedSampler', (['dataset_val'], {'shuffle': '(False)'}), '(dataset_val, shuffle=False)\n', (12931, 12959), False, 'from torch.utils.data import DataLoader, DistributedSampler\n'), ((12994, 13039), 'torch.utils.data.RandomSampler', 'torch.utils.data.RandomSampler', (['dataset_train'], {}), '(dataset_train)\n', (13024, 13039), False, 'import torch\n'), ((13062, 13109), 'torch.utils.data.SequentialSampler', 'torch.utils.data.SequentialSampler', (['dataset_val'], {}), '(dataset_val)\n', (13096, 13109), False, 'import torch\n'), ((13738, 13770), 'datasets.coco.build', 'datasets.coco.build', (['"""val"""', 'args'], {}), "('val', args)\n", (13757, 13770), False, 'import datasets\n'), ((13789, 13824), 'datasets.get_coco_api_from_dataset', 'get_coco_api_from_dataset', (['coco_val'], {}), '(coco_val)\n', (13814, 13824), False, 'from datasets import get_coco_api_from_dataset\n'), ((13853, 13891), 'datasets.get_coco_api_from_dataset', 'get_coco_api_from_dataset', (['dataset_val'], {}), '(dataset_val)\n', (13878, 13891), False, 'from datasets import get_coco_api_from_dataset\n'), ((13954, 14005), 'torch.load', 'torch.load', (['args.frozen_weights'], {'map_location': '"""cpu"""'}), "(args.frozen_weights, map_location='cpu')\n", (13964, 14005), False, 'import torch\n'), ((14809, 14906), 'engine.evaluate', 'evaluate', (['model', 'criterion', 'postprocessors', 'data_loader_val', 'base_ds', 'device', 'args.output_dir'], {}), '(model, criterion, postprocessors, data_loader_val, base_ds, device,\n args.output_dir)\n', (14817, 14906), False, 'from engine import evaluate, train_one_epoch\n'), ((15368, 15470), 'engine.train_one_epoch', 'train_one_epoch', (['model', 'criterion', 'data_loader_train', 'optimizer', 'device', 'epoch', 'args.clip_max_norm'], {}), '(model, criterion, data_loader_train, optimizer, device,\n epoch, args.clip_max_norm)\n', (15383, 15470), False, 'from engine import evaluate, train_one_epoch\n'), ((17334, 17345), 'time.time', 'time.time', ([], {}), '()\n', (17343, 17345), False, 'import time\n'), ((825, 849), 'os.path.exists', 'os.path.exists', (['img_path'], {}), '(img_path)\n', (839, 849), False, 'import os\n'), ((3742, 3768), 'os.path.exists', 'os.path.exists', (['image_path'], {}), '(image_path)\n', (3756, 3768), False, 'import os\n'), ((4881, 4917), 'torch.tensor', 'torch.tensor', (['idx'], {'dtype': 'torch.int64'}), '(idx, dtype=torch.int64)\n', (4893, 4917), False, 'import torch\n'), ((4935, 4961), 'os.path.exists', 'os.path.exists', (['image_path'], {}), '(image_path)\n', (4949, 4961), False, 'import os\n'), ((11060, 11075), 'util.misc.get_sha', 'utils.get_sha', ([], {}), '()\n', (11073, 11075), True, 'import util.misc as utils\n'), ((12668, 12697), 'datasets.coco.make_coco_transforms', 'make_coco_transforms', (['"""train"""'], {}), "('train')\n", (12688, 12697), False, 'from datasets.coco import make_coco_transforms\n'), ((12778, 12805), 'datasets.coco.make_coco_transforms', 'make_coco_transforms', (['"""val"""'], {}), "('val')\n", (12798, 12805), False, 'from datasets.coco import make_coco_transforms\n'), ((14203, 14291), 'torch.hub.load_state_dict_from_url', 'torch.hub.load_state_dict_from_url', (['args.resume'], {'map_location': '"""cpu"""', 'check_hash': '(True)'}), "(args.resume, map_location='cpu',\n check_hash=True)\n", (14237, 14291), False, 'import torch\n'), ((14344, 14387), 'torch.load', 'torch.load', (['args.resume'], {'map_location': '"""cpu"""'}), "(args.resume, map_location='cpu')\n", (14354, 14387), False, 'import torch\n'), ((14989, 15077), 'util.misc.save_on_master', 'utils.save_on_master', (["coco_evaluator.coco_eval['bbox'].eval", "(output_dir / 'eval.pth')"], {}), "(coco_evaluator.coco_eval['bbox'].eval, output_dir /\n 'eval.pth')\n", (15009, 15077), True, 'import util.misc as utils\n'), ((16642, 16665), 'util.misc.is_main_process', 'utils.is_main_process', ([], {}), '()\n', (16663, 16665), True, 'import util.misc as utils\n'), ((2774, 2800), 'os.path.dirname', 'os.path.dirname', (['json_path'], {}), '(json_path)\n', (2789, 2800), False, 'import os\n'), ((5664, 5679), 'numpy.array', 'np.array', (['polys'], {}), '(polys)\n', (5672, 5679), True, 'import numpy as np\n'), ((5793, 5813), 'numpy.min', 'np.min', (['poly[..., 0]'], {}), '(poly[..., 0])\n', (5799, 5813), True, 'import numpy as np\n'), ((5835, 5855), 'numpy.min', 'np.min', (['poly[..., 1]'], {}), '(poly[..., 1])\n', (5841, 5855), True, 'import numpy as np\n'), ((5877, 5897), 'numpy.max', 'np.max', (['poly[..., 0]'], {}), '(poly[..., 0])\n', (5883, 5897), True, 'import numpy as np\n'), ((5919, 5939), 'numpy.max', 'np.max', (['poly[..., 1]'], {}), '(poly[..., 1])\n', (5925, 5939), True, 'import numpy as np\n'), ((17679, 17700), 'pathlib.Path', 'Path', (['args.output_dir'], {}), '(args.output_dir)\n', (17683, 17700), False, 'from pathlib import Path\n'), ((2003, 2021), 'numpy.array', 'np.array', (['polygons'], {}), '(polygons)\n', (2011, 2021), True, 'import numpy as np\n'), ((2497, 2515), 'os.path.dirname', 'os.path.dirname', (['p'], {}), '(p)\n', (2512, 2515), False, 'import os\n'), ((6016, 6060), 'torch.as_tensor', 'torch.as_tensor', (['bboxes'], {'dtype': 'torch.float32'}), '(bboxes, dtype=torch.float32)\n', (6031, 6060), False, 'import torch\n'), ((1265, 1296), 'numpy.array', 'np.array', (["annotation['polygon']"], {}), "(annotation['polygon'])\n", (1273, 1296), True, 'import numpy as np\n'), ((16749, 16770), 'json.dumps', 'json.dumps', (['log_stats'], {}), '(log_stats)\n', (16759, 16770), False, 'import json\n')]
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : DecisionTree.py @Author : <NAME> @Emial : <EMAIL> @Date : 2022/02/21 16:59 @Description : 决策树 """ import time import numpy as np def loadData(fileName): """ 加载文件 @Args: fileName: 加载的文件路径 @Returns: dataArr: 数据集 labelArr: 标签集 @Riase: """ # 存放数据和标记 dataArr = [] labelArr = [] # 读取文件 fr = open(fileName) # 遍历文件中的每一行 for line in fr.readlines(): curLine = line.strip().split(',') # 将数据进行了二值化处理 dataArr.append([int(int(num) > 128) for num in curLine[1:]]) # 标签 labelArr.append(int(curLine[0])) return dataArr, labelArr def majorClass(labelArr): """ 找到当前标签集中数目最多的标签 @Args: labelArr: 标签集 @Returns: 出现次数最多的标签 @Riase: """ # 存储不同类别标签数目 classDict = {} # 遍历所有标签 maxtimes = -1 maxClass = 0 for i in range(len(labelArr)): if labelArr[i] in classDict.keys(): classDict[labelArr[i]] += 1 else: classDict[labelArr[i]] = 1 # 只找出现次数最多的标签 if classDict[labelArr[i]] > maxtimes: maxtimes = classDict[labelArr[i]] maxClass = labelArr[i] # 降序排序 # classSort = sorted(classDict.items(), key=lambda x: x[1], reverse=True) # 返回出现次数最多的标签 return maxClass # return classSort[0][0] def calc_H_D(trainLabelArr): """ 计算数据集D的经验熵 @Args: trainLabelArr: 数据集的标签集 @Returns: H_D: 经验熵 @Riase: """ # 初始化H_D H_D = 0 # 使用集合处理trainLabelSet trainLabelSet = set([label for label in trainLabelArr]) # 遍历 for i in trainLabelSet: # 计算 |Ck|/|D| p = trainLabelArr[trainLabelArr == i].size / trainLabelArr.size # 经验熵累加求和 H_D += -1 * p * np.log2(p) return H_D def calcH_D_A(trainDataArr_DevFeature, trianLabelArr): """ 计算经验条件熵 @Args: trainDataArr_DevFeature: 切割后只有feature那列数据的数组 trianLabelArr: 标签集 @Returns: H_D_A: 经验条件熵 @Riase: """ # 初始化H_D_A H_D_A = 0 trainDataSet = set([label for label in trainDataArr_DevFeature]) # 遍历特征 for i in trainDataSet: # 计算H(D|A) H_D_A += trainDataArr_DevFeature[trainDataArr_DevFeature == i].size / trainDataArr_DevFeature.size \ * calc_H_D(trianLabelArr[trainDataArr_DevFeature == i]) return H_D_A def calcBestFeature(trainDataList, trainLabelList): """ 计算信息增益最大的特征 @Args: trainDataList: 数据集 trainLabelList: 数据集标签 @Returns: maxFeature: 信息增益最大的特征 maxG_D_A: 最大信息增益值 @Riase: """ trainDataArr = np.array(trainDataList) trainLabelArr = np.array(trainLabelList) # 获取特征数目 featureNum = trainDataArr.shape[1] # 初始化最大信息增益 maxG_D_A = -1 # 初始化最大信息增益的特征 maxFeature = -1 # 计算经验熵 H_D = calc_H_D(trainLabelArr) # 遍历每一个特征 for feature in range(featureNum): # 计算条件熵H(D|A) # 选取一列特征 trainDataArr_DevideByFeature = np.array(trainDataArr[:, feature].flat) # 计算信息增益G(D|A) G_D_A = H_D - calcH_D_A(trainDataArr_DevideByFeature, trainLabelArr) # 更新最大的信息增益以及对应的feature if G_D_A > maxG_D_A: maxG_D_A = G_D_A maxFeature = feature return maxFeature, maxG_D_A def getSubDataArr(trainDataArr, trainLabelArr, A, a): """ 更新数据集和标签集 @Args: trainDataArr: 要更新的数据集 trainLabelArr: 要更新的标签集 A: 要去除的特征索引 a: 当data[A]== a时,说明该行样本时要保留的 @Returns: retDataArr: 新的数据集 retLabelArr: 新的标签集 @Riase: """ retDataArr = [] retLabelArr = [] # 对当前数据的每一个样本进行遍历 for i in range(len(trainDataArr)): # 如果当前样本的特征为指定特征值a if trainDataArr[i][A] == a: # 那么将该样本的第A个特征切割掉,放入返回的数据集中 retDataArr.append(trainDataArr[i][0:A] + trainDataArr[i][A+1:]) #将该样本的标签放入返回标签集中 retLabelArr.append(trainLabelArr[i]) # 返回新的数据集和标签集 return retDataArr, retLabelArr def createTree(*dataSet): """ 递归创建决策树 @Args: dataSet: (trainDataList, trainLabelList) @Returns: treeDict: 树节点 @Riase: """ # 设置阈值Epsilon Epsilon = 0.1 trainDataList = dataSet[0][0] trainLabelList = dataSet[0][1] print("Start a node...", len(trainDataList[0]), len(trainLabelList)) classDict = {i for i in trainLabelList} # 数据集D中所有实例属于同一类 if len(classDict) == 1: return trainLabelList[0] # 如果A为空集,则置T为单节点数,并将D中实例数最大的类Ck作为该节点的类,返回T # 即如果已经没有特征可以用来再分化了,就返回占大多数的类别 if len(trainDataList[0]) == 0: return majorClass(trainLabelList) # 否则,选择信息增益最大的特征 Ag, EpsilonGet = calcBestFeature(trainDataList, trainLabelList) # 信息增益小于阈值Epsilon,置为单节点树 if EpsilonGet < Epsilon: return majorClass(trainLabelList) # 否则,对Ag的每一可能值ai,依Ag=ai将D分割为若干非空子集Di,将Di中实例数最大的 # 类作为标记,构建子节点,由节点及其子节点构成树T,返回T treeDict = {Ag:{}} # 特征值为0时,进入0分支 # getSubDataArr(trainDataList, trainLabelList, Ag, 0):在当前数据集中切割当前feature,返回新的数据集和标签集 treeDict[Ag][0] = createTree(getSubDataArr(trainDataList, trainLabelList, Ag, 0)) treeDict[Ag][1] = createTree(getSubDataArr(trainDataList, trainLabelList, Ag, 1)) return treeDict def predict(testDataList, tree): """ 预测标签 @Args: testDataList: 测试集 tree: 决策树 @Returns: 预测结果 @Riase: """ # 死循环,直到找到一个有效地分类 while True: # 因为有时候当前字典只有一个节点 # 例如{73: {0: {74:6}}}看起来节点很多,但是对于字典的最顶层来说,只有73一个key,其余都是value # 若还是采用for来读取的话不太合适,所以使用下行这种方式读取key和value (key, value), = tree.items() if type(tree[key]).__name__ == "dict": dataVal = testDataList[key] del testDataList[key] # 将tree更新为其子节点的字典 tree = value[dataVal] if type(tree).__name__ == "int": return tree else: return value def model_test(testDataList, testLabelList, tree): """ 测试准确率 @Args: testDataList: 测试数据集 testLabelList: 测试数据集标签 tree: 决策树 @Returns: 准确率 @Riase: """ # 错误判断次数 errorCnt = 0 #遍历测试集中每一个测试样本 for i in range(len(testDataList)): #判断预测与标签中结果是否一致 if testLabelList[i] != predict(testDataList[i], tree): errorCnt += 1 #返回准确率 return 1 - errorCnt / len(testDataList) if __name__ == '__main__': # 开始时间 start = time.time() # 获取训练集 print("Start read transSet......") trainDataList, trainLabelList = loadData('../data/mnist_train.csv') # 获取测试集 print("Start read testSet......") testDataList, testLabelList = loadData('../data/mnist_test.csv') # 创建决策树 print("Start create tree......") tree = createTree((trainDataList, trainLabelList)) print("tree is:", tree) # 测试准确率 print("Start test......") accur = model_test(testDataList, testLabelList, tree) print("The accur is:{}".format(accur)) # 结束时间 end = time.time() print("Time span: {}".format(end - start))
[ "numpy.log2", "numpy.array", "time.time" ]
[((2776, 2799), 'numpy.array', 'np.array', (['trainDataList'], {}), '(trainDataList)\n', (2784, 2799), True, 'import numpy as np\n'), ((2820, 2844), 'numpy.array', 'np.array', (['trainLabelList'], {}), '(trainLabelList)\n', (2828, 2844), True, 'import numpy as np\n'), ((6624, 6635), 'time.time', 'time.time', ([], {}), '()\n', (6633, 6635), False, 'import time\n'), ((7178, 7189), 'time.time', 'time.time', ([], {}), '()\n', (7187, 7189), False, 'import time\n'), ((3150, 3189), 'numpy.array', 'np.array', (['trainDataArr[:, feature].flat'], {}), '(trainDataArr[:, feature].flat)\n', (3158, 3189), True, 'import numpy as np\n'), ((1893, 1903), 'numpy.log2', 'np.log2', (['p'], {}), '(p)\n', (1900, 1903), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 1 20:33:32 2019 @authors: <NAME> (<EMAIL>) <NAME> (<EMAIL>) """ from collections import Counter from scipy import signal import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.use('TkAgg') class EmotionalSlice: """ This class performs the slicing of emotion and heart rate instances of the experiment participants. Besides, it generates synthetic data of the HR vector according to the size of the emotional slice. """ def __init__(self): """ Default constructor Returns ------- None. """ self.hr_plot_dir = 'miband/plot/' # Heart rate plot subdirectory self.hrData = {} # Heart rate dataset tagged with emotion class self.timeBetweenInstances = 60 # Time distance between instances (seconds) self.sliceSize = 30 # Slice size self.sliceLimit = 3 # Slice size limit #%% dataLoad def dataLoad(self): """ It loads the tagged dataset from a dictionary to a list. tagHrList: imei, hrTimestamp, emotionts, emotion, activity, hr, longitude, latitude, and altitude Returns ------- None. """ self.tagHrList = [] for k, v in self.hrData.items(): for k1, v1 in v.items(): if 'emotion' in v1: temp = [] for key, value in v1.items(): temp.append(value) self.tagHrList.append([int(temp[0]), int(k1), int(temp[1]), temp[2], temp[3], int(temp[4]), float(temp[5]), float(temp[6])]) #%% initSlice def initSlice(self): """ Init a slice """ self.start = int(self.previous[1]) # First time-stamp self.hr = [] # Heart rate list initialization self.ts = [] # Time-stamp list initialization self.emotions = [] # Emotion list initialization self.instancesCounter = 0 # Instances counter #%% hr_norm def hr_norm(self, hr_data): """ Normalize heart rate data Parameters ---------- hr_data : List DESCRIPTION. Heart rate data Returns ------- list DESCRIPTION. Normalized heart rate """ min_value = list(filter(lambda x: (x[0] == self.previous[0]), self.minmax))[0][1] max_value = list(filter(lambda x: (x[0] == self.previous[0]), self.minmax))[0][2] return ([(i - min_value) / (max_value - min_value) for i in hr_data]) #%% duplication_ts method def duplication_ts(self, hr_norm, sliceSize): """ Generates the duplication of time series values to adjust the number of HR instances according to the fixed size of the Emotional Slicing. Parameters ---------- hr_norm : list DESCRIPTION. Heart Rate list normalized sliceSize : int DESCRIPTION. Slice size Returns ------- hr : list DESCRIPTION. Heart Rate list with duplication of time series values """ hr = np.zeros(sliceSize) i = 0 flag = True while flag: if sliceSize - len(hr_norm) <= 0: segment = np.abs(sliceSize - len(hr_norm)) hr[i] = hr_norm[i:segment] # it Loses the initial segment of the signal data else: b = hr_norm[0 : sliceSize - len(hr_norm)] goal = np.hstack((hr_norm, b)) while len(goal) != sliceSize: b = hr_norm[0 : sliceSize - len(goal)] goal = np.hstack((goal, b)) hr = goal i += 1 flag = False return hr #%% closeSlice def closeSlice(self): """ It closes a slice conformed by instances of heart rate and timestamp with emotion, activity, and location data. Returns ------- None. """ if (self.instancesCounter > self.sliceLimit): sliceDuration = int(self.ts[self.instancesCounter - 1]) - int(self.ts[0]) emotionsCounter = Counter(self.emotions) hrCounter = Counter(self.hr) if len(hrCounter) > 1: self.predominantEmotion = max(zip( emotionsCounter.values(), # Emotion counting emotionsCounter.keys() # Emotion name )) if self.instancesCounter < self.sliceSize: self.ohr = self.hr self.ots = self.ts self.addSyntheticData() else: #self.slicePlot() # It plots an emotional slicing with a fixed size of HR instances. self.ohr = [] self.ots = [] self.labels.append([ self.current[0], # IMEI self.slicesCounter, # Slice consecutive self.catEmotion(), # Categorical emotion self.predominantEmotion[1], # Emotion name self.predominantEmotion[0] # Total instances with this emotion ]) self.hr_sliceSize_norm = self.hr_norm(self.hr) if len(self.hr) == self.sliceSize else [] self.ohr_norm = self.hr_norm(self.ohr) if self.ohr else [] quadrant = self.catVA() # 10 Valence and Arousal quadrant self.features.append([ self.previous[0], # 0 IMEI self.slicesCounter, # 1 Slice consecutive self.hr, # 2 Heart rate list self.instancesCounter, # 3 Instances number sliceDuration, # 4 Slice duration (seconds) self.previous[4], # 5 Activity name self.catActivity(), # 6 Categorical activity self.catEmotion(), # 7 Categorical emotion self.predominantEmotion[1], # 8 Emotion name self.predominantEmotion[0], # 9 Emotion instances total list(quadrant.keys())[0], # 10 Valence and Arousal quadrant number quadrant.get(list(quadrant.keys())[0]), # 11 Valence and Arousal quadrant self.ts, # 12 Heart Rate time-stamp int(self.previous[2]), # 13 Emotion time-stamp self.hr_sliceSize_norm, # 14 Normalized Heart rate y with the same lenght of slice size self.previous[6], # 15 longitude self.previous[7], # 16 latitude # 17 Assigns normalized HR with resampled HR time series values if the segment size limit is lower than the slice size. self.hr_sliceSize_norm if self.hr_sliceSize_norm else self.ohr_norm, # 18 Assigns normalized HR with duplicate time series values if the segment size limit is lower than the slice size. list(self.hr_sliceSize_norm if self.hr_sliceSize_norm else self.duplication_ts( self.hr_norm(self.hr), self.sliceSize)) ]) self.slicesCounter = self.slicesCounter + 1 self.initSlice() else: self.initSlice() else: self.initSlice() #%% addInstanceToSlice def addInstanceToSlice(self): """ Add data instances to a slice. Returns ------- None. """ self.ts.append(self.current[1]) self.hr.append(self.current[5]) self.emotions.append(self.current[3]) self.instancesCounter = self.instancesCounter + 1 if self.instancesCounter >= self.sliceSize: self.closeSlice() #%% buildSlices def buildSlices(self, slice_plot_dir, hrData, timeBetweenInstances, sliceSize, sliceLimit): """ Slice of emotions algorithm. Define the heart rate vectors with the emotional blocks and it balances the vector size with the resampling of the signal through the Fourier series. Parameters ---------- slice_plot_dir : String DESCRIPTION. Emotional slicing plot subdirectory hrData : dictionary DESCRIPTION. Heart rate dataset tagged with emotion class. timeBetweenInstances : int DESCRIPTION. Time distance between instances (seconds) sliceSize : int DESCRIPTION. Slice size sliceLimit : int DESCRIPTION. Slice size limit Returns ------- None. """ self.plotDir = slice_plot_dir self.hrData = hrData self.dataLoad() self.timeBetweenInstances = timeBetweenInstances # Time distance between instances (seconds), default = 120 self.features = [] # Fatures list self.labels = [] # Labels list self.sliceSize = sliceSize # Slice size, default = 20 self.sliceLimit = sliceLimit # Slice limit size, default = 2 self.slicesCounter = 0 self.previous = self.tagHrList[0] self.initSlice() self.current = self.previous # Save the first instance self.addInstanceToSlice() self.getMinMaxByImei() for row in range(1, len(self.tagHrList)): self.previous = self.tagHrList[row - 1] self.current = self.tagHrList[row] if self.previous[0] == self.current[0]: # Are the IMEIs the same? if int(self.current[1]) - int(self.previous[1]) <= self.timeBetweenInstances: # Is the instance in the same slice? if self.current[4].lower() == 'pelicula'.lower(): # Is the activity a movie? if self.previous[3] != self.current[3]: # Is the emotion the same? self.closeSlice() self.addInstanceToSlice() else: self.addInstanceToSlice() else: self.closeSlice() self.addInstanceToSlice() else: self.closeSlice() self.addInstanceToSlice() #%% getMinMaxByImei def getMinMaxByImei(self): """ Get the minimum and maximum heart rate values ​​of all participants. Returns ------- None. """ imeiList = list(set(map(lambda x:x[0], self.tagHrList))) newList = [[] for i in range(len(imeiList))] for imei, hrts, ets, e, a, hr, lo, la in self.tagHrList: newList[imeiList.index(imei)].append(hr) self.minmax = [] for i in range(len(newList)): self.minmax.append([imeiList[i], min(newList[i]), max(newList[i])]) #%% addSyntheticData def addSyntheticData(self): """ This method verifies slices of less than 30 instances and adds synthetic data with resampling of heart rate and timestamp. Resample ts to num samples using Fourier method. Returns ------- None. """ x = np.asarray(self.ots) y = np.asarray(self.ohr) f1 = signal.resample(y, self.sliceSize) f = [int(round(i)) for i in f1] max_x = len(x) - 1 xnew1 = np.linspace(x[0], x[max_x], self.sliceSize, endpoint = True) xnew = [int(i) for i in xnew1] self.ots = xnew self.ohr = f #self.resampledSlicePlot(x, y, f, xnew, max_x) # It plots a adjusted slice #%% resampledSlicePlot def resampledSlicePlot(self, x, y, f, xnew, max_x): """ This method generates the resampled heart rate and emotion slice plot. Parameters ---------- x : array DESCRIPTION. Timestamp y : array DESCRIPTION. Heart rate f : array DESCRIPTION. Heart rate resampled using Fourier method xnew : array DESCRIPTION. timestamp resampled max_x : int DESCRIPTION. Maximum timestamp Returns ------- None. """ plt.figure(figsize = (18, 8)) plt.xticks(fontsize = 20) plt.yticks(fontsize = 20) plt.plot(x, y, 'go-', xnew, f, '.-', x[max_x], y[0], 'ro') text = 'Slice of ' + str(self.sliceSize)+' HR instances of participant ' + str(self.previous[0]) +' labeled "'+ self.predominantEmotion[1] + '"' plt.title(text, fontsize = 22) plt.xlabel('Time series', fontsize = 20) plt.ylabel('Heart rate', fontsize = 20) plt.legend(['data', 'Fourier method resampled'], loc='best', prop={'size': 22}) plt.savefig(self.plotDir + 'hr_resampled_'+ str(self.slicesCounter) + '_' + str(self.previous[0]) + '.svg') plt.close() #%% slicePlot def slicePlot(self): """ This method plots an Emotional Slicing with a fixed size of HR instances. Returns ------- None. """ x = [int(i) for i in self.ts] y = [int(round(i)) for i in self.hr] plt.figure(figsize=(18,8)) plt.xticks(fontsize = 20) plt.yticks(fontsize = 20) text = 'Slice of ' + str(self.sliceSize)+' HR instances of participant ' + str(self.previous[0]) +' labeled "'+ self.predominantEmotion[1] + '"' plt.title(text, fontsize = 18) plt.xlabel('Time series', fontsize = 20) plt.ylabel('Heart rate', fontsize = 20) plt.plot(x, y) plt.savefig(self.plotDir + 'hr_'+ str(self.slicesCounter) + '_' + str(self.previous[0]) + '.svg') plt.close() #%% Categorical imei def catEmotion(self): """ Convert nominal emotion to categorical emotion. Returns ------- catEmotion : int DESCRIPTION. Categorical emotion """ emotionID = { 'feliz': 0, 'divertido': 1, 'alegre': 2, 'contento': 3, 'satisfecho': 4, 'calmado': 5, 'relajado': 6, 'cansado': 7, 'aburrido':8, 'deprimido':9, 'avergonzado':10, 'triste':11, 'estresado':12, 'asustado':13, 'enojado':14, 'en pánico':15, 'neutral':16 } return (emotionID.get(self.predominantEmotion[1])) #%% Categorical Valence and Arousal quadrant def catVA(self): """ It groups emotions by arousal and valence quadrant. Returns ------- quadrant : int DESCRIPTION. Categorical quadrant """ quadrant = {} emotion = self.catEmotion() if emotion >= 0 and emotion <= 3: quadrant = {0: 'HVHA'} elif emotion >= 4 and emotion <= 7: quadrant = {1: 'HVLA'} elif emotion >= 8 and emotion <= 11: quadrant = {2: 'LVLA'} elif emotion >= 12 and emotion <= 15: quadrant = {3: 'LVHA'} else: quadrant = {4: 'Neutral'} return (quadrant) #%% Categorical activity def catActivity(self): """ Convert nominal activity to categorical activity. Returns ------- catActivity : int DESCRIPTION. Categorical activity """ activityID = { 'trabajar': 0, 'estudiar': 1, 'leer': 2, 'ejercitar': 3, 'conducir': 4, 'cita': 5, 'descansar': 6, 'comprar': 7, 'amigos':8, 'festejar':9, 'alimentar':10, 'pelicula':11, 'limpiar':12, 'viajar':13, 'jugar':14, 'dormir':15, 'asearse':16, 'caminar': 17, 'esperar': 18, 'casa': 19, 'cuidarse': 20 } return (activityID.get(self.previous[4]))
[ "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "scipy.signal.resample", "matplotlib.pyplot.close", "numpy.asarray", "matplotlib.pyplot.yticks", "numpy.zeros", "matplotlib.pyplot.legend", "collections.Counter", "numpy.hstack", "matplotlib.pyplot.figure", "matplotlib.use", "numpy.linspace", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.xlabel" ]
[((272, 295), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (286, 295), False, 'import matplotlib\n'), ((3573, 3592), 'numpy.zeros', 'np.zeros', (['sliceSize'], {}), '(sliceSize)\n', (3581, 3592), True, 'import numpy as np\n'), ((12613, 12633), 'numpy.asarray', 'np.asarray', (['self.ots'], {}), '(self.ots)\n', (12623, 12633), True, 'import numpy as np\n'), ((12646, 12666), 'numpy.asarray', 'np.asarray', (['self.ohr'], {}), '(self.ohr)\n', (12656, 12666), True, 'import numpy as np\n'), ((12680, 12714), 'scipy.signal.resample', 'signal.resample', (['y', 'self.sliceSize'], {}), '(y, self.sliceSize)\n', (12695, 12714), False, 'from scipy import signal\n'), ((12798, 12856), 'numpy.linspace', 'np.linspace', (['x[0]', 'x[max_x]', 'self.sliceSize'], {'endpoint': '(True)'}), '(x[0], x[max_x], self.sliceSize, endpoint=True)\n', (12809, 12856), True, 'import numpy as np\n'), ((13652, 13679), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 8)'}), '(figsize=(18, 8))\n', (13662, 13679), True, 'import matplotlib.pyplot as plt\n'), ((13690, 13713), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(20)'}), '(fontsize=20)\n', (13700, 13713), True, 'import matplotlib.pyplot as plt\n'), ((13724, 13747), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(20)'}), '(fontsize=20)\n', (13734, 13747), True, 'import matplotlib.pyplot as plt\n'), ((13758, 13816), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""go-"""', 'xnew', 'f', '""".-"""', 'x[max_x]', 'y[0]', '"""ro"""'], {}), "(x, y, 'go-', xnew, f, '.-', x[max_x], y[0], 'ro')\n", (13766, 13816), True, 'import matplotlib.pyplot as plt\n'), ((13978, 14006), 'matplotlib.pyplot.title', 'plt.title', (['text'], {'fontsize': '(22)'}), '(text, fontsize=22)\n', (13987, 14006), True, 'import matplotlib.pyplot as plt\n'), ((14017, 14055), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time series"""'], {'fontsize': '(20)'}), "('Time series', fontsize=20)\n", (14027, 14055), True, 'import matplotlib.pyplot as plt\n'), ((14066, 14103), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Heart rate"""'], {'fontsize': '(20)'}), "('Heart rate', fontsize=20)\n", (14076, 14103), True, 'import matplotlib.pyplot as plt\n'), ((14114, 14193), 'matplotlib.pyplot.legend', 'plt.legend', (["['data', 'Fourier method resampled']"], {'loc': '"""best"""', 'prop': "{'size': 22}"}), "(['data', 'Fourier method resampled'], loc='best', prop={'size': 22})\n", (14124, 14193), True, 'import matplotlib.pyplot as plt\n'), ((14318, 14329), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (14327, 14329), True, 'import matplotlib.pyplot as plt\n'), ((14622, 14649), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 8)'}), '(figsize=(18, 8))\n', (14632, 14649), True, 'import matplotlib.pyplot as plt\n'), ((14657, 14680), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(20)'}), '(fontsize=20)\n', (14667, 14680), True, 'import matplotlib.pyplot as plt\n'), ((14691, 14714), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(20)'}), '(fontsize=20)\n', (14701, 14714), True, 'import matplotlib.pyplot as plt\n'), ((14878, 14906), 'matplotlib.pyplot.title', 'plt.title', (['text'], {'fontsize': '(18)'}), '(text, fontsize=18)\n', (14887, 14906), True, 'import matplotlib.pyplot as plt\n'), ((14917, 14955), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time series"""'], {'fontsize': '(20)'}), "('Time series', fontsize=20)\n", (14927, 14955), True, 'import matplotlib.pyplot as plt\n'), ((14966, 15003), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Heart rate"""'], {'fontsize': '(20)'}), "('Heart rate', fontsize=20)\n", (14976, 15003), True, 'import matplotlib.pyplot as plt\n'), ((15014, 15028), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (15022, 15028), True, 'import matplotlib.pyplot as plt\n'), ((15143, 15154), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (15152, 15154), True, 'import matplotlib.pyplot as plt\n'), ((4673, 4695), 'collections.Counter', 'Counter', (['self.emotions'], {}), '(self.emotions)\n', (4680, 4695), False, 'from collections import Counter\n'), ((4720, 4736), 'collections.Counter', 'Counter', (['self.hr'], {}), '(self.hr)\n', (4727, 4736), False, 'from collections import Counter\n'), ((3961, 3984), 'numpy.hstack', 'np.hstack', (['(hr_norm, b)'], {}), '((hr_norm, b))\n', (3970, 3984), True, 'import numpy as np\n'), ((4117, 4137), 'numpy.hstack', 'np.hstack', (['(goal, b)'], {}), '((goal, b))\n', (4126, 4137), True, 'import numpy as np\n')]
import pytest import numpy from pyckmeans.knee import KneeLocator @pytest.mark.parametrize('direction', ['increasing', 'decreasing']) @pytest.mark.parametrize('curve', ['convex', 'concave']) def test_simple(direction, curve): x = numpy.array([1.0, 2.0, 3.0 ,4.0, 5.0, 6.0, 7.0, 8.0, 9.0 ]) y = numpy.array([1.0, 2.2, 3.4, 4.5, 7.0, 10.0, 15.0, 22.0, 30.0]) kl_0 = KneeLocator(x, y, curve=curve, direction=direction, interp_method='interp1d') print('kl_0.knee:', kl_0.knee) print('kl_0.elbow:', kl_0.elbow) print('kl_0.norm_elbow:', kl_0.norm_elbow) print('kl_0.elbow_y:', kl_0.elbow_y) print('kl_0.norm_elbow_y:', kl_0.norm_elbow_y) print('kl_0.all_elbows:', kl_0.all_elbows) print('kl_0.all_norm_elbows:', kl_0.all_norm_elbows) print('kl_0.all_elbows_y:', kl_0.all_elbows_y) print('kl_0.all_norm_elbows_y:', kl_0.all_norm_elbows_y) kl_1 = KneeLocator(x, y, curve=curve, direction=direction, interp_method='polynomial') with pytest.raises(ValueError): KneeLocator(x, y, curve=curve, direction=direction, interp_method='XYZ')
[ "pytest.mark.parametrize", "pytest.raises", "pyckmeans.knee.KneeLocator", "numpy.array" ]
[((69, 135), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""direction"""', "['increasing', 'decreasing']"], {}), "('direction', ['increasing', 'decreasing'])\n", (92, 135), False, 'import pytest\n'), ((137, 192), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""curve"""', "['convex', 'concave']"], {}), "('curve', ['convex', 'concave'])\n", (160, 192), False, 'import pytest\n'), ((236, 294), 'numpy.array', 'numpy.array', (['[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]'], {}), '([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])\n', (247, 294), False, 'import numpy\n'), ((307, 369), 'numpy.array', 'numpy.array', (['[1.0, 2.2, 3.4, 4.5, 7.0, 10.0, 15.0, 22.0, 30.0]'], {}), '([1.0, 2.2, 3.4, 4.5, 7.0, 10.0, 15.0, 22.0, 30.0])\n', (318, 369), False, 'import numpy\n'), ((382, 459), 'pyckmeans.knee.KneeLocator', 'KneeLocator', (['x', 'y'], {'curve': 'curve', 'direction': 'direction', 'interp_method': '"""interp1d"""'}), "(x, y, curve=curve, direction=direction, interp_method='interp1d')\n", (393, 459), False, 'from pyckmeans.knee import KneeLocator\n'), ((899, 978), 'pyckmeans.knee.KneeLocator', 'KneeLocator', (['x', 'y'], {'curve': 'curve', 'direction': 'direction', 'interp_method': '"""polynomial"""'}), "(x, y, curve=curve, direction=direction, interp_method='polynomial')\n", (910, 978), False, 'from pyckmeans.knee import KneeLocator\n'), ((989, 1014), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1002, 1014), False, 'import pytest\n'), ((1024, 1096), 'pyckmeans.knee.KneeLocator', 'KneeLocator', (['x', 'y'], {'curve': 'curve', 'direction': 'direction', 'interp_method': '"""XYZ"""'}), "(x, y, curve=curve, direction=direction, interp_method='XYZ')\n", (1035, 1096), False, 'from pyckmeans.knee import KneeLocator\n')]
# evaluate_hypotheses.py # This script evaluates our preregistered hypotheses using # the doctopics file produced by MALLET. # This version of evaluate_hypotheses is redesigned to permit # being called repeatedly as a function from measure_variation. import sys, csv import numpy as np from scipy.spatial.distance import cosine from collections import Counter def getdoc(anid): ''' Gets the docid part of a character id ''' if '|' in anid: thedoc = anid.split('|')[0] elif '_' in anid: thedoc = anid.split('|')[0] else: print('error', anid) thedoc = anid return thedoc def understand_why(selfcomp, social, structural, hypidx, whethercorrect): ''' We know whether the model got this hypothesis wrong or right. Now, using the hypothesis-index (just its number in the list of hypotheses), we want to assign credit or blame to the relevant class of hypotheses. ''' hypidx = int(hypidx) if hypidx <= 6: selfcomp[whethercorrect] += 1 if hypidx >= 7 and hypidx <= 46: structural[whethercorrect] += 1 elif hypidx >= 47 and hypidx <= 56: social[whethercorrect] += 1 elif hypidx >= 57 and hypidx <= 73: structural[whethercorrect] += 1 elif hypidx >= 74 and hypidx <= 84: social[whethercorrect] += 1 elif hypidx == 85 or hypidx == 86: structural[whethercorrect] += 1 elif hypidx >= 87 and hypidx <= 92: social[whethercorrect] += 1 elif hypidx >= 93: selfcomp[whethercorrect] += 1 def evaluate_a_model(doctopic_path): hypotheses = [] significant_persons = set() with open('../../evaluation/hypotheses.tsv', encoding = 'utf-8') as f: reader = csv.DictReader(f, delimiter = '\t') for row in reader: ids = [row['firstsim'], row['secondsim'], row['distractor']] for anid in ids: if '_' in anid: anid = anid.replace('_', '|') significant_persons.add(anid) hypotheses.append(row) numtopics = 0 chardict = dict() with open(doctopic_path, encoding = 'utf-8') as f: for line in f: fields = line.strip().split('\t') charid = fields[1] if charid not in significant_persons: continue else: vector = np.array(fields[2 : ], dtype = 'float32') veclen = len(vector) if numtopics == 0: numtopics = veclen elif numtopics != veclen: print('error: should not change once set') chardict[charid] = vector right = 0 wrong = 0 answers = [] social = Counter() structural = Counter() selfcomp = Counter() for idx, h in enumerate(hypotheses): skip = False ids = [h['firstsim'], h['secondsim'], h['distractor']] first = chardict[h['firstsim']] second = chardict[h['secondsim']] distract = chardict[h['distractor']] hypothesisnum = h['hypothesisnum'] pair_cos = cosine(first, second) # first comparison distraction1cos = cosine(first, distract) if distraction1cos < pair_cos: wrong += 1 understand_why(selfcomp, social, structural, hypothesisnum, 'wrong') elif distraction1cos == pair_cos: print('error') else: right += 1 understand_why(selfcomp, social, structural, hypothesisnum, 'right') # second comparison distraction2cos = cosine(second, distract) if distraction2cos < pair_cos: wrong += 1 understand_why(selfcomp, social, structural, hypothesisnum, 'wrong') elif distraction2cos == pair_cos: print('error') else: right += 1 understand_why(selfcomp, social, structural, hypothesisnum, 'right') print('Cosine: ', right / (wrong + right)) total = right / (wrong + right) selftotal = selfcomp['right'] / (selfcomp['wrong'] + selfcomp['right']) soctotal = social['right'] / (social['wrong'] + social['right']) structotal = structural['right'] / (structural['wrong'] + structural['right']) return total, selftotal, soctotal, structotal
[ "csv.DictReader", "collections.Counter", "scipy.spatial.distance.cosine", "numpy.array" ]
[((2758, 2767), 'collections.Counter', 'Counter', ([], {}), '()\n', (2765, 2767), False, 'from collections import Counter\n'), ((2785, 2794), 'collections.Counter', 'Counter', ([], {}), '()\n', (2792, 2794), False, 'from collections import Counter\n'), ((2810, 2819), 'collections.Counter', 'Counter', ([], {}), '()\n', (2817, 2819), False, 'from collections import Counter\n'), ((1756, 1789), 'csv.DictReader', 'csv.DictReader', (['f'], {'delimiter': '"""\t"""'}), "(f, delimiter='\\t')\n", (1770, 1789), False, 'import sys, csv\n'), ((3138, 3159), 'scipy.spatial.distance.cosine', 'cosine', (['first', 'second'], {}), '(first, second)\n', (3144, 3159), False, 'from scipy.spatial.distance import cosine\n'), ((3215, 3238), 'scipy.spatial.distance.cosine', 'cosine', (['first', 'distract'], {}), '(first, distract)\n', (3221, 3238), False, 'from scipy.spatial.distance import cosine\n'), ((3628, 3652), 'scipy.spatial.distance.cosine', 'cosine', (['second', 'distract'], {}), '(second, distract)\n', (3634, 3652), False, 'from scipy.spatial.distance import cosine\n'), ((2399, 2436), 'numpy.array', 'np.array', (['fields[2:]'], {'dtype': '"""float32"""'}), "(fields[2:], dtype='float32')\n", (2407, 2436), True, 'import numpy as np\n')]
# 数据处理部分之前的代码,加入部分数据处理的库 import gzip import json import os import random import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import paddle.fluid as fluid import pandas as pd from PIL import Image from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear def load_data(mode='train'): datafile = 'work/mnist.json.gz' print('loading mnist dataset from {} ......'.format(datafile)) # 加载json数据文件 data = json.load(gzip.open(datafile)) print('mnist dataset load done') # 读取到的数据区分训练集,验证集,测试集 train_set, val_set, eval_set = data if mode == 'train': # 获得训练数据集 imgs, labels = train_set[0], train_set[1] elif mode == 'valid': # 获得验证数据集 imgs, labels = val_set[0], val_set[1] elif mode == 'eval': # 获得测试数据集 imgs, labels = eval_set[0], eval_set[1] else: raise Exception("mode can only be one of ['train', 'valid', 'eval']") print("{}-数据集数量: {}".format(mode, len(imgs))) # 校验数据 imgs_length = len(imgs) # 校验数据 assert len(imgs) == len(labels), \ "length of train_imgs({}) should be the same as train_labels({})".format(len(imgs), len(labels)) # 获得数据集长度 imgs_length = len(imgs) # 定义数据集每个数据的序号,根据序号读取数据 index_list = list(range(imgs_length)) # 读入数据时用到的批次大小 BATCHSIZE = 100 IMG_ROWS = 28 IMG_COLS = 28 # 定义数据生成器 def data_generator(): if mode == 'train': # 训练模式下打乱数据 random.shuffle(index_list) imgs_list = [] labels_list = [] for i in index_list: # 将数据处理成希望的格式,比如类型为float32,shape为[1, 28, 28] img = np.reshape(imgs[i], [1, IMG_ROWS, IMG_COLS]).astype('float32') label = np.reshape(labels[i], [1]).astype('int64') imgs_list.append(img) labels_list.append(label) if len(imgs_list) == BATCHSIZE: # 获得一个batchsize的数据,并返回 yield np.array(imgs_list), np.array(labels_list) # 清空数据读取列表 imgs_list = [] labels_list = [] # 如果剩余数据的数目小于BATCHSIZE, # 则剩余数据一起构成一个大小为len(imgs_list)的mini-batch if len(imgs_list) > 0: yield np.array(imgs_list), np.array(labels_list) return data_generator # 数据处理部分之后的代码,数据读取的部分调用Load_data函数 # 定义网络结构,同上一节所使用的网络结构 # 多层卷积神经网络实现 class MNIST(fluid.dygraph.Layer): def __init__(self, name_scope): super(MNIST, self).__init__(name_scope) # 定义卷积层,输出特征通道num_filters设置为20,卷积核的大小filter_size为5,卷积步长stride=1,padding=2 # 激活函数使用relu self.conv1 = Conv2D(num_channels=1, num_filters=20, filter_size=5, stride=1, padding=2, act='relu') # 定义池化层,池化核pool_size=2,池化步长为2,选择最大池化方式 self.pool1 = Pool2D(pool_size=2, pool_stride=2, pool_type='max') # 定义卷积层,输出特征通道num_filters设置为20,卷积核的大小filter_size为5,卷积步长stride=1,padding=2 self.conv2 = Conv2D(num_channels=20, num_filters=20, filter_size=5, stride=1, padding=2, act='relu') # 定义池化层,池化核pool_size=2,池化步长为2,选择最大池化方式 self.pool2 = Pool2D(pool_size=2, pool_stride=2, pool_type='max') # 定义一层全连接层,输出维度是1,不使用激活函数 self.fc = Linear(input_dim=980, output_dim=10, act="softmax") # 定义网络前向计算过程,卷积后紧接着使用池化层,最后使用全连接层计算最终输出 def forward(self, inputs, label=None): x = self.conv1(inputs) x = self.pool1(x) x = self.conv2(x) x = self.pool2(x) x = fluid.layers.reshape(x, [x.shape[0], -1]) x = self.fc(x) # 如果label不是None,则计算分类精度并返回 if label is not None: # print(label) acc = fluid.layers.accuracy(input=x, label=label) return x, acc else: return x def trian_model(): # 训练配置,并启动训练过程 with fluid.dygraph.guard(): model = MNIST("mnist") model.train() # 调用加载数据的函数 train_loader = load_data('train') # 创建异步数据读取器 place = fluid.CPUPlace() data_loader = fluid.io.DataLoader.from_generator(capacity=5, return_list=True) data_loader.set_batch_generator(train_loader, places=place) optimizer = fluid.optimizer.SGDOptimizer(learning_rate=0.001, parameter_list=model.parameters()) EPOCH_NUM = 10 iter = 0 iters = [] losses = [] accs = [] for epoch_id in range(EPOCH_NUM): for batch_id, data in enumerate(data_loader): # 准备数据,变得更加简洁 image_data, label_data = data image = fluid.dygraph.to_variable(image_data) label = fluid.dygraph.to_variable(label_data) # 前向计算的过程 predict, acc = model(image, label) # 计算损失,取一个批次样本损失的平均值 # loss = fluid.layers.square_error_cost(predict, label) # 损失函数改为交叉熵 loss = fluid.layers.cross_entropy(predict, label) avg_loss = fluid.layers.mean(loss) # 每训练了200批次的数据,打印下当前Loss的情况 if batch_id % 200 == 0: print("epoch: {}, batch: {}, loss is: {}, acc is {}".format(epoch_id, batch_id, avg_loss.numpy(), acc.numpy())) iters.append(iter) losses.append(avg_loss.numpy()) accs.append(acc.numpy()) iter = iter + 100 # show_trianning(iters, accs) # 后向传播,更新参数的过程 avg_loss.backward() optimizer.minimize(avg_loss) model.clear_gradients() show_trianning(iters, losses) show_trianning(iters, accs) # 保存模型参数 fluid.save_dygraph(model.state_dict(), 'mnist') def show_trianning(iters, losses): # 画出训练过程中Loss的变化曲线 plt.figure() plt.title("trainning", fontsize=24) plt.xlabel("iter", fontsize=14) plt.ylabel("trainning", fontsize=14) plt.plot(iters, losses, color='red', label='train loss') plt.grid() plt.show() # 读取一张本地的样例图片,转变成模型输入的格式 def load_image(img_path): # 从img_path中读取图像,并转为灰度图 im = Image.open(img_path).convert('L') # im.show() im = im.resize((28, 28), Image.ANTIALIAS) im = np.array(im).reshape(1, 1, 28, 28).astype(np.float32) # 图像归一化 im = 1.0 - im / 255. return im def eval_model(): # 定义预测过程 with fluid.dygraph.guard(): model = MNIST("mnist") params_file_path = 'mnist' img_path = r'work/example_0.png' # 加载模型参数 model_dict, _ = fluid.load_dygraph("mnist") model.load_dict(model_dict) model.eval() tensor_img = load_image(img_path) # 模型反馈10个分类标签的对应概率 results = model(fluid.dygraph.to_variable(tensor_img)) # 取概率最大的标签作为预测输出 lab = np.argsort(results.numpy()) print(lab) print("本次预测的数字是: ", lab[0][-1]) def show_test_img(): example = mpimg.imread('work/example_0.png') # 显示图像 plt.imshow(example) plt.show() def test_model(): with fluid.dygraph.guard(): print('start evaluation .......') # 加载模型参数 model = MNIST("mnist") model_state_dict, _ = fluid.load_dygraph('mnist') model.load_dict(model_state_dict) model.eval() eval_loader = load_data('eval') acc_set = [] avg_loss_set = [] for batch_id, data in enumerate(eval_loader()): x_data, y_data = data img = fluid.dygraph.to_variable(x_data) label = fluid.dygraph.to_variable(y_data) prediction, acc = model(img, label) loss = fluid.layers.cross_entropy(input=prediction, label=label) avg_loss = fluid.layers.mean(loss) acc_set.append(float(acc.numpy())) avg_loss_set.append(float(avg_loss.numpy())) # 计算多个batch的平均损失和准确率 acc_val_mean = np.array(acc_set).mean() avg_loss_val_mean = np.array(avg_loss_set).mean() print('loss={}, acc={}'.format(avg_loss_val_mean, acc_val_mean)) record_result(avg_loss_val_mean, acc_val_mean) def record_result(avg_loss_val_mean, acc_val_mean): result_path = r'results.csv' if not os.path.exists(result_path): result = pd.DataFrame(columns=('loss', 'acc')) row = {'loss': avg_loss_val_mean, 'acc': acc_val_mean} result = result.append(row, ignore_index=True) result.to_csv('results.csv', index=True) else: result = pd.read_csv(result_path, index_col=[0]) row = {'loss': avg_loss_val_mean, 'acc': acc_val_mean} result = result.append(row, ignore_index=True) os.remove(result_path) result.to_csv('results.csv', index=True) print("record done") if __name__ == '__main__': # load_data() # trian_model() # show_test_img() # eval_model() # test_model() for i in range(2): trian_model() # eval_model() test_model()
[ "matplotlib.pyplot.title", "os.remove", "pandas.read_csv", "random.shuffle", "matplotlib.pyplot.figure", "paddle.fluid.io.DataLoader.from_generator", "paddle.fluid.dygraph.nn.Linear", "paddle.fluid.layers.mean", "pandas.DataFrame", "matplotlib.pyplot.imshow", "os.path.exists", "paddle.fluid.dygraph.guard", "numpy.reshape", "paddle.fluid.layers.cross_entropy", "matplotlib.image.imread", "matplotlib.pyplot.show", "paddle.fluid.layers.reshape", "paddle.fluid.dygraph.nn.Pool2D", "paddle.fluid.dygraph.to_variable", "paddle.fluid.CPUPlace", "paddle.fluid.dygraph.nn.Conv2D", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.grid", "paddle.fluid.layers.accuracy", "gzip.open", "matplotlib.pyplot.plot", "PIL.Image.open", "numpy.array", "paddle.fluid.load_dygraph", "matplotlib.pyplot.xlabel" ]
[((4923, 4935), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4933, 4935), True, 'import matplotlib.pyplot as plt\n'), ((4937, 4972), 'matplotlib.pyplot.title', 'plt.title', (['"""trainning"""'], {'fontsize': '(24)'}), "('trainning', fontsize=24)\n", (4946, 4972), True, 'import matplotlib.pyplot as plt\n'), ((4974, 5005), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iter"""'], {'fontsize': '(14)'}), "('iter', fontsize=14)\n", (4984, 5005), True, 'import matplotlib.pyplot as plt\n'), ((5007, 5043), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""trainning"""'], {'fontsize': '(14)'}), "('trainning', fontsize=14)\n", (5017, 5043), True, 'import matplotlib.pyplot as plt\n'), ((5045, 5101), 'matplotlib.pyplot.plot', 'plt.plot', (['iters', 'losses'], {'color': '"""red"""', 'label': '"""train loss"""'}), "(iters, losses, color='red', label='train loss')\n", (5053, 5101), True, 'import matplotlib.pyplot as plt\n'), ((5103, 5113), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (5111, 5113), True, 'import matplotlib.pyplot as plt\n'), ((5115, 5125), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5123, 5125), True, 'import matplotlib.pyplot as plt\n'), ((5903, 5937), 'matplotlib.image.imread', 'mpimg.imread', (['"""work/example_0.png"""'], {}), "('work/example_0.png')\n", (5915, 5937), True, 'import matplotlib.image as mpimg\n'), ((5947, 5966), 'matplotlib.pyplot.imshow', 'plt.imshow', (['example'], {}), '(example)\n', (5957, 5966), True, 'import matplotlib.pyplot as plt\n'), ((5968, 5978), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5976, 5978), True, 'import matplotlib.pyplot as plt\n'), ((448, 467), 'gzip.open', 'gzip.open', (['datafile'], {}), '(datafile)\n', (457, 467), False, 'import gzip\n'), ((2282, 2372), 'paddle.fluid.dygraph.nn.Conv2D', 'Conv2D', ([], {'num_channels': '(1)', 'num_filters': '(20)', 'filter_size': '(5)', 'stride': '(1)', 'padding': '(2)', 'act': '"""relu"""'}), "(num_channels=1, num_filters=20, filter_size=5, stride=1, padding=2,\n act='relu')\n", (2288, 2372), False, 'from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear\n'), ((2425, 2476), 'paddle.fluid.dygraph.nn.Pool2D', 'Pool2D', ([], {'pool_size': '(2)', 'pool_stride': '(2)', 'pool_type': '"""max"""'}), "(pool_size=2, pool_stride=2, pool_type='max')\n", (2431, 2476), False, 'from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear\n'), ((2568, 2659), 'paddle.fluid.dygraph.nn.Conv2D', 'Conv2D', ([], {'num_channels': '(20)', 'num_filters': '(20)', 'filter_size': '(5)', 'stride': '(1)', 'padding': '(2)', 'act': '"""relu"""'}), "(num_channels=20, num_filters=20, filter_size=5, stride=1, padding=2,\n act='relu')\n", (2574, 2659), False, 'from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear\n'), ((2712, 2763), 'paddle.fluid.dygraph.nn.Pool2D', 'Pool2D', ([], {'pool_size': '(2)', 'pool_stride': '(2)', 'pool_type': '"""max"""'}), "(pool_size=2, pool_stride=2, pool_type='max')\n", (2718, 2763), False, 'from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear\n'), ((2804, 2855), 'paddle.fluid.dygraph.nn.Linear', 'Linear', ([], {'input_dim': '(980)', 'output_dim': '(10)', 'act': '"""softmax"""'}), "(input_dim=980, output_dim=10, act='softmax')\n", (2810, 2855), False, 'from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear\n'), ((3029, 3070), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['x', '[x.shape[0], -1]'], {}), '(x, [x.shape[0], -1])\n', (3049, 3070), True, 'import paddle.fluid as fluid\n'), ((3292, 3313), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (3311, 3313), True, 'import paddle.fluid as fluid\n'), ((3430, 3446), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (3444, 3446), True, 'import paddle.fluid as fluid\n'), ((3463, 3527), 'paddle.fluid.io.DataLoader.from_generator', 'fluid.io.DataLoader.from_generator', ([], {'capacity': '(5)', 'return_list': '(True)'}), '(capacity=5, return_list=True)\n', (3497, 3527), True, 'import paddle.fluid as fluid\n'), ((5438, 5459), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (5457, 5459), True, 'import paddle.fluid as fluid\n'), ((5579, 5606), 'paddle.fluid.load_dygraph', 'fluid.load_dygraph', (['"""mnist"""'], {}), "('mnist')\n", (5597, 5606), True, 'import paddle.fluid as fluid\n'), ((6005, 6026), 'paddle.fluid.dygraph.guard', 'fluid.dygraph.guard', ([], {}), '()\n', (6024, 6026), True, 'import paddle.fluid as fluid\n'), ((6124, 6151), 'paddle.fluid.load_dygraph', 'fluid.load_dygraph', (['"""mnist"""'], {}), "('mnist')\n", (6142, 6151), True, 'import paddle.fluid as fluid\n'), ((6995, 7022), 'os.path.exists', 'os.path.exists', (['result_path'], {}), '(result_path)\n', (7009, 7022), False, 'import os\n'), ((7035, 7072), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "('loss', 'acc')"}), "(columns=('loss', 'acc'))\n", (7047, 7072), True, 'import pandas as pd\n'), ((7240, 7279), 'pandas.read_csv', 'pd.read_csv', (['result_path'], {'index_col': '[0]'}), '(result_path, index_col=[0])\n', (7251, 7279), True, 'import pandas as pd\n'), ((7388, 7410), 'os.remove', 'os.remove', (['result_path'], {}), '(result_path)\n', (7397, 7410), False, 'import os\n'), ((1336, 1362), 'random.shuffle', 'random.shuffle', (['index_list'], {}), '(index_list)\n', (1350, 1362), False, 'import random\n'), ((3168, 3211), 'paddle.fluid.layers.accuracy', 'fluid.layers.accuracy', ([], {'input': 'x', 'label': 'label'}), '(input=x, label=label)\n', (3189, 3211), True, 'import paddle.fluid as fluid\n'), ((5210, 5230), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (5220, 5230), False, 'from PIL import Image\n'), ((5728, 5765), 'paddle.fluid.dygraph.to_variable', 'fluid.dygraph.to_variable', (['tensor_img'], {}), '(tensor_img)\n', (5753, 5765), True, 'import paddle.fluid as fluid\n'), ((6358, 6391), 'paddle.fluid.dygraph.to_variable', 'fluid.dygraph.to_variable', (['x_data'], {}), '(x_data)\n', (6383, 6391), True, 'import paddle.fluid as fluid\n'), ((6403, 6436), 'paddle.fluid.dygraph.to_variable', 'fluid.dygraph.to_variable', (['y_data'], {}), '(y_data)\n', (6428, 6436), True, 'import paddle.fluid as fluid\n'), ((6486, 6543), 'paddle.fluid.layers.cross_entropy', 'fluid.layers.cross_entropy', ([], {'input': 'prediction', 'label': 'label'}), '(input=prediction, label=label)\n', (6512, 6543), True, 'import paddle.fluid as fluid\n'), ((6558, 6581), 'paddle.fluid.layers.mean', 'fluid.layers.mean', (['loss'], {}), '(loss)\n', (6575, 6581), True, 'import paddle.fluid as fluid\n'), ((3906, 3943), 'paddle.fluid.dygraph.to_variable', 'fluid.dygraph.to_variable', (['image_data'], {}), '(image_data)\n', (3931, 3943), True, 'import paddle.fluid as fluid\n'), ((3956, 3993), 'paddle.fluid.dygraph.to_variable', 'fluid.dygraph.to_variable', (['label_data'], {}), '(label_data)\n', (3981, 3993), True, 'import paddle.fluid as fluid\n'), ((4161, 4203), 'paddle.fluid.layers.cross_entropy', 'fluid.layers.cross_entropy', (['predict', 'label'], {}), '(predict, label)\n', (4187, 4203), True, 'import paddle.fluid as fluid\n'), ((4220, 4243), 'paddle.fluid.layers.mean', 'fluid.layers.mean', (['loss'], {}), '(loss)\n', (4237, 4243), True, 'import paddle.fluid as fluid\n'), ((6709, 6726), 'numpy.array', 'np.array', (['acc_set'], {}), '(acc_set)\n', (6717, 6726), True, 'import numpy as np\n'), ((6756, 6778), 'numpy.array', 'np.array', (['avg_loss_set'], {}), '(avg_loss_set)\n', (6764, 6778), True, 'import numpy as np\n'), ((1480, 1524), 'numpy.reshape', 'np.reshape', (['imgs[i]', '[1, IMG_ROWS, IMG_COLS]'], {}), '(imgs[i], [1, IMG_ROWS, IMG_COLS])\n', (1490, 1524), True, 'import numpy as np\n'), ((1554, 1580), 'numpy.reshape', 'np.reshape', (['labels[i]', '[1]'], {}), '(labels[i], [1])\n', (1564, 1580), True, 'import numpy as np\n'), ((1927, 1946), 'numpy.array', 'np.array', (['imgs_list'], {}), '(imgs_list)\n', (1935, 1946), True, 'import numpy as np\n'), ((1948, 1969), 'numpy.array', 'np.array', (['labels_list'], {}), '(labels_list)\n', (1956, 1969), True, 'import numpy as np\n'), ((5306, 5318), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (5314, 5318), True, 'import numpy as np\n'), ((1723, 1742), 'numpy.array', 'np.array', (['imgs_list'], {}), '(imgs_list)\n', (1731, 1742), True, 'import numpy as np\n'), ((1744, 1765), 'numpy.array', 'np.array', (['labels_list'], {}), '(labels_list)\n', (1752, 1765), True, 'import numpy as np\n')]
import abc import logging.config import os import numpy as np from rec_to_nwb.processing.time.continuous_time_extractor import \ ContinuousTimeExtractor from rec_to_nwb.processing.time.timestamp_converter import TimestampConverter path = os.path.dirname(os.path.abspath(__file__)) logging.config.fileConfig( fname=os.path.join(str(path), os.pardir, os.pardir, os.pardir, 'logging.conf'), disable_existing_loggers=False) logger = logging.getLogger(__name__) class TimestampManager(abc.ABC): def __init__(self, directories, continuous_time_directories): self.directories = directories self.continuous_time_directories = continuous_time_directories self.continuous_time_extractor = ContinuousTimeExtractor() self.timestamp_converter = TimestampConverter() self.number_of_datasets = self._get_number_of_datasets() self.file_lengths_in_datasets = self.__calculate_file_lengths_in_datasets() @abc.abstractmethod def _get_timestamps(self, dataset_id): pass def retrieve_real_timestamps(self, dataset_id, convert_timestamps=True): timestamps_ids = self.read_timestamps_ids(dataset_id) if not convert_timestamps: return timestamps_ids continuous_time = self.continuous_time_extractor.get_continuous_time_array_file( self.continuous_time_directories[dataset_id]) return self.timestamp_converter.convert_timestamps(continuous_time, timestamps_ids) def read_timestamps_ids(self, dataset_id): return self._get_timestamps(dataset_id) def get_final_data_shape(self): return sum(self.file_lengths_in_datasets), def get_number_of_datasets(self): return self.number_of_datasets def get_file_lengths_in_datasets(self): return self.file_lengths_in_datasets def __calculate_file_lengths_in_datasets(self): return [self._get_data_shape(i) for i in range(self.number_of_datasets)] def _get_number_of_datasets(self): return np.shape(self.directories)[0] def _get_data_shape(self, dataset_num): return np.shape(self.read_timestamps_ids(dataset_num))[0]
[ "rec_to_nwb.processing.time.continuous_time_extractor.ContinuousTimeExtractor", "numpy.shape", "os.path.abspath", "rec_to_nwb.processing.time.timestamp_converter.TimestampConverter" ]
[((260, 285), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (275, 285), False, 'import os\n'), ((747, 772), 'rec_to_nwb.processing.time.continuous_time_extractor.ContinuousTimeExtractor', 'ContinuousTimeExtractor', ([], {}), '()\n', (770, 772), False, 'from rec_to_nwb.processing.time.continuous_time_extractor import ContinuousTimeExtractor\n'), ((808, 828), 'rec_to_nwb.processing.time.timestamp_converter.TimestampConverter', 'TimestampConverter', ([], {}), '()\n', (826, 828), False, 'from rec_to_nwb.processing.time.timestamp_converter import TimestampConverter\n'), ((2049, 2075), 'numpy.shape', 'np.shape', (['self.directories'], {}), '(self.directories)\n', (2057, 2075), True, 'import numpy as np\n')]
from numpy.random import seed import tensorflow def set_seed(): seed(1) tensorflow.random.set_seed(2)
[ "tensorflow.random.set_seed", "numpy.random.seed" ]
[((69, 76), 'numpy.random.seed', 'seed', (['(1)'], {}), '(1)\n', (73, 76), False, 'from numpy.random import seed\n'), ((81, 110), 'tensorflow.random.set_seed', 'tensorflow.random.set_seed', (['(2)'], {}), '(2)\n', (107, 110), False, 'import tensorflow\n')]
import os import utils import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from experiments_manager import ExperimentsManager from sklearn.preprocessing import MinMaxScaler from device_session_classifier import DeviceSessionClassifier from device_sequence_classifier import DeviceSequenceClassifier from device_classifier import DeviceClassifier from multiple_device_classifier import MultipleDeviceClassifier from sklearn import metrics sns.set_style("white") def eval_classifier( classifier, dataset, model_name, dataset_name, classification_method, seq_len, opt_seq_len, metrics_headers, metrics_dir): dataset_metrics, confusion_matrix = classifier.eval_on_dataset(dataset) shape = dataset_metrics['class'].shape dataset_metrics['device'] = np.full(shape, classifier.dev_name) dataset_metrics['model'] = np.full(shape, model_name) dataset_metrics['dataset'] = np.full(shape, dataset_name) dataset_metrics['classification_method'] = np.full(shape, classification_method) dataset_metrics['seq_len'] = np.full(shape, seq_len) dataset_metrics['opt_seq_len'] = np.full(shape, opt_seq_len) os.makedirs(metrics_dir, exist_ok=True) conf_matrix_dir = os.path.join(metrics_dir, 'confusion_matrix') os.makedirs(conf_matrix_dir, exist_ok=True) metrics_csv = os.path.join(metrics_dir, 'metrics.csv') confusion_matrix_csv = os.path.join( conf_matrix_dir, '{}_{}_{}_{}.csv'.format(model_name, dataset_name, 'session', seq_len)) if os.path.exists(metrics_csv): header = False else: header = metrics_headers # dataset_metrics_df = pd.DataFrame({k: [v] for k, v in dataset_metrics.items()}, columns=metrics_headers) dataset_metrics_df = pd.DataFrame(dataset_metrics, columns=metrics_headers) dataset_metrics_df.to_csv(metrics_csv, mode='a', header=header, index=False) pd.DataFrame(confusion_matrix).to_csv(confusion_matrix_csv) def run_experiment_with_datasets_devices(exp, datasets, devices, models_dir, metrics_dir): y_col = 'device_category' use_cols = pd.read_csv(os.path.abspath('data/use_cols.csv')) metrics_headers = list(pd.read_csv(os.path.abspath('data/metrics_headers.csv'))) for dataset_name in datasets: print('@', dataset_name) dataset = utils.load_data_from_csv('data/{}.csv'.format(dataset_name), use_cols=use_cols) for dev_name in devices: print('@@', dev_name) for model_pkl in os.listdir(os.path.join(models_dir, dev_name)): model_name = os.path.splitext(model_pkl)[0] print('@@@', model_name) exp(y_col, use_cols, metrics_headers, models_dir, metrics_dir, dataset_name, dataset, dev_name, model_pkl, model_name) def run_multi_dev_experiments(datasets, dev_model_csv, pred_methods): y_col = 'device_category' use_cols = pd.read_csv(os.path.abspath('data/use_cols.csv')) metrics_headers = list(pd.read_csv(os.path.abspath('data/metrics_headers.csv'))) dev_model_combos = pd.read_csv(dev_model_csv) for dataset_name in datasets: print('@', dataset_name) dataset = utils.load_data_from_csv('data/{}.csv'.format(dataset_name), use_cols=use_cols) for idx, dev_model_combo in dev_model_combos.iterrows(): print('@@', dev_model_combo) for pred_method in pred_methods: multi_dev_cls = MultipleDeviceClassifier( dev_model_combo, is_model_pkl=True, pred_method=pred_method, use_cols=use_cols, y_col=y_col) eval_classifier( classifier=multi_dev_cls, dataset=dataset, model_name=dev_model_combo.to_dict(), dataset_name=dataset_name, classification_method='multi_dev', seq_len=dev_model_combo.to_dict(), opt_seq_len=dev_model_combo.to_dict(), metrics_headers=metrics_headers, metrics_dir=metrics_dir) def dev_sess_cls_exp( y_col, use_cols, metrics_headers, models_dir, metrics_dir, dataset_name, dataset, dev_name, model_pkl, model_name): # Device session classifier print("@@@@ Device session classifier") dev_sess_cls = DeviceSessionClassifier( dev_name, os.path.join(models_dir, dev_name, model_pkl), is_model_pkl=True, use_cols=use_cols, y_col=y_col) eval_classifier( classifier=dev_sess_cls, dataset=dataset, model_name=model_name, dataset_name=dataset_name, classification_method='session', seq_len=1, opt_seq_len=1, metrics_headers=metrics_headers, metrics_dir=metrics_dir) def dev_seq_cls_exp( y_col, use_cols, metrics_headers, models_dir, metrics_dir, dataset_name, dataset, dev_name, model_pkl, model_name): # Device sequence classifier print("@@@@ Device sequence classifier") dev_seq_cls = DeviceSequenceClassifier( dev_name, os.path.join(models_dir, dev_name, model_pkl), is_model_pkl=True, use_cols=use_cols, y_col=y_col) if dataset_name == 'train': update = True else: update = False opt_seq_len = dev_seq_cls.find_opt_seq_len(dataset, update=update) print('{} seq_length: {}, optimal sequence length: {}' .format(dataset_name, dev_seq_cls.opt_seq_len, opt_seq_len)) eval_classifier( classifier=dev_seq_cls, dataset=dataset, model_name=model_name, dataset_name=dataset_name, classification_method='sequence', seq_len=dev_seq_cls.opt_seq_len, opt_seq_len=opt_seq_len, metrics_headers=metrics_headers, metrics_dir=metrics_dir) datasets = ['validation', 'test'] devices = list(pd.read_csv(os.path.abspath('data/devices.csv'))) models_dir = os.path.abspath('models') metrics_dir = os.path.abspath('metrics/sess_cls') run_experiment_with_datasets_devices(dev_sess_cls_exp, datasets, devices, models_dir, metrics_dir) datasets = ['train', 'validation', 'test'] models_dir = os.path.abspath('models/best') metrics_dir = os.path.abspath('metrics/seq_cls') run_experiment_with_datasets_devices(dev_seq_cls_exp, datasets, devices, models_dir, metrics_dir) opt_models_metrics_csv = os.path.join(metrics_dir,'metrics.csv') opt_models_metrics = pd.read_csv(opt_models_metrics_csv) train_metrics = opt_models_metrics.groupby('dataset').get_group('train') dev_model_combos = {dev_name: [{'model': dev_metrics['model'], 'opt_seq_len': dev_metrics['opt_seq_len']}] for dev_name, dev_metrics in train_metrics.groupby('device')} multi_dev_models_dir = os.path.join('models/multi_dev') os.makedirs(multi_dev_models_dir, exist_ok=True) dev_model_csv = os.path.join(multi_dev_models_dir, 'dev_model.csv') pd.DataFrame(dev_model_combos).to_csv(dev_model_csv) pred_methods = ['first', 'random', 'all'] run_multi_dev_experiments(datasets, dev_model_csv, pred_methods) print('YAYYY!!!') # # device = 'watch' # other_device = 'watch' # model_pkl = r'models/{0}/{0}_cart_entropy_100_samples_leaf.pkl'.format(device) # dataset_csv = 'data/validation.csv' # sc = DeviceSequenceClassifier(device, model_pkl, is_model_pkl=True) # # def perform_feature_scaling(x_train): # scaler = MinMaxScaler() # scaler.fit(x_train) # return scaler.transform(x_train) # # # m = sc.load_model_from_pkl(model_pkl) # # validation = sc.load_data_from_csv(dataset_csv) # # # all_sess = sc.split_data(validation)[0] # other_dev_sess = validation.groupby(sc.y_col).get_group(other_device) # other_dev_sess = sc.split_data(other_dev_sess)[0] # # opt_seq_len = sc.find_opt_seq_len(validation) # seqs = [other_dev_sess[i:i+seq_len] for i in range(len(other_dev_sess)-seq_len)] # # # seq_len = 1 # # seqs = [sessions[0:seq_len]] # # classification = 1 if device == other_device else 0 # # y_actual = [classification] * 100 # x = m.predict(other_dev_sess) # print(metrics.accuracy_score(y_actual,x)) # pred = sc.predict(seqs) # y_actual = [classification] * len(seqs) # print(metrics.accuracy_score(y_actual,pred)) # print(pred) # print("YAYY!!")
[ "numpy.full", "seaborn.set_style", "os.path.abspath", "pandas.DataFrame", "os.makedirs", "pandas.read_csv", "os.path.exists", "os.path.splitext", "multiple_device_classifier.MultipleDeviceClassifier", "os.path.join" ]
[((480, 502), 'seaborn.set_style', 'sns.set_style', (['"""white"""'], {}), "('white')\n", (493, 502), True, 'import seaborn as sns\n'), ((6227, 6252), 'os.path.abspath', 'os.path.abspath', (['"""models"""'], {}), "('models')\n", (6242, 6252), False, 'import os\n'), ((6267, 6302), 'os.path.abspath', 'os.path.abspath', (['"""metrics/sess_cls"""'], {}), "('metrics/sess_cls')\n", (6282, 6302), False, 'import os\n'), ((6460, 6490), 'os.path.abspath', 'os.path.abspath', (['"""models/best"""'], {}), "('models/best')\n", (6475, 6490), False, 'import os\n'), ((6505, 6539), 'os.path.abspath', 'os.path.abspath', (['"""metrics/seq_cls"""'], {}), "('metrics/seq_cls')\n", (6520, 6539), False, 'import os\n'), ((6665, 6705), 'os.path.join', 'os.path.join', (['metrics_dir', '"""metrics.csv"""'], {}), "(metrics_dir, 'metrics.csv')\n", (6677, 6705), False, 'import os\n'), ((6726, 6761), 'pandas.read_csv', 'pd.read_csv', (['opt_models_metrics_csv'], {}), '(opt_models_metrics_csv)\n', (6737, 6761), True, 'import pandas as pd\n'), ((7049, 7081), 'os.path.join', 'os.path.join', (['"""models/multi_dev"""'], {}), "('models/multi_dev')\n", (7061, 7081), False, 'import os\n'), ((7082, 7130), 'os.makedirs', 'os.makedirs', (['multi_dev_models_dir'], {'exist_ok': '(True)'}), '(multi_dev_models_dir, exist_ok=True)\n', (7093, 7130), False, 'import os\n'), ((7147, 7198), 'os.path.join', 'os.path.join', (['multi_dev_models_dir', '"""dev_model.csv"""'], {}), "(multi_dev_models_dir, 'dev_model.csv')\n", (7159, 7198), False, 'import os\n'), ((871, 906), 'numpy.full', 'np.full', (['shape', 'classifier.dev_name'], {}), '(shape, classifier.dev_name)\n', (878, 906), True, 'import numpy as np\n'), ((938, 964), 'numpy.full', 'np.full', (['shape', 'model_name'], {}), '(shape, model_name)\n', (945, 964), True, 'import numpy as np\n'), ((998, 1026), 'numpy.full', 'np.full', (['shape', 'dataset_name'], {}), '(shape, dataset_name)\n', (1005, 1026), True, 'import numpy as np\n'), ((1074, 1111), 'numpy.full', 'np.full', (['shape', 'classification_method'], {}), '(shape, classification_method)\n', (1081, 1111), True, 'import numpy as np\n'), ((1145, 1168), 'numpy.full', 'np.full', (['shape', 'seq_len'], {}), '(shape, seq_len)\n', (1152, 1168), True, 'import numpy as np\n'), ((1206, 1233), 'numpy.full', 'np.full', (['shape', 'opt_seq_len'], {}), '(shape, opt_seq_len)\n', (1213, 1233), True, 'import numpy as np\n'), ((1238, 1277), 'os.makedirs', 'os.makedirs', (['metrics_dir'], {'exist_ok': '(True)'}), '(metrics_dir, exist_ok=True)\n', (1249, 1277), False, 'import os\n'), ((1300, 1345), 'os.path.join', 'os.path.join', (['metrics_dir', '"""confusion_matrix"""'], {}), "(metrics_dir, 'confusion_matrix')\n", (1312, 1345), False, 'import os\n'), ((1350, 1393), 'os.makedirs', 'os.makedirs', (['conf_matrix_dir'], {'exist_ok': '(True)'}), '(conf_matrix_dir, exist_ok=True)\n', (1361, 1393), False, 'import os\n'), ((1412, 1452), 'os.path.join', 'os.path.join', (['metrics_dir', '"""metrics.csv"""'], {}), "(metrics_dir, 'metrics.csv')\n", (1424, 1452), False, 'import os\n'), ((1598, 1625), 'os.path.exists', 'os.path.exists', (['metrics_csv'], {}), '(metrics_csv)\n', (1612, 1625), False, 'import os\n'), ((1829, 1883), 'pandas.DataFrame', 'pd.DataFrame', (['dataset_metrics'], {'columns': 'metrics_headers'}), '(dataset_metrics, columns=metrics_headers)\n', (1841, 1883), True, 'import pandas as pd\n'), ((3125, 3151), 'pandas.read_csv', 'pd.read_csv', (['dev_model_csv'], {}), '(dev_model_csv)\n', (3136, 3151), True, 'import pandas as pd\n'), ((2179, 2215), 'os.path.abspath', 'os.path.abspath', (['"""data/use_cols.csv"""'], {}), "('data/use_cols.csv')\n", (2194, 2215), False, 'import os\n'), ((2979, 3015), 'os.path.abspath', 'os.path.abspath', (['"""data/use_cols.csv"""'], {}), "('data/use_cols.csv')\n", (2994, 3015), False, 'import os\n'), ((4576, 4621), 'os.path.join', 'os.path.join', (['models_dir', 'dev_name', 'model_pkl'], {}), '(models_dir, dev_name, model_pkl)\n', (4588, 4621), False, 'import os\n'), ((5368, 5413), 'os.path.join', 'os.path.join', (['models_dir', 'dev_name', 'model_pkl'], {}), '(models_dir, dev_name, model_pkl)\n', (5380, 5413), False, 'import os\n'), ((6176, 6211), 'os.path.abspath', 'os.path.abspath', (['"""data/devices.csv"""'], {}), "('data/devices.csv')\n", (6191, 6211), False, 'import os\n'), ((7199, 7229), 'pandas.DataFrame', 'pd.DataFrame', (['dev_model_combos'], {}), '(dev_model_combos)\n', (7211, 7229), True, 'import pandas as pd\n'), ((1969, 1999), 'pandas.DataFrame', 'pd.DataFrame', (['confusion_matrix'], {}), '(confusion_matrix)\n', (1981, 1999), True, 'import pandas as pd\n'), ((2256, 2299), 'os.path.abspath', 'os.path.abspath', (['"""data/metrics_headers.csv"""'], {}), "('data/metrics_headers.csv')\n", (2271, 2299), False, 'import os\n'), ((3056, 3099), 'os.path.abspath', 'os.path.abspath', (['"""data/metrics_headers.csv"""'], {}), "('data/metrics_headers.csv')\n", (3071, 3099), False, 'import os\n'), ((2576, 2610), 'os.path.join', 'os.path.join', (['models_dir', 'dev_name'], {}), '(models_dir, dev_name)\n', (2588, 2610), False, 'import os\n'), ((3502, 3624), 'multiple_device_classifier.MultipleDeviceClassifier', 'MultipleDeviceClassifier', (['dev_model_combo'], {'is_model_pkl': '(True)', 'pred_method': 'pred_method', 'use_cols': 'use_cols', 'y_col': 'y_col'}), '(dev_model_combo, is_model_pkl=True, pred_method=\n pred_method, use_cols=use_cols, y_col=y_col)\n', (3526, 3624), False, 'from multiple_device_classifier import MultipleDeviceClassifier\n'), ((2642, 2669), 'os.path.splitext', 'os.path.splitext', (['model_pkl'], {}), '(model_pkl)\n', (2658, 2669), False, 'import os\n')]
from . import Cosmology, MassFunction, HaloPhysics import numpy as np from scipy.special import spherical_jn from scipy.integrate import simps class MassIntegrals: """ Class to compute and store the various mass integrals of the form .. math:: I_p^{q_1,q_2}(k_1,...k_p) = \\int n(m)b^{(q_1)}(m)b^{(q_2)}\\frac{m^p}{\\rho_M^p}u(k_1|m)..u(k_p|m)dm which are needed to compute the power spectrum model. Here :math:`b^{(q)}` is the q-th order bias (with :math:`b^{0}=1`), :math:`u(k|m)` is the normalized halo profile and :math:`n(m)` is the mass function. All integrals are performed via Simpson's rule over a specified mass range, and are simply returned if they are already computed. For the :math:`I_1^{1,0} = I_1^1` integral, the integral must be corrected to ensure that we recover the bias consistency relation :math:`I_1^1 \\rightarrow 1` as :math:`k \\rightarrow 0`. This requires an infinite mass range, so we instead approximate; .. math:: I_1^1(k)_{\mathrm{corrected}} = I_1^1(k) + ( 1 - I_1^1(0) ) \\frac{u(k|m_min)}{u(k|0)} for normalized halo profile :math:`u(k|m)`. Note that this can also be used to compute :math:`{}_iJ_p^{q_1,q_2}` and :math:`{}_iK_p^{q_1,q_2}[f]` type integrals required for the exclusion counts covariance. Args: cosmology (Cosmology): Instance of the Cosmology class containing relevant cosmology and functions. mass_function (MassFunction): Instance of the MassFunction class, containing the mass function and bias. halo_physics (HaloPhysics): Instance of the HaloPhysics class, containing the halo profiles and concentrations. kh_vector (np.ndarray): Array (or float) of wavenumbers in :math:`h\mathrm{Mpc}^{-1}` units from which to compute mass integrals. Keyword Args: min_logM_h (float): Minimum mass in :math:`\log_{10}(M/h^{-1}M_\mathrm{sun})` units, default: 6.001. max_logM_h (float): Maximum mass in :math:`\log_{10}(M/h^{-1}M_\mathrm{sun})` units, default: 16.999. npoints (int): Number of logarithmically spaced mass grid points, default: 10000. verb (bool): If true output useful messages througout run-time, default: False. """ def __init__(self,cosmology,mass_function,halo_physics,kh_vector,min_logM_h=6.001, max_logM_h=16.999, npoints=int(1e4),verb=False,m_low=-1): """ Initialize the class with relevant model hyperparameters. """ # Write attributes, if they're of the correct type if isinstance(cosmology, Cosmology): self.cosmology = cosmology else: raise TypeError('cosmology input must be an instance of the Cosmology class!') if isinstance(mass_function, MassFunction): self.mass_function = mass_function else: raise TypeError('mass_function input must be an instance of the MassFunction class!') if isinstance(halo_physics, HaloPhysics): self.halo_physics = halo_physics else: raise TypeError('halo_physics input must be an instance of the HaloPhysics class!') # Run some important checks interp_min = self.halo_physics.min_logM_h interp_max = self.halo_physics.max_logM_h assert min_logM_h >= interp_min, 'Minimum mass must be greater than the interpolation limit (10^%.2f)'%interp_min assert max_logM_h <= interp_max, 'Minimum mass must be less than the interpolation limit (10^%.2f)'%interp_max # Save other attributes self.min_logM_h = min_logM_h self.max_logM_h = max_logM_h self.npoints = npoints self.verb = verb # Define a mass vector for computations self.logM_h_grid = np.linspace(self.min_logM_h,self.max_logM_h, self.npoints) # Load and convert masses and wavenumbers self.m_h_grid = 10.**self.logM_h_grid # in Msun/h self.kh_vectors = kh_vector # in h/Mpc self.N_k = len(self.kh_vectors) # define number of k points def compute_I_00(self): """Compute the I_0^0 integral, if not already computed. Returns: float: Value of :math:`I_0^0` """ if not hasattr(self,'I_00'): self.I_00 = simps(self._I_p_q1q2_integrand(0,0,0),self.logM_h_grid) return self.I_00.copy() def compute_I_01(self): """Compute the I_0^1 integral, if not already computed. Returns: float: Value of :math:`I_0^1` """ if not hasattr(self,'I_01'): self.I_01 = simps(self._I_p_q1q2_integrand(0,1,0),self.logM_h_grid) return self.I_01.copy() def compute_I_02(self): """Compute the I_0^2 integral, if not already computed. Returns: float: Value of :math:`I_0^2` """ if not hasattr(self,'I_02'): self.I_02 = simps(self._I_p_q1q2_integrand(0,2,0),self.logM_h_grid) return self.I_02.copy() def compute_I_10(self, apply_correction = False): """Compute the I_1^0 integral, if not already computed. Also apply the correction noted in the class header if required. When computing :math:`{}_i J_1^1` type integrals (over a finite mass bin), the correction should *not* be applied. Keyword Args: apply_correction (bool): Whether to apply the correction in the class header to ensure the bias consistency relation is upheld. Returns: float: Array of :math:`I_1^0` values for each k. """ if not hasattr(self,'I_10'): self.I_10 = simps(self._I_p_q1q2_integrand(1,0,0),self.logM_h_grid) if apply_correction: A = 1. - simps(self._I_p_q1q2_integrand(1,0,0,zero_k=True),self.logM_h_grid) # compute window functions min_m_h = np.power(10.,self.min_logM_h) min_window = self.halo_physics.halo_profile(min_m_h,self.kh_vectors).ravel() zero_window = self.halo_physics.halo_profile(min_m_h,0.).ravel() self.I_10 += A*min_window/zero_window return self.I_10.copy() def compute_I_11(self,apply_correction = True): """Compute the :math:`I_1^1(k)` integral, if not already computed. Also apply the correction noted in the class header if required. When computing :math:`{}_i J_1^1` type integrals (over a finite mass bin), the correction should *not* be applied. Keyword Args: apply_correction (bool): Whether to apply the correction in the class header to ensure the bias consistency relation is upheld. Returns: np.ndarray: Array of :math:`I_1^1` values for each k. """ if not hasattr(self,'I_11'): # Compute the integral over the utilized mass range self.I_11 = simps(self._I_p_q1q2_integrand(1,1,0),self.logM_h_grid,axis=1) if apply_correction: A = 1. - simps(self._I_p_q1q2_integrand(1,1,0,zero_k=True),self.logM_h_grid) # compute window functions min_m_h = np.power(10.,self.min_logM_h) min_window = self.halo_physics.halo_profile(min_m_h,self.kh_vectors).ravel() zero_window = self.halo_physics.halo_profile(min_m_h,0.).ravel() self.I_11 += A*min_window/zero_window return self.I_11.copy() def compute_I_111(self): """Compute the :math:`I_1^{1,1}(k)` integral, if not already computed. Returns: np.ndarray: Array of :math:`I_1^{1,1}` values for each k. """ if not hasattr(self,'I_111'): self.I_111 = simps(self._I_p_q1q2_integrand(1,1,1),self.logM_h_grid,axis=1) return self.I_111.copy() def compute_I_12(self,apply_correction = True): """Compute the :math:`I_1^2(k)` integral, if not already computed. Also apply the correction noted in the class header if required. When computing :math:`{}_i J_1^2` type integrals (over a finite mass bin), the correction should *not* be applied. Keyword Args: apply_correction (bool): Whether to apply the correction in the class header to ensure the bias consistency relation is upheld. Returns: np.ndarray: Array of :math:`I_1^2` values for each k. """ if not hasattr(self,'I_12'): self.I_12 = simps(self._I_p_q1q2_integrand(1,2,0),self.logM_h_grid) if apply_correction: A = - simps(self._I_p_q1q2_integrand(1,2,0,zero_k=True),self.logM_h_grid) # compute window functions min_m_h = np.power(10.,self.min_logM_h) min_window = self.halo_physics.halo_profile(min_m_h,self.kh_vectors).ravel() zero_window = self.halo_physics.halo_profile(min_m_h,0.).ravel() self.I_12 += A*min_window/zero_window return self.I_12.copy() def compute_I_20(self): """Compute the :math:`I_2^0(k,k)` integral, if not already computed. Note that we assume both k-vectors are the same here. Returns: np.ndarray: Array of :math:`I_2^0` values for each k. """ if not hasattr(self,'I_20'): self.I_20 = simps(self._I_p_q1q2_integrand(2,0,0),self.logM_h_grid,axis=1) return self.I_20.copy() def compute_I_21(self): """Compute the :math:`I_2^1(k,k)` integral, if not already computed. Note that we assume both k-vectors are the same here. Returns: np.ndarray: Array of :math:`I_2^1` values for each k. """ if not hasattr(self,'I_21'): self.I_21 = simps(self._I_p_q1q2_integrand(2,1,0),self.logM_h_grid,axis=1) return self.I_21.copy() def _I_p_q1q2_integrand(self,p,q1,q2,zero_k=False): """Compute the integrand of the :math:`I_p^{q1,q2}` function defined in the class description. This is done over the :math:`\log_{10}(M/h^{-1}M_\mathrm{sun}) grid defined in the __init__ function. Note that this is the same as the integrand for the :math:`{}_i J_p^{q1,q2}` function (for integrals over a finite mass range). It also assumes an integration variable :math:`\log_{10}(M/h^{-1}M_\mathrm{sun}) and integrates for each k in the k-vector specified in the class definition. If zero_k is set, it returns the value of the integrand at :math:`k = 0` instead. Args: p (int): Number of halo profiles to include. q1 (int): Order of the first bias term. q2 (int): Order of the second bias term. Keyword Args: zero_k (bool): If True, return the integral evaluated at k = 0. Default: False. """ assert type(p)==type(q1)==type(q2)==int if p==0: fourier_profiles = 1. else: if zero_k: fourier_profiles = np.power(self.halo_physics.halo_profile(self.m_h_grid,-1,norm_only=True),p) else: fourier_profiles = np.power(self._compute_fourier_profile(),p) # Compute d(n(M))/d(log10(M/h^{-1}Msun)) dn_dlogm = self._compute_mass_function() return dn_dlogm * fourier_profiles * self._return_bias(q1) * self._return_bias(q2) def _compute_fourier_profile(self): """ Compute the halo profile :math:`m / \rho u(k|m)` for specified masses and k if not already computed. Returns: np.ndarray: array of :math:`m / \rho u(k|m)` values. """ if not hasattr(self,'fourier_profile'): self.fourier_profile = self.halo_physics.halo_profile(self.m_h_grid,self.kh_vectors) return self.fourier_profile.copy() def _compute_mass_function(self): """Compute the mass function for specified masses if not already computed. Returns: np.ndarray: :math:`dn/d\log_{10}(M/h^{-1}M_\mathrm{sun})` array """ if not hasattr(self,'mass_function_grid'): self.mass_function_grid = self.mass_function.mass_function(self.m_h_grid) return self.mass_function_grid.copy() def _compute_linear_bias(self): """Compute the linear bias function for specified masses if not already computed. Returns: np.ndarray: Array of Eulerian linear biases :math:`b_1^E(m)` """ if not hasattr(self,'linear_bias_grid'): self.linear_bias_grid = self.mass_function.linear_halo_bias(self.m_h_grid) return self.linear_bias_grid.copy() def _compute_second_order_bias(self): """Compute the second order bias function for specified masses if not already computed. Returns: np.ndarray: Array of second order Eulerian biases :math:`b_2^E(m)` """ if not hasattr(self,'second_order_bias_grid'): self.second_order_bias_grid = self.mass_function.second_order_bias(self.m_h_grid) return self.second_order_bias_grid.copy() def _return_bias(self,q): """Return the q-th order halo bias function for all masses in the self.logM_h_grid attribute. Args: q (int): Order of bias. Setting q = 0 returns unity. Currently only :math:`q\leq 2` is implemented. Returns: np.ndarray: Array of q-th order Eulerian biases. """ if q==0: return 1. elif q==1: return self._compute_linear_bias() elif q==2: return self._compute_second_order_bias() else: raise Exception('%-th order bias not yet implemented!'%q) def _K_p_q1q2_f_integrand(self,p,q1,q2,f_exclusion,alpha): """Compute the integrand of the :math:`{}_iK_p^{q1,q2}[f]` functions defined in Philcox et al. (2020). This is done over the :math:`\log_{10}(M/h^{-1}M_\mathrm{sun}) grid defined in the __init__ function. Note that the upper mass limit should be infinity (or some large value) for these types of integrals. It also assumes an integration variable :math:`\log_{10}(M/h^{-1}M_\mathrm{sun}) and integrates for each k in the k-vector specified in the class definition. If zero_k is set, it returns the value of the integrand at :math:`k = 0` instead. Args: p (int): Number of halo profiles to include. q1 (int): Order of the first bias term. q2 (int): Order of the second bias term. f_exclusion (function): Arbitrary function of the exclusion radius :math:`R_\mathrm{ex}` to be included in the integrand. alpha (float): Dimensionless ratio of exclusion to Lagrangian halo radius. """ assert type(p)==type(q1)==type(q2)==int if p==0: fourier_profiles = 1. else: fourier_profiles = np.power(self._compute_fourier_profile(),p) # Compute exclusion radius if not hasattr(self,'R_ex'): R_ex = np.power(3.*self.m_h_grid/(4.*np.pi*self.cosmology.rhoM),1./3.) R_ex += np.power(3.*min(self.m_h_grid)/(4.*np.pi*self.cosmology.rhoM),1./3.) self.R_ex = R_ex.reshape(1,-1) * alpha # Compute d(n(M))/d(log10(M/h^{-1}Msun)) dn_dlogm = self._compute_mass_function() return dn_dlogm * fourier_profiles * self._return_bias(q1) * self._return_bias(q2) * f_exclusion(self.R_ex) def compute_K_Theta_01(self,alpha): """Compute the :math:`K_0^1[\Theta](k)` integral, if not already computed. :math:`Theta` is the Fourier transform of the exclusion window function. Arguments: alpha (float): Dimensionless ratio of exclusion to Lagrangian halo radius Returns: np.ndarray: Array of :math:`K_0^1[\Theta](k)` values for each k. """ # Define function Theta = lambda R: 4.*np.pi*R**2./self.kh_vectors.reshape(-1,1)*spherical_jn(1,self.kh_vectors.reshape(-1,1)*R) if not hasattr(self,'K_Theta_01'): self.K_Theta_01 = simps(self._K_p_q1q2_f_integrand(0,1,0,Theta,alpha),self.logM_h_grid,axis=1) return self.K_Theta_01.copy() def compute_K_Theta_10(self,alpha): """Compute the :math:`K_1^0[\Theta](k)` integral, if not already computed. :math:`Theta` is the Fourier transform of the exclusion window function. Arguments: alpha (float): Dimensionless ratio of exclusion to Lagrangian halo radius Returns: np.ndarray: Array of :math:`K_1^0[\Theta](k)` values for each k. """ # Define function Theta = lambda R: 4.*np.pi*R**2./self.kh_vectors.reshape(-1,1)*spherical_jn(1,self.kh_vectors.reshape(-1,1)*R) if not hasattr(self,'K_Theta_10'): self.K_Theta_10 = simps(self._K_p_q1q2_f_integrand(1,0,0,Theta,alpha),self.logM_h_grid,axis=1) return self.K_Theta_10.copy() def compute_K_S_01(self,alpha, S_L_interpolator): """Compute the :math:`K_0^1[S](k)` integral, if not already computed. :math:`S` is the integral of the 2PCF windowed by the halo exclusion function of radius :math:`R_\mathrm{ex}``. Arguments: alpha (float): Dimensionless ratio of exclusion to Lagrangian halo radius S_L_interpolator (interp1d): Interpolator for the linear :math:`S(R_\mathrm{ex})` function Returns: np.ndarray: Array of :math:`K_0^1[S](k)` values for each k. """ if not hasattr(self,'K_S_01'): self.K_S_01 = simps(self._K_p_q1q2_f_integrand(0,1,0,S_L_interpolator,alpha),self.logM_h_grid,axis=1) return self.K_S_01.copy() def compute_K_S_21(self,alpha, S_NL_interpolator): """Compute the :math:`K_2^1[S](k)` integral, if not already computed. :math:`S` is the integral of the 2PCF windowed by the halo exclusion function of radius :math:`R_\mathrm{ex}``. Note this function uses the non-linear form. Arguments: alpha (float): Dimensionless ratio of exclusion to Lagrangian halo radius S_NL_interpolator (interp1d): Interpolator for the non-linear :math:`S(R_\mathrm{ex})` function Returns: np.ndarray: Array of :math:`K_2^1[S](k)` values for each k. """ if not hasattr(self,'K_S_21'): self.K_S_21 = simps(self._K_p_q1q2_f_integrand(2,1,0,S_NL_interpolator,alpha),self.logM_h_grid,axis=1) return self.K_S_21.copy() def compute_K_V_11(self,alpha): """Compute the :math:`K_1^1[V](k)` integral, if not already computed. :mathrm:`V` is the volume of the exclusion window function. Arguments: alpha (float): Dimensionless ratio of exclusion to Lagrangian halo radius Returns: np.ndarray: Array of :math:`K_1^1[V](k)` values for each k. """ # Define function V = lambda R: 4.*np.pi*R**3./3. if not hasattr(self,'K_V_11'): self.K_V_11 = simps(self._K_p_q1q2_f_integrand(1,1,0,V,alpha),self.logM_h_grid,axis=1) return self.K_V_11.copy() def compute_K_V_20(self,alpha): """Compute the :math:`K_2^0[V](k)` integral, if not already computed. :mathrm:`V` is the volume of the exclusion window function. Arguments: alpha (float): Dimensionless ratio of exclusion to Lagrangian halo radius Returns: np.ndarray: Array of :math:`K_2^0[V](k)` values for each k. """ # Define function V = lambda R: 4.*np.pi*R**3./3. if not hasattr(self,'K_V_20'): self.K_V_20 = simps(self._K_p_q1q2_f_integrand(2,0,0,V,alpha),self.logM_h_grid,axis=1) return self.K_V_20.copy() def compute_K_PTheta_11(self,alpha, PTheta_interpolator): """Compute the :math:`K_2^1[P \ast \Theta](k)` integral, if not already computed. :math:`\Theta` is the Fourier transform of the exclusion window function which is convolved with the power spectrum. Arguments: alpha (float): Dimensionless ratio of exclusion to Lagrangian halo radius PTheta_interpolator (interp1d): Interpolator for the non-linear :math:`S(R_\mathrm{ex})` function Returns: np.ndarray: Array of :math:`K_1^1[P\ast \Theta](k)` values for each k. """ if not hasattr(self,'K_PTheta_11'): self.K_PTheta_11 = simps(self._K_p_q1q2_f_integrand(1,1,0,PTheta_interpolator,alpha),self.logM_h_grid,axis=1) return self.K_PTheta_11.copy()
[ "numpy.power", "numpy.linspace" ]
[((3743, 3802), 'numpy.linspace', 'np.linspace', (['self.min_logM_h', 'self.max_logM_h', 'self.npoints'], {}), '(self.min_logM_h, self.max_logM_h, self.npoints)\n', (3754, 3802), True, 'import numpy as np\n'), ((14928, 15006), 'numpy.power', 'np.power', (['(3.0 * self.m_h_grid / (4.0 * np.pi * self.cosmology.rhoM))', '(1.0 / 3.0)'], {}), '(3.0 * self.m_h_grid / (4.0 * np.pi * self.cosmology.rhoM), 1.0 / 3.0)\n', (14936, 15006), True, 'import numpy as np\n'), ((5844, 5875), 'numpy.power', 'np.power', (['(10.0)', 'self.min_logM_h'], {}), '(10.0, self.min_logM_h)\n', (5852, 5875), True, 'import numpy as np\n'), ((7095, 7126), 'numpy.power', 'np.power', (['(10.0)', 'self.min_logM_h'], {}), '(10.0, self.min_logM_h)\n', (7103, 7126), True, 'import numpy as np\n'), ((8639, 8670), 'numpy.power', 'np.power', (['(10.0)', 'self.min_logM_h'], {}), '(10.0, self.min_logM_h)\n', (8647, 8670), True, 'import numpy as np\n')]
import numpy as np import pickle import cv2 from sklearn.model_selection import train_test_split import pickle import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras import layers data = pickle.loads(open('output/embeddings.pickle', "rb").read()) x = d = np.array(data["embeddings"]) y = pickle.loads(open('./output/le.pickle', "rb").read()).fit_transform(data["names"]) x_train, x_test, y_train, y_test = train_test_split(x, y) train_images = x_train / 255.0 test_images = x_test / 255.0 print(train_images.shape) print(test_images.shape) # model = tf.keras.Sequential([ # tf.keras.layers.Flatten(input_shape=(11, 11)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(32, activation='relu'), tf.keras.layers.Dense(14) ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) model.fit(train_images, y_train, epochs=120) test_loss, test_acc = model.evaluate(test_images, y_test, verbose=2) print('\nTest accuracy:', test_acc) model.save('output/nn_model') # f = open('output/', "wb") # f.write(pickle.dumps(model)) # f.close()
[ "sklearn.model_selection.train_test_split", "tensorflow.keras.losses.SparseCategoricalCrossentropy", "numpy.array", "tensorflow.keras.layers.Dense" ]
[((287, 315), 'numpy.array', 'np.array', (["data['embeddings']"], {}), "(data['embeddings'])\n", (295, 315), True, 'import numpy as np\n'), ((440, 462), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {}), '(x, y)\n', (456, 462), False, 'from sklearn.model_selection import train_test_split\n'), ((667, 712), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (688, 712), True, 'import tensorflow as tf\n'), ((718, 762), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(64)'], {'activation': '"""relu"""'}), "(64, activation='relu')\n", (739, 762), True, 'import tensorflow as tf\n'), ((768, 812), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(32)'], {'activation': '"""relu"""'}), "(32, activation='relu')\n", (789, 812), True, 'import tensorflow as tf\n'), ((818, 843), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(14)'], {}), '(14)\n', (839, 843), True, 'import tensorflow as tf\n'), ((900, 963), 'tensorflow.keras.losses.SparseCategoricalCrossentropy', 'tf.keras.losses.SparseCategoricalCrossentropy', ([], {'from_logits': '(True)'}), '(from_logits=True)\n', (945, 963), True, 'import tensorflow as tf\n')]
import autoarray as aa import numpy as np from test_autoarray.mock.mock_inversion import MockPixelizationGrid, MockRegMapper class TestRegularizationinstance: def test__regularization_matrix__compare_to_regularization_util(self): pixel_neighbors = np.array( [ [1, 3, 7, 2], [4, 2, 0, -1], [1, 5, 3, -1], [4, 6, 0, -1], [7, 1, 5, 3], [4, 2, 8, -1], [7, 3, 0, -1], [4, 8, 6, -1], [7, 5, -1, -1], ] ) pixel_neighbors_size = np.array([4, 3, 3, 3, 4, 3, 3, 3, 2]) pixelization_grid = MockPixelizationGrid( pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size ) mapper = MockRegMapper(pixelization_grid=pixelization_grid) reg = aa.reg.Constant(coefficient=1.0) regularization_matrix = reg.regularization_matrix_from_mapper(mapper=mapper) regularization_matrix_util = aa.util.regularization.constant_regularization_matrix_from_pixel_neighbors( coefficient=1.0, pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size, ) assert (regularization_matrix == regularization_matrix_util).all() class TestRegularizationWeighted: def test__weights__compare_to_regularization_util(self): reg = aa.reg.AdaptiveBrightness(inner_coefficient=10.0, outer_coefficient=15.0) pixel_signals = np.array([0.21, 0.586, 0.45]) mapper = MockRegMapper(pixel_signals=pixel_signals) weights = reg.regularization_weights_from_mapper(mapper=mapper) weights_util = aa.util.regularization.adaptive_regularization_weights_from_pixel_signals( inner_coefficient=10.0, outer_coefficient=15.0, pixel_signals=pixel_signals ) assert (weights == weights_util).all() def test__regularization_matrix__compare_to_regularization_util(self): reg = aa.reg.AdaptiveBrightness( inner_coefficient=1.0, outer_coefficient=2.0, signal_scale=1.0 ) pixel_neighbors = np.array( [ [1, 4, -1, -1], [2, 4, 0, -1], [3, 4, 5, 1], [5, 2, -1, -1], [5, 0, 1, 2], [2, 3, 4, -1], ] ) pixel_neighbors_size = np.array([2, 3, 4, 2, 4, 3]) pixel_signals = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) pixelization_grid = MockPixelizationGrid( pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size ) mapper = MockRegMapper( pixelization_grid=pixelization_grid, pixel_signals=pixel_signals ) regularization_matrix = reg.regularization_matrix_from_mapper(mapper=mapper) regularization_weights = aa.util.regularization.adaptive_regularization_weights_from_pixel_signals( pixel_signals=pixel_signals, inner_coefficient=1.0, outer_coefficient=2.0 ) regularization_matrix_util = aa.util.regularization.weighted_regularization_matrix_from_pixel_neighbors( regularization_weights=regularization_weights, pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size, ) assert (regularization_matrix == regularization_matrix_util).all()
[ "autoarray.reg.AdaptiveBrightness", "test_autoarray.mock.mock_inversion.MockRegMapper", "autoarray.util.regularization.adaptive_regularization_weights_from_pixel_signals", "autoarray.util.regularization.constant_regularization_matrix_from_pixel_neighbors", "test_autoarray.mock.mock_inversion.MockPixelizationGrid", "numpy.array", "autoarray.reg.Constant", "autoarray.util.regularization.weighted_regularization_matrix_from_pixel_neighbors" ]
[((264, 412), 'numpy.array', 'np.array', (['[[1, 3, 7, 2], [4, 2, 0, -1], [1, 5, 3, -1], [4, 6, 0, -1], [7, 1, 5, 3], [\n 4, 2, 8, -1], [7, 3, 0, -1], [4, 8, 6, -1], [7, 5, -1, -1]]'], {}), '([[1, 3, 7, 2], [4, 2, 0, -1], [1, 5, 3, -1], [4, 6, 0, -1], [7, 1,\n 5, 3], [4, 2, 8, -1], [7, 3, 0, -1], [4, 8, 6, -1], [7, 5, -1, -1]])\n', (272, 412), True, 'import numpy as np\n'), ((622, 659), 'numpy.array', 'np.array', (['[4, 3, 3, 3, 4, 3, 3, 3, 2]'], {}), '([4, 3, 3, 3, 4, 3, 3, 3, 2])\n', (630, 659), True, 'import numpy as np\n'), ((689, 790), 'test_autoarray.mock.mock_inversion.MockPixelizationGrid', 'MockPixelizationGrid', ([], {'pixel_neighbors': 'pixel_neighbors', 'pixel_neighbors_size': 'pixel_neighbors_size'}), '(pixel_neighbors=pixel_neighbors, pixel_neighbors_size=\n pixel_neighbors_size)\n', (709, 790), False, 'from test_autoarray.mock.mock_inversion import MockPixelizationGrid, MockRegMapper\n'), ((826, 876), 'test_autoarray.mock.mock_inversion.MockRegMapper', 'MockRegMapper', ([], {'pixelization_grid': 'pixelization_grid'}), '(pixelization_grid=pixelization_grid)\n', (839, 876), False, 'from test_autoarray.mock.mock_inversion import MockPixelizationGrid, MockRegMapper\n'), ((892, 924), 'autoarray.reg.Constant', 'aa.reg.Constant', ([], {'coefficient': '(1.0)'}), '(coefficient=1.0)\n', (907, 924), True, 'import autoarray as aa\n'), ((1048, 1225), 'autoarray.util.regularization.constant_regularization_matrix_from_pixel_neighbors', 'aa.util.regularization.constant_regularization_matrix_from_pixel_neighbors', ([], {'coefficient': '(1.0)', 'pixel_neighbors': 'pixel_neighbors', 'pixel_neighbors_size': 'pixel_neighbors_size'}), '(\n coefficient=1.0, pixel_neighbors=pixel_neighbors, pixel_neighbors_size=\n pixel_neighbors_size)\n', (1122, 1225), True, 'import autoarray as aa\n'), ((1451, 1524), 'autoarray.reg.AdaptiveBrightness', 'aa.reg.AdaptiveBrightness', ([], {'inner_coefficient': '(10.0)', 'outer_coefficient': '(15.0)'}), '(inner_coefficient=10.0, outer_coefficient=15.0)\n', (1476, 1524), True, 'import autoarray as aa\n'), ((1550, 1579), 'numpy.array', 'np.array', (['[0.21, 0.586, 0.45]'], {}), '([0.21, 0.586, 0.45])\n', (1558, 1579), True, 'import numpy as np\n'), ((1598, 1640), 'test_autoarray.mock.mock_inversion.MockRegMapper', 'MockRegMapper', ([], {'pixel_signals': 'pixel_signals'}), '(pixel_signals=pixel_signals)\n', (1611, 1640), False, 'from test_autoarray.mock.mock_inversion import MockPixelizationGrid, MockRegMapper\n'), ((1738, 1898), 'autoarray.util.regularization.adaptive_regularization_weights_from_pixel_signals', 'aa.util.regularization.adaptive_regularization_weights_from_pixel_signals', ([], {'inner_coefficient': '(10.0)', 'outer_coefficient': '(15.0)', 'pixel_signals': 'pixel_signals'}), '(\n inner_coefficient=10.0, outer_coefficient=15.0, pixel_signals=pixel_signals\n )\n', (1811, 1898), True, 'import autoarray as aa\n'), ((2050, 2143), 'autoarray.reg.AdaptiveBrightness', 'aa.reg.AdaptiveBrightness', ([], {'inner_coefficient': '(1.0)', 'outer_coefficient': '(2.0)', 'signal_scale': '(1.0)'}), '(inner_coefficient=1.0, outer_coefficient=2.0,\n signal_scale=1.0)\n', (2075, 2143), True, 'import autoarray as aa\n'), ((2189, 2294), 'numpy.array', 'np.array', (['[[1, 4, -1, -1], [2, 4, 0, -1], [3, 4, 5, 1], [5, 2, -1, -1], [5, 0, 1, 2],\n [2, 3, 4, -1]]'], {}), '([[1, 4, -1, -1], [2, 4, 0, -1], [3, 4, 5, 1], [5, 2, -1, -1], [5, \n 0, 1, 2], [2, 3, 4, -1]])\n', (2197, 2294), True, 'import numpy as np\n'), ((2455, 2483), 'numpy.array', 'np.array', (['[2, 3, 4, 2, 4, 3]'], {}), '([2, 3, 4, 2, 4, 3])\n', (2463, 2483), True, 'import numpy as np\n'), ((2508, 2548), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]'], {}), '([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])\n', (2516, 2548), True, 'import numpy as np\n'), ((2578, 2679), 'test_autoarray.mock.mock_inversion.MockPixelizationGrid', 'MockPixelizationGrid', ([], {'pixel_neighbors': 'pixel_neighbors', 'pixel_neighbors_size': 'pixel_neighbors_size'}), '(pixel_neighbors=pixel_neighbors, pixel_neighbors_size=\n pixel_neighbors_size)\n', (2598, 2679), False, 'from test_autoarray.mock.mock_inversion import MockPixelizationGrid, MockRegMapper\n'), ((2715, 2794), 'test_autoarray.mock.mock_inversion.MockRegMapper', 'MockRegMapper', ([], {'pixelization_grid': 'pixelization_grid', 'pixel_signals': 'pixel_signals'}), '(pixelization_grid=pixelization_grid, pixel_signals=pixel_signals)\n', (2728, 2794), False, 'from test_autoarray.mock.mock_inversion import MockPixelizationGrid, MockRegMapper\n'), ((2937, 3090), 'autoarray.util.regularization.adaptive_regularization_weights_from_pixel_signals', 'aa.util.regularization.adaptive_regularization_weights_from_pixel_signals', ([], {'pixel_signals': 'pixel_signals', 'inner_coefficient': '(1.0)', 'outer_coefficient': '(2.0)'}), '(\n pixel_signals=pixel_signals, inner_coefficient=1.0, outer_coefficient=2.0)\n', (3010, 3090), True, 'import autoarray as aa\n'), ((3146, 3353), 'autoarray.util.regularization.weighted_regularization_matrix_from_pixel_neighbors', 'aa.util.regularization.weighted_regularization_matrix_from_pixel_neighbors', ([], {'regularization_weights': 'regularization_weights', 'pixel_neighbors': 'pixel_neighbors', 'pixel_neighbors_size': 'pixel_neighbors_size'}), '(\n regularization_weights=regularization_weights, pixel_neighbors=\n pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size)\n', (3220, 3353), True, 'import autoarray as aa\n')]
# Author: Ruthger import logging from typing import Optional, Tuple import random from PIL.Image import Image import numpy as np from keras.models import load_model import h5py from keras.preprocessing.image import img_to_array import io logger = logging.getLogger(__name__) # Prediction result datatype, simply stores the name and freshness class PredictionRes: name: str fresh: bool def __init__(self, name: str, fresh: float) -> None: self.name = name self.fresh = fresh # Utility function that extracts freshness and name components from a unified label, e.g. "freshApple" def extract_label_components(name: str) -> Tuple[str, bool]: rotten = True if name.startswith("fresh"): fruit_name = name.split("fresh")[-1] rotten = False if name.startswith("rotten"): fruit_name = name.split("rotten")[-1] return (fruit_name, not rotten) # Partial abstract Classifier class, provides boiler plate for label conversion # but implementors are expected to specialize _predict and _retrain; class Classifier: labels = {} image_type: str image_x: int image_y: int def __init__(self, labels, image_type, image_x, image_y) -> None: self.labels = labels self.image_type = image_type self.image_x = image_x self.image_y = image_y def classify(self, image: Image) -> Optional[PredictionRes]: res = self._predict(image) if res == None: logger.info("failed to predict") return None try: fruit_name = self.labels[res] except: logger.info("Could not get the correct label") fruit_name = "Unknown" # Means our labels don't match which is probably user error fruit_name, fresh = extract_label_components(fruit_name) return PredictionRes(fruit_name, fresh) def _predict(self, _: Image) -> Optional[int]: logger.info("BASE CLASSIFIER") assert False def retrain(self, images: list[Tuple[str, Image]]): # Remap labels from text to internal numbers (since ML models work on numbers) labels_swap = {} for k,v in self.labels.items(): labels_swap[v] = k mapped = [(labels_swap[image[0]], image[1]) for image in images] return self._retrain(mapped) def _retrain(self, _: list[Tuple[int, Image]]) -> None: logger.info("BASE CLASSIFIER RETRAIN") assert False # Simple random clasifier, mainly serves for testing purposes, does not support retraining. class RandomClassifier(Classifier): def __init__(self, labels) -> None: super().__init__(labels, "L", 0, 0) def _predict(self, _: Image) -> Optional[int]: logger.info("RANDOM CLASSIFIER") return random.randrange(0, len(self.labels)) # Classifier implementation supporing keras models # internally stored as an h5 file. class KerasClassifier(Classifier): model_bytes: bytes # Loads the h5 file from memory and loads the actual keras model def _load_model(self): with h5py.File(io.BytesIO(self.model_bytes)) as h5: return load_model(h5) def __init__(self, h5: bytes, labels, image_type, image_x, image_y) -> None: super().__init__(labels, image_type, image_x, image_y) self.model_bytes = h5 # Load the model once to trigger any errors that may occur later self._load_model() # Converts the image into expected dimensions and encoding def _fix_image(self, img: Image) -> Image: return img.resize((self.image_x, self.image_y)).convert(self.image_type) def _predict(self, image: Image) -> Optional[int]: logger.info("KERAS CLASSIFIER") model = self._load_model() image = self._fix_image(image) # wrap into a numpy array as predict expects a batch img_data = np.array([img_to_array(image)]) try: predictions = np.argmax(model.predict(img_data), axis=1) except Exception as e: logger.info("KERAS ERROR OOPS") logger.info(e) return None return int(predictions[0]) def _retrain(self, images: list[Tuple[int, Image]]) -> Optional[Classifier]: logger.info("KERAS CLASSIFIER RETRAIN") try: model = self._load_model() # Transform the PIL images to expected format X_train = np.asarray([img_to_array(self._fix_image(image[1])) for image in images]) Y_train = np.asarray([image[0] for image in images]) model.fit(X_train, Y_train, epochs=5) # resave the model so that its a distinct new model h5bytes = io.BytesIO(bytearray()) with h5py.File(h5bytes, mode='w') as h5: model.save(h5) # Create a new instance with the new h5, but pass the same meta data return KerasClassifier(h5bytes.getvalue(), self.labels, self.image_type, self.image_x, self.image_y) except Exception as e: logger.info(e) return None # Classifier implementation for SciKit models, # SciKit models themselves are also just pickled in storage, so no special conversion is needed class SciKitClassifier(Classifier): model = None def __init__(self, model, labels, image_type, image_x, image_y) -> None: super().__init__(labels, image_type, image_x, image_y) self.model = model def _predict(self, image: Image) -> Optional[int]: logger.info("SCIKIT CLASSIFIER") image = image.resize((self.image_x, self.image_y)).convert(self.image_type) img_data = np.asarray(image.getdata(), dtype=np.int32).flatten() return int(self.model.predict([img_data])[0]) def _retrain(self, _: list[Tuple[int, Image]]) -> None: assert False, "SCIKIT RETRAIN IS NOT IMPLEMENTED YET"
[ "keras.models.load_model", "io.BytesIO", "h5py.File", "numpy.asarray", "keras.preprocessing.image.img_to_array", "logging.getLogger" ]
[((250, 277), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (267, 277), False, 'import logging\n'), ((3179, 3193), 'keras.models.load_model', 'load_model', (['h5'], {}), '(h5)\n', (3189, 3193), False, 'from keras.models import load_model\n'), ((4580, 4622), 'numpy.asarray', 'np.asarray', (['[image[0] for image in images]'], {}), '([image[0] for image in images])\n', (4590, 4622), True, 'import numpy as np\n'), ((3123, 3151), 'io.BytesIO', 'io.BytesIO', (['self.model_bytes'], {}), '(self.model_bytes)\n', (3133, 3151), False, 'import io\n'), ((3930, 3949), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['image'], {}), '(image)\n', (3942, 3949), False, 'from keras.preprocessing.image import img_to_array\n'), ((4826, 4854), 'h5py.File', 'h5py.File', (['h5bytes'], {'mode': '"""w"""'}), "(h5bytes, mode='w')\n", (4835, 4854), False, 'import h5py\n')]
""" Module to analyze vessel pulsatility during the heart cycle in ecg-gated CT radius change - area change - volume change Authors: <NAME> and <NAME>. Created 2019. """ import os import sys import time import openpyxl import pirt import numpy as np import visvis as vv from stentseg.utils.datahandling import select_dir, loadvol, loadmodel, loadmesh from stentseg.stentdirect.stentgraph import create_mesh from stentseg.motion.vis import create_mesh_with_abs_displacement from stentseg.utils import PointSet, fitting from lspeas.utils.vis import showModelsStatic from lspeas.utils.deforminfo import DeformInfo from lspeas.utils.curvature import measure_curvature #todo: check xyz vs zyx! from lspeas.utils import meshlib assert openpyxl.__version__ < "2.4", "Do pip install openpyxl==2.3.5" #todo: move function to lspeas utils? def load_excel_centerline(basedirCenterline, vol, ptcode, ctcode, filename=None): """ Load centerline data from excel Centerline exported from Terarecon; X Y Z coordinates in colums """ if filename is None: filename = '{}_{}_centerline.xlsx'.format(ptcode,ctcode) excel_location = os.path.join(basedirCenterline,ptcode) #read sheet try: wb = openpyxl.load_workbook(os.path.join(excel_location,filename),read_only=True) except FileNotFoundError: wb = openpyxl.load_workbook(os.path.join(basedirCenterline,filename),read_only=True) sheet = wb.get_sheet_by_name(wb.sheetnames[0]) # data on first sheet colStart = 2 # col C rowStart = 1 # row 2 excel coordx = sheet.columns[colStart][rowStart:] coordy = sheet.columns[colStart+1][rowStart:] coordz = sheet.columns[colStart+2][rowStart:] #convert to values coordx = [obj.value for obj in coordx] coordy = [obj.value for obj in coordy] coordz = [obj.value for obj in coordz] #from list to array centerlineX = np.asarray(coordx, dtype=np.float32) centerlineY = np.asarray(coordy, dtype=np.float32) centerlineZ = np.asarray(coordz, dtype=np.float32) centerlineZ = np.flip(centerlineZ, axis=0) # z of volume is also flipped # convert centerline coordinates to world coordinates (mm) origin = vol1.origin # z,y,x sampling = vol1.sampling # z,y,x centerlineX = centerlineX*sampling[2] +origin[2] centerlineY = centerlineY*sampling[1] +origin[1] centerlineZ = (centerlineZ-0.5*vol1.shape[0])*sampling[0] + origin[0] return centerlineX, centerlineY, centerlineZ # Select the ssdf basedir basedir = select_dir( os.getenv('LSPEAS_BASEDIR', ''), r'D:\LSPEAS\LSPEAS_ssdf', r'F:\LSPEAS_ssdf_backup', r'F:\LSPEAS_ssdf_BACKUP') basedirMesh = select_dir( r'D:\Profiles\koenradesma\SURFdrive\UTdrive\MedDataMimics\LSPEAS_Mimics', r'C:\Users\Maaike\SURFdrive\UTdrive\MedDataMimics\LSPEAS_Mimics', r"C:\stack\data\lspeas\vaatwand") basedirCenterline = select_dir( r"C:\stack\data\lspeas\vaatwand", r'D:\Profiles\koenradesma\SURFdrive\UTdrive\LSPEAS_centerlines_terarecon', r'C:\Users\Maaike\SURFdrive\UTdrive\LSPEAS_centerlines_terarecon', r"C:\stack\data\lspeas\vaatwand") # Select dataset ptcode = 'LSPEAS_003' ctcode1 = 'discharge' cropname = 'ring' modelname = 'modelavgreg' cropvol = 'stent' drawModelLines = False # True or False drawRingMesh, ringMeshDisplacement = True, False meshColor = [(1,1,0,1)] removeStent = True # for iso visualization dimensions = 'xyz' showAxis = False showVol = 'ISO' # MIP or ISO or 2D or None showvol2D = False drawVessel = True clim = (0,2500) clim2D = -200,500 # MPR clim2 = (0,2) isoTh = 180 # 250 ## Load data # Load CT image data for reference, and deform data to measure motion try: # If we run this script without restart, we can re-use volume and deforms vol1 deforms except NameError: vol1 = loadvol(basedir, ptcode, ctcode1, cropvol, 'avgreg').vol s_deforms = loadvol(basedir, ptcode, ctcode1, cropvol, 'deforms') deforms = [s_deforms[key] for key in dir(s_deforms) if key.startswith('deform')] deforms = [pirt.DeformationFieldBackward(*fields) for fields in deforms] # Load vessel mesh (mimics) # We make sure that it is a mesh without faces, which makes our sampling easier try: ppvessel except NameError: # Load mesh with visvis, then put in our meshlib.Mesh() and let it ensure that # the mesh is closed, check the winding, etc. so that we can cut it with planes, # and reliably calculate volume. filename = '{}_{}_neck.stl'.format(ptcode,ctcode1) vesselMesh = loadmesh(basedirMesh, ptcode[-3:], filename) #inverts Z vv.processing.unwindFaces(vesselMesh) vesselMesh = meshlib.Mesh(vesselMesh._vertices) vesselMesh.ensure_closed() ppvessel = PointSet(vesselMesh.get_flat_vertices()) # Must be flat! # Load ring model try: modelmesh1 except NameError: s1 = loadmodel(basedir, ptcode, ctcode1, cropname, modelname) if drawRingMesh: if not ringMeshDisplacement: modelmesh1 = create_mesh(s1.model, 0.7) # Param is thickness else: modelmesh1 = create_mesh_with_abs_displacement(s1.model, radius = 0.7, dim=dimensions) # Load vessel centerline (excel terarecon) (is very fast) centerline = PointSet(np.column_stack( load_excel_centerline(basedirCenterline, vol1, ptcode, ctcode1, filename=None))) ## Setup visualization # Show ctvolume, vessel mesh, ring model - this uses figure 1 and clears it axes1, cbars = showModelsStatic(ptcode, ctcode1, [vol1], [s1], [modelmesh1], [vv.BaseMesh(*vesselMesh.get_vertices_and_faces())], showVol, clim, isoTh, clim2, clim2D, drawRingMesh, ringMeshDisplacement, drawModelLines, showvol2D, showAxis, drawVessel, vesselType=1, climEditor=True, removeStent=removeStent, meshColor=meshColor) axes1 = axes1[0] axes1.position = 0, 0, 0.6, 1 # Show or hide the volume (showing is nice, but also slows things down) tex3d = axes1.wobjects[1] tex3d.visible = False # VesselMeshes vesselVisMesh1 = axes1.wobjects[4] vesselVisMesh1.cullFaces = "front" # Show the back # vesselVisMesh2 = vv.Mesh(axes1, *vesselMesh.get_vertices_and_faces()) vesselVisMesh2 = vv.Mesh(axes1, np.zeros((6, 3), np.float32), np.zeros((3, 3), np.int32)) vesselVisMesh2.cullFaces = "back" vesselVisMesh2.faceColor = "red" # Show the centerline vv.plot(centerline, ms='.', ls='', mw=8, mc='b', alpha=0.5) # Initialize 2D view axes2 = vv.Axes(vv.gcf()) axes2.position = 0.65, 0.05, 0.3, 0.4 axes2.daspectAuto = False axes2.camera = '2d' axes2.axis.showGrid = True axes2.axis.axisColor = 'k' # Initialize axes to put widgets and labels in container = vv.Wibject(vv.gcf()) container.position = 0.65, 0.5, 0.3, 0.5 # Create labels to show measurements labelpool = [] for i in range(16): label = vv.Label(container) label.fontSize = 11 label.position = 10, 100 + 25 * i, -20, 25 labelpool.append(label) # Initialize sliders and buttons slider_ref = vv.Slider(container, fullRange=(1, len(centerline)-2), value=10) slider_ves = vv.Slider(container, fullRange=(1, len(centerline)-2), value=10) button_go = vv.PushButton(container, "Take all measurements (incl. volume)") slider_ref.position = 10, 5, -20, 25 slider_ves.position = 10, 40, -20, 25 button_go.position = 10, 70, -20, 25 button_go.bgcolor = slider_ref.bgcolor = slider_ves.bgcolor = 0.8, 0.8, 1.0 # Initialize line objects for showing the plane orthogonal to centerline slider_ref.line_plane = vv.plot([], [], [], axes=axes1, ls='-', lw=3, lc='w', alpha = 0.9) slider_ves.line_plane = vv.plot([], [], [], axes=axes1, ls='-', lw=3, lc='y', alpha = 0.9) # Initialize line objects for showing selected points close to that plane slider_ref.line_3d = vv.plot([], [], [], axes=axes1, ms='.', ls='', mw=8, mc='w', alpha = 0.9) slider_ves.line_3d = vv.plot([], [], [], axes=axes1, ms='.', ls='', mw=8, mc='y', alpha = 0.9) # Initialize line objects for showing selected points and ellipse in 2D line_2d = vv.plot([], [], axes=axes2, ms='.', ls='', mw=8, mc='y') line_ellipse1 = vv.plot([], [], axes=axes2, ms='', ls='-', lw=2, lc='b') line_ellipse2 = vv.plot([], [], axes=axes2, ms='', ls='+', lw=2, lc='b') ## Functions to update visualization and do measurements def get_plane_points_from_centerline_index(i): """ Get a set of points that lie on the plane orthogonal to the centerline at the given index. The points are such that they can be drawn as a line for visualization purposes. The plane equation can be obtained via a plane-fit. """ if True: # Cubic fit of the centerline i = max(1.1, min(i, centerline.shape[0] - 2.11)) # Sample center point and two points right below/above, using # "cardinal" interpolating (C1-continuous), or "basic" approximating (C2-continious). pp = [] for j in [i - 0.1, i, i + 0.1]: index = int(j) t = j - index coefs = pirt.interp.get_cubic_spline_coefs(t, "basic") samples = centerline[index - 1], centerline[index], centerline[index + 1], centerline[index + 2] pp.append(samples[0] * coefs[0] + samples[1] * coefs[1] + samples[2] * coefs[2] + samples[3] * coefs[3]) # Get center point and vector pointing down the centerline p = pp[1] vec1 = (pp[2] - pp[1]).normalize() else: # Linear fit of the centerline i = max(0, min(i, centerline.shape[0] - 2)) index = int(i) t = i - index # Sample two points of interest pa, pb = centerline[index], centerline[index + 1] # Get center point and vector pointing down the centerline p = t * pb + (1 - t) * pa vec1 = (pb - pa).normalize() # Get two orthogonal vectors that define the plane that is orthogonal # to the above vector. We can use an arbitrary vector to get the first, # but there is a tiiiiiny chance that it is equal to vec1 so that the # normal collapese. vec2 = vec1.cross([0, 1, 0]) if vec2.norm() == 0: vec2 = vec1.cross((1, 0, 0)) vec3 = vec1.cross(vec2) # Sample some point on the plane and get the plane's equation pp = PointSet(3) radius = 6 pp.append(p) for t in np.linspace(0, 2 * np.pi, 12): pp.append(p + np.sin(t) * radius * vec2 + np.cos(t) * radius * vec3) return pp def get_vessel_points_from_plane_points(pp): """ Select points from the vessel points that are very close to the plane defined by the given plane points. Returns a 2D and a 3D point set. """ abcd = fitting.fit_plane(pp) # Get 2d and 3d coordinates of points that lie (almost) on the plane # pp2 = fitting.project_to_plane(ppvessel, abcd) # pp3 = fitting.project_from_plane(pp2, abcd) signed_distances = fitting.signed_distance_to_plane(ppvessel, abcd) distances = np.abs(signed_distances) # Select points to consider. This is just to reduce the search space somewhat. selection = np.where(distances < 5)[0] # We assume that each tree points in ppvessel makes up a triangle (face) # We make sure of that when we load the mesh. # Select first index of each face (every 3 vertices is 1 face), and remove duplicates selection_faces = set(3 * (selection // 3)) # Now iterate over the faces (triangles), and check each edge. If the two # points are on different sides of the plane, then we interpolate on the # edge to get the exact spot where the edge intersects the plane. sampled_pp3 = PointSet(3) visited_edges = set() for fi in selection_faces: # for each face index for edge in [(fi + 0, fi + 1), (fi + 0, fi + 2), (fi + 1, fi + 2)]: if signed_distances[edge[0]] * signed_distances[edge[1]] < 0: if edge not in visited_edges: visited_edges.add(edge) d1, d2 = distances[edge[0]], distances[edge[1]] w1, w2 = d2 / (d1 + d2), d1 / (d1 + d2) p = w1 * ppvessel[edge[0]] + w2 * ppvessel[edge[1]] sampled_pp3.append(p) return fitting.project_to_plane(sampled_pp3, abcd), sampled_pp3 def get_distance_along_centerline(): """ Get the distance along the centerline between the two reference points, (using linear interpolation at the ends). """ i1 = slider_ref.value i2 = slider_ves.value index1 = int(np.ceil(i1)) index2 = int(np.floor(i2)) t1 = i1 - index1 # -1 < t1 <= 0 t2 = i2 - index2 # 0 <= t2 < 1 dist = 0 dist += -t1 * (centerline[index1] - centerline[index1 - 1]).norm() dist += +t2 * (centerline[index2] - centerline[index2 + 1]).norm() for index in range(index1, index2): dist += (centerline[index + 1] - centerline[index]).norm() return float(dist) def triangle_area(p1, p2, p3): """ Calcualate triangle area based on its three vertices. """ # Use Heron's formula to calculate a triangle's area # https://www.mathsisfun.com/geometry/herons-formula.html a = p1.distance(p2) b = p2.distance(p3) c = p3.distance(p1) s = (a + b + c) / 2 return (s * (s - a) * (s - b) * (s - c)) ** 0.5 def deform_points_2d(pp2, plane): """ Given a 2D pointset (and the plane that they are on), return a list with the deformed versions of that pointset. """ pp3 = fitting.project_from_plane(pp2, plane) #todo: shouldn't origin be subtracted?! see dynamic.py deformed = [] for phase in range(len(deforms)): deform = deforms[phase] dx = deform.get_field_in_points(pp3, 0) #todo: shouldn't this be z=0 y=1 x=2! see dynamic.py; adapt in all functions?! dy = deform.get_field_in_points(pp3, 1) dz = deform.get_field_in_points(pp3, 2) deform_vectors = PointSet(np.stack([dx, dy, dz], 1)) pp3_deformed = pp3 + deform_vectors deformed.append(fitting.project_to_plane(pp3_deformed, plane)) return deformed def measure_centerline_strain(): """ Measure the centerline strain. """ i1 = slider_ref.value i2 = slider_ves.value # Get the centerline section of interest index1 = int(np.ceil(i1)) index2 = int(np.floor(i2)) section = centerline[index1:index2 + 1] # get this section of the centerline for each phase sections = [] for phase in range(len(deforms)): deform = deforms[phase] dx = deform.get_field_in_points(section, 0) dy = deform.get_field_in_points(section, 1) dz = deform.get_field_in_points(section, 2) deform_vectors = PointSet(np.stack([dx, dy, dz], 1)) sections.append(section + deform_vectors) # Measure the strain of the full section, by measuring the total length in each phase. lengths = [] for phase in range(len(deforms)): section = sections[phase] length = sum(float(section[i].distance(section[i + 1])) for i in range(len(section) - 1)) lengths.append(length) if min(lengths) == 0: return 0 else: # Strain as delta-length divided by initial length return (max(lengths) - min(lengths)) / min(lengths) # ... or as what Wikipedia calls "stretch ratio"> # return max(lengths) / min(lengths) def take_measurements(measure_volume_change): """ This gets called when the slider is releases. We take measurements and update the corresponding texts and visualizations. """ # Get points that form the contour of the vessel in 2D pp = get_plane_points_from_centerline_index(slider_ves.value) pp2, pp3 = get_vessel_points_from_plane_points(pp) plane = pp2.plane # Collect measurements in a dict. That way we can process it in one step at the end measurements = {} # Store slider positions, so we can reproduce this measurement later measurements["centerline indices"] = slider_ref.value, slider_ves.value # Early exit? if len(pp2) == 0: line_2d.SetPoints(pp2) line_ellipse1.SetPoints(pp2) line_ellipse2.SetPoints(pp2) vesselVisMesh2.SetFaces(np.zeros((3, 3), np.int32)) vesselVisMesh2.SetNormals(None) process_measurements(measurements) return # Measure length of selected part of the centerline and the strain in that section measurements["centerline distance"] = get_distance_along_centerline() measurements["centerline strain"] = measure_centerline_strain() # Measure centerline curvature curvature_mean, curvature_max, curvature_max_pos, curvature_max_change = measure_curvature(centerline, deforms) measurements["curvature mean"] = DeformInfo(curvature_mean) measurements["curvature max"] = DeformInfo(curvature_max) measurements["curvature max pos"] = DeformInfo(curvature_max_pos) measurements["curvature max change"] = curvature_max_change # Get ellipse and its center point ellipse = fitting.fit_ellipse(pp2) p0 = PointSet([ellipse[0], ellipse[1]]) # Sample ellipse to calculate its area pp_ellipse = fitting.sample_ellipse(ellipse, 256) # results in N + 1 points area = 0 for i in range(len(pp_ellipse)-1): area += triangle_area(p0, pp_ellipse[i], pp_ellipse[i + 1]) # measurements["reference area"] = float(area) # Do a quick check to be sure that this triangle-approximation is close enough assert abs(area - fitting.area(ellipse)) < 2, "area mismatch" # mm2 typically ~ 0.1 mm2 # Measure ellipse area (and how it changes) measurements["ellipse area"] = DeformInfo(unit="mm2") for pp_ellipse_def in deform_points_2d(pp_ellipse, plane): area = 0 for i in range(len(pp_ellipse_def)-1): area += triangle_area(p0, pp_ellipse_def[i], pp_ellipse_def[i + 1]) measurements["ellipse area"].append(area) # # Measure expansion of ellipse in 256 locations? # # Measure distances from center to ellipse edge. We first get the distances # # in each face, for each point. Then we aggregate these distances to # # expansion measures. So in the end we have 256 expansion measures. # distances_per_point = [[] for i in range(len(pp_ellipse))] # for pp_ellipse_def in deform_points_2d(pp_ellipse, plane): # # todo: Should distance be measured to p0 or to p0 in that phase? # for i, d in enumerate(pp_ellipse_def.distance(p0)): # distances_per_point[i].append(float(d)) # distances_per_point = distances_per_point[:-1] # Because pp_ellipse[-1] == pp_ellipse[0] # # # measurements["expansions"] = DeformInfo() # 256 values, not 10 # for i in range(len(distances_per_point)): # distances = distances_per_point[i] # measurements["expansions"].append((max(distances) - min(distances)) / min(distances)) # Measure radii of ellipse major and minor axis (and how it changes) pp_ellipse4 = fitting.sample_ellipse(ellipse, 4) # major, minor, major, minor measurements["ellipse expansion major1"] = DeformInfo(unit="mm") measurements["ellipse expansion minor1"] = DeformInfo(unit="mm") measurements["ellipse expansion major2"] = DeformInfo(unit="mm") measurements["ellipse expansion minor2"] = DeformInfo(unit="mm") for pp_ellipse4_def in deform_points_2d(pp_ellipse4, plane): measurements["ellipse expansion major1"].append(float( pp_ellipse4_def[0].distance(p0) )) measurements["ellipse expansion minor1"].append(float( pp_ellipse4_def[1].distance(p0) )) measurements["ellipse expansion major2"].append(float( pp_ellipse4_def[2].distance(p0) )) measurements["ellipse expansion minor2"].append(float( pp_ellipse4_def[3].distance(p0) )) # Measure how the volume changes - THIS BIT IS COMPUTATIONALLY EXPENSIVE submesh = meshlib.Mesh(np.zeros((3, 3))) if measure_volume_change: # Update the submesh plane1 = fitting.fit_plane(get_plane_points_from_centerline_index(slider_ref.value)) plane2 = fitting.fit_plane(get_plane_points_from_centerline_index(slider_ves.value)) plane2 = [-x for x in plane2] # flip the plane upside doen submesh = vesselMesh.cut_plane(plane1).cut_plane(plane2) # Measure its motion measurements["volume"] = DeformInfo(unit="mm3") submesh._ori_vertices = submesh._vertices.copy() for phase in range(len(deforms)): deform = deforms[phase] submesh._vertices = submesh._ori_vertices.copy() dx = deform.get_field_in_points(submesh._vertices, 0) dy = deform.get_field_in_points(submesh._vertices, 1) dz = deform.get_field_in_points(submesh._vertices, 2) submesh._vertices[:, 0] += dx submesh._vertices[:, 1] += dy submesh._vertices[:, 2] += dz measurements["volume"].append(submesh.volume()) # Show measurements process_measurements(measurements) # Update line objects line_2d.SetPoints(pp2) line_ellipse1.SetPoints(fitting.sample_ellipse(ellipse)) major_minor = PointSet(2) for p in [p0, pp_ellipse4[0], p0, pp_ellipse4[2], p0, pp_ellipse4[1], p0, pp_ellipse4[3]]: major_minor.append(p) line_ellipse2.SetPoints(major_minor) axes2.SetLimits(margin=0.12) # Update submesh object vertices, faces = submesh.get_vertices_and_faces() vesselVisMesh2.SetVertices(vertices) vesselVisMesh2.SetFaces(np.zeros((3, 3), np.int32) if len(faces) == 0 else faces) vesselVisMesh2.SetNormals(None) # Global value that will be a dictionary with measurements mm = {} def process_measurements(measurements): """ Show measurements. Now the results are shown in a label object, but we could do anything here ... """ # Store in global for further processing mm.clear() mm.update(measurements) # Print in shell print("Measurements:") for key, val in measurements.items(): val = val.summary if isinstance(val, DeformInfo) else val print(key.rjust(16) + ": " + str(val)) # Show in labels index = 0 for key, val in measurements.items(): val = val.summary if isinstance(val, DeformInfo) else val val = "{:0.4g}".format(val) if isinstance(val, float) else val labelpool[index].text = key + ": " + str(val) index += 1 # Clean remaining labels for index in range(index, len(labelpool)): labelpool[index].text = "" def on_sliding(e): """ When the slider is moved, update the centerline position indicator. """ slider = e.owner pp = get_plane_points_from_centerline_index(slider.value) slider.line_plane.SetPoints(pp) def on_sliding_done(e): """ When the slider is released, update the whole thing. """ slider = e.owner pp = get_plane_points_from_centerline_index(slider.value) slider.line_plane.SetPoints(pp) take_measurements(False) # dont do volume def on_button_press(e): """ When the button is pressed, take measurements. """ take_measurements(True) def set_sliders(value_ref, value_ves): """ Set the sliders to a specific position, e.g. to reproduce a measurement. """ slider_ref.value = value_ref slider_ves.value = value_ves # Connect! slider_ref.eventSliding.Bind(on_sliding) slider_ves.eventSliding.Bind(on_sliding) slider_ref.eventSliderChanged.Bind(on_sliding_done) slider_ves.eventSliderChanged.Bind(on_sliding_done) button_go.eventMouseDown.Bind(on_button_press) #todo: visualize mesh with motion and use colors to represent radius change #todo: add torsion and angular rotation of centerline
[ "numpy.abs", "stentseg.utils.datahandling.loadmodel", "stentseg.utils.fitting.project_to_plane", "stentseg.utils.fitting.project_from_plane", "numpy.floor", "pirt.DeformationFieldBackward", "stentseg.utils.fitting.fit_ellipse", "stentseg.utils.fitting.area", "numpy.sin", "os.path.join", "visvis.processing.unwindFaces", "visvis.Label", "stentseg.utils.fitting.fit_plane", "visvis.PushButton", "lspeas.utils.deforminfo.DeformInfo", "stentseg.utils.datahandling.loadmesh", "numpy.linspace", "stentseg.motion.vis.create_mesh_with_abs_displacement", "pirt.interp.get_cubic_spline_coefs", "lspeas.utils.curvature.measure_curvature", "numpy.stack", "stentseg.utils.datahandling.loadvol", "numpy.ceil", "visvis.gcf", "numpy.asarray", "numpy.cos", "stentseg.utils.fitting.signed_distance_to_plane", "stentseg.utils.datahandling.select_dir", "os.getenv", "stentseg.stentdirect.stentgraph.create_mesh", "numpy.flip", "visvis.plot", "stentseg.utils.PointSet", "numpy.zeros", "stentseg.utils.fitting.sample_ellipse", "numpy.where", "lspeas.utils.meshlib.Mesh" ]
[((2749, 2960), 'stentseg.utils.datahandling.select_dir', 'select_dir', (['"""D:\\\\Profiles\\\\koenradesma\\\\SURFdrive\\\\UTdrive\\\\MedDataMimics\\\\LSPEAS_Mimics"""', '"""C:\\\\Users\\\\Maaike\\\\SURFdrive\\\\UTdrive\\\\MedDataMimics\\\\LSPEAS_Mimics"""', '"""C:\\\\stack\\\\data\\\\lspeas\\\\vaatwand"""'], {}), "(\n 'D:\\\\Profiles\\\\koenradesma\\\\SURFdrive\\\\UTdrive\\\\MedDataMimics\\\\LSPEAS_Mimics'\n , 'C:\\\\Users\\\\Maaike\\\\SURFdrive\\\\UTdrive\\\\MedDataMimics\\\\LSPEAS_Mimics',\n 'C:\\\\stack\\\\data\\\\lspeas\\\\vaatwand')\n", (2759, 2960), False, 'from stentseg.utils.datahandling import select_dir, loadvol, loadmodel, loadmesh\n'), ((2973, 3220), 'stentseg.utils.datahandling.select_dir', 'select_dir', (['"""C:\\\\stack\\\\data\\\\lspeas\\\\vaatwand"""', '"""D:\\\\Profiles\\\\koenradesma\\\\SURFdrive\\\\UTdrive\\\\LSPEAS_centerlines_terarecon"""', '"""C:\\\\Users\\\\Maaike\\\\SURFdrive\\\\UTdrive\\\\LSPEAS_centerlines_terarecon"""', '"""C:\\\\stack\\\\data\\\\lspeas\\\\vaatwand"""'], {}), "('C:\\\\stack\\\\data\\\\lspeas\\\\vaatwand',\n 'D:\\\\Profiles\\\\koenradesma\\\\SURFdrive\\\\UTdrive\\\\LSPEAS_centerlines_terarecon'\n , 'C:\\\\Users\\\\Maaike\\\\SURFdrive\\\\UTdrive\\\\LSPEAS_centerlines_terarecon',\n 'C:\\\\stack\\\\data\\\\lspeas\\\\vaatwand')\n", (2983, 3220), False, 'from stentseg.utils.datahandling import select_dir, loadvol, loadmodel, loadmesh\n'), ((6543, 6602), 'visvis.plot', 'vv.plot', (['centerline'], {'ms': '"""."""', 'ls': '""""""', 'mw': '(8)', 'mc': '"""b"""', 'alpha': '(0.5)'}), "(centerline, ms='.', ls='', mw=8, mc='b', alpha=0.5)\n", (6550, 6602), True, 'import visvis as vv\n'), ((7342, 7406), 'visvis.PushButton', 'vv.PushButton', (['container', '"""Take all measurements (incl. volume)"""'], {}), "(container, 'Take all measurements (incl. volume)')\n", (7355, 7406), True, 'import visvis as vv\n'), ((7700, 7764), 'visvis.plot', 'vv.plot', (['[]', '[]', '[]'], {'axes': 'axes1', 'ls': '"""-"""', 'lw': '(3)', 'lc': '"""w"""', 'alpha': '(0.9)'}), "([], [], [], axes=axes1, ls='-', lw=3, lc='w', alpha=0.9)\n", (7707, 7764), True, 'import visvis as vv\n'), ((7792, 7856), 'visvis.plot', 'vv.plot', (['[]', '[]', '[]'], {'axes': 'axes1', 'ls': '"""-"""', 'lw': '(3)', 'lc': '"""y"""', 'alpha': '(0.9)'}), "([], [], [], axes=axes1, ls='-', lw=3, lc='y', alpha=0.9)\n", (7799, 7856), True, 'import visvis as vv\n'), ((7956, 8027), 'visvis.plot', 'vv.plot', (['[]', '[]', '[]'], {'axes': 'axes1', 'ms': '"""."""', 'ls': '""""""', 'mw': '(8)', 'mc': '"""w"""', 'alpha': '(0.9)'}), "([], [], [], axes=axes1, ms='.', ls='', mw=8, mc='w', alpha=0.9)\n", (7963, 8027), True, 'import visvis as vv\n'), ((8052, 8123), 'visvis.plot', 'vv.plot', (['[]', '[]', '[]'], {'axes': 'axes1', 'ms': '"""."""', 'ls': '""""""', 'mw': '(8)', 'mc': '"""y"""', 'alpha': '(0.9)'}), "([], [], [], axes=axes1, ms='.', ls='', mw=8, mc='y', alpha=0.9)\n", (8059, 8123), True, 'import visvis as vv\n'), ((8212, 8268), 'visvis.plot', 'vv.plot', (['[]', '[]'], {'axes': 'axes2', 'ms': '"""."""', 'ls': '""""""', 'mw': '(8)', 'mc': '"""y"""'}), "([], [], axes=axes2, ms='.', ls='', mw=8, mc='y')\n", (8219, 8268), True, 'import visvis as vv\n'), ((8287, 8343), 'visvis.plot', 'vv.plot', (['[]', '[]'], {'axes': 'axes2', 'ms': '""""""', 'ls': '"""-"""', 'lw': '(2)', 'lc': '"""b"""'}), "([], [], axes=axes2, ms='', ls='-', lw=2, lc='b')\n", (8294, 8343), True, 'import visvis as vv\n'), ((8362, 8418), 'visvis.plot', 'vv.plot', (['[]', '[]'], {'axes': 'axes2', 'ms': '""""""', 'ls': '"""+"""', 'lw': '(2)', 'lc': '"""b"""'}), "([], [], axes=axes2, ms='', ls='+', lw=2, lc='b')\n", (8369, 8418), True, 'import visvis as vv\n'), ((1180, 1219), 'os.path.join', 'os.path.join', (['basedirCenterline', 'ptcode'], {}), '(basedirCenterline, ptcode)\n', (1192, 1219), False, 'import os\n'), ((1945, 1981), 'numpy.asarray', 'np.asarray', (['coordx'], {'dtype': 'np.float32'}), '(coordx, dtype=np.float32)\n', (1955, 1981), True, 'import numpy as np\n'), ((2001, 2037), 'numpy.asarray', 'np.asarray', (['coordy'], {'dtype': 'np.float32'}), '(coordy, dtype=np.float32)\n', (2011, 2037), True, 'import numpy as np\n'), ((2057, 2093), 'numpy.asarray', 'np.asarray', (['coordz'], {'dtype': 'np.float32'}), '(coordz, dtype=np.float32)\n', (2067, 2093), True, 'import numpy as np\n'), ((2113, 2141), 'numpy.flip', 'np.flip', (['centerlineZ'], {'axis': '(0)'}), '(centerlineZ, axis=0)\n', (2120, 2141), True, 'import numpy as np\n'), ((2606, 2637), 'os.getenv', 'os.getenv', (['"""LSPEAS_BASEDIR"""', '""""""'], {}), "('LSPEAS_BASEDIR', '')\n", (2615, 2637), False, 'import os\n'), ((6388, 6416), 'numpy.zeros', 'np.zeros', (['(6, 3)', 'np.float32'], {}), '((6, 3), np.float32)\n', (6396, 6416), True, 'import numpy as np\n'), ((6418, 6444), 'numpy.zeros', 'np.zeros', (['(3, 3)', 'np.int32'], {}), '((3, 3), np.int32)\n', (6426, 6444), True, 'import numpy as np\n'), ((6644, 6652), 'visvis.gcf', 'vv.gcf', ([], {}), '()\n', (6650, 6652), True, 'import visvis as vv\n'), ((6871, 6879), 'visvis.gcf', 'vv.gcf', ([], {}), '()\n', (6877, 6879), True, 'import visvis as vv\n'), ((7013, 7032), 'visvis.Label', 'vv.Label', (['container'], {}), '(container)\n', (7021, 7032), True, 'import visvis as vv\n'), ((10463, 10474), 'stentseg.utils.PointSet', 'PointSet', (['(3)'], {}), '(3)\n', (10471, 10474), False, 'from stentseg.utils import PointSet, fitting\n'), ((10523, 10552), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(12)'], {}), '(0, 2 * np.pi, 12)\n', (10534, 10552), True, 'import numpy as np\n'), ((10870, 10891), 'stentseg.utils.fitting.fit_plane', 'fitting.fit_plane', (['pp'], {}), '(pp)\n', (10887, 10891), False, 'from stentseg.utils import PointSet, fitting\n'), ((11097, 11145), 'stentseg.utils.fitting.signed_distance_to_plane', 'fitting.signed_distance_to_plane', (['ppvessel', 'abcd'], {}), '(ppvessel, abcd)\n', (11129, 11145), False, 'from stentseg.utils import PointSet, fitting\n'), ((11163, 11187), 'numpy.abs', 'np.abs', (['signed_distances'], {}), '(signed_distances)\n', (11169, 11187), True, 'import numpy as np\n'), ((11838, 11849), 'stentseg.utils.PointSet', 'PointSet', (['(3)'], {}), '(3)\n', (11846, 11849), False, 'from stentseg.utils import PointSet, fitting\n'), ((13731, 13769), 'stentseg.utils.fitting.project_from_plane', 'fitting.project_from_plane', (['pp2', 'plane'], {}), '(pp2, plane)\n', (13757, 13769), False, 'from stentseg.utils import PointSet, fitting\n'), ((17019, 17057), 'lspeas.utils.curvature.measure_curvature', 'measure_curvature', (['centerline', 'deforms'], {}), '(centerline, deforms)\n', (17036, 17057), False, 'from lspeas.utils.curvature import measure_curvature\n'), ((17096, 17122), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', (['curvature_mean'], {}), '(curvature_mean)\n', (17106, 17122), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((17160, 17185), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', (['curvature_max'], {}), '(curvature_max)\n', (17170, 17185), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((17227, 17256), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', (['curvature_max_pos'], {}), '(curvature_max_pos)\n', (17237, 17256), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((17379, 17403), 'stentseg.utils.fitting.fit_ellipse', 'fitting.fit_ellipse', (['pp2'], {}), '(pp2)\n', (17398, 17403), False, 'from stentseg.utils import PointSet, fitting\n'), ((17414, 17448), 'stentseg.utils.PointSet', 'PointSet', (['[ellipse[0], ellipse[1]]'], {}), '([ellipse[0], ellipse[1]])\n', (17422, 17448), False, 'from stentseg.utils import PointSet, fitting\n'), ((17513, 17549), 'stentseg.utils.fitting.sample_ellipse', 'fitting.sample_ellipse', (['ellipse', '(256)'], {}), '(ellipse, 256)\n', (17535, 17549), False, 'from stentseg.utils import PointSet, fitting\n'), ((18018, 18040), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', ([], {'unit': '"""mm2"""'}), "(unit='mm2')\n", (18028, 18040), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((19386, 19420), 'stentseg.utils.fitting.sample_ellipse', 'fitting.sample_ellipse', (['ellipse', '(4)'], {}), '(ellipse, 4)\n', (19408, 19420), False, 'from stentseg.utils import PointSet, fitting\n'), ((19499, 19520), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', ([], {'unit': '"""mm"""'}), "(unit='mm')\n", (19509, 19520), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((19569, 19590), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', ([], {'unit': '"""mm"""'}), "(unit='mm')\n", (19579, 19590), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((19639, 19660), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', ([], {'unit': '"""mm"""'}), "(unit='mm')\n", (19649, 19660), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((19709, 19730), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', ([], {'unit': '"""mm"""'}), "(unit='mm')\n", (19719, 19730), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((21586, 21597), 'stentseg.utils.PointSet', 'PointSet', (['(2)'], {}), '(2)\n', (21594, 21597), False, 'from stentseg.utils import PointSet, fitting\n'), ((4012, 4065), 'stentseg.utils.datahandling.loadvol', 'loadvol', (['basedir', 'ptcode', 'ctcode1', 'cropvol', '"""deforms"""'], {}), "(basedir, ptcode, ctcode1, cropvol, 'deforms')\n", (4019, 4065), False, 'from stentseg.utils.datahandling import select_dir, loadvol, loadmodel, loadmesh\n'), ((4663, 4707), 'stentseg.utils.datahandling.loadmesh', 'loadmesh', (['basedirMesh', 'ptcode[-3:]', 'filename'], {}), '(basedirMesh, ptcode[-3:], filename)\n', (4671, 4707), False, 'from stentseg.utils.datahandling import select_dir, loadvol, loadmodel, loadmesh\n'), ((4724, 4761), 'visvis.processing.unwindFaces', 'vv.processing.unwindFaces', (['vesselMesh'], {}), '(vesselMesh)\n', (4749, 4761), True, 'import visvis as vv\n'), ((4780, 4814), 'lspeas.utils.meshlib.Mesh', 'meshlib.Mesh', (['vesselMesh._vertices'], {}), '(vesselMesh._vertices)\n', (4792, 4814), False, 'from lspeas.utils import meshlib\n'), ((4995, 5051), 'stentseg.utils.datahandling.loadmodel', 'loadmodel', (['basedir', 'ptcode', 'ctcode1', 'cropname', 'modelname'], {}), '(basedir, ptcode, ctcode1, cropname, modelname)\n', (5004, 5051), False, 'from stentseg.utils.datahandling import select_dir, loadvol, loadmodel, loadmesh\n'), ((11291, 11314), 'numpy.where', 'np.where', (['(distances < 5)'], {}), '(distances < 5)\n', (11299, 11314), True, 'import numpy as np\n'), ((12436, 12479), 'stentseg.utils.fitting.project_to_plane', 'fitting.project_to_plane', (['sampled_pp3', 'abcd'], {}), '(sampled_pp3, abcd)\n', (12460, 12479), False, 'from stentseg.utils import PointSet, fitting\n'), ((12746, 12757), 'numpy.ceil', 'np.ceil', (['i1'], {}), '(i1)\n', (12753, 12757), True, 'import numpy as np\n'), ((12777, 12789), 'numpy.floor', 'np.floor', (['i2'], {}), '(i2)\n', (12785, 12789), True, 'import numpy as np\n'), ((14549, 14560), 'numpy.ceil', 'np.ceil', (['i1'], {}), '(i1)\n', (14556, 14560), True, 'import numpy as np\n'), ((14580, 14592), 'numpy.floor', 'np.floor', (['i2'], {}), '(i2)\n', (14588, 14592), True, 'import numpy as np\n'), ((20301, 20317), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (20309, 20317), True, 'import numpy as np\n'), ((20767, 20789), 'lspeas.utils.deforminfo.DeformInfo', 'DeformInfo', ([], {'unit': '"""mm3"""'}), "(unit='mm3')\n", (20777, 20789), False, 'from lspeas.utils.deforminfo import DeformInfo\n'), ((21534, 21565), 'stentseg.utils.fitting.sample_ellipse', 'fitting.sample_ellipse', (['ellipse'], {}), '(ellipse)\n', (21556, 21565), False, 'from stentseg.utils import PointSet, fitting\n'), ((1283, 1321), 'os.path.join', 'os.path.join', (['excel_location', 'filename'], {}), '(excel_location, filename)\n', (1295, 1321), False, 'import os\n'), ((3938, 3990), 'stentseg.utils.datahandling.loadvol', 'loadvol', (['basedir', 'ptcode', 'ctcode1', 'cropvol', '"""avgreg"""'], {}), "(basedir, ptcode, ctcode1, cropvol, 'avgreg')\n", (3945, 3990), False, 'from stentseg.utils.datahandling import select_dir, loadvol, loadmodel, loadmesh\n'), ((4168, 4206), 'pirt.DeformationFieldBackward', 'pirt.DeformationFieldBackward', (['*fields'], {}), '(*fields)\n', (4197, 4206), False, 'import pirt\n'), ((9201, 9247), 'pirt.interp.get_cubic_spline_coefs', 'pirt.interp.get_cubic_spline_coefs', (['t', '"""basic"""'], {}), "(t, 'basic')\n", (9235, 9247), False, 'import pirt\n'), ((14177, 14202), 'numpy.stack', 'np.stack', (['[dx, dy, dz]', '(1)'], {}), '([dx, dy, dz], 1)\n', (14185, 14202), True, 'import numpy as np\n'), ((14274, 14319), 'stentseg.utils.fitting.project_to_plane', 'fitting.project_to_plane', (['pp3_deformed', 'plane'], {}), '(pp3_deformed, plane)\n', (14298, 14319), False, 'from stentseg.utils import PointSet, fitting\n'), ((14983, 15008), 'numpy.stack', 'np.stack', (['[dx, dy, dz]', '(1)'], {}), '([dx, dy, dz], 1)\n', (14991, 15008), True, 'import numpy as np\n'), ((16540, 16566), 'numpy.zeros', 'np.zeros', (['(3, 3)', 'np.int32'], {}), '((3, 3), np.int32)\n', (16548, 16566), True, 'import numpy as np\n'), ((21959, 21985), 'numpy.zeros', 'np.zeros', (['(3, 3)', 'np.int32'], {}), '((3, 3), np.int32)\n', (21967, 21985), True, 'import numpy as np\n'), ((1405, 1446), 'os.path.join', 'os.path.join', (['basedirCenterline', 'filename'], {}), '(basedirCenterline, filename)\n', (1417, 1446), False, 'import os\n'), ((5138, 5164), 'stentseg.stentdirect.stentgraph.create_mesh', 'create_mesh', (['s1.model', '(0.7)'], {}), '(s1.model, 0.7)\n', (5149, 5164), False, 'from stentseg.stentdirect.stentgraph import create_mesh\n'), ((5228, 5299), 'stentseg.motion.vis.create_mesh_with_abs_displacement', 'create_mesh_with_abs_displacement', (['s1.model'], {'radius': '(0.7)', 'dim': 'dimensions'}), '(s1.model, radius=0.7, dim=dimensions)\n', (5261, 5299), False, 'from stentseg.motion.vis import create_mesh_with_abs_displacement\n'), ((17859, 17880), 'stentseg.utils.fitting.area', 'fitting.area', (['ellipse'], {}), '(ellipse)\n', (17871, 17880), False, 'from stentseg.utils import PointSet, fitting\n'), ((10605, 10614), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (10611, 10614), True, 'import numpy as np\n'), ((10577, 10586), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (10583, 10586), True, 'import numpy as np\n')]
from multiprocessing.sharedctypes import Value import numpy as np import warnings from ..core import Bullet from ..scene_maker import BulletSceneMaker from ..collision_checker import BulletCollisionChecker from ..robots import PandaDualArm import gym import pybullet as p from gym import spaces from gym.envs.registration import register class PandaDualArmEnvBase: def __init__(self, render=False, arm_distance=0.4, task_ll=[0, -0.5, 0], task_ul=[0.5, 0.5, 0.5]): self.is_render = render self.bullet = Bullet(render=render) self.scene_maker = BulletSceneMaker(self.bullet) self.robot = PandaDualArm( self.bullet, panda1_position=[0,arm_distance/2,0], panda2_position=[0,-arm_distance/2,0] ) self._make_env() self.checker = BulletCollisionChecker(self.bullet) self.task_ll = task_ll self.task_ul = task_ul def _make_env(self): self.scene_maker.create_plane(z_offset=-0.4) self.scene_maker.create_table(length=2.0, width=1.5, height=0.4, x_offset=0.5) self.bullet.place_visualizer( target_position=np.zeros(3), distance=1.6, yaw=45, pitch=-30 ) def render( self, mode: str, width: int = 720, height: int = 480, target_position: np.ndarray = np.zeros(3), distance: float = 1.4, yaw: float = 45, pitch: float = -30, roll: float = 0, ): return self.bullet.render( mode, width=width, height=height, target_position=target_position, distance=distance, yaw=yaw, pitch=pitch, roll=roll, ) def get_random_configuration(self, collision_free=False): if not collision_free: return self.robot.get_random_joint_angles(set=False) else: random_joint_angles = None with self.robot.no_set_joint(): for i in range(100): self.robot.get_random_joint_angles(set=True) if not self.checker.is_collision(): random_joint_angles = self.robot.get_joint_angles() break return random_joint_angles def get_random_free_configuration_in_taskspace(self, panda1_first=True): if panda1_first: first_robot = self.robot.panda1 second_robot = self.robot.panda2 else: first_robot = self.robot.panda2 second_robot = self.robot.panda1 for robot in [first_robot, second_robot]: while True: robot.get_random_joint_angles(set=True) ee_position = robot.get_ee_position() is_collision_free = not self.checker.is_collision() is_in_taskspace = np.all(self.task_ll < ee_position) \ & np.all(ee_position < self.task_ul) if is_collision_free & is_in_taskspace: break return self.robot.get_joint_angles() def reset(self): joints_init = self.get_random_configuration(collision_free=True) if joints_init is not None: self.robot.set_joint_angles(joints_init) return joints_init else: warnings.warn('env.reset() can`t find feasible reset configuration') return None def is_limit(self): joint_angles = self.robot.get_joint_angles() is_ll = np.any(joint_angles == self.robot.joint_ll) is_ul = np.any(joint_angles == self.robot.joint_ul) return is_ll | is_ul def is_collision(self, joint_angles=None): if joint_angles is None: joint_angles = self.robot.get_joint_angles() result = False with self.robot.no_set_joint(): self.robot.set_joint_angles(joint_angles) if self.checker.is_collision(): result = True return result | self.is_limit() def set_debug_mode(self): self.bullet.physics_client.configureDebugVisualizer(p.COV_ENABLE_GUI, 1) self.bullet.physics_client.configureDebugVisualizer(p.COV_ENABLE_MOUSE_PICKING, 1) # joint_angles = self.worker.get_joint_angles() # self.param_idxs = [] # for idx in self.worker.ctrl_joint_idxs: # name = self.worker.joint_info[idx]["joint_name"].decode("utf-8") # param_idx = self.bullet.physics_client.addUserDebugParameter( # name,-4,4, # joint_angles[idx] # ) # self.param_idxs.append(param_idx) def do_debug_mode(self): joint_param_values = [] for param in self.param_idxs: joint_param_values.append(p.readUserDebugParameter(param)) self.worker.set_joint_angles(joint_param_values) class PandaDualArmGymEnv(PandaDualArmEnvBase, gym.Env): """ joint """ def __init__(self, render=False, reward_type="joint", level=0.1): self.reward_type = reward_type self.level = level super().__init__(render=render, arm_distance=0.4) self.n_obs = 1 self.task_ll = np.array([-1.2, -1.2, -1.2]) self.task_ul = np.array([1.2, 1.2, 1.2]) self.observation_space = spaces.Dict(dict( observation=spaces.Box(-1, 1, shape=(1,), dtype=np.float32), achieved_goal=spaces.Box( self.robot.joint_ll, self.robot.joint_ul, shape=(self.robot.n_joints,), dtype=np.float32 ), desired_goal=spaces.Box( self.robot.joint_ll, self.robot.joint_ul, shape=(self.robot.n_joints,), dtype=np.float32 ), )) self.action_space = spaces.Box(-1.0, 1.0, shape=(self.robot.n_joints,), dtype=np.float32) self._goal = None self.eps = 0.1 self.max_joint_change = 0.1 @property def goal(self): return self._goal.copy() @goal.setter def goal(self, arr: np.ndarray): self._goal = arr def get_observation(self): return dict( observation=0., achieved_goal=self.robot.get_joint_angles(), desired_goal=self.goal, ) def set_action(self, action: np.ndarray): joint_prev = self.robot.get_joint_angles() action = action.copy() action = np.clip(action, self.action_space.low, self.action_space.high) joint_target = self.robot.get_joint_angles() joint_target += action * self.max_joint_change joint_target = np.clip(joint_target, self.robot.joint_ll, self.robot.joint_ul) if self.checker.is_collision() & self.is_limit(): self.robot.set_joint_angles(joint_prev) self._collision_flag = True self._collision_flag = False self.robot.set_joint_angles(joint_target) def is_success(self, joint_curr: np.ndarray, joint_goal: np.ndarray): return np.linalg.norm(joint_curr - joint_goal) < self.eps def reset(self): random_joint1 = self.get_random_configuration(collision_free=True) while True: random_joint2 = self.get_random_configuration(collision_free=False) goal = random_joint1 + (random_joint2 - random_joint1) * self.level if not self.is_collision(goal): self.robot.set_joint_angles(goal) goal_ee = self.robot.get_ee_position() break self.start = random_joint1 self.goal = goal self.robot.set_joint_angles(self.start) start_ee = self.robot.get_ee_position() if self.is_render: ee1, ee2 = start_ee[:3], start_ee[3:] self.scene_maker.view_position("goal1", goal_ee[:3]) self.scene_maker.view_position("goal2", goal_ee[3:]) self.scene_maker.view_position("curr1", start_ee[:3]) self.scene_maker.view_position("curr2", start_ee[3:]) return self.get_observation() def step(self, action: np.ndarray): self.set_action(action) obs_ = self.get_observation() done = False info = dict( is_success=self.is_success(obs_["achieved_goal"], obs_["desired_goal"]), actions=action.copy(), collisions=self._collision_flag, ) reward = self.compute_reward(obs_["achieved_goal"], obs_["desired_goal"], info) if self.is_render: self.scene_maker.view_position("curr1", self.robot.get_ee_position()[:3]) self.scene_maker.view_position("curr2", self.robot.get_ee_position()[3:]) return obs_, reward, done, info def compute_reward(self, achieved_goal, desired_goal, info): if len(achieved_goal.shape) == 2: actions = np.array([i["actions"] for i in info]) collisions = np.array([i["collisions"] for i in info]) else: actions = info["actions"] collisions = info["collisions"] r = - np.linalg.norm(achieved_goal-desired_goal, axis=-1) if "action" in self.reward_type: r -= np.linalg.norm(actions, axis=-1) / 10 if "col" in self.reward_type: r -= collisions * 1. return r class PandaDualArmGymEnvSingle(PandaDualArmEnvBase, gym.Env): """ joint """ def __init__(self, render=False, reward_type="joint", arm="left", level=1.0): self.arm = arm self.reward_type = reward_type self.level = level super().__init__(render=render, arm_distance=0.4) if self.arm == "left": self.worker = self.robot.panda1 self.coworker = self.robot.panda2 elif self.arm == "right": self.worker = self.robot.panda2 self.coworker = self.robot.panda1 self.n_obs = 7 #self.task_ll = np.array([-1.2, -1.2, -1.2]) #self.task_ul = np.array([1.2, 1.2, 1.2]) self.observation_space = spaces.Dict(dict( observation=spaces.Box( low=self.coworker.joint_ll, high=self.coworker.joint_ul, shape=(self.coworker.n_joints,), dtype=np.float32 ), achieved_goal=spaces.Box( self.worker.joint_ll, self.worker.joint_ul, shape=(self.worker.n_joints,), dtype=np.float32 ), desired_goal=spaces.Box( self.worker.joint_ll, self.worker.joint_ul, shape=(self.worker.n_joints,), dtype=np.float32 ), )) self.action_space = spaces.Box(-1.0, 1.0, shape=(self.worker.n_joints,), dtype=np.float32) self._goal = None self.eps = 0.1 self.max_joint_change = 0.1 @property def goal(self): return self._goal.copy() @goal.setter def goal(self, arr: np.ndarray): self._goal = arr # def get_worker_joint_angle(self): # if self.arm == "left": # return self.robot.get_joint_angles()[:7] # elif self.arm == "right": # return self.robot.get_joint_angles()[7:] # raise ValueError("wrong arm type") # def get_coworker_joint_angle(self): # if self.arm == "left": # return self.robot.get_joint_angles()[7:] # elif self.arm == "right": # return self.robot.get_joint_angles()[:7] # raise ValueError("wrong arm type") # def set_worker_joint_angle(self, worker_joint_angles): # curr_joint_angles = self.robot.get_joint_angles() # if self.arm == "left": # target_joint_angles = np.hstack([worker_joint_angles, curr_joint_angles[7:]]) # elif self.arm == "right": # target_joint_angles = np.hstack([curr_joint_angles[:7], worker_joint_angles]) # else: # raise ValueError("wrong arm type") # self.robot.set_joint_angles(target_joint_angles) def get_observation(self): return dict( observation=self.coworker.get_joint_angles(), achieved_goal=self.worker.get_joint_angles(), desired_goal=self.goal, ) def set_action(self, action: np.ndarray): joint_prev = self.worker.get_joint_angles() action = action.copy() action = np.clip(action, self.action_space.low, self.action_space.high) joint_target = joint_prev.copy() joint_target += action * self.max_joint_change self.worker.set_joint_angles(joint_target) if self.checker.is_collision(): self.worker.set_joint_angles(joint_prev) self._collision_flag = True else: self._collision_flag = False def is_success(self, joint_curr: np.ndarray, joint_goal: np.ndarray): return np.linalg.norm(joint_curr - joint_goal) < self.eps def reset(self): random_start_joints = self.get_random_configuration(collision_free=True) if self.arm == "left": random_joints_worker = random_start_joints[:7] random_joints_coworker = random_start_joints[7:] elif self.arm == "right": random_joints_worker = random_start_joints[7:] random_joints_coworker = random_start_joints[:7] while True: random_joints_worker2 = self.worker.get_random_joint_angles(set=True) #random_joint2 = self.get_random_configuration(collision_free=False) goal = random_joints_worker + (random_joints_worker2 - random_joints_worker) * self.level self.worker.set_joint_angles(goal) self.coworker.set_joint_angles(random_joints_coworker) if not self.is_collision(): goal_ee = self.robot.get_ee_position() break self.start = random_joints_worker self.goal = goal self.robot.set_joint_angles(random_start_joints) start_ee = self.robot.get_ee_position() if self.is_render: self.scene_maker.view_position("goal1", goal_ee[:3]) self.scene_maker.view_position("goal2", goal_ee[3:]) self.scene_maker.view_position("curr1", start_ee[:3]) self.scene_maker.view_position("curr2", start_ee[3:]) return self.get_observation() def step(self, action: np.ndarray): self.set_action(action) obs_ = self.get_observation() done = False info = dict( is_success=self.is_success(obs_["achieved_goal"], obs_["desired_goal"]), actions=action.copy(), collisions=self._collision_flag, ) reward = self.compute_reward(obs_["achieved_goal"], obs_["desired_goal"], info) if self.is_render: self.scene_maker.view_position("curr1", self.robot.get_ee_position()[:3]) self.scene_maker.view_position("curr2", self.robot.get_ee_position()[3:]) return obs_, reward, done, info def compute_reward(self, achieved_goal, desired_goal, info): if len(achieved_goal.shape) == 2: actions = np.array([i["actions"] for i in info]) collisions = np.array([i["collisions"] for i in info]) else: actions = info["actions"] collisions = info["collisions"] r = - np.linalg.norm(achieved_goal-desired_goal, axis=-1) if "action" in self.reward_type: r -= np.linalg.norm(actions, axis=-1) / 10 if "col" in self.reward_type: r -= collisions * 1. return r register( id='MyPandaDualArmReach-v0', entry_point='pybullet_wrapper:PandaDualArmGymEnv', max_episode_steps=100, ) register( id='MyPandaDualArmReach-v1', entry_point='pybullet_wrapper:PandaDualArmGymEnvSingle', max_episode_steps=100, )
[ "numpy.zeros", "numpy.all", "numpy.clip", "numpy.any", "pybullet.readUserDebugParameter", "numpy.array", "gym.spaces.Box", "numpy.linalg.norm", "warnings.warn", "gym.envs.registration.register" ]
[((15825, 15941), 'gym.envs.registration.register', 'register', ([], {'id': '"""MyPandaDualArmReach-v0"""', 'entry_point': '"""pybullet_wrapper:PandaDualArmGymEnv"""', 'max_episode_steps': '(100)'}), "(id='MyPandaDualArmReach-v0', entry_point=\n 'pybullet_wrapper:PandaDualArmGymEnv', max_episode_steps=100)\n", (15833, 15941), False, 'from gym.envs.registration import register\n'), ((15952, 16074), 'gym.envs.registration.register', 'register', ([], {'id': '"""MyPandaDualArmReach-v1"""', 'entry_point': '"""pybullet_wrapper:PandaDualArmGymEnvSingle"""', 'max_episode_steps': '(100)'}), "(id='MyPandaDualArmReach-v1', entry_point=\n 'pybullet_wrapper:PandaDualArmGymEnvSingle', max_episode_steps=100)\n", (15960, 16074), False, 'from gym.envs.registration import register\n'), ((1389, 1400), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1397, 1400), True, 'import numpy as np\n'), ((3594, 3637), 'numpy.any', 'np.any', (['(joint_angles == self.robot.joint_ll)'], {}), '(joint_angles == self.robot.joint_ll)\n', (3600, 3637), True, 'import numpy as np\n'), ((3654, 3697), 'numpy.any', 'np.any', (['(joint_angles == self.robot.joint_ul)'], {}), '(joint_angles == self.robot.joint_ul)\n', (3660, 3697), True, 'import numpy as np\n'), ((5276, 5304), 'numpy.array', 'np.array', (['[-1.2, -1.2, -1.2]'], {}), '([-1.2, -1.2, -1.2])\n', (5284, 5304), True, 'import numpy as np\n'), ((5328, 5353), 'numpy.array', 'np.array', (['[1.2, 1.2, 1.2]'], {}), '([1.2, 1.2, 1.2])\n', (5336, 5353), True, 'import numpy as np\n'), ((5938, 6007), 'gym.spaces.Box', 'spaces.Box', (['(-1.0)', '(1.0)'], {'shape': '(self.robot.n_joints,)', 'dtype': 'np.float32'}), '(-1.0, 1.0, shape=(self.robot.n_joints,), dtype=np.float32)\n', (5948, 6007), False, 'from gym import spaces\n'), ((6579, 6641), 'numpy.clip', 'np.clip', (['action', 'self.action_space.low', 'self.action_space.high'], {}), '(action, self.action_space.low, self.action_space.high)\n', (6586, 6641), True, 'import numpy as np\n'), ((6773, 6836), 'numpy.clip', 'np.clip', (['joint_target', 'self.robot.joint_ll', 'self.robot.joint_ul'], {}), '(joint_target, self.robot.joint_ll, self.robot.joint_ul)\n', (6780, 6836), True, 'import numpy as np\n'), ((10883, 10953), 'gym.spaces.Box', 'spaces.Box', (['(-1.0)', '(1.0)'], {'shape': '(self.worker.n_joints,)', 'dtype': 'np.float32'}), '(-1.0, 1.0, shape=(self.worker.n_joints,), dtype=np.float32)\n', (10893, 10953), False, 'from gym import spaces\n'), ((12596, 12658), 'numpy.clip', 'np.clip', (['action', 'self.action_space.low', 'self.action_space.high'], {}), '(action, self.action_space.low, self.action_space.high)\n', (12603, 12658), True, 'import numpy as np\n'), ((3407, 3475), 'warnings.warn', 'warnings.warn', (['"""env.reset() can`t find feasible reset configuration"""'], {}), "('env.reset() can`t find feasible reset configuration')\n", (3420, 3475), False, 'import warnings\n'), ((7164, 7203), 'numpy.linalg.norm', 'np.linalg.norm', (['(joint_curr - joint_goal)'], {}), '(joint_curr - joint_goal)\n', (7178, 7203), True, 'import numpy as np\n'), ((8982, 9020), 'numpy.array', 'np.array', (["[i['actions'] for i in info]"], {}), "([i['actions'] for i in info])\n", (8990, 9020), True, 'import numpy as np\n'), ((9046, 9087), 'numpy.array', 'np.array', (["[i['collisions'] for i in info]"], {}), "([i['collisions'] for i in info])\n", (9054, 9087), True, 'import numpy as np\n'), ((9198, 9251), 'numpy.linalg.norm', 'np.linalg.norm', (['(achieved_goal - desired_goal)'], {'axis': '(-1)'}), '(achieved_goal - desired_goal, axis=-1)\n', (9212, 9251), True, 'import numpy as np\n'), ((13084, 13123), 'numpy.linalg.norm', 'np.linalg.norm', (['(joint_curr - joint_goal)'], {}), '(joint_curr - joint_goal)\n', (13098, 13123), True, 'import numpy as np\n'), ((15353, 15391), 'numpy.array', 'np.array', (["[i['actions'] for i in info]"], {}), "([i['actions'] for i in info])\n", (15361, 15391), True, 'import numpy as np\n'), ((15417, 15458), 'numpy.array', 'np.array', (["[i['collisions'] for i in info]"], {}), "([i['collisions'] for i in info])\n", (15425, 15458), True, 'import numpy as np\n'), ((15569, 15622), 'numpy.linalg.norm', 'np.linalg.norm', (['(achieved_goal - desired_goal)'], {'axis': '(-1)'}), '(achieved_goal - desired_goal, axis=-1)\n', (15583, 15622), True, 'import numpy as np\n'), ((1150, 1161), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1158, 1161), True, 'import numpy as np\n'), ((4866, 4897), 'pybullet.readUserDebugParameter', 'p.readUserDebugParameter', (['param'], {}), '(param)\n', (4890, 4897), True, 'import pybullet as p\n'), ((9309, 9341), 'numpy.linalg.norm', 'np.linalg.norm', (['actions'], {'axis': '(-1)'}), '(actions, axis=-1)\n', (9323, 9341), True, 'import numpy as np\n'), ((15680, 15712), 'numpy.linalg.norm', 'np.linalg.norm', (['actions'], {'axis': '(-1)'}), '(actions, axis=-1)\n', (15694, 15712), True, 'import numpy as np\n'), ((2931, 2965), 'numpy.all', 'np.all', (['(self.task_ll < ee_position)'], {}), '(self.task_ll < ee_position)\n', (2937, 2965), True, 'import numpy as np\n'), ((3004, 3038), 'numpy.all', 'np.all', (['(ee_position < self.task_ul)'], {}), '(ee_position < self.task_ul)\n', (3010, 3038), True, 'import numpy as np\n'), ((5429, 5476), 'gym.spaces.Box', 'spaces.Box', (['(-1)', '(1)'], {'shape': '(1,)', 'dtype': 'np.float32'}), '(-1, 1, shape=(1,), dtype=np.float32)\n', (5439, 5476), False, 'from gym import spaces\n'), ((5508, 5613), 'gym.spaces.Box', 'spaces.Box', (['self.robot.joint_ll', 'self.robot.joint_ul'], {'shape': '(self.robot.n_joints,)', 'dtype': 'np.float32'}), '(self.robot.joint_ll, self.robot.joint_ul, shape=(self.robot.\n n_joints,), dtype=np.float32)\n', (5518, 5613), False, 'from gym import spaces\n'), ((5716, 5821), 'gym.spaces.Box', 'spaces.Box', (['self.robot.joint_ll', 'self.robot.joint_ul'], {'shape': '(self.robot.n_joints,)', 'dtype': 'np.float32'}), '(self.robot.joint_ll, self.robot.joint_ul, shape=(self.robot.\n n_joints,), dtype=np.float32)\n', (5726, 5821), False, 'from gym import spaces\n'), ((10215, 10338), 'gym.spaces.Box', 'spaces.Box', ([], {'low': 'self.coworker.joint_ll', 'high': 'self.coworker.joint_ul', 'shape': '(self.coworker.n_joints,)', 'dtype': 'np.float32'}), '(low=self.coworker.joint_ll, high=self.coworker.joint_ul, shape=(\n self.coworker.n_joints,), dtype=np.float32)\n', (10225, 10338), False, 'from gym import spaces\n'), ((10447, 10555), 'gym.spaces.Box', 'spaces.Box', (['self.worker.joint_ll', 'self.worker.joint_ul'], {'shape': '(self.worker.n_joints,)', 'dtype': 'np.float32'}), '(self.worker.joint_ll, self.worker.joint_ul, shape=(self.worker.\n n_joints,), dtype=np.float32)\n', (10457, 10555), False, 'from gym import spaces\n'), ((10658, 10766), 'gym.spaces.Box', 'spaces.Box', (['self.worker.joint_ll', 'self.worker.joint_ul'], {'shape': '(self.worker.n_joints,)', 'dtype': 'np.float32'}), '(self.worker.joint_ll, self.worker.joint_ul, shape=(self.worker.\n n_joints,), dtype=np.float32)\n', (10668, 10766), False, 'from gym import spaces\n')]
import gym import gym_flowers import numpy as np import os os.environ['LD_LIBRARY_PATH']+=':'+os.environ['HOME']+'/.mujoco/mjpro150/bin:' # env = gym.make('ModularArm012-v0') env = gym.make('MultiTaskFetchArm4-v5') obs = env.reset() goal = np.array([-1,-1,-1]) task = 2 env.unwrapped.reset_task_goal(goal, task) env.render() task_id = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14],[15,16,17],[18,19,20],[21,22,23], [24,25,26], [27,28,29],[30,31,32],[33,34,35]] n_tasks = env.unwrapped.nb_tasks for i in range(100000): act = np.array([1,0,0,0.1]) obs = env.step(act) # print(obs[0]['observation'][9:15]) for i in range(n_tasks): ag = obs[0]['achieved_goal'] g = np.zeros([3 * n_tasks]) g[task_id[i]] = obs[0]['desired_goal'][task_id[task]] task_descr = np.zeros([n_tasks]) task_descr[i] = 1 r = env.unwrapped.compute_reward(ag, g, task_descr=task_descr, info={}) print('Task ', i, 'reward', r) # print(ag) # print(g) env.render()
[ "numpy.zeros", "numpy.array", "gym.make" ]
[((182, 215), 'gym.make', 'gym.make', (['"""MultiTaskFetchArm4-v5"""'], {}), "('MultiTaskFetchArm4-v5')\n", (190, 215), False, 'import gym\n'), ((241, 263), 'numpy.array', 'np.array', (['[-1, -1, -1]'], {}), '([-1, -1, -1])\n', (249, 263), True, 'import numpy as np\n'), ((543, 567), 'numpy.array', 'np.array', (['[1, 0, 0, 0.1]'], {}), '([1, 0, 0, 0.1])\n', (551, 567), True, 'import numpy as np\n'), ((708, 731), 'numpy.zeros', 'np.zeros', (['[3 * n_tasks]'], {}), '([3 * n_tasks])\n', (716, 731), True, 'import numpy as np\n'), ((815, 834), 'numpy.zeros', 'np.zeros', (['[n_tasks]'], {}), '([n_tasks])\n', (823, 834), True, 'import numpy as np\n')]
import numpy as np import os import keras from keras.applications import inception_v3, inception_resnet_v2, vgg19 from keras.models import Sequential from keras.layers.core import Dense, Flatten from keras.layers.convolutional import Conv2D from keras.optimizers import Adam def build_model(input_shape, with_one_by_one=True, keep_training_pretrained=False, pretrained_class=vgg19.VGG19, num_dense=64, ): model = Sequential() # # # 1x1 convolution to make sure we only have 3 channels n_channels_for_pretrained = 3 one_by_one = Conv2D(n_channels_for_pretrained, 1, padding="same", input_shape=input_shape) one_by_one.trainable = with_one_by_one model.add(one_by_one) pretrained_input_shape = tuple([n_channels_for_pretrained, *input_shape[1:]]) pretrained_layers = pretrained_class( include_top=False, input_shape=pretrained_input_shape ) for layer in pretrained_layers.layers: layer.trainable = keep_training_pretrained model.add(pretrained_layers) model.add(Flatten()) model.add(Dense(2*num_dense, activation=None)) model.add(keras.layers.PReLU()) model.add(Dense(num_dense, activation=None)) model.add(keras.layers.PReLU()) model.add(Dense(1, activation=None)) return model def compile_model(model, logger_filename, adam_lr=0.001, ): learning_rate = adam_lr adam = Adam(lr=learning_rate) model.compile(loss="mean_squared_error", optimizer=adam, ) # can only manually set weights _after_ compiling one_by_one_weights = np.zeros((1, 1, 5, 3)) for i in range(3): # by default, irg should be RGB one_by_one_weights[0, 0, 3-i, i] = 1. model.layers[0].set_weights( [one_by_one_weights, np.zeros(3)]) if os.path.exists(logger_filename): logger_filename_tmp = logger_filename + ".old" os.rename(logger_filename, logger_filename_tmp) return model
[ "keras.layers.core.Dense", "os.rename", "numpy.zeros", "keras.optimizers.Adam", "os.path.exists", "keras.layers.PReLU", "keras.layers.convolutional.Conv2D", "keras.layers.core.Flatten", "keras.models.Sequential" ]
[((486, 498), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (496, 498), False, 'from keras.models import Sequential\n'), ((614, 691), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['n_channels_for_pretrained', '(1)'], {'padding': '"""same"""', 'input_shape': 'input_shape'}), "(n_channels_for_pretrained, 1, padding='same', input_shape=input_shape)\n", (620, 691), False, 'from keras.layers.convolutional import Conv2D\n'), ((1570, 1592), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'learning_rate'}), '(lr=learning_rate)\n', (1574, 1592), False, 'from keras.optimizers import Adam\n'), ((1773, 1795), 'numpy.zeros', 'np.zeros', (['(1, 1, 5, 3)'], {}), '((1, 1, 5, 3))\n', (1781, 1795), True, 'import numpy as np\n'), ((1998, 2029), 'os.path.exists', 'os.path.exists', (['logger_filename'], {}), '(logger_filename)\n', (2012, 2029), False, 'import os\n'), ((1189, 1198), 'keras.layers.core.Flatten', 'Flatten', ([], {}), '()\n', (1196, 1198), False, 'from keras.layers.core import Dense, Flatten\n'), ((1214, 1251), 'keras.layers.core.Dense', 'Dense', (['(2 * num_dense)'], {'activation': 'None'}), '(2 * num_dense, activation=None)\n', (1219, 1251), False, 'from keras.layers.core import Dense, Flatten\n'), ((1265, 1285), 'keras.layers.PReLU', 'keras.layers.PReLU', ([], {}), '()\n', (1283, 1285), False, 'import keras\n'), ((1301, 1334), 'keras.layers.core.Dense', 'Dense', (['num_dense'], {'activation': 'None'}), '(num_dense, activation=None)\n', (1306, 1334), False, 'from keras.layers.core import Dense, Flatten\n'), ((1350, 1370), 'keras.layers.PReLU', 'keras.layers.PReLU', ([], {}), '()\n', (1368, 1370), False, 'import keras\n'), ((1386, 1411), 'keras.layers.core.Dense', 'Dense', (['(1)'], {'activation': 'None'}), '(1, activation=None)\n', (1391, 1411), False, 'from keras.layers.core import Dense, Flatten\n'), ((2094, 2141), 'os.rename', 'os.rename', (['logger_filename', 'logger_filename_tmp'], {}), '(logger_filename, logger_filename_tmp)\n', (2103, 2141), False, 'import os\n'), ((1976, 1987), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1984, 1987), True, 'import numpy as np\n')]
import os os.chdir('osmFISH_Ziesel/') import numpy as np import pandas as pd import matplotlib matplotlib.use('qt5agg') matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 import matplotlib.pyplot as plt import scipy.stats as st from matplotlib.lines import Line2D import pickle with open ('data/SpaGE_pkl/osmFISH_Cortex.pkl', 'rb') as f: datadict = pickle.load(f) osmFISH_data = datadict['osmFISH_data'] del datadict Gene_Order = osmFISH_data.columns ### SpaGE SpaGE_imputed_Ziesel = pd.read_csv('Results/SpaGE_LeaveOneOut.csv',header=0,index_col=0,sep=',') SpaGE_imputed_Ziesel = SpaGE_imputed_Ziesel.loc[:,Gene_Order] SpaGE_Corr_Ziesel = pd.Series(index = Gene_Order) for i in Gene_Order: SpaGE_Corr_Ziesel[i] = st.spearmanr(osmFISH_data[i],SpaGE_imputed_Ziesel[i])[0] ### gimVI gimVI_imputed_Ziesel = pd.read_csv('Results/gimVI_LeaveOneOut.csv',header=0,index_col=0,sep=',') gimVI_imputed_Ziesel = gimVI_imputed_Ziesel.loc[:,[x.upper() for x in np.array(Gene_Order,dtype='str')]] gimVI_Corr_Ziesel = pd.Series(index = Gene_Order) for i in Gene_Order: gimVI_Corr_Ziesel[i] = st.spearmanr(osmFISH_data[i],gimVI_imputed_Ziesel[str(i).upper()])[0] gimVI_Corr_Ziesel[np.isnan(gimVI_Corr_Ziesel)] = 0 ### Seurat Seurat_imputed_Ziesel = pd.read_csv('Results/Seurat_LeaveOneOut.csv',header=0,index_col=0,sep=',').T Seurat_imputed_Ziesel = Seurat_imputed_Ziesel.loc[:,Gene_Order] Seurat_Corr_Ziesel = pd.Series(index = Gene_Order) for i in Gene_Order: Seurat_Corr_Ziesel[i] = st.spearmanr(osmFISH_data[i],Seurat_imputed_Ziesel[i])[0] ### Liger Liger_imputed_Ziesel = pd.read_csv('Results/Liger_LeaveOneOut.csv',header=0,index_col=0,sep=',').T Liger_imputed_Ziesel = Liger_imputed_Ziesel.loc[:,Gene_Order] Liger_Corr_Ziesel = pd.Series(index = Gene_Order) for i in Gene_Order: Liger_Corr_Ziesel[i] = st.spearmanr(osmFISH_data[i],Liger_imputed_Ziesel[i])[0] Liger_Corr_Ziesel[np.isnan(Liger_Corr_Ziesel)] = 0 os.chdir('osmFISH_AllenVISp/') ### SpaGE SpaGE_imputed_AllenVISp = pd.read_csv('Results/SpaGE_LeaveOneOut.csv',header=0,index_col=0,sep=',') SpaGE_imputed_AllenVISp = SpaGE_imputed_AllenVISp.loc[:,Gene_Order] SpaGE_Corr_AllenVISp = pd.Series(index = Gene_Order) for i in Gene_Order: SpaGE_Corr_AllenVISp[i] = st.spearmanr(osmFISH_data[i],SpaGE_imputed_AllenVISp[i])[0] ### gimVI gimVI_imputed_AllenVISp = pd.read_csv('Results/gimVI_LeaveOneOut.csv',header=0,index_col=0,sep=',') gimVI_imputed_AllenVISp = gimVI_imputed_AllenVISp.loc[:,[x.upper() for x in np.array(Gene_Order,dtype='str')]] gimVI_Corr_AllenVISp = pd.Series(index = Gene_Order) for i in Gene_Order: gimVI_Corr_AllenVISp[i] = st.spearmanr(osmFISH_data[i],gimVI_imputed_AllenVISp[str(i).upper()])[0] gimVI_Corr_AllenVISp[np.isnan(gimVI_Corr_AllenVISp)] = 0 ### Seurat Seurat_imputed_AllenVISp = pd.read_csv('Results/Seurat_LeaveOneOut.csv',header=0,index_col=0,sep=',').T Seurat_imputed_AllenVISp = Seurat_imputed_AllenVISp.loc[:,Gene_Order] Seurat_Corr_AllenVISp = pd.Series(index = Gene_Order) for i in Gene_Order: Seurat_Corr_AllenVISp[i] = st.spearmanr(osmFISH_data[i],Seurat_imputed_AllenVISp[i])[0] ### Liger Liger_imputed_AllenVISp = pd.read_csv('Results/Liger_LeaveOneOut.csv',header=0,index_col=0,sep=',').T Liger_imputed_AllenVISp = Liger_imputed_AllenVISp.loc[:,Gene_Order] Liger_Corr_AllenVISp = pd.Series(index = Gene_Order) for i in Gene_Order: Liger_Corr_AllenVISp[i] = st.spearmanr(osmFISH_data[i],Liger_imputed_AllenVISp[i])[0] Liger_Corr_AllenVISp[np.isnan(Liger_Corr_AllenVISp)] = 0 os.chdir('osmFISH_AllenSSp/') ### SpaGE SpaGE_imputed_AllenSSp = pd.read_csv('Results/SpaGE_LeaveOneOut.csv',header=0,index_col=0,sep=',') SpaGE_imputed_AllenSSp = SpaGE_imputed_AllenSSp.loc[:,Gene_Order] SpaGE_Corr_AllenSSp = pd.Series(index = Gene_Order) for i in Gene_Order: SpaGE_Corr_AllenSSp[i] = st.spearmanr(osmFISH_data[i],SpaGE_imputed_AllenSSp[i])[0] ### gimVI gimVI_imputed_AllenSSp = pd.read_csv('Results/gimVI_LeaveOneOut.csv',header=0,index_col=0,sep=',') gimVI_imputed_AllenSSp = gimVI_imputed_AllenSSp.loc[:,[x.upper() for x in np.array(Gene_Order,dtype='str')]] gimVI_Corr_AllenSSp = pd.Series(index = Gene_Order) for i in Gene_Order: gimVI_Corr_AllenSSp[i] = st.spearmanr(osmFISH_data[i],gimVI_imputed_AllenSSp[str(i).upper()])[0] gimVI_Corr_AllenSSp[np.isnan(gimVI_Corr_AllenSSp)] = 0 ### Seurat Seurat_imputed_AllenSSp = pd.read_csv('Results/Seurat_LeaveOneOut.csv',header=0,index_col=0,sep=',').T Seurat_imputed_AllenSSp = Seurat_imputed_AllenSSp.loc[:,Gene_Order] Seurat_Corr_AllenSSp = pd.Series(index = Gene_Order) for i in Gene_Order: Seurat_Corr_AllenSSp[i] = st.spearmanr(osmFISH_data[i],Seurat_imputed_AllenSSp[i])[0] ### Liger Liger_imputed_AllenSSp = pd.read_csv('Results/Liger_LeaveOneOut.csv',header=0,index_col=0,sep=',').T Liger_imputed_AllenSSp = Liger_imputed_AllenSSp.loc[:,Gene_Order] Liger_Corr_AllenSSp = pd.Series(index = Gene_Order) for i in Gene_Order: Liger_Corr_AllenSSp[i] = st.spearmanr(osmFISH_data[i],Liger_imputed_AllenSSp[i])[0] Liger_Corr_AllenSSp[np.isnan(Liger_Corr_AllenSSp)] = 0 ### Comparison plots plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(5, 3)) ax.boxplot([SpaGE_Corr_Ziesel, Seurat_Corr_Ziesel, Liger_Corr_Ziesel,gimVI_Corr_Ziesel], positions = [1,5,9,13],boxprops=dict(color='red'), capprops=dict(color='red'),whiskerprops=dict(color='red'),flierprops=dict(color='red', markeredgecolor='red'), medianprops=dict(color='red')) ax.boxplot([SpaGE_Corr_AllenVISp, Seurat_Corr_AllenVISp, Liger_Corr_AllenVISp,gimVI_Corr_AllenVISp], positions = [2,6,10,14],boxprops=dict(color='blue'), capprops=dict(color='blue'),whiskerprops=dict(color='blue'),flierprops=dict(color='blue', markeredgecolor='blue'), medianprops=dict(color='blue')) ax.boxplot([SpaGE_Corr_AllenSSp, Seurat_Corr_AllenSSp, Liger_Corr_AllenSSp,gimVI_Corr_AllenSSp], positions = [3,7,11,15],boxprops=dict(color='purple'), capprops=dict(color='purple'),whiskerprops=dict(color='purple'),flierprops=dict(color='purple', markeredgecolor='purple'), medianprops=dict(color='purple')) y = SpaGE_Corr_Ziesel x = np.random.normal(1, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = SpaGE_Corr_AllenVISp x = np.random.normal(2, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = SpaGE_Corr_AllenSSp x = np.random.normal(3, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = Seurat_Corr_Ziesel x = np.random.normal(5, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = Seurat_Corr_AllenVISp x = np.random.normal(6, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = Seurat_Corr_AllenSSp x = np.random.normal(7, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = Liger_Corr_Ziesel x = np.random.normal(9, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = Liger_Corr_AllenVISp x = np.random.normal(10, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = Liger_Corr_AllenSSp x = np.random.normal(11, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = gimVI_Corr_Ziesel x = np.random.normal(13, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = gimVI_Corr_AllenVISp x = np.random.normal(14, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) y = gimVI_Corr_AllenSSp x = np.random.normal(15, 0.05, len(y)) plt.plot(x, y, 'k.', alpha=0.2) plt.xticks((2,6,10,14),('SpaGE','Seurat', 'Liger','gimVI'),size=12) plt.yticks(size=8) plt.gca().set_ylim([-0.4,0.8]) plt.ylabel('Spearman Correlation',size=12) colors = ['red', 'blue', 'purple'] lines = [Line2D([0], [0], color=c, linewidth=3, linestyle='-') for c in colors] labels = ['Ziesel', 'AllenVISp','AllenSSp'] plt.legend(lines, labels) plt.show()
[ "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.lines.Line2D", "pandas.read_csv", "matplotlib.pyplot.legend", "matplotlib.pyplot.yticks", "scipy.stats.spearmanr", "numpy.isnan", "matplotlib.pyplot.style.use", "matplotlib.use", "pickle.load", "pandas.Series", "numpy.array", "matplotlib.pyplot.gca", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.subplots", "os.chdir" ]
[((11, 38), 'os.chdir', 'os.chdir', (['"""osmFISH_Ziesel/"""'], {}), "('osmFISH_Ziesel/')\n", (19, 38), False, 'import os\n'), ((102, 126), 'matplotlib.use', 'matplotlib.use', (['"""qt5agg"""'], {}), "('qt5agg')\n", (116, 126), False, 'import matplotlib\n'), ((546, 622), 'pandas.read_csv', 'pd.read_csv', (['"""Results/SpaGE_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/SpaGE_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (557, 622), True, 'import pandas as pd\n'), ((708, 735), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (717, 735), True, 'import pandas as pd\n'), ((882, 958), 'pandas.read_csv', 'pd.read_csv', (['"""Results/gimVI_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/gimVI_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (893, 958), True, 'import pandas as pd\n'), ((1087, 1114), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (1096, 1114), True, 'import pandas as pd\n'), ((1496, 1523), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (1505, 1523), True, 'import pandas as pd\n'), ((1836, 1863), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (1845, 1863), True, 'import pandas as pd\n'), ((2030, 2060), 'os.chdir', 'os.chdir', (['"""osmFISH_AllenVISp/"""'], {}), "('osmFISH_AllenVISp/')\n", (2038, 2060), False, 'import os\n'), ((2101, 2177), 'pandas.read_csv', 'pd.read_csv', (['"""Results/SpaGE_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/SpaGE_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (2112, 2177), True, 'import pandas as pd\n'), ((2272, 2299), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (2281, 2299), True, 'import pandas as pd\n'), ((2455, 2531), 'pandas.read_csv', 'pd.read_csv', (['"""Results/gimVI_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/gimVI_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (2466, 2531), True, 'import pandas as pd\n'), ((2669, 2696), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (2678, 2696), True, 'import pandas as pd\n'), ((3102, 3129), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (3111, 3129), True, 'import pandas as pd\n'), ((3460, 3487), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (3469, 3487), True, 'import pandas as pd\n'), ((3666, 3695), 'os.chdir', 'os.chdir', (['"""osmFISH_AllenSSp/"""'], {}), "('osmFISH_AllenSSp/')\n", (3674, 3695), False, 'import os\n'), ((3735, 3811), 'pandas.read_csv', 'pd.read_csv', (['"""Results/SpaGE_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/SpaGE_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (3746, 3811), True, 'import pandas as pd\n'), ((3903, 3930), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (3912, 3930), True, 'import pandas as pd\n'), ((4083, 4159), 'pandas.read_csv', 'pd.read_csv', (['"""Results/gimVI_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/gimVI_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (4094, 4159), True, 'import pandas as pd\n'), ((4294, 4321), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (4303, 4321), True, 'import pandas as pd\n'), ((4719, 4746), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (4728, 4746), True, 'import pandas as pd\n'), ((5071, 5098), 'pandas.Series', 'pd.Series', ([], {'index': 'Gene_Order'}), '(index=Gene_Order)\n', (5080, 5098), True, 'import pandas as pd\n'), ((5293, 5316), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (5306, 5316), True, 'import matplotlib.pyplot as plt\n'), ((5328, 5356), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 3)'}), '(figsize=(5, 3))\n', (5340, 5356), True, 'import matplotlib.pyplot as plt\n'), ((6432, 6463), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (6440, 6463), True, 'import matplotlib.pyplot as plt\n'), ((6530, 6561), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (6538, 6561), True, 'import matplotlib.pyplot as plt\n'), ((6627, 6658), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (6635, 6658), True, 'import matplotlib.pyplot as plt\n'), ((6723, 6754), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (6731, 6754), True, 'import matplotlib.pyplot as plt\n'), ((6822, 6853), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (6830, 6853), True, 'import matplotlib.pyplot as plt\n'), ((6920, 6951), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (6928, 6951), True, 'import matplotlib.pyplot as plt\n'), ((7015, 7046), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (7023, 7046), True, 'import matplotlib.pyplot as plt\n'), ((7114, 7145), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (7122, 7145), True, 'import matplotlib.pyplot as plt\n'), ((7212, 7243), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (7220, 7243), True, 'import matplotlib.pyplot as plt\n'), ((7308, 7339), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (7316, 7339), True, 'import matplotlib.pyplot as plt\n'), ((7407, 7438), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (7415, 7438), True, 'import matplotlib.pyplot as plt\n'), ((7505, 7536), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""k."""'], {'alpha': '(0.2)'}), "(x, y, 'k.', alpha=0.2)\n", (7513, 7536), True, 'import matplotlib.pyplot as plt\n'), ((7540, 7614), 'matplotlib.pyplot.xticks', 'plt.xticks', (['(2, 6, 10, 14)', "('SpaGE', 'Seurat', 'Liger', 'gimVI')"], {'size': '(12)'}), "((2, 6, 10, 14), ('SpaGE', 'Seurat', 'Liger', 'gimVI'), size=12)\n", (7550, 7614), True, 'import matplotlib.pyplot as plt\n'), ((7609, 7627), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'size': '(8)'}), '(size=8)\n', (7619, 7627), True, 'import matplotlib.pyplot as plt\n'), ((7661, 7704), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Spearman Correlation"""'], {'size': '(12)'}), "('Spearman Correlation', size=12)\n", (7671, 7704), True, 'import matplotlib.pyplot as plt\n'), ((7867, 7892), 'matplotlib.pyplot.legend', 'plt.legend', (['lines', 'labels'], {}), '(lines, labels)\n', (7877, 7892), True, 'import matplotlib.pyplot as plt\n'), ((7894, 7904), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7902, 7904), True, 'import matplotlib.pyplot as plt\n'), ((400, 414), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (411, 414), False, 'import pickle\n'), ((1256, 1283), 'numpy.isnan', 'np.isnan', (['gimVI_Corr_Ziesel'], {}), '(gimVI_Corr_Ziesel)\n', (1264, 1283), True, 'import numpy as np\n'), ((1328, 1405), 'pandas.read_csv', 'pd.read_csv', (['"""Results/Seurat_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/Seurat_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (1339, 1405), True, 'import pandas as pd\n'), ((1672, 1748), 'pandas.read_csv', 'pd.read_csv', (['"""Results/Liger_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/Liger_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (1683, 1748), True, 'import pandas as pd\n'), ((1992, 2019), 'numpy.isnan', 'np.isnan', (['Liger_Corr_Ziesel'], {}), '(Liger_Corr_Ziesel)\n', (2000, 2019), True, 'import numpy as np\n'), ((2847, 2877), 'numpy.isnan', 'np.isnan', (['gimVI_Corr_AllenVISp'], {}), '(gimVI_Corr_AllenVISp)\n', (2855, 2877), True, 'import numpy as np\n'), ((2925, 3002), 'pandas.read_csv', 'pd.read_csv', (['"""Results/Seurat_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/Seurat_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (2936, 3002), True, 'import pandas as pd\n'), ((3287, 3363), 'pandas.read_csv', 'pd.read_csv', (['"""Results/Liger_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/Liger_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (3298, 3363), True, 'import pandas as pd\n'), ((3625, 3655), 'numpy.isnan', 'np.isnan', (['Liger_Corr_AllenVISp'], {}), '(Liger_Corr_AllenVISp)\n', (3633, 3655), True, 'import numpy as np\n'), ((4469, 4498), 'numpy.isnan', 'np.isnan', (['gimVI_Corr_AllenSSp'], {}), '(gimVI_Corr_AllenSSp)\n', (4477, 4498), True, 'import numpy as np\n'), ((4545, 4622), 'pandas.read_csv', 'pd.read_csv', (['"""Results/Seurat_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/Seurat_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (4556, 4622), True, 'import pandas as pd\n'), ((4901, 4977), 'pandas.read_csv', 'pd.read_csv', (['"""Results/Liger_LeaveOneOut.csv"""'], {'header': '(0)', 'index_col': '(0)', 'sep': '""","""'}), "('Results/Liger_LeaveOneOut.csv', header=0, index_col=0, sep=',')\n", (4912, 4977), True, 'import pandas as pd\n'), ((5233, 5262), 'numpy.isnan', 'np.isnan', (['Liger_Corr_AllenSSp'], {}), '(Liger_Corr_AllenSSp)\n', (5241, 5262), True, 'import numpy as np\n'), ((7750, 7803), 'matplotlib.lines.Line2D', 'Line2D', (['[0]', '[0]'], {'color': 'c', 'linewidth': '(3)', 'linestyle': '"""-"""'}), "([0], [0], color=c, linewidth=3, linestyle='-')\n", (7756, 7803), False, 'from matplotlib.lines import Line2D\n'), ((788, 842), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'SpaGE_imputed_Ziesel[i]'], {}), '(osmFISH_data[i], SpaGE_imputed_Ziesel[i])\n', (800, 842), True, 'import scipy.stats as st\n'), ((1577, 1632), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'Seurat_imputed_Ziesel[i]'], {}), '(osmFISH_data[i], Seurat_imputed_Ziesel[i])\n', (1589, 1632), True, 'import scipy.stats as st\n'), ((1916, 1970), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'Liger_imputed_Ziesel[i]'], {}), '(osmFISH_data[i], Liger_imputed_Ziesel[i])\n', (1928, 1970), True, 'import scipy.stats as st\n'), ((2355, 2412), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'SpaGE_imputed_AllenVISp[i]'], {}), '(osmFISH_data[i], SpaGE_imputed_AllenVISp[i])\n', (2367, 2412), True, 'import scipy.stats as st\n'), ((3186, 3244), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'Seurat_imputed_AllenVISp[i]'], {}), '(osmFISH_data[i], Seurat_imputed_AllenVISp[i])\n', (3198, 3244), True, 'import scipy.stats as st\n'), ((3543, 3600), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'Liger_imputed_AllenVISp[i]'], {}), '(osmFISH_data[i], Liger_imputed_AllenVISp[i])\n', (3555, 3600), True, 'import scipy.stats as st\n'), ((3985, 4041), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'SpaGE_imputed_AllenSSp[i]'], {}), '(osmFISH_data[i], SpaGE_imputed_AllenSSp[i])\n', (3997, 4041), True, 'import scipy.stats as st\n'), ((4802, 4859), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'Seurat_imputed_AllenSSp[i]'], {}), '(osmFISH_data[i], Seurat_imputed_AllenSSp[i])\n', (4814, 4859), True, 'import scipy.stats as st\n'), ((5153, 5209), 'scipy.stats.spearmanr', 'st.spearmanr', (['osmFISH_data[i]', 'Liger_imputed_AllenSSp[i]'], {}), '(osmFISH_data[i], Liger_imputed_AllenSSp[i])\n', (5165, 5209), True, 'import scipy.stats as st\n'), ((7629, 7638), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (7636, 7638), True, 'import matplotlib.pyplot as plt\n'), ((1029, 1062), 'numpy.array', 'np.array', (['Gene_Order'], {'dtype': '"""str"""'}), "(Gene_Order, dtype='str')\n", (1037, 1062), True, 'import numpy as np\n'), ((2608, 2641), 'numpy.array', 'np.array', (['Gene_Order'], {'dtype': '"""str"""'}), "(Gene_Order, dtype='str')\n", (2616, 2641), True, 'import numpy as np\n'), ((4234, 4267), 'numpy.array', 'np.array', (['Gene_Order'], {'dtype': '"""str"""'}), "(Gene_Order, dtype='str')\n", (4242, 4267), True, 'import numpy as np\n')]
import numpy as np import jax.numpy as jnp def radial_profile(data): """ Compute the radial profile of 2d image :param data: 2d image :return: radial profile """ center = data.shape[0]/2 y, x = jnp.indices((data.shape)) r = jnp.sqrt((x - center)**2 + (y - center)**2) r = r.astype('int32') tbin = jnp.bincount(r.ravel(), data.ravel()) nr = jnp.bincount(r.ravel()) radialprofile = tbin / nr return radialprofile def measure_power_spectrum(map_data, pixel_size): """ measures power 2d data :param power: map (nxn) :param pixel_size: pixel_size (rad/pixel) :return: ell :return: power spectrum """ data_ft = jnp.fft.fftshift(jnp.fft.fft2(map_data)) / map_data.shape[0] nyquist = np.int(map_data.shape[0]/2) power_spectrum_1d = radial_profile(jnp.real(data_ft*jnp.conj(data_ft)))[:nyquist] * (pixel_size)**2 k = np.arange(power_spectrum_1d.shape[0]) ell = 2. * np.pi * k / pixel_size / 360 return ell, power_spectrum_1d def make_power_map(power_spectrum, size, kps=None, zero_freq_val=1e7): #Ok we need to make a map of the power spectrum in Fourier space k1 = np.fft.fftfreq(size) k2 = np.fft.fftfreq(size) kcoords = np.meshgrid(k1,k2) # Now we can compute the k vector k = np.sqrt(kcoords[0]**2 + kcoords[1]**2) if kps is None: kps = np.linspace(0,0.5,len(power_spectrum)) # And we can interpolate the PS at these positions ps_map = np.interp(k.flatten(), kps, power_spectrum).reshape([size,size]) ps_map = ps_map ps_map[0,0] = zero_freq_val return ps_map # Carefull, this is not fftshifted
[ "numpy.meshgrid", "jax.numpy.fft.fft2", "numpy.fft.fftfreq", "numpy.arange", "numpy.int", "jax.numpy.conj", "jax.numpy.indices", "jax.numpy.sqrt", "numpy.sqrt" ]
[((209, 232), 'jax.numpy.indices', 'jnp.indices', (['data.shape'], {}), '(data.shape)\n', (220, 232), True, 'import jax.numpy as jnp\n'), ((241, 288), 'jax.numpy.sqrt', 'jnp.sqrt', (['((x - center) ** 2 + (y - center) ** 2)'], {}), '((x - center) ** 2 + (y - center) ** 2)\n', (249, 288), True, 'import jax.numpy as jnp\n'), ((726, 755), 'numpy.int', 'np.int', (['(map_data.shape[0] / 2)'], {}), '(map_data.shape[0] / 2)\n', (732, 755), True, 'import numpy as np\n'), ((863, 900), 'numpy.arange', 'np.arange', (['power_spectrum_1d.shape[0]'], {}), '(power_spectrum_1d.shape[0])\n', (872, 900), True, 'import numpy as np\n'), ((1122, 1142), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['size'], {}), '(size)\n', (1136, 1142), True, 'import numpy as np\n'), ((1150, 1170), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['size'], {}), '(size)\n', (1164, 1170), True, 'import numpy as np\n'), ((1183, 1202), 'numpy.meshgrid', 'np.meshgrid', (['k1', 'k2'], {}), '(k1, k2)\n', (1194, 1202), True, 'import numpy as np\n'), ((1244, 1286), 'numpy.sqrt', 'np.sqrt', (['(kcoords[0] ** 2 + kcoords[1] ** 2)'], {}), '(kcoords[0] ** 2 + kcoords[1] ** 2)\n', (1251, 1286), True, 'import numpy as np\n'), ((670, 692), 'jax.numpy.fft.fft2', 'jnp.fft.fft2', (['map_data'], {}), '(map_data)\n', (682, 692), True, 'import jax.numpy as jnp\n'), ((809, 826), 'jax.numpy.conj', 'jnp.conj', (['data_ft'], {}), '(data_ft)\n', (817, 826), True, 'import jax.numpy as jnp\n')]
""" This module illustrates how to generate a three-dimensional plot and a contour plot. For the example, the f(x,y) = x**2 * y**3 will be reproduced. """ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d X = np.linspace(-2, 2) Y = np.linspace(-1, 1) x, y = np.meshgrid(X, Y) z = x**2 * y**3 fig = plt.figure() ax = fig.add_subplot(projection="3d") ax.plot_surface(x, y, z) ax.set_xlabel("$x$", usetex=True) ax.set_ylabel("$y$", usetex=True) ax.set_zlabel("$z$", usetex=True) ax.set_title("Graph of the function $f(x,y) = x^2y^3$", usetex=True) plt.show() fig, ax = plt.subplots() ax.contour(x, y, z) ax.set_title("Contour of $f(x) = x^2y^3$", usetex=True) ax.set_xlabel("$x$", usetex=True) ax.set_ylabel("$y$", usetex=True) plt.show()
[ "numpy.meshgrid", "matplotlib.pyplot.show", "matplotlib.pyplot.figure", "numpy.linspace", "matplotlib.pyplot.subplots" ]
[((247, 265), 'numpy.linspace', 'np.linspace', (['(-2)', '(2)'], {}), '(-2, 2)\n', (258, 265), True, 'import numpy as np\n'), ((270, 288), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)'], {}), '(-1, 1)\n', (281, 288), True, 'import numpy as np\n'), ((297, 314), 'numpy.meshgrid', 'np.meshgrid', (['X', 'Y'], {}), '(X, Y)\n', (308, 314), True, 'import numpy as np\n'), ((338, 350), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (348, 350), True, 'import matplotlib.pyplot as plt\n'), ((587, 597), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (595, 597), True, 'import matplotlib.pyplot as plt\n'), ((609, 623), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (621, 623), True, 'import matplotlib.pyplot as plt\n'), ((769, 779), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (777, 779), True, 'import matplotlib.pyplot as plt\n')]
import os import inspect import numpy as np from scipy.sparse import coo_matrix from composites.laminate import read_stack from structsolve import solve from meshless.espim.read_mesh import read_mesh from meshless.espim.plate2d_calc_k0 import calc_k0 from meshless.espim.plate2d_add_k0s import add_k0s THISDIR = os.path.dirname(inspect.getfile(inspect.currentframe())) def test_calc_linear_static(): mesh = read_mesh(os.path.join(THISDIR, 'nastran_plate_16_nodes.dat')) E11 = 71.e9 nu = 0.33 plyt = 0.007 lam = read_stack([0], plyt=plyt, laminaprop=(E11, E11, nu)) for tria in mesh.elements.values(): tria.prop = lam for node in mesh.nodes.values(): node.prop = lam for prop_from_nodes in [False, True]: for k0s_method in ['cell-based', 'cell-based-no-smoothing']: #, 'edge-based' k0 = calc_k0(mesh, prop_from_nodes) add_k0s(k0, mesh, prop_from_nodes, k0s_method, alpha=0.2) k0run = k0.copy() dof = 5 n = k0.shape[0] // dof fext = np.zeros(n*dof, dtype=np.float64) fext[mesh.nodes[4].index*dof + 2] = 500. fext[mesh.nodes[7].index*dof + 2] = 500. fext[mesh.nodes[5].index*dof + 2] = 1000. fext[mesh.nodes[6].index*dof + 2] = 1000. i, j = np.indices(k0run.shape) # boundary conditions for nid in [1, 10, 11, 12]: for j in [0, 1, 2, 3]: k0run[mesh.nodes[nid].index*dof+j, :] = 0 k0run[:, mesh.nodes[nid].index*dof+j] = 0 k0run = coo_matrix(k0run) u = solve(k0run, fext, silent=True) ans = np.loadtxt(os.path.join(THISDIR, 'nastran_plate_16_nodes.result.txt'), dtype=float) xyz = np.array([n.xyz for n in mesh.nodes.values()]) ind = np.lexsort((xyz[:, 1], xyz[:, 0])) xyz = xyz[ind] nodes = np.array(list(mesh.nodes.values()))[ind] pick = [n.index for n in nodes] assert np.allclose(u[2::5][pick].reshape(4, 4).T, ans, rtol=0.05) if __name__ == '__main__': test_calc_linear_static()
[ "numpy.lexsort", "meshless.espim.plate2d_calc_k0.calc_k0", "numpy.zeros", "numpy.indices", "scipy.sparse.coo_matrix", "composites.laminate.read_stack", "structsolve.solve", "inspect.currentframe", "os.path.join", "meshless.espim.plate2d_add_k0s.add_k0s" ]
[((535, 588), 'composites.laminate.read_stack', 'read_stack', (['[0]'], {'plyt': 'plyt', 'laminaprop': '(E11, E11, nu)'}), '([0], plyt=plyt, laminaprop=(E11, E11, nu))\n', (545, 588), False, 'from composites.laminate import read_stack\n'), ((347, 369), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (367, 369), False, 'import inspect\n'), ((425, 476), 'os.path.join', 'os.path.join', (['THISDIR', '"""nastran_plate_16_nodes.dat"""'], {}), "(THISDIR, 'nastran_plate_16_nodes.dat')\n", (437, 476), False, 'import os\n'), ((858, 888), 'meshless.espim.plate2d_calc_k0.calc_k0', 'calc_k0', (['mesh', 'prop_from_nodes'], {}), '(mesh, prop_from_nodes)\n', (865, 888), False, 'from meshless.espim.plate2d_calc_k0 import calc_k0\n'), ((901, 958), 'meshless.espim.plate2d_add_k0s.add_k0s', 'add_k0s', (['k0', 'mesh', 'prop_from_nodes', 'k0s_method'], {'alpha': '(0.2)'}), '(k0, mesh, prop_from_nodes, k0s_method, alpha=0.2)\n', (908, 958), False, 'from meshless.espim.plate2d_add_k0s import add_k0s\n'), ((1065, 1100), 'numpy.zeros', 'np.zeros', (['(n * dof)'], {'dtype': 'np.float64'}), '(n * dof, dtype=np.float64)\n', (1073, 1100), True, 'import numpy as np\n'), ((1332, 1355), 'numpy.indices', 'np.indices', (['k0run.shape'], {}), '(k0run.shape)\n', (1342, 1355), True, 'import numpy as np\n'), ((1615, 1632), 'scipy.sparse.coo_matrix', 'coo_matrix', (['k0run'], {}), '(k0run)\n', (1625, 1632), False, 'from scipy.sparse import coo_matrix\n'), ((1649, 1680), 'structsolve.solve', 'solve', (['k0run', 'fext'], {'silent': '(True)'}), '(k0run, fext, silent=True)\n', (1654, 1680), False, 'from structsolve import solve\n'), ((1886, 1920), 'numpy.lexsort', 'np.lexsort', (['(xyz[:, 1], xyz[:, 0])'], {}), '((xyz[:, 1], xyz[:, 0]))\n', (1896, 1920), True, 'import numpy as np\n'), ((1710, 1768), 'os.path.join', 'os.path.join', (['THISDIR', '"""nastran_plate_16_nodes.result.txt"""'], {}), "(THISDIR, 'nastran_plate_16_nodes.result.txt')\n", (1722, 1768), False, 'import os\n')]
""" A Reccurent Neural Network (LSTM) implementation example using TensorFlow library """ import AlphaBase import os import tensorflow as tf #from tensorflow.models.rnn import rnn, rnn_cell import numpy as np import LanguageSource as LanguageSource import LangTestData as langTestData # Get training data lang_data_dir = '/home/frank/data/LanguageDetectionModel/exp_data_test' alpha_file_name = 'alpha_dog.pk' if os.path.isfile(alpha_file_name): alpha_set = AlphaBase.AlphaBase.load_object_from_file(alpha_file_name) else: alpha_set = AlphaBase.AlphaBase() alpha_set.start(lang_data_dir, 10000000) alpha_set.compress(0.999) alpha_set.save_object_to_file(alpha_file_name) print('alpha size:', alpha_set.alpha_size, 'alpha compressed size', alpha_set.alpha_compressed_size) lang_data = LanguageSource.LanguageSource(alpha_set) lang_data.begin(lang_data_dir) # Parameters learning_rate = 0.00001 training_cycles = 100000000 batch_size = 128 display_step = 10 # Network Parameters # number of characters in the set of languages, also the size of the one-hot vector encoding characters n_input = alpha_set.alpha_compressed_size n_steps = 64 # time steps n_hidden = 512 # hidden layer num of features n_classes = 21 # total number of class, (the number of languages in the database) # Get test data lang_db_test = langTestData.LangTestData() x_test, y_test = lang_db_test.read_data('/home/frank/data/LanguageDetectionModel/europarl.test', n_steps) test_data = lang_data.get_ml_data_matrix(n_input, x_test) # get one-hot version of data y_test2 = [lang_data.language_name_to_index[y_l] for y_l in y_test] # convert the language names to indexes test_label = lang_data.get_class_rep(y_test2, n_classes) # convert the class indexes to one-hot vectors test_len = len(y_test) # get the number of test strings # tf Graph # input x = tf.placeholder("float", [n_steps, None, n_input]) # desired output y = tf.placeholder("float", [None, n_classes]) # Tensorflow LSTM cell requires 2x n_hidden length (state & cell) i_state = tf.placeholder("float", [None, 2 * n_hidden]) # Define weights weights = { 'hidden': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights 'out': tf.Variable(tf.random_normal([n_hidden, n_classes])) } biases = { 'hidden': tf.Variable(tf.random_normal([n_hidden])), 'out': tf.Variable(tf.random_normal([n_classes])) } def lm_rnn(_x, _i_state, _weights, _biases): # Reformat _x from [ ] to [n_steps*batch_size x n_input] xin = tf.reshape(_x, [-1, n_input]) # Linear activation xin = tf.matmul(xin, _weights['hidden']) + _biases['hidden'] # Split data because rnn cell needs a list of inputs for the RNN inner loop xin = tf.split(0, n_steps, xin) # n_steps * (batch_size, n_hidden) # Define a lstm cell with tensorflow lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden, forget_bias=0.95) # lstm_cell = rnn_cell.LSTMCell(n_hidden, use_peepholes=True, cell_clip=2, forget_bias=0.99) # Get lstm cell output # outputs - a list of n_step matrix of shape [? x n_hidden] # states - a list of n_step vectors of size [2*n_hidden] outputs, states = tf.nn.rnn(lstm_cell, xin, initial_state=_i_state) # Linear activation # Get inner loop last output logits = tf.matmul(outputs[-1], _weights['out']) + _biases['out'] return logits predictions = lm_rnn(x, i_state, weights, biases) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(predictions, y)) # Softmax loss optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer # Evaluate model correct_predictions = tf.equal(tf.argmax(predictions, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32)) # Initializing the variables init = tf.initialize_all_variables() # Launch the graph with tf.Session() as sess: sess.run(init) step = 1 # Keep training until reach max iterations while step * batch_size < training_cycles: # batch_xs - list (of length batch_size) of strings each of length n_input, # batch_ys - list (of length batch_size) of language ids (strings, example: 'bg','ep',...) batch_xs, batch_ys = lang_data.get_next_batch_one_hot(batch_size, n_steps) # Fit training using batch data sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, i_state: np.zeros((batch_size, 2 * n_hidden))}) if step % display_step == 0: # Calculate batch accuracy acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, i_state: np.zeros((batch_size, 2 * n_hidden))}) # Calculate batch loss loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, i_state: np.zeros((batch_size, 2 * n_hidden))}) # Read a new batch for validation batch_xs, batch_ys = lang_data.get_next_batch_one_hot(batch_size, n_steps) acc_val = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, i_state: np.zeros((batch_size, 2 * n_hidden))}) # Calculate batch loss loss_val = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, i_state: np.zeros((batch_size, 2 * n_hidden))}) print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc) + ", Validation Loss=" + "{:.6f}".format(loss_val) + ", Validation Accuracy= " + "{:.5f}".format(acc_val)) step += 1 print("Optimization Finished!") # Calculate accuracy """ acc_sum = 0.0 for i in range(test_len): test_string = x_test_nat[i] test_x_mat = lang_data.get_ml_data_matrix_3([test_string]) y_t = lang_data.language_name_to_index[y_test[i]] test_y_mat = lang_data.get_class_rep([y_t], n_classes) acc = sess.run(accuracy, feed_dict={x: test_x_mat, y: test_y_mat, i_state: np.zeros((1, 2 * n_hidden))}) acc_sum += acc print(i, acc, acc_sum) """ print("Testing Accuracy:", sess.run(accuracy, feed_dict={x: test_data, y: test_label, i_state: np.zeros((test_len, 2 * n_hidden))}))
[ "tensorflow.reshape", "tensorflow.matmul", "os.path.isfile", "AlphaBase.AlphaBase.load_object_from_file", "tensorflow.split", "AlphaBase.AlphaBase", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.placeholder", "LangTestData.LangTestData", "tensorflow.nn.rnn_cell.BasicLSTMCell", "tensorflow.cast", "tensorflow.initialize_all_variables", "tensorflow.Session", "tensorflow.random_normal", "tensorflow.argmax", "numpy.zeros", "LanguageSource.LanguageSource", "tensorflow.nn.rnn", "tensorflow.train.AdamOptimizer" ]
[((416, 447), 'os.path.isfile', 'os.path.isfile', (['alpha_file_name'], {}), '(alpha_file_name)\n', (430, 447), False, 'import os\n'), ((808, 848), 'LanguageSource.LanguageSource', 'LanguageSource.LanguageSource', (['alpha_set'], {}), '(alpha_set)\n', (837, 848), True, 'import LanguageSource as LanguageSource\n'), ((1338, 1365), 'LangTestData.LangTestData', 'langTestData.LangTestData', ([], {}), '()\n', (1363, 1365), True, 'import LangTestData as langTestData\n'), ((1856, 1905), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[n_steps, None, n_input]'], {}), "('float', [n_steps, None, n_input])\n", (1870, 1905), True, 'import tensorflow as tf\n'), ((1927, 1969), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, n_classes]'], {}), "('float', [None, n_classes])\n", (1941, 1969), True, 'import tensorflow as tf\n'), ((2046, 2091), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, 2 * n_hidden]'], {}), "('float', [None, 2 * n_hidden])\n", (2060, 2091), True, 'import tensorflow as tf\n'), ((3848, 3877), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (3875, 3877), True, 'import tensorflow as tf\n'), ((465, 523), 'AlphaBase.AlphaBase.load_object_from_file', 'AlphaBase.AlphaBase.load_object_from_file', (['alpha_file_name'], {}), '(alpha_file_name)\n', (506, 523), False, 'import AlphaBase\n'), ((546, 567), 'AlphaBase.AlphaBase', 'AlphaBase.AlphaBase', ([], {}), '()\n', (565, 567), False, 'import AlphaBase\n'), ((2521, 2550), 'tensorflow.reshape', 'tf.reshape', (['_x', '[-1, n_input]'], {}), '(_x, [-1, n_input])\n', (2531, 2550), True, 'import tensorflow as tf\n'), ((2732, 2757), 'tensorflow.split', 'tf.split', (['(0)', 'n_steps', 'xin'], {}), '(0, n_steps, xin)\n', (2740, 2757), True, 'import tensorflow as tf\n'), ((2852, 2908), 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['n_hidden'], {'forget_bias': '(0.95)'}), '(n_hidden, forget_bias=0.95)\n', (2880, 2908), True, 'import tensorflow as tf\n'), ((3181, 3230), 'tensorflow.nn.rnn', 'tf.nn.rnn', (['lstm_cell', 'xin'], {'initial_state': '_i_state'}), '(lstm_cell, xin, initial_state=_i_state)\n', (3190, 3230), True, 'import tensorflow as tf\n'), ((3480, 3535), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', (['predictions', 'y'], {}), '(predictions, y)\n', (3519, 3535), True, 'import tensorflow as tf\n'), ((3699, 3724), 'tensorflow.argmax', 'tf.argmax', (['predictions', '(1)'], {}), '(predictions, 1)\n', (3708, 3724), True, 'import tensorflow as tf\n'), ((3726, 3741), 'tensorflow.argmax', 'tf.argmax', (['y', '(1)'], {}), '(y, 1)\n', (3735, 3741), True, 'import tensorflow as tf\n'), ((3769, 3809), 'tensorflow.cast', 'tf.cast', (['correct_predictions', 'tf.float32'], {}), '(correct_predictions, tf.float32)\n', (3776, 3809), True, 'import tensorflow as tf\n'), ((3903, 3915), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3913, 3915), True, 'import tensorflow as tf\n'), ((2149, 2186), 'tensorflow.random_normal', 'tf.random_normal', (['[n_input, n_hidden]'], {}), '([n_input, n_hidden])\n', (2165, 2186), True, 'import tensorflow as tf\n'), ((2236, 2275), 'tensorflow.random_normal', 'tf.random_normal', (['[n_hidden, n_classes]'], {}), '([n_hidden, n_classes])\n', (2252, 2275), True, 'import tensorflow as tf\n'), ((2316, 2344), 'tensorflow.random_normal', 'tf.random_normal', (['[n_hidden]'], {}), '([n_hidden])\n', (2332, 2344), True, 'import tensorflow as tf\n'), ((2370, 2399), 'tensorflow.random_normal', 'tf.random_normal', (['[n_classes]'], {}), '([n_classes])\n', (2386, 2399), True, 'import tensorflow as tf\n'), ((2586, 2620), 'tensorflow.matmul', 'tf.matmul', (['xin', "_weights['hidden']"], {}), "(xin, _weights['hidden'])\n", (2595, 2620), True, 'import tensorflow as tf\n'), ((3302, 3341), 'tensorflow.matmul', 'tf.matmul', (['outputs[-1]', "_weights['out']"], {}), "(outputs[-1], _weights['out'])\n", (3311, 3341), True, 'import tensorflow as tf\n'), ((3565, 3616), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (3587, 3616), True, 'import tensorflow as tf\n'), ((4471, 4507), 'numpy.zeros', 'np.zeros', (['(batch_size, 2 * n_hidden)'], {}), '((batch_size, 2 * n_hidden))\n', (4479, 4507), True, 'import numpy as np\n'), ((6520, 6554), 'numpy.zeros', 'np.zeros', (['(test_len, 2 * n_hidden)'], {}), '((test_len, 2 * n_hidden))\n', (6528, 6554), True, 'import numpy as np\n'), ((4717, 4753), 'numpy.zeros', 'np.zeros', (['(batch_size, 2 * n_hidden)'], {}), '((batch_size, 2 * n_hidden))\n', (4725, 4753), True, 'import numpy as np\n'), ((4916, 4952), 'numpy.zeros', 'np.zeros', (['(batch_size, 2 * n_hidden)'], {}), '((batch_size, 2 * n_hidden))\n', (4924, 4952), True, 'import numpy as np\n'), ((5228, 5264), 'numpy.zeros', 'np.zeros', (['(batch_size, 2 * n_hidden)'], {}), '((batch_size, 2 * n_hidden))\n', (5236, 5264), True, 'import numpy as np\n'), ((5435, 5471), 'numpy.zeros', 'np.zeros', (['(batch_size, 2 * n_hidden)'], {}), '((batch_size, 2 * n_hidden))\n', (5443, 5471), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 18 18:20:34 2020 @author: ishidaira """ from cvxopt import matrix import numpy as np from numpy import linalg import cvxopt from numpy import linalg as LA from sklearn import preprocessing from imblearn.over_sampling import SMOTE import pandas as pd from sklearn.model_selection import train_test_split import seaborn as sns from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from precision import precision from imblearn.over_sampling import SVMSMOTE from fsvmClass import HYP_SVM # three kernel functions def linear_kernel(x1, x2): return np.dot(x1, x2) # param p def polynomial_kernel(x, y, p=1.5): return (1 + np.dot(x, y)) ** p # param sigmma def gaussian_kernel(x, y, sigma=1.0): # print(-linalg.norm(x-y)**2) x = np.asarray(x) y = np.asarray(y) return np.exp((-linalg.norm(x - y) ** 2) / (2 * (sigma ** 2))) class BFSVM(object): # initial function def __init__(self, kernel=None, fuzzyvalue='Logistic',databalance='origine',a = 4, b = 3, C=None, P=None, sigma=None): self.kernel = kernel self.C = C self.P = P self.sigma = sigma self.fuzzyvalue = fuzzyvalue self.a = a self.b = b self.databalance = databalance if self.C is not None: self.C = float(self.C) def mvalue(self, X_train, X_test,y_train): # print('fuzzy value:', self.fuzzyvalue ) clf = HYP_SVM(kernel='polynomial', C=1.5, P=1.5) clf.m_func(X_train,X_test,y_train) clf.fit(X_train,X_test, y_train) score = clf.project(X_train)-clf.b if self.fuzzyvalue=='Lin': m_value = (score-max(score))/(max(score)-min(score)) elif self.fuzzyvalue=='Bridge': s_up = np.percentile(score,55) s_down = np.percentile(score,45) m_value = np.zeros((len(score))) for i in range(len(score)): if score[i]>s_up: m_value[i] = 1 elif score[i]<=s_down: m_value[i] = 0 else: m_value[i] = (score[i]-s_down)/(s_up-s_down) elif self.fuzzyvalue=='Logistic': a = self.a b = self.b m_value = np.zeros((len(score))) for i in range(len(score)): m_value[i] = np.exp(a*score[i]+b)/(np.exp(a*score[i]+b)+1) self.m_value = m_value def fit(self, X_train, X_test, y): # extract the number of samples and attributes of train and test n_samples, n_features = X_train.shape nt_samples, nt_features = X_test.shape # initialize a 2n*2n matrix of Kernel function K(xi,xj) self.K = np.zeros((2*n_samples, 2*n_samples)) for i in range(n_samples): for j in range(n_samples): if self.kernel == 'polynomial': self.K[i, j] = polynomial_kernel(X_train[i], X_train[j],self.P) elif self.kernel == 'gaussian': self.K[i, j] = gaussian_kernel(X_train[i], X_train[j], self.sigma) else: self.K[i, j] = linear_kernel(X_train[i], X_train[j]) # print(K[i,j]) X_train = np.asarray(X_train) X_test = np.asarray(X_test) # P = K(xi,xj) P = cvxopt.matrix(self.K) # q = [-1,...,-1,-2,...,-2] q = np.concatenate((np.ones(n_samples) * -1,np.ones(n_samples) * -2)) q = cvxopt.matrix(q) #equality constraints # A = [1,...,1,0,...,0] A = np.concatenate((np.ones(n_samples) * 1,np.zeros(n_samples))) A = cvxopt.matrix(A) A = matrix(A, (1, 2*n_samples), 'd') # changes done # b = [0.0] b = cvxopt.matrix(0.0) #inequality constraints if self.C is None: # tmp1 = -1 as diagonal, n*n tmp1 = np.diag(np.ones(n_samples) * -1) # tmp1 = 2*tmp1 n*2n tmp1 = np.hstack((tmp1,tmp1)) # tmp2 = n*2n, the second matrix n*n diagonal as -1 tmp2 = np.diag(np.ones(n_samples) * -1) tmp2 = np.hstack((np.diag(np.zeros(n_samples)),tmp2)) G = cvxopt.matrix(np.vstack((tmp1, tmp2))) G = matrix(G, (6*n_samples,2*n_samples), 'd') # h = [0,0,0,...,0] 2n*1 h = cvxopt.matrix(np.zeros(2*n_samples)) else: # tmp1 = -1 as diagonal, n*n tmp1 = np.diag(np.ones(n_samples) * -1) # tmp1 = 2*tmp1 n*2n tmp1 = np.hstack((tmp1,tmp1)) # tmp2 = n*2n, the second matrix n*n diagonal as -1 tmp2 = np.diag(np.ones(n_samples) * -1) tmp2 = np.hstack((np.diag(np.zeros(n_samples)),tmp2)) tmp3 = np.identity(n_samples) # tmp3 = 2*tmp3 n*2n tmp3 = np.hstack((tmp3,tmp3)) # tmp4 = n*2n, the second matrix n*n diagonal as 1 tmp4 = np.identity(n_samples) tmp4 = np.hstack((np.diag(np.zeros(n_samples)),tmp4)) # G = tmp1,tmp2,tmp3,tmp4 shape 4n*2n G = cvxopt.matrix(np.vstack((tmp1,tmp2,tmp3,tmp4))) #G = matrix(G, (6*n_samples,2*n_samples), 'd') # h = 4n*1 tmp1 = np.zeros(2*n_samples) tmp2 = np.ones(n_samples) * self.C * self.m_value tmp3 = np.ones(n_samples) * self.C * (1 - self.m_value) h = cvxopt.matrix(np.hstack((tmp1,tmp2,tmp3))) # solve QP problem solution = cvxopt.solvers.qp(P, q, G, h, A, b) # print(solution['status']) # Lagrange multipliers # a = [epsilon1,...,epsilonN,beta1,...,betaN] a = np.ravel(solution['x']) epsilon = a[:n_samples] beta = a[n_samples:] # Support vectors have non zero lagrange multipliers sv = np.array(list(epsilon+beta > 1e-5) and list(beta > 1e-5)) ind = np.arange(len(epsilon))[sv] self.epsilon_org = epsilon self.epsilon = epsilon[sv] self.beta_org = beta self.beta = beta[sv] self.sv = X_train[sv] self.sv_y = y[sv] self.sv_yorg = y X_train = np.asarray(X_train) self.K = self.K[:n_samples,:n_samples] # Intercept self.b = 0 for n in range(len(self.epsilon)): self.b -= np.sum(self.epsilon * self.K[ind[n], sv]) self.b /= len(self.epsilon) # Weight vector if self.kernel == 'polynomial' or 'gaussian' or 'linear': self.w = np.zeros(n_features) for n in range(len(self.epsilon)): self.w += self.epsilon[n] * self.sv[n] else: self.w = None def project(self, X): if self.w is None: return np.dot(X, self.w) + self.b else: y_predict = np.zeros(len(X)) X = np.asarray(X) for i in range(len(X)): s = 0 for epsilon,sv in zip(self.epsilon,self.sv): if self.kernel == 'polynomial': s += epsilon * polynomial_kernel(sv, X[i], self.P) elif self.kernel == 'gaussian': s += epsilon * gaussian_kernel(X[i], sv, self.sigma) else: s += epsilon * linear_kernel(X[i], sv) y_predict[i] = s # print(y_predict[i]) return y_predict + self.b # predict function def predict(self, X): return np.sign(self.project(X)) # Test Code for _LSSVMtrain def fsvmTrain(SamplingMethode): train = pd.read_csv("../data.csv", header=0) for col in train.columns: for i in range(1000): train[col][i] = int(train[col][i]) features = train.columns[1:21] X = train[features] y = train['Creditability'] min_max_scaler = preprocessing.MinMaxScaler() X = min_max_scaler.fit_transform(X) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) if SamplingMethode == 'upSampling': X_train, y_train = upSampling(X_train,y_train) elif SamplingMethode == 'lowSampling': y_train = np.array(y_train) y_train = y_train.reshape(len(y_train), 1) train = np.append(y_train, np.array(X_train), axis=1) train = pd.DataFrame(train) train = np.array(lowSampling(train)) X_train = train[:,1:] y_train = train[:,0] X_train = np.asarray(X_train) y_train = np.asarray(y_train) for i in range(len(y_train)): if y_train[i] == 0: y_train[i] = -1 clf = BFSVM(kernel='polynomial',C=1.5, P=1.5) clf.mvalue(X_train,X_test, y_train) clf.fit(X_train,X_test, y_train) y_predict = clf.predict(X_test) y_test = np.array(y_test) for i in range(len(y_test)): if y_test[i] == 0: y_test[i] = -1 print(np.mean(y_predict!=y_test)) precision(y_predict,y_test) if __name__ == '__main__': fsvmTrain('lowSampling')
[ "numpy.sum", "numpy.ravel", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.preprocessing.MinMaxScaler", "numpy.ones", "numpy.mean", "numpy.linalg.norm", "numpy.exp", "pandas.DataFrame", "numpy.identity", "fsvmClass.HYP_SVM", "cvxopt.solvers.qp", "cvxopt.matrix", "numpy.asarray", "numpy.hstack", "numpy.percentile", "numpy.dot", "numpy.vstack", "precision.precision", "numpy.zeros", "numpy.array" ]
[((643, 657), 'numpy.dot', 'np.dot', (['x1', 'x2'], {}), '(x1, x2)\n', (649, 657), True, 'import numpy as np\n'), ((838, 851), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (848, 851), True, 'import numpy as np\n'), ((860, 873), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (870, 873), True, 'import numpy as np\n'), ((7789, 7825), 'pandas.read_csv', 'pd.read_csv', (['"""../data.csv"""'], {'header': '(0)'}), "('../data.csv', header=0)\n", (7800, 7825), True, 'import pandas as pd\n'), ((8044, 8072), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', ([], {}), '()\n', (8070, 8072), False, 'from sklearn import preprocessing\n'), ((8152, 8205), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(X, y, test_size=0.2, random_state=0)\n', (8168, 8205), False, 'from sklearn.model_selection import train_test_split\n'), ((8649, 8668), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (8659, 8668), True, 'import numpy as np\n'), ((8683, 8702), 'numpy.asarray', 'np.asarray', (['y_train'], {}), '(y_train)\n', (8693, 8702), True, 'import numpy as np\n'), ((8974, 8990), 'numpy.array', 'np.array', (['y_test'], {}), '(y_test)\n', (8982, 8990), True, 'import numpy as np\n'), ((9120, 9148), 'precision.precision', 'precision', (['y_predict', 'y_test'], {}), '(y_predict, y_test)\n', (9129, 9148), False, 'from precision import precision\n'), ((1487, 1529), 'fsvmClass.HYP_SVM', 'HYP_SVM', ([], {'kernel': '"""polynomial"""', 'C': '(1.5)', 'P': '(1.5)'}), "(kernel='polynomial', C=1.5, P=1.5)\n", (1494, 1529), False, 'from fsvmClass import HYP_SVM\n'), ((2776, 2816), 'numpy.zeros', 'np.zeros', (['(2 * n_samples, 2 * n_samples)'], {}), '((2 * n_samples, 2 * n_samples))\n', (2784, 2816), True, 'import numpy as np\n'), ((3297, 3316), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (3307, 3316), True, 'import numpy as np\n'), ((3334, 3352), 'numpy.asarray', 'np.asarray', (['X_test'], {}), '(X_test)\n', (3344, 3352), True, 'import numpy as np\n'), ((3389, 3410), 'cvxopt.matrix', 'cvxopt.matrix', (['self.K'], {}), '(self.K)\n', (3402, 3410), False, 'import cvxopt\n'), ((3538, 3554), 'cvxopt.matrix', 'cvxopt.matrix', (['q'], {}), '(q)\n', (3551, 3554), False, 'import cvxopt\n'), ((3720, 3736), 'cvxopt.matrix', 'cvxopt.matrix', (['A'], {}), '(A)\n', (3733, 3736), False, 'import cvxopt\n'), ((3758, 3792), 'cvxopt.matrix', 'matrix', (['A', '(1, 2 * n_samples)', '"""d"""'], {}), "(A, (1, 2 * n_samples), 'd')\n", (3764, 3792), False, 'from cvxopt import matrix\n'), ((3839, 3857), 'cvxopt.matrix', 'cvxopt.matrix', (['(0.0)'], {}), '(0.0)\n', (3852, 3857), False, 'import cvxopt\n'), ((5642, 5677), 'cvxopt.solvers.qp', 'cvxopt.solvers.qp', (['P', 'q', 'G', 'h', 'A', 'b'], {}), '(P, q, G, h, A, b)\n', (5659, 5677), False, 'import cvxopt\n'), ((5820, 5843), 'numpy.ravel', 'np.ravel', (["solution['x']"], {}), "(solution['x'])\n", (5828, 5843), True, 'import numpy as np\n'), ((6333, 6352), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (6343, 6352), True, 'import numpy as np\n'), ((9088, 9116), 'numpy.mean', 'np.mean', (['(y_predict != y_test)'], {}), '(y_predict != y_test)\n', (9095, 9116), True, 'import numpy as np\n'), ((722, 734), 'numpy.dot', 'np.dot', (['x', 'y'], {}), '(x, y)\n', (728, 734), True, 'import numpy as np\n'), ((4080, 4103), 'numpy.hstack', 'np.hstack', (['(tmp1, tmp1)'], {}), '((tmp1, tmp1))\n', (4089, 4103), True, 'import numpy as np\n'), ((4369, 4415), 'cvxopt.matrix', 'matrix', (['G', '(6 * n_samples, 2 * n_samples)', '"""d"""'], {}), "(G, (6 * n_samples, 2 * n_samples), 'd')\n", (4375, 4415), False, 'from cvxopt import matrix\n'), ((4662, 4685), 'numpy.hstack', 'np.hstack', (['(tmp1, tmp1)'], {}), '((tmp1, tmp1))\n', (4671, 4685), True, 'import numpy as np\n'), ((4899, 4921), 'numpy.identity', 'np.identity', (['n_samples'], {}), '(n_samples)\n', (4910, 4921), True, 'import numpy as np\n'), ((4974, 4997), 'numpy.hstack', 'np.hstack', (['(tmp3, tmp3)'], {}), '((tmp3, tmp3))\n', (4983, 4997), True, 'import numpy as np\n'), ((5079, 5101), 'numpy.identity', 'np.identity', (['n_samples'], {}), '(n_samples)\n', (5090, 5101), True, 'import numpy as np\n'), ((5384, 5407), 'numpy.zeros', 'np.zeros', (['(2 * n_samples)'], {}), '(2 * n_samples)\n', (5392, 5407), True, 'import numpy as np\n'), ((6513, 6554), 'numpy.sum', 'np.sum', (['(self.epsilon * self.K[ind[n], sv])'], {}), '(self.epsilon * self.K[ind[n], sv])\n', (6519, 6554), True, 'import numpy as np\n'), ((6703, 6723), 'numpy.zeros', 'np.zeros', (['n_features'], {}), '(n_features)\n', (6711, 6723), True, 'import numpy as np\n'), ((7037, 7050), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (7047, 7050), True, 'import numpy as np\n'), ((8363, 8380), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (8371, 8380), True, 'import numpy as np\n'), ((8510, 8529), 'pandas.DataFrame', 'pd.DataFrame', (['train'], {}), '(train)\n', (8522, 8529), True, 'import pandas as pd\n'), ((1825, 1849), 'numpy.percentile', 'np.percentile', (['score', '(55)'], {}), '(score, 55)\n', (1838, 1849), True, 'import numpy as np\n'), ((1870, 1894), 'numpy.percentile', 'np.percentile', (['score', '(45)'], {}), '(score, 45)\n', (1883, 1894), True, 'import numpy as np\n'), ((3677, 3696), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (3685, 3696), True, 'import numpy as np\n'), ((4328, 4351), 'numpy.vstack', 'np.vstack', (['(tmp1, tmp2)'], {}), '((tmp1, tmp2))\n', (4337, 4351), True, 'import numpy as np\n'), ((4479, 4502), 'numpy.zeros', 'np.zeros', (['(2 * n_samples)'], {}), '(2 * n_samples)\n', (4487, 4502), True, 'import numpy as np\n'), ((5248, 5283), 'numpy.vstack', 'np.vstack', (['(tmp1, tmp2, tmp3, tmp4)'], {}), '((tmp1, tmp2, tmp3, tmp4))\n', (5257, 5283), True, 'import numpy as np\n'), ((5566, 5595), 'numpy.hstack', 'np.hstack', (['(tmp1, tmp2, tmp3)'], {}), '((tmp1, tmp2, tmp3))\n', (5575, 5595), True, 'import numpy as np\n'), ((6939, 6956), 'numpy.dot', 'np.dot', (['X', 'self.w'], {}), '(X, self.w)\n', (6945, 6956), True, 'import numpy as np\n'), ((8467, 8484), 'numpy.array', 'np.array', (['X_train'], {}), '(X_train)\n', (8475, 8484), True, 'import numpy as np\n'), ((894, 912), 'numpy.linalg.norm', 'linalg.norm', (['(x - y)'], {}), '(x - y)\n', (905, 912), False, 'from numpy import linalg\n'), ((3476, 3494), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (3483, 3494), True, 'import numpy as np\n'), ((3500, 3518), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (3507, 3518), True, 'import numpy as np\n'), ((3654, 3672), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (3661, 3672), True, 'import numpy as np\n'), ((4003, 4021), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (4010, 4021), True, 'import numpy as np\n'), ((4194, 4212), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (4201, 4212), True, 'import numpy as np\n'), ((4585, 4603), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (4592, 4603), True, 'import numpy as np\n'), ((4776, 4794), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (4783, 4794), True, 'import numpy as np\n'), ((5425, 5443), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (5432, 5443), True, 'import numpy as np\n'), ((5487, 5505), 'numpy.ones', 'np.ones', (['n_samples'], {}), '(n_samples)\n', (5494, 5505), True, 'import numpy as np\n'), ((4257, 4276), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (4265, 4276), True, 'import numpy as np\n'), ((4839, 4858), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (4847, 4858), True, 'import numpy as np\n'), ((5140, 5159), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (5148, 5159), True, 'import numpy as np\n'), ((2411, 2435), 'numpy.exp', 'np.exp', (['(a * score[i] + b)'], {}), '(a * score[i] + b)\n', (2417, 2435), True, 'import numpy as np\n'), ((2433, 2457), 'numpy.exp', 'np.exp', (['(a * score[i] + b)'], {}), '(a * score[i] + b)\n', (2439, 2457), True, 'import numpy as np\n')]
from unittest import TestCase import moderngl import numpy import platform class ContextTests(TestCase): def test_create_destroy(self): """Create and destroy a context""" for _ in range(25): ctx = moderngl.create_context(standalone=True) ctx.release() def test_context_switch(self): """Ensure context switching is working""" ctx1 = moderngl.create_context(standalone=True) ctx2 = moderngl.create_context(standalone=True) with ctx1 as ctx: buffer1 = ctx.buffer(reserve=1024) with ctx2 as ctx: buffer2 = ctx.buffer(reserve=1024) self.assertEqual(buffer1.glo, buffer2.glo) ctx1.release() ctx2.release() def test_exit(self): """Ensure the previous context was activated on exit""" ctx1 = moderngl.create_context(standalone=True) ctx2 = moderngl.create_context(standalone=True) with ctx1 as ctx: ctx.buffer(reserve=1024) # Will error out if no context is active "moderngl.error.Error: cannot create buffer" ctx1.buffer(reserve=1024) ctx1.release() ctx2.release() def test_share(self): """Create resources with shared context""" if platform.system().lower() in ["darwin", "linux"]: self.skipTest('Context sharing not supported on darwin') data1 = numpy.array([1, 2, 3, 4], dtype='u1') data2 = numpy.array([4, 3, 2, 1], dtype='u1') ctx1 = moderngl.create_context(standalone=True) ctx2 = moderngl.create_context(standalone=True, share=True) with ctx1 as ctx: b1 = ctx.buffer(data=data1) with ctx2 as ctx: b2 = ctx.buffer(data=data2) # Because the resources are shared the name should increment self.assertEqual(b1.glo, 1) self.assertEqual(b2.glo, 2) # Ensure we can read the same buffer data in both contexts with ctx1: self.assertEqual(b1.read(), b'\x01\x02\x03\x04') self.assertEqual(b2.read(), b'\x04\x03\x02\x01') with ctx2: self.assertEqual(b1.read(), b'\x01\x02\x03\x04') self.assertEqual(b2.read(), b'\x04\x03\x02\x01') ctx1.release() ctx2.release() def test_extensions(self): ctx = moderngl.create_context(standalone=True) # self.assertTrue("GL_ARB_vertex_array_object" in ctx.extensions) # self.assertTrue("GL_ARB_transform_feedback2" in ctx.extensions) # self.assertTrue("GL_ARB_shader_subroutine" in ctx.extensions) self.assertIsInstance(ctx.extensions, set) self.assertTrue(len(ctx.extensions) > 0) ctx.release() def test_attributes(self): """Ensure enums are present in the context instance""" ctx = moderngl.create_context(standalone=True) # Flags self.assertIsInstance(ctx.NOTHING, int) self.assertIsInstance(ctx.BLEND, int) self.assertIsInstance(ctx.DEPTH_TEST, int) self.assertIsInstance(ctx.CULL_FACE, int) self.assertIsInstance(ctx.RASTERIZER_DISCARD, int) self.assertIsInstance(ctx.PROGRAM_POINT_SIZE, int) # Primitive modes self.assertIsInstance(ctx.POINTS, int) self.assertIsInstance(ctx.LINES, int) self.assertIsInstance(ctx.LINE_LOOP, int) self.assertIsInstance(ctx.LINE_STRIP, int) self.assertIsInstance(ctx.TRIANGLES, int) self.assertIsInstance(ctx.TRIANGLE_STRIP, int) self.assertIsInstance(ctx.TRIANGLE_FAN, int) self.assertIsInstance(ctx.LINES_ADJACENCY, int) self.assertIsInstance(ctx.LINE_STRIP_ADJACENCY, int) self.assertIsInstance(ctx.TRIANGLES_ADJACENCY, int) self.assertIsInstance(ctx.TRIANGLE_STRIP_ADJACENCY, int) self.assertIsInstance(ctx.PATCHES, int) # Texture filters self.assertIsInstance(ctx.LINEAR, int) self.assertIsInstance(ctx.NEAREST, int) self.assertIsInstance(ctx.NEAREST_MIPMAP_NEAREST, int) self.assertIsInstance(ctx.LINEAR_MIPMAP_LINEAR, int) self.assertIsInstance(ctx.LINEAR_MIPMAP_NEAREST, int) self.assertIsInstance(ctx.NEAREST_MIPMAP_LINEAR, int) # Blend functions self.assertIsInstance(ctx.ZERO, int) self.assertIsInstance(ctx.ONE, int) self.assertIsInstance(ctx.SRC_COLOR, int) self.assertIsInstance(ctx.ONE_MINUS_SRC_COLOR, int) self.assertIsInstance(ctx.SRC_ALPHA, int) self.assertIsInstance(ctx.ONE_MINUS_SRC_ALPHA, int) self.assertIsInstance(ctx.DST_ALPHA, int) self.assertIsInstance(ctx.ONE_MINUS_DST_ALPHA, int) self.assertIsInstance(ctx.DST_COLOR, int) self.assertIsInstance(ctx.ONE_MINUS_DST_COLOR, int) # Blend shortcuts self.assertIsInstance(ctx.DEFAULT_BLENDING, tuple) self.assertIsInstance(ctx.ADDITIVE_BLENDING, tuple) self.assertIsInstance(ctx.PREMULTIPLIED_ALPHA, tuple) # Blend equations self.assertIsInstance(ctx.FUNC_ADD, int) self.assertIsInstance(ctx.FUNC_SUBTRACT, int) self.assertIsInstance(ctx.FUNC_REVERSE_SUBTRACT, int) self.assertIsInstance(ctx.MIN, int) self.assertIsInstance(ctx.MAX, int) # Provoking vertex self.assertIsInstance(ctx.FIRST_VERTEX_CONVENTION, int) self.assertIsInstance(ctx.LAST_VERTEX_CONVENTION, int) def test_enable_direct(self): ctx = moderngl.create_context(standalone=True) ctx.error # consume error during initialization # We already support this, but it's a safe value GL_PROGRAM_POINT_SIZE = 0x8642 ctx.enable_direct(GL_PROGRAM_POINT_SIZE) self.assertEqual(ctx.error, "GL_NO_ERROR") ctx.disable_direct(GL_PROGRAM_POINT_SIZE) self.assertEqual(ctx.error, "GL_NO_ERROR")
[ "platform.system", "numpy.array", "moderngl.create_context" ]
[((400, 440), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (423, 440), False, 'import moderngl\n'), ((456, 496), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (479, 496), False, 'import moderngl\n'), ((856, 896), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (879, 896), False, 'import moderngl\n'), ((912, 952), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (935, 952), False, 'import moderngl\n'), ((1418, 1455), 'numpy.array', 'numpy.array', (['[1, 2, 3, 4]'], {'dtype': '"""u1"""'}), "([1, 2, 3, 4], dtype='u1')\n", (1429, 1455), False, 'import numpy\n'), ((1472, 1509), 'numpy.array', 'numpy.array', (['[4, 3, 2, 1]'], {'dtype': '"""u1"""'}), "([4, 3, 2, 1], dtype='u1')\n", (1483, 1509), False, 'import numpy\n'), ((1526, 1566), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (1549, 1566), False, 'import moderngl\n'), ((1582, 1634), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)', 'share': '(True)'}), '(standalone=True, share=True)\n', (1605, 1634), False, 'import moderngl\n'), ((2355, 2395), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (2378, 2395), False, 'import moderngl\n'), ((2847, 2887), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (2870, 2887), False, 'import moderngl\n'), ((5504, 5544), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (5527, 5544), False, 'import moderngl\n'), ((232, 272), 'moderngl.create_context', 'moderngl.create_context', ([], {'standalone': '(True)'}), '(standalone=True)\n', (255, 272), False, 'import moderngl\n'), ((1282, 1299), 'platform.system', 'platform.system', ([], {}), '()\n', (1297, 1299), False, 'import platform\n')]
import gym import random import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.optimizers import Adam from rl.agents import DQNAgent from rl.policy import BoltzmannQPolicy from rl.memory import SequentialMemory env = gym.make('CartPole-v1') state_space = env.observation_space.shape[0] action_space = env.action_space.n #Create a deep learning model with keras def build_model(state_space, action_space): model = Sequential() model.add(Flatten(input_shape = (1, state_space))) model.add(Dense(24, activation = 'relu' )) model.add(Dense(24, activation = 'relu' )) model.add(Dense(action_space, activation = 'linear' )) return model # Build the agent with Keras-RL def build_agent(model, actions): policy = BoltzmannQPolicy() memory = SequentialMemory(limit = 50000, window_length=1) dqn = DQNAgent(model = model, memory = memory, policy = policy, nb_actions = actions, nb_steps_warmup = 10, target_model_update = 1e-2) return dqn #create the model model = build_model(state_space, action_space) # create agent dqn = build_agent(model, action_space) dqn.compile(Adam(lr=1e-3), metrics = ['mae']) dqn.fit(env, nb_steps = 10000, visualize = False ,verbose = 1) # print(model.summary()) # test the trained model scores = dqn.test(env, nb_episodes = 100, visualize = False) print(np.mean(scores.history['episode_reward'])) # visualize _ = dqn.test(env, nb_episodes=10, visualize = True)
[ "rl.memory.SequentialMemory", "gym.make", "tensorflow.keras.layers.Dense", "rl.policy.BoltzmannQPolicy", "numpy.mean", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.models.Sequential", "rl.agents.DQNAgent", "tensorflow.keras.layers.Flatten" ]
[((303, 326), 'gym.make', 'gym.make', (['"""CartPole-v1"""'], {}), "('CartPole-v1')\n", (311, 326), False, 'import gym\n'), ((504, 516), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (514, 516), False, 'from tensorflow.keras.models import Sequential\n'), ((821, 839), 'rl.policy.BoltzmannQPolicy', 'BoltzmannQPolicy', ([], {}), '()\n', (837, 839), False, 'from rl.policy import BoltzmannQPolicy\n'), ((853, 899), 'rl.memory.SequentialMemory', 'SequentialMemory', ([], {'limit': '(50000)', 'window_length': '(1)'}), '(limit=50000, window_length=1)\n', (869, 899), False, 'from rl.memory import SequentialMemory\n'), ((912, 1033), 'rl.agents.DQNAgent', 'DQNAgent', ([], {'model': 'model', 'memory': 'memory', 'policy': 'policy', 'nb_actions': 'actions', 'nb_steps_warmup': '(10)', 'target_model_update': '(0.01)'}), '(model=model, memory=memory, policy=policy, nb_actions=actions,\n nb_steps_warmup=10, target_model_update=0.01)\n', (920, 1033), False, 'from rl.agents import DQNAgent\n'), ((1192, 1206), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (1196, 1206), False, 'from tensorflow.keras.optimizers import Adam\n'), ((1408, 1449), 'numpy.mean', 'np.mean', (["scores.history['episode_reward']"], {}), "(scores.history['episode_reward'])\n", (1415, 1449), True, 'import numpy as np\n'), ((531, 568), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {'input_shape': '(1, state_space)'}), '(input_shape=(1, state_space))\n', (538, 568), False, 'from tensorflow.keras.layers import Dense, Flatten\n'), ((586, 614), 'tensorflow.keras.layers.Dense', 'Dense', (['(24)'], {'activation': '"""relu"""'}), "(24, activation='relu')\n", (591, 614), False, 'from tensorflow.keras.layers import Dense, Flatten\n'), ((633, 661), 'tensorflow.keras.layers.Dense', 'Dense', (['(24)'], {'activation': '"""relu"""'}), "(24, activation='relu')\n", (638, 661), False, 'from tensorflow.keras.layers import Dense, Flatten\n'), ((680, 720), 'tensorflow.keras.layers.Dense', 'Dense', (['action_space'], {'activation': '"""linear"""'}), "(action_space, activation='linear')\n", (685, 720), False, 'from tensorflow.keras.layers import Dense, Flatten\n')]
import os import pickle import random import numpy as np from carla.env.env_rendering import EnvRenderer, get_gt_factors from carla.train_agent import env_fnc from PIL import Image from tqdm import tqdm def check_dir(directory): if not os.path.exists(directory): print('{} not exist. calling mkdir!'.format(directory)) os.makedirs(directory) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--env', type=str, default='MiniGrid-Contextual-v0') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--norm_obs', default=False, action='store_true') parser.add_argument('--context_config', help="which context configuration to load") parser.add_argument('--n_samples', type=int, default=100) parser.add_argument('--root_path', type=str, default='') parser.add_argument('--tile_size', type=int, default=8) parser.add_argument('--reward', help="choose reward configuration") parser.add_argument('--grid_size', type=int, default=8) parser.add_argument('--n_objects', type=int, default=4) args = parser.parse_args() env_kwargs = dict(env_id=args.env, seed=args.seed, norm_obs=args.norm_obs, tile_size=args.tile_size, context_config=args.context_config, reward=args.reward, contextual=True, grid_size=args.grid_size, n_objects=args.n_objects) env = env_fnc(**env_kwargs)() max_n_goodies = env.unwrapped.n_goodies max_n_obstacles = env.unwrapped.n_obstacles total_objects = max_n_goodies + max_n_obstacles + 2 # +2 for agent and goal env_renderer = EnvRenderer(total_objects=total_objects, grid_size=args.grid_size, tile_size=args.tile_size, context_config=args.context_config) sample_counter = {} for i in tqdm(range(args.n_samples)): env.unwrapped.random_context = True env.unwrapped.n_obstacles = np.random.randint(0, max_n_obstacles + 1) env.unwrapped.n_goodies = np.random.randint(0, max_n_goodies + 1) obs = env.reset() # set random agent direction env.unwrapped.agent_dir = np.random.randint(0, 4) gt, agent_pos, agent_dir = get_gt_factors(env.unwrapped, total_objects, max_n_goodies, max_n_obstacles) valid_pos, valid_pos_transformed = env_renderer.get_empty_positions(agent_pos, agent_dir) # set random agent position agent_pos = random.choice(valid_pos_transformed) img = env_renderer.render_gt(gt, agent_pos, agent_dir) context = np.argmax(obs['context']) context = str(context) if context in sample_counter: sample_counter[context] += 1 else: sample_counter[context] = 0 img_path = os.path.join(args.root_path, context) check_dir(img_path) im = Image.fromarray(img) im.save('{}/{}.jpg'.format(img_path, sample_counter[context])) with open('{}/{}.pkl'.format(img_path, sample_counter[context]), 'wb') as f: pickle.dump(gt, f)
[ "pickle.dump", "os.makedirs", "argparse.ArgumentParser", "carla.env.env_rendering.EnvRenderer", "numpy.argmax", "os.path.exists", "carla.train_agent.env_fnc", "carla.env.env_rendering.get_gt_factors", "random.choice", "numpy.random.randint", "PIL.Image.fromarray", "os.path.join" ]
[((431, 456), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (454, 456), False, 'import argparse\n'), ((1661, 1793), 'carla.env.env_rendering.EnvRenderer', 'EnvRenderer', ([], {'total_objects': 'total_objects', 'grid_size': 'args.grid_size', 'tile_size': 'args.tile_size', 'context_config': 'args.context_config'}), '(total_objects=total_objects, grid_size=args.grid_size,\n tile_size=args.tile_size, context_config=args.context_config)\n', (1672, 1793), False, 'from carla.env.env_rendering import EnvRenderer, get_gt_factors\n'), ((246, 271), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (260, 271), False, 'import os\n'), ((345, 367), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (356, 367), False, 'import os\n'), ((1443, 1464), 'carla.train_agent.env_fnc', 'env_fnc', ([], {}), '(**env_kwargs)\n', (1450, 1464), False, 'from carla.train_agent import env_fnc\n'), ((1970, 2011), 'numpy.random.randint', 'np.random.randint', (['(0)', '(max_n_obstacles + 1)'], {}), '(0, max_n_obstacles + 1)\n', (1987, 2011), True, 'import numpy as np\n'), ((2046, 2085), 'numpy.random.randint', 'np.random.randint', (['(0)', '(max_n_goodies + 1)'], {}), '(0, max_n_goodies + 1)\n', (2063, 2085), True, 'import numpy as np\n'), ((2184, 2207), 'numpy.random.randint', 'np.random.randint', (['(0)', '(4)'], {}), '(0, 4)\n', (2201, 2207), True, 'import numpy as np\n'), ((2243, 2319), 'carla.env.env_rendering.get_gt_factors', 'get_gt_factors', (['env.unwrapped', 'total_objects', 'max_n_goodies', 'max_n_obstacles'], {}), '(env.unwrapped, total_objects, max_n_goodies, max_n_obstacles)\n', (2257, 2319), False, 'from carla.env.env_rendering import EnvRenderer, get_gt_factors\n'), ((2476, 2512), 'random.choice', 'random.choice', (['valid_pos_transformed'], {}), '(valid_pos_transformed)\n', (2489, 2512), False, 'import random\n'), ((2596, 2621), 'numpy.argmax', 'np.argmax', (["obs['context']"], {}), "(obs['context'])\n", (2605, 2621), True, 'import numpy as np\n'), ((2806, 2843), 'os.path.join', 'os.path.join', (['args.root_path', 'context'], {}), '(args.root_path, context)\n', (2818, 2843), False, 'import os\n'), ((2886, 2906), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (2901, 2906), False, 'from PIL import Image\n'), ((3075, 3093), 'pickle.dump', 'pickle.dump', (['gt', 'f'], {}), '(gt, f)\n', (3086, 3093), False, 'import pickle\n')]
#!/usr/bin/env python # coding: utf-8 from nltk.tokenize import sent_tokenize from nltk import word_tokenize from sklearn.model_selection import train_test_split from nltk.stem.snowball import SnowballStemmer from sklearn.preprocessing import StandardScaler from sklearn.model_selection import KFold from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import BernoulliNB, MultinomialNB from sklearn import datasets from pandas import DataFrame import nltk import numpy as np import nltk.stem from sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix, accuracy_score import itertools from sklearn.linear_model import LogisticRegression import os from sklearn.svm import SVC from numpy import random def load_text(pos_path, neg_path): #pos_path = 'rt-polarity.pos' #neg_path = 'rt-polarity.neg' f_pos = open(pos_path, 'r', encoding='ISO-8859-1') f_neg = open(neg_path, 'r', encoding='ISO-8859-1') all_sentences = [] for sentence in sent_tokenize(f_pos.read()): all_sentences.append({'context': sentence, 'sentiment': 'positive'}) for sentence in sent_tokenize(f_neg.read()): all_sentences.append({'context': sentence, 'sentiment': 'negative'}) f_pos.close() f_neg.close() return all_sentences def create_df(sentences_with_class): sent = DataFrame(sentences_with_class) return sent # generate all possible combinations of parameters (including default) def generate_parameter(): list_of_parameters = [['lemm', 'stem', None], # use lemmatize or stem [None, 'english'], # use stopword or not [0, 0.1, 0.01] # min_df ] para_groups = list(itertools.product(*list_of_parameters)) return para_groups # analyzer for use in CountVectorizer stemmer = SnowballStemmer('english') class StemmedCountVectorizer(CountVectorizer): def build_analyzer(self): analyzer = super(StemmedCountVectorizer, self).build_analyzer() return lambda doc: ([stemmer.stem(w) for w in analyzer(doc)]) lemmatizer = nltk.stem.WordNetLemmatizer() class LemmCountVectorizer(CountVectorizer): def build_analyzer(self): analyzer = super(LemmCountVectorizer, self).build_analyzer() return lambda doc: ([stemmer.stem(w) for w in analyzer(doc)]) def random_model(test_X): random_results = [] two_outcomes = ['positive', 'negative'] for line in test_X: random_results.append(random.choice(two_outcomes)) return random_results def run_Classifier(para_groups, clfs, train): # set up all containers for test results all_scores = [] all_paras = [] all_clf_pipes = [] #all_conf_mat = [] with open('accuracy_summarys_final.txt', 'a+') as f: current_iter = 1 for clf in clfs: f.write('\n---------------------------------------------\n') f.write('Current experimenting type of classifier: ' + str(clf) + ' \n\n\n') for paras in para_groups: print('current iteration: ' + str(current_iter)) current_iter = current_iter + 1 if (paras[0] == 'lemm'): vectorizer = LemmCountVectorizer(min_df=paras[2], analyzer="word", stop_words=paras[1]) if (paras[0] == 'stem'): vectorizer = StemmedCountVectorizer(min_df=paras[2], analyzer="word", stop_words=paras[1]) else: vectorizer = CountVectorizer(min_df=paras[2], stop_words=paras[1]) pipe = Pipeline([ ('count_vectorizer', vectorizer), ('classifier', clf) ]) kf_clf_scores = [] kf_random_scores = [] # use cross-validation X = train.context kf = KFold(n_splits= 8, shuffle=True) for train_index, test_index in kf.split(X): train_X = df.iloc[train_index]['context'].values train_Y = df.iloc[train_index]['sentiment'].values test_X = df.iloc[test_index]['context'].values test_Y = df.iloc[test_index]['sentiment'].values pipe.fit(train_X, train_Y) random_Y = random_model(test_X) current_clf_score = accuracy_score(test_Y, pipe.predict(test_X)) random_score = accuracy_score(test_Y, random_Y) kf_clf_scores.append(current_clf_score) kf_random_scores.append(random_score) all_scores.append(sum(kf_clf_scores)/len(kf_clf_scores)) all_paras.append(paras) all_clf_pipes.append(pipe) f.write('Parameters: ' + str(paras) + '\n') f.write('Score: ' + str(sum(kf_clf_scores)/len(kf_clf_scores)) + '\n') f.write('Random Model Score: ' + str(sum(kf_random_scores)/len(kf_random_scores)) + '\n\n') return all_scores, all_paras, all_clf_pipes def find_best_model(all_scores, all_paras, pipes, clfs, para_groups): best_clf_pipes = [] best_paras = [] with open('best_models_final.txt', 'a+') as best: i = 0 for clf in clfs: subarr_acc = all_scores[i : i+len(para_groups)-1] best_acc = max(subarr_acc) best_idx = subarr_acc.index(max(subarr_acc)) i = i + len(para_groups) best.write('The best ' + str(clf) + ' used the following parameters: ' + str(all_paras[best_idx]) + ' \n') best.write('Train Accuracy: ' + str(best_acc) + '\n') best.write('--------------------------------------\n') best_paras.append(all_paras[best_idx]) best_clf_pipes.append(pipes[best_idx]) return best_clf_pipes, best_paras # this function has been discarded def test_best_model(clf_pipes, paras, test_df): clfs = [BernoulliNB(), LogisticRegression(solver='lbfgs', max_iter=400), SVC(kernel = 'linear'), MultinomialNB()] with open('best_models_final.txt', 'a+') as best: best.write('\n\n\nBelow are test accuracies and confusion matrices of the above best models: \n\n') for i in range(len(clf_pipes)): Y_predict = clf_pipes[i].predict(test_df.context) model_acc = accuracy_score(test_df.sentiment, Y_predict) con_m = confusion_matrix(test_df.sentiment, Y_predict) best.write('Best ' + str(clfs[i]) + ' \n') best.write('Test Accuracy: ' + str(best_acc) + '\n') best.write('Confusion matrix: ' + str(con_m) ) best.write('--------------------------------------\n') # run_test_set is similar to run_Classifier but without implementation of cross-validation def run_test_set(clfs, para_groups, training_set_df, test_set_df): with open('best_models_test_set_final.txt', 'a+') as best: for i in range(len(clfs)): print('current iteration: ' + str(i)) paras = para_groups[i] if (paras[0] == 'lemm'): vectorizer = LemmCountVectorizer(min_df=paras[2], analyzer="word", stop_words=paras[1]) if (paras[0] == 'stem'): vectorizer = StemmedCountVectorizer(min_df=paras[2], analyzer="word", stop_words=paras[1]) else: vectorizer = CountVectorizer(min_df=paras[2], stop_words=paras[1]) pipe = Pipeline([ ('count_vectorizer', vectorizer), ('classifier', clfs[i]) ]) pipe.fit(training_set_df.context,training_set_df.sentiment) test_y_hat = pipe.predict(test_set_df.context) test_acc = accuracy_score(test_set_df.sentiment, test_y_hat) conf_mtx = confusion_matrix(test_set_df.sentiment, test_y_hat, labels = ['positive', 'negative']) best.write(str(clfs[i]) + ' with parameters: ' + str(para_groups[i]) + ' has test accuracy: ' + str(test_acc) + '\n') best.write('Its confusion matrix is\n' + str(conf_mtx) + '\n\n') df = create_df(load_text(r'rt-polarity.pos', r'rt-polarity.neg')) para_groups = generate_parameter() train_df, test_df = train_test_split(df, test_size=0.2) clfs = [BernoulliNB(), LogisticRegression(solver='lbfgs', max_iter=400), SVC(kernel = 'linear'), MultinomialNB()] all_scores, all_paras, all_clf_pipes = run_Classifier(para_groups, clfs, train_df) find_best_model(all_scores, all_paras, all_clf_pipes, clfs, para_groups) print('Running clfs on test set...') # manually examine the best clfs and parameters in 'best_models.txt' and typed the data below best_para_groups = [('stem', None, 0) , ('stem', None, 0), ('stem', None, 0), ('lemm', None, 0) ] run_test_set(clfs, best_para_groups, train_df, test_df)
[ "pandas.DataFrame", "numpy.random.choice", "nltk.stem.snowball.SnowballStemmer", "sklearn.metrics.confusion_matrix", "sklearn.feature_extraction.text.CountVectorizer", "sklearn.naive_bayes.MultinomialNB", "nltk.stem.WordNetLemmatizer", "sklearn.model_selection.train_test_split", "sklearn.metrics.accuracy_score", "sklearn.model_selection.KFold", "sklearn.linear_model.LogisticRegression", "sklearn.svm.SVC", "sklearn.pipeline.Pipeline", "itertools.product", "sklearn.naive_bayes.BernoulliNB" ]
[((1878, 1904), 'nltk.stem.snowball.SnowballStemmer', 'SnowballStemmer', (['"""english"""'], {}), "('english')\n", (1893, 1904), False, 'from nltk.stem.snowball import SnowballStemmer\n'), ((2142, 2171), 'nltk.stem.WordNetLemmatizer', 'nltk.stem.WordNetLemmatizer', ([], {}), '()\n', (2169, 2171), False, 'import nltk\n'), ((8813, 8848), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df'], {'test_size': '(0.2)'}), '(df, test_size=0.2)\n', (8829, 8848), False, 'from sklearn.model_selection import train_test_split\n'), ((1376, 1407), 'pandas.DataFrame', 'DataFrame', (['sentences_with_class'], {}), '(sentences_with_class)\n', (1385, 1407), False, 'from pandas import DataFrame\n'), ((8858, 8871), 'sklearn.naive_bayes.BernoulliNB', 'BernoulliNB', ([], {}), '()\n', (8869, 8871), False, 'from sklearn.naive_bayes import BernoulliNB, MultinomialNB\n'), ((8873, 8921), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'solver': '"""lbfgs"""', 'max_iter': '(400)'}), "(solver='lbfgs', max_iter=400)\n", (8891, 8921), False, 'from sklearn.linear_model import LogisticRegression\n'), ((8923, 8943), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""'}), "(kernel='linear')\n", (8926, 8943), False, 'from sklearn.svm import SVC\n'), ((8947, 8962), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {}), '()\n', (8960, 8962), False, 'from sklearn.naive_bayes import BernoulliNB, MultinomialNB\n'), ((1764, 1802), 'itertools.product', 'itertools.product', (['*list_of_parameters'], {}), '(*list_of_parameters)\n', (1781, 1802), False, 'import itertools\n'), ((6335, 6348), 'sklearn.naive_bayes.BernoulliNB', 'BernoulliNB', ([], {}), '()\n', (6346, 6348), False, 'from sklearn.naive_bayes import BernoulliNB, MultinomialNB\n'), ((6350, 6398), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'solver': '"""lbfgs"""', 'max_iter': '(400)'}), "(solver='lbfgs', max_iter=400)\n", (6368, 6398), False, 'from sklearn.linear_model import LogisticRegression\n'), ((6400, 6420), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""'}), "(kernel='linear')\n", (6403, 6420), False, 'from sklearn.svm import SVC\n'), ((6424, 6439), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {}), '()\n', (6437, 6439), False, 'from sklearn.naive_bayes import BernoulliNB, MultinomialNB\n'), ((2537, 2564), 'numpy.random.choice', 'random.choice', (['two_outcomes'], {}), '(two_outcomes)\n', (2550, 2564), False, 'from numpy import random\n'), ((6748, 6792), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['test_df.sentiment', 'Y_predict'], {}), '(test_df.sentiment, Y_predict)\n', (6762, 6792), False, 'from sklearn.metrics import confusion_matrix, accuracy_score\n'), ((6813, 6859), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['test_df.sentiment', 'Y_predict'], {}), '(test_df.sentiment, Y_predict)\n', (6829, 6859), False, 'from sklearn.metrics import confusion_matrix, accuracy_score\n'), ((7947, 8016), 'sklearn.pipeline.Pipeline', 'Pipeline', (["[('count_vectorizer', vectorizer), ('classifier', clfs[i])]"], {}), "([('count_vectorizer', vectorizer), ('classifier', clfs[i])])\n", (7955, 8016), False, 'from sklearn.pipeline import Pipeline\n'), ((8246, 8295), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['test_set_df.sentiment', 'test_y_hat'], {}), '(test_set_df.sentiment, test_y_hat)\n', (8260, 8295), False, 'from sklearn.metrics import confusion_matrix, accuracy_score\n'), ((8332, 8420), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['test_set_df.sentiment', 'test_y_hat'], {'labels': "['positive', 'negative']"}), "(test_set_df.sentiment, test_y_hat, labels=['positive',\n 'negative'])\n", (8348, 8420), False, 'from sklearn.metrics import confusion_matrix, accuracy_score\n'), ((3709, 3774), 'sklearn.pipeline.Pipeline', 'Pipeline', (["[('count_vectorizer', vectorizer), ('classifier', clf)]"], {}), "([('count_vectorizer', vectorizer), ('classifier', clf)])\n", (3717, 3774), False, 'from sklearn.pipeline import Pipeline\n'), ((4030, 4061), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(8)', 'shuffle': '(True)'}), '(n_splits=8, shuffle=True)\n', (4035, 4061), False, 'from sklearn.model_selection import KFold\n'), ((7848, 7901), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'min_df': 'paras[2]', 'stop_words': 'paras[1]'}), '(min_df=paras[2], stop_words=paras[1])\n', (7863, 7901), False, 'from sklearn.feature_extraction.text import CountVectorizer\n'), ((3623, 3676), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'min_df': 'paras[2]', 'stop_words': 'paras[1]'}), '(min_df=paras[2], stop_words=paras[1])\n', (3638, 3676), False, 'from sklearn.feature_extraction.text import CountVectorizer\n'), ((4660, 4692), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['test_Y', 'random_Y'], {}), '(test_Y, random_Y)\n', (4674, 4692), False, 'from sklearn.metrics import confusion_matrix, accuracy_score\n')]
import datetime import pytest from fuzzyfields import Timestamp, MalformedFieldError from . import has_pandas, requires_pandas if has_pandas: import numpy import pandas else: class numpy: @classmethod def datetime64(cls, x): pass class pandas: @classmethod def to_datetime(cls, x): pass @requires_pandas @pytest.mark.parametrize('value', [ 'not a date', '10/notAMonth/2016', '2016-00-01', '2016-13-13', '2016-01-00', '2016-02-30' ]) def test_malformed(value): v = Timestamp() with pytest.raises(MalformedFieldError) as e: v.parse(value) assert str(e.value) == f"Malformed field: expected date, got '{value}'" @requires_pandas @pytest.mark.parametrize('dayfirst', [False, True]) @pytest.mark.parametrize('yearfirst', [False, True]) @pytest.mark.parametrize('value', [ '11 March 2016', '11th March 2016', 'March 11th 2016', '11 mar 2016', '2016-03-11', '2016/03/11', '2016.03.11', '20160311', ]) def test_unambiguous(dayfirst, yearfirst, value): expect = pandas.to_datetime('11 March 2016') v = Timestamp(dayfirst=dayfirst, yearfirst=yearfirst) assert v.parse(value) == expect @requires_pandas def test_ambiguous(): """European notation is preferred to the American one by default """ expect = pandas.to_datetime('10 nov 2012') v = Timestamp() assert v.parse('10/11/2012') == expect assert v.parse('10/11/12') == expect assert v.parse('10-11-12') == expect assert v.parse('10.11.12') == expect v = Timestamp(dayfirst=False) assert v.parse('11/10/12') == expect @requires_pandas def test_leapyear(): v = Timestamp() with pytest.raises(MalformedFieldError) as e: v.parse('2015/02/29') assert str(e.value) == "Malformed field: expected date, got '2015/02/29'" assert v.parse('2016/02/29') == pandas.to_datetime('29 feb 2016') @requires_pandas @pytest.mark.parametrize('output,expect', [ ('pandas', pandas.to_datetime('2012-11-10')), ('numpy', numpy.datetime64('2012-11-10')), ('datetime', datetime.datetime(2012, 11, 10)), ('%Y/%m/%d', '2012/11/10'), ('%m %Y', '11 2012'), ]) def test_format(output, expect): v = Timestamp(output=output) assert v.parse('10/11/12') == expect @requires_pandas @pytest.mark.parametrize('value,expect', [ ('1677-09-21', '1677-09-22'), ('1677-09-22', '1677-09-22'), ('1677-09-23', '1677-09-23'), ('2262-04-10', '2262-04-10'), ('2262-04-11', '2262-04-11'), ('2262-04-12', '2262-04-11'), ]) def test_outofbounds_pandas(value, expect, recwarn): v = Timestamp() assert v.parse(value) == pandas.to_datetime(expect) if value == expect: assert not recwarn else: assert len(recwarn) == 1 assert str(recwarn.pop().message) == ( f'Timestamp {value} 00:00:00 is out of bounds; forcing it to ' f'{expect}') @requires_pandas @pytest.mark.parametrize('output,value,expect', [ ('numpy', '1000-01-01', numpy.datetime64('1000-01-01')), ('numpy', '5000-01-01', numpy.datetime64('5000-01-01')), ('datetime', '1000-01-01', datetime.datetime(1000, 1, 1)), ('datetime', '5000-01-01', datetime.datetime(5000, 1, 1)), ('%Y-%m-%d', '1000-01-01', '1000-01-01'), ('%Y-%m-%d', '5000-01-01', '5000-01-01'), ]) def test_outofbounds_notpandas(output, value, expect, recwarn): """Only output='pandas' has the problem of clipping """ v = Timestamp(output=output) assert v.parse(value) == expect assert not recwarn
[ "fuzzyfields.Timestamp", "numpy.datetime64", "datetime.datetime", "pytest.raises", "pandas.to_datetime", "pytest.mark.parametrize" ]
[((381, 510), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value"""', "['not a date', '10/notAMonth/2016', '2016-00-01', '2016-13-13',\n '2016-01-00', '2016-02-30']"], {}), "('value', ['not a date', '10/notAMonth/2016',\n '2016-00-01', '2016-13-13', '2016-01-00', '2016-02-30'])\n", (404, 510), False, 'import pytest\n'), ((733, 783), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dayfirst"""', '[False, True]'], {}), "('dayfirst', [False, True])\n", (756, 783), False, 'import pytest\n'), ((785, 836), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""yearfirst"""', '[False, True]'], {}), "('yearfirst', [False, True])\n", (808, 836), False, 'import pytest\n'), ((838, 1004), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value"""', "['11 March 2016', '11th March 2016', 'March 11th 2016', '11 mar 2016',\n '2016-03-11', '2016/03/11', '2016.03.11', '20160311']"], {}), "('value', ['11 March 2016', '11th March 2016',\n 'March 11th 2016', '11 mar 2016', '2016-03-11', '2016/03/11',\n '2016.03.11', '20160311'])\n", (861, 1004), False, 'import pytest\n'), ((2316, 2552), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value,expect"""', "[('1677-09-21', '1677-09-22'), ('1677-09-22', '1677-09-22'), ('1677-09-23',\n '1677-09-23'), ('2262-04-10', '2262-04-10'), ('2262-04-11',\n '2262-04-11'), ('2262-04-12', '2262-04-11')]"], {}), "('value,expect', [('1677-09-21', '1677-09-22'), (\n '1677-09-22', '1677-09-22'), ('1677-09-23', '1677-09-23'), (\n '2262-04-10', '2262-04-10'), ('2262-04-11', '2262-04-11'), (\n '2262-04-12', '2262-04-11')])\n", (2339, 2552), False, 'import pytest\n'), ((552, 563), 'fuzzyfields.Timestamp', 'Timestamp', ([], {}), '()\n', (561, 563), False, 'from fuzzyfields import Timestamp, MalformedFieldError\n'), ((1071, 1106), 'pandas.to_datetime', 'pandas.to_datetime', (['"""11 March 2016"""'], {}), "('11 March 2016')\n", (1089, 1106), False, 'import pandas\n'), ((1115, 1164), 'fuzzyfields.Timestamp', 'Timestamp', ([], {'dayfirst': 'dayfirst', 'yearfirst': 'yearfirst'}), '(dayfirst=dayfirst, yearfirst=yearfirst)\n', (1124, 1164), False, 'from fuzzyfields import Timestamp, MalformedFieldError\n'), ((1332, 1365), 'pandas.to_datetime', 'pandas.to_datetime', (['"""10 nov 2012"""'], {}), "('10 nov 2012')\n", (1350, 1365), False, 'import pandas\n'), ((1374, 1385), 'fuzzyfields.Timestamp', 'Timestamp', ([], {}), '()\n', (1383, 1385), False, 'from fuzzyfields import Timestamp, MalformedFieldError\n'), ((1561, 1586), 'fuzzyfields.Timestamp', 'Timestamp', ([], {'dayfirst': '(False)'}), '(dayfirst=False)\n', (1570, 1586), False, 'from fuzzyfields import Timestamp, MalformedFieldError\n'), ((1676, 1687), 'fuzzyfields.Timestamp', 'Timestamp', ([], {}), '()\n', (1685, 1687), False, 'from fuzzyfields import Timestamp, MalformedFieldError\n'), ((2230, 2254), 'fuzzyfields.Timestamp', 'Timestamp', ([], {'output': 'output'}), '(output=output)\n', (2239, 2254), False, 'from fuzzyfields import Timestamp, MalformedFieldError\n'), ((2626, 2637), 'fuzzyfields.Timestamp', 'Timestamp', ([], {}), '()\n', (2635, 2637), False, 'from fuzzyfields import Timestamp, MalformedFieldError\n'), ((3483, 3507), 'fuzzyfields.Timestamp', 'Timestamp', ([], {'output': 'output'}), '(output=output)\n', (3492, 3507), False, 'from fuzzyfields import Timestamp, MalformedFieldError\n'), ((573, 607), 'pytest.raises', 'pytest.raises', (['MalformedFieldError'], {}), '(MalformedFieldError)\n', (586, 607), False, 'import pytest\n'), ((1697, 1731), 'pytest.raises', 'pytest.raises', (['MalformedFieldError'], {}), '(MalformedFieldError)\n', (1710, 1731), False, 'import pytest\n'), ((1883, 1916), 'pandas.to_datetime', 'pandas.to_datetime', (['"""29 feb 2016"""'], {}), "('29 feb 2016')\n", (1901, 1916), False, 'import pandas\n'), ((2667, 2693), 'pandas.to_datetime', 'pandas.to_datetime', (['expect'], {}), '(expect)\n', (2685, 2693), False, 'import pandas\n'), ((1995, 2027), 'pandas.to_datetime', 'pandas.to_datetime', (['"""2012-11-10"""'], {}), "('2012-11-10')\n", (2013, 2027), False, 'import pandas\n'), ((2044, 2074), 'numpy.datetime64', 'numpy.datetime64', (['"""2012-11-10"""'], {}), "('2012-11-10')\n", (2060, 2074), False, 'import numpy\n'), ((2094, 2125), 'datetime.datetime', 'datetime.datetime', (['(2012)', '(11)', '(10)'], {}), '(2012, 11, 10)\n', (2111, 2125), False, 'import datetime\n'), ((3032, 3062), 'numpy.datetime64', 'numpy.datetime64', (['"""1000-01-01"""'], {}), "('1000-01-01')\n", (3048, 3062), False, 'import numpy\n'), ((3093, 3123), 'numpy.datetime64', 'numpy.datetime64', (['"""5000-01-01"""'], {}), "('5000-01-01')\n", (3109, 3123), False, 'import numpy\n'), ((3157, 3186), 'datetime.datetime', 'datetime.datetime', (['(1000)', '(1)', '(1)'], {}), '(1000, 1, 1)\n', (3174, 3186), False, 'import datetime\n'), ((3220, 3249), 'datetime.datetime', 'datetime.datetime', (['(5000)', '(1)', '(1)'], {}), '(5000, 1, 1)\n', (3237, 3249), False, 'import datetime\n')]
from .filters import Filter import numpy as np from astropy.io import fits from scipy.constants import c class SED: """ Represents an SED Wavelength is given in micron, Fnu is in Jy. """ def __init__(self, wavelengths, fnu, ferr=None): if (ferr is not None) and (len(ferr.shape) > 1) and (ferr.shape[0] != 2): raise ValueError('SED ferr should be either 1-dimensional ' '(symmetric errors) or shape (2, N) (lower, ' 'upper error)') self.wavelengths = np.array(wavelengths) self.fnu = np.array(fnu) self.ferr = ferr def __mul__(self, other): new = self.copy() new.fnu = self.fnu * other if self.ferr is not None: new.ferr = self.ferr * other return new def __truediv__(self, other): new = self.copy() new.fnu = self.fnu / other if self.ferr is not None: new.ferr = self.ferr / other return new def copy(self): """Returns a copy""" return type(self)(self.wavelengths.copy(), self.fnu.copy()) class HighresSED(SED): """ Represents an SED that is sampled at high spectral resolution, probably originating from a library of models. """ def __init__(self, wavelengths, fnu, ferr=None): super().__init__(wavelengths, fnu, ferr) @classmethod def from_cigale_fits(cls, filename, flux_column='Fnu', fluxfactor=1, hdu_index=1, combine_column_list=True): ''' Create a full SED from a cigale output (name_best_fit.fits) and convert to Jy. fluxfactor : float, default: 1. The factor with which we multiply the flux to convert it to Jy, on top of the default mJy to Jy conversion. If the CIGALE INPUT was (mistakingly) in Jy, set this to 1e3. combine_column_list : bool, default True. Only used if flux_column is iterable. If True, return a single HighresSED, where the flux is the sum of the given flux columns. If False, return an equally large list of HighresSEDs. ''' hdu = fits.open(filename)[hdu_index] wavelengths = hdu.data['wavelength'] / 1e3 # from nm to micron def get_fnu(fluxcol): fnu = hdu.data[fluxcol] * fluxfactor if fluxcol == 'Fnu': fnu /= 1e3 # From mJy to Jy else: # from W/nm to per W/Hz fnu = np.square(wavelengths) * fnu / (c * 1e3) return fnu if isinstance(flux_column, (list, tuple)): if not combine_column_list: return [cls(wavelengths, get_fnu(fluxcol)) for fluxcol in flux_column] fnu = sum([get_fnu(fluxcol) for fluxcol in flux_column]) else: fnu = get_fnu(flux_column) return cls(wavelengths, fnu) def to_broadband(self, filters, quick=False): ''' Transforms the full SED to broadband (returns new BroadbandSED). Parameters ---------- filters : iterable The elements should be either of class `Filter`, or strings from which a filter can be created. When calling this function multiple times, create the `Filter`s beforehand so you can reuse them. If using strings, the `Filter`s will be loaded from disk which is slow. quick : bool, default False If True, take the flux closest to the filters pivot wavelength, instead of doing the convolution. ''' ffilters = [] # make sure to copy fnu_bands = [] for filt in filters: if not isinstance(filt, Filter): filt = Filter(filt) ffilters.append(filt) if quick: best_idx = np.searchsorted(self.wavelengths, filt.pivot_wavelength()) fnu = self.fnu[best_idx] else: fnu = filt.convolve(self.wavelengths, self.fnu) fnu_bands.append(fnu) return BroadbandSED(ffilters, fnu_bands) def blueshift(self, z): ''' Blueshift the spectrum (to bring it to restframe), by shifting all wavelengths. ''' # Divide by (1+z) becaues fnu (F_nu dnu = F_lambda dlambda stays # constant when redshifting). See Hogg 2002 and Hogg 2000 on K-correction. self.fnu = self.fnu / (1 + z) self.wavelengths = self.wavelengths / (1+z) def redshift(self, z): '''Redshift the model spectrum, by shifting all wavelengths.''' self.fnu = self.fnu * (1 + z) self.wavelengths = self.wavelengths * (1 + z) class BroadbandSED(SED): """ An SED measured over a few broadbands. """ def __init__(self, filters, fnu, ferr=None): wavelengths = [] filter_objs = [] # create new copy so we can modify list for filt in filters: if not isinstance(filt, Filter): filt = Filter(filt) filter_objs.append(filt) wavelengths.append(filt.pivot_wavelength()) super().__init__(wavelengths, fnu, ferr) self.filters = filter_objs def k_correct(self, z, modelSED): """Perform a K-correction, assuming an underlying model SED. Returns a new BroadbandSED with the corrected values. For each broadband, the model SED is scaled to the appropriate level, so its normalization does not matter. The modelSED is redshifted (matching the BroadbandSED before doing the K-correct). """ # isinstance fails due to multiple model imports if not 'HighresSED' in str(type(modelSED)): raise ValueError('modelSED must be a HighresSED, was', type(modelSED)) model_broad = modelSED.to_broadband(self.filters) fnu_kcorr = [] for i, filt in enumerate(self.filters): scalef = self.fnu[i] / model_broad.fnu[i] model_f = modelSED * scalef model_f.blueshift(z) fnu_band = filt.convolve(model_f.wavelengths, model_f.fnu) fnu_kcorr.append(fnu_band) return BroadbandSED(self.filters, fnu_kcorr) def copy(self): """Returns a copy""" return type(self)(self.filters, self.fnu.copy(), self.ferr.copy())
[ "numpy.square", "numpy.array", "astropy.io.fits.open" ]
[((564, 585), 'numpy.array', 'np.array', (['wavelengths'], {}), '(wavelengths)\n', (572, 585), True, 'import numpy as np\n'), ((605, 618), 'numpy.array', 'np.array', (['fnu'], {}), '(fnu)\n', (613, 618), True, 'import numpy as np\n'), ((2210, 2229), 'astropy.io.fits.open', 'fits.open', (['filename'], {}), '(filename)\n', (2219, 2229), False, 'from astropy.io import fits\n'), ((2536, 2558), 'numpy.square', 'np.square', (['wavelengths'], {}), '(wavelengths)\n', (2545, 2558), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np def load_cifar10(num_batch_train, num_batch_test, mode='RGB'): """Load CIFAR-10 dataset with Tensorflow built-in function. Generate and shuffle CIFAR-10 iterators via using tf.data.Data. :param num_batch_train: An integer. :param num_batch_test: An integer. :param mode: String in {'RGB', 'HSV', 'TUV'} :return train_slice, test_slice: Iterator for training and testing data. """ assert isinstance(num_batch_train, int) assert isinstance(num_batch_test, int) dataset = tf.keras.datasets.cifar10 (x_train, y_train), (x_test, y_test) = dataset.load_data() # By converting dtype to make Tensorflow automatically use GPU. x_train = tf.image.convert_image_dtype(x_train, tf.float32) x_test = tf.image.convert_image_dtype(x_test, tf.float32) if mode == 'RGB': pass elif mode == 'HSV': x_train = tf.image.rgb_to_hsv(x_train) x_test = tf.image.rgb_to_hsv(x_test) elif mode == 'TUV': x_train = tf.image.rgb_to_hsv(x_train) x_test = tf.image.rgb_to_hsv(x_test) x_train, x_test = hsv_to_tuv(x_train), hsv_to_tuv(x_test) else: raise NotImplementedError( 'Input mode is not valid, could be RGB, HSV, TUV, your input: {}'.format(mode)) train_slice = tf.data.Dataset.from_tensor_slices((x_train, y_train)) test_slice = tf.data.Dataset.from_tensor_slices((x_test, y_test)) train_slice = train_slice.shuffle(x_train.shape[0]) train_slice = train_slice.batch(num_batch_train) test_slice = test_slice.batch(num_batch_test) train_slice = train_slice.prefetch(buffer_size=num_batch_train) test_slice = test_slice.prefetch(buffer_size=num_batch_test) return train_slice, test_slice def inverse_specific_labeled_images(img, label, anomaly_label): """Inverse images which has specific labels via negative images and plus 1. :param img: Floating point images in range of [0.0, 1.0] with shape [batch_size, image_size, image_size, image_channel]. :param label: A integer tensor with shape [batch_size,]. :param anomaly_label: An integer in range [0, 9]. :return img: Images with some batch inversed with same shape as input images. """ assert isinstance(anomaly_label, int) assert anomaly_label >= 0 assert anomaly_label < 10 mask_anomaly = tf.where(tf.equal(label, anomaly_label), tf.ones(label.shape), tf.zeros(label.shape)) if len(img._shape_as_list()) == 4: batch_size = mask_anomaly.shape[0] mask_anomaly = tf.reshape(mask_anomaly, [batch_size, 1, 1, 1]) elif len(img._shape_as_list()) == 2: pass else: raise NotImplementedError('Your img._shape_as_list(): {}'.format(img._shape_as_list())) mask_normal = 1.0 - mask_anomaly img = tf.cast(img, tf.float32) img = tf.subtract( tf.multiply(tf.ones(img.shape), mask_anomaly), tf.multiply(img, mask_anomaly)) + tf.multiply(img, mask_normal) return img def inverse_multiple_labeled_images(img, label, anomaly_label): """Inverse images which has specific labels via negative images and plus 1. :param img: Floating point images in range of [0.0, 1.0] with shape [batch_size, image_size, image_size, image_channel]. :param label: A integer tensor with shape [batch_size,]. :param anomaly_label: A list of integer of [0, 9] :return img: Images with some batch inversed with same shape as input images. """ assert isinstance(anomaly_label, list) mask_anomaly = tf.where(tf.equal(label, anomaly_label[0]), tf.ones(label.shape), tf.zeros(label.shape)) for idx, i in enumerate(anomaly_label[1::]): # Accumulate the anomaly mask from all of elements in anomaly_label. # Each of loop will detect each label that in the anomaly_label or not? # If True then, put the mask_anomaly as 1 otherwise, 0. if idx < len(anomaly_label[1::]): # Checking that the idx does not go out of anomaly mask idx. mask_anomaly = tf.add( tf.where(tf.equal(label, anomaly_label[idx + 1]), tf.ones(label.shape), tf.zeros(label.shape)), mask_anomaly) # For checking for given labels and anomaly masks work correctly. # print(f'label {label}') # print(f'mask_anomaly {mask_anomaly}') if len(img._shape_as_list()) == 4: batch_size = mask_anomaly.shape[0] mask_anomaly = tf.reshape(mask_anomaly, [batch_size, 1, 1, 1]) elif len(img._shape_as_list()) == 2: pass else: raise NotImplementedError('Your img._shape_as_list(): {}'.format( img._shape_as_list())) mask_normal = 1.0 - mask_anomaly img = tf.cast(img, tf.float32) img = tf.subtract( tf.multiply(tf.ones(img.shape), mask_anomaly), tf.multiply(img, mask_anomaly)) + tf.multiply(img, mask_normal) return img def hsv_to_tuv(hsv_img): """Convert HSV space images into TUV space images. Note: TUV is purposed image space by Obad<NAME>. :param hsv_img: Floating point HSV images in range of [0.0, 1.0] with shape [batch_size, image_size, image_size, image_channel]. Degree has an unit as radiance. :return: tuv_img: Floating point TUV images with same shape as input images. """ t = tf.sin(hsv_img[:, :, :, 0])*hsv_img[:, :, :, 1] u = tf.cos(hsv_img[:, :, :, 0])*hsv_img[:, :, :, 1] v = hsv_img[:, :, :, 2] tuv_img = tf.stack([t, u, v], axis=-1) return tuv_img def tuv_to_hsv(tuv_img): """Converting TUV space images back to HSV space images. :param tuv_img: Floating point TUV images in range of [0.0, 1.0] with shape [batch_size, image_size, image_size, image_channel]. Degree has an unit as radiance. :return hsv_img: Floating point HSV images with same shape as input images. """ h = tf.atan(tuv_img[:, :, :, 0]/tuv_img[:, :, :, 1]) s = tuv_img[:, :, :, 0]/tf.sin(h) v = tuv_img[:, :, :, 2] hsv_img = tf.stack([h, s, v], axis=-1) return hsv_img def rearrange_label_loss(locat_label, locat_loss): """Load TXT files which contain a label and a loss for each test images. Rearrange labels in order and using that orders to reorder losses. :param locat_label: A string shows location of TXT file. :param locat_loss: A string shows location of TXT file. :return rearrange_label, rearrange_loss: Tensors of rearranged labels and losses. """ label = np.loadtxt(locat_label, dtype=np.uint8, delimiter='\n') loss = np.loadtxt(locat_loss, dtype=np.float32, delimiter='\n') rearrange_label = [] rearrange_loss = [] index = np.argsort(label) for i in index: rearrange_label.append(label[i]) rearrange_loss.append(loss[i]) return rearrange_label, rearrange_loss
[ "tensorflow.ones", "tensorflow.sin", "tensorflow.reshape", "tensorflow.image.rgb_to_hsv", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.stack", "tensorflow.cast", "numpy.argsort", "tensorflow.zeros", "tensorflow.multiply", "numpy.loadtxt", "tensorflow.atan", "tensorflow.cos", "tensorflow.equal", "tensorflow.image.convert_image_dtype" ]
[((725, 774), 'tensorflow.image.convert_image_dtype', 'tf.image.convert_image_dtype', (['x_train', 'tf.float32'], {}), '(x_train, tf.float32)\n', (753, 774), True, 'import tensorflow as tf\n'), ((788, 836), 'tensorflow.image.convert_image_dtype', 'tf.image.convert_image_dtype', (['x_test', 'tf.float32'], {}), '(x_test, tf.float32)\n', (816, 836), True, 'import tensorflow as tf\n'), ((1325, 1379), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['(x_train, y_train)'], {}), '((x_train, y_train))\n', (1359, 1379), True, 'import tensorflow as tf\n'), ((1397, 1449), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['(x_test, y_test)'], {}), '((x_test, y_test))\n', (1431, 1449), True, 'import tensorflow as tf\n'), ((2836, 2860), 'tensorflow.cast', 'tf.cast', (['img', 'tf.float32'], {}), '(img, tf.float32)\n', (2843, 2860), True, 'import tensorflow as tf\n'), ((4775, 4799), 'tensorflow.cast', 'tf.cast', (['img', 'tf.float32'], {}), '(img, tf.float32)\n', (4782, 4799), True, 'import tensorflow as tf\n'), ((5548, 5576), 'tensorflow.stack', 'tf.stack', (['[t, u, v]'], {'axis': '(-1)'}), '([t, u, v], axis=-1)\n', (5556, 5576), True, 'import tensorflow as tf\n'), ((5985, 6035), 'tensorflow.atan', 'tf.atan', (['(tuv_img[:, :, :, 0] / tuv_img[:, :, :, 1])'], {}), '(tuv_img[:, :, :, 0] / tuv_img[:, :, :, 1])\n', (5992, 6035), True, 'import tensorflow as tf\n'), ((6114, 6142), 'tensorflow.stack', 'tf.stack', (['[h, s, v]'], {'axis': '(-1)'}), '([h, s, v], axis=-1)\n', (6122, 6142), True, 'import tensorflow as tf\n'), ((6590, 6645), 'numpy.loadtxt', 'np.loadtxt', (['locat_label'], {'dtype': 'np.uint8', 'delimiter': '"""\n"""'}), "(locat_label, dtype=np.uint8, delimiter='\\n')\n", (6600, 6645), True, 'import numpy as np\n'), ((6657, 6713), 'numpy.loadtxt', 'np.loadtxt', (['locat_loss'], {'dtype': 'np.float32', 'delimiter': '"""\n"""'}), "(locat_loss, dtype=np.float32, delimiter='\\n')\n", (6667, 6713), True, 'import numpy as np\n'), ((6775, 6792), 'numpy.argsort', 'np.argsort', (['label'], {}), '(label)\n', (6785, 6792), True, 'import numpy as np\n'), ((2399, 2429), 'tensorflow.equal', 'tf.equal', (['label', 'anomaly_label'], {}), '(label, anomaly_label)\n', (2407, 2429), True, 'import tensorflow as tf\n'), ((2431, 2451), 'tensorflow.ones', 'tf.ones', (['label.shape'], {}), '(label.shape)\n', (2438, 2451), True, 'import tensorflow as tf\n'), ((2453, 2474), 'tensorflow.zeros', 'tf.zeros', (['label.shape'], {}), '(label.shape)\n', (2461, 2474), True, 'import tensorflow as tf\n'), ((2581, 2628), 'tensorflow.reshape', 'tf.reshape', (['mask_anomaly', '[batch_size, 1, 1, 1]'], {}), '(mask_anomaly, [batch_size, 1, 1, 1])\n', (2591, 2628), True, 'import tensorflow as tf\n'), ((2973, 3002), 'tensorflow.multiply', 'tf.multiply', (['img', 'mask_normal'], {}), '(img, mask_normal)\n', (2984, 3002), True, 'import tensorflow as tf\n'), ((3581, 3614), 'tensorflow.equal', 'tf.equal', (['label', 'anomaly_label[0]'], {}), '(label, anomaly_label[0])\n', (3589, 3614), True, 'import tensorflow as tf\n'), ((3616, 3636), 'tensorflow.ones', 'tf.ones', (['label.shape'], {}), '(label.shape)\n', (3623, 3636), True, 'import tensorflow as tf\n'), ((3638, 3659), 'tensorflow.zeros', 'tf.zeros', (['label.shape'], {}), '(label.shape)\n', (3646, 3659), True, 'import tensorflow as tf\n'), ((4507, 4554), 'tensorflow.reshape', 'tf.reshape', (['mask_anomaly', '[batch_size, 1, 1, 1]'], {}), '(mask_anomaly, [batch_size, 1, 1, 1])\n', (4517, 4554), True, 'import tensorflow as tf\n'), ((4920, 4949), 'tensorflow.multiply', 'tf.multiply', (['img', 'mask_normal'], {}), '(img, mask_normal)\n', (4931, 4949), True, 'import tensorflow as tf\n'), ((5402, 5429), 'tensorflow.sin', 'tf.sin', (['hsv_img[:, :, :, 0]'], {}), '(hsv_img[:, :, :, 0])\n', (5408, 5429), True, 'import tensorflow as tf\n'), ((5458, 5485), 'tensorflow.cos', 'tf.cos', (['hsv_img[:, :, :, 0]'], {}), '(hsv_img[:, :, :, 0])\n', (5464, 5485), True, 'import tensorflow as tf\n'), ((6062, 6071), 'tensorflow.sin', 'tf.sin', (['h'], {}), '(h)\n', (6068, 6071), True, 'import tensorflow as tf\n'), ((914, 942), 'tensorflow.image.rgb_to_hsv', 'tf.image.rgb_to_hsv', (['x_train'], {}), '(x_train)\n', (933, 942), True, 'import tensorflow as tf\n'), ((960, 987), 'tensorflow.image.rgb_to_hsv', 'tf.image.rgb_to_hsv', (['x_test'], {}), '(x_test)\n', (979, 987), True, 'import tensorflow as tf\n'), ((2939, 2969), 'tensorflow.multiply', 'tf.multiply', (['img', 'mask_anomaly'], {}), '(img, mask_anomaly)\n', (2950, 2969), True, 'import tensorflow as tf\n'), ((4886, 4916), 'tensorflow.multiply', 'tf.multiply', (['img', 'mask_anomaly'], {}), '(img, mask_anomaly)\n', (4897, 4916), True, 'import tensorflow as tf\n'), ((1030, 1058), 'tensorflow.image.rgb_to_hsv', 'tf.image.rgb_to_hsv', (['x_train'], {}), '(x_train)\n', (1049, 1058), True, 'import tensorflow as tf\n'), ((1076, 1103), 'tensorflow.image.rgb_to_hsv', 'tf.image.rgb_to_hsv', (['x_test'], {}), '(x_test)\n', (1095, 1103), True, 'import tensorflow as tf\n'), ((2904, 2922), 'tensorflow.ones', 'tf.ones', (['img.shape'], {}), '(img.shape)\n', (2911, 2922), True, 'import tensorflow as tf\n'), ((4843, 4861), 'tensorflow.ones', 'tf.ones', (['img.shape'], {}), '(img.shape)\n', (4850, 4861), True, 'import tensorflow as tf\n'), ((4106, 4145), 'tensorflow.equal', 'tf.equal', (['label', 'anomaly_label[idx + 1]'], {}), '(label, anomaly_label[idx + 1])\n', (4114, 4145), True, 'import tensorflow as tf\n'), ((4172, 4192), 'tensorflow.ones', 'tf.ones', (['label.shape'], {}), '(label.shape)\n', (4179, 4192), True, 'import tensorflow as tf\n'), ((4194, 4215), 'tensorflow.zeros', 'tf.zeros', (['label.shape'], {}), '(label.shape)\n', (4202, 4215), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python import matplotlib import matplotlib.pyplot as plt import numpy import os from cycler import cycler # Set matplotlib defaults to agree with MATLAB code plt.rc("legend", framealpha=None) plt.rc("legend", edgecolor='black') plt.rc("font", family="serif") # Following option for TeX text seems to not work with EPS figures? #plt.rc("text", usetex=True) # NOTE: set clip_on=False in plotting to get consistent style with MATLAB def mlmc_plot(filename, nvert, error_bars=False): """ Utility to generate MLMC diagnostic plots based on input text file generated by MLMC driver code mlmc_test. mlmc_plot(filename, nvert, error_bars=False) Inputs: filename: string, (base of) filename with output from mlmc_test routine nvert : int, number of vertical plots <= 3 nvert == 1 generates fig1: (1),(2) fig2: (5),(6) nvert == 2 generates fig1: (1),(2),(5),(6) nvert == 3 generates fig1: (1)-(6) error_bars: bool, flag to add error bars in plots of level differences Outputs: Matplotlib figure(s) for Convergence tests (1) Var[P_l - P_{l-1}] per level (2) E[|P_l - P_{l-1}|] per level (3) cost per level (4) kurtosis per level Complexity tests (5) number of samples per level (6) normalised cost per accuracy target """ # # read in data # # Default file extension is .txt if none supplied if not os.path.splitext(filename)[1]: file = open(filename + ".txt", "r") else: file = open(filename, "r") # Declare lists for data del1 = [] del2 = [] var1 = [] var2 = [] kur1 = [] chk1 = [] cost = [] l = [] epss = [] mlmc_cost = [] std_cost = [] Ns = [] ls = [] # Default values for number of samples and file_version N = 0 file_version = 0.8 complexity_flag = False # first read convergence tests rather than complexity tests for line in file: # Recognise file version line from the fact that it starts with '*** MLMC file version' if line[0:21] == '*** MLMC file version': file_version = float(line[23:30]) # Recognise number of samples line from the fact that it starts with '*** using' if line[0:9] == '*** using': N = int(line[14:20]) # Recognise whether we should switch to reading complexity tests if line[0:19] == '*** MLMC complexity': complexity_flag = True # now start to read complexity tests # Recognise MLMC complexity test lines from the fact that line[0] is an integer # Also need complexity_flag == True because line[0] is an integer also identifies # the convergence test lines if '0' <= line[0] <= '9' and complexity_flag: splitline = [float(x) for x in line.split()] epss.append(splitline[0]) mlmc_cost.append(splitline[2]) std_cost.append(splitline[3]) Ns.append(splitline[5:]) ls.append(list(range(0,len(splitline[5:])))) # Recognise convergence test lines from the fact that line[1] is an integer # and possibly also line[0] (or line[0] is whitespace) if (line[0] == ' ' or '0' <= line[0] <= '9') and '0' <= line[1] <= '9': splitline = [float(x) for x in line.split()] l.append(splitline[0]) del1.append(splitline[1]) del2.append(splitline[2]) var1.append(splitline[3]) var2.append(splitline[4]) kur1.append(splitline[5]) chk1.append(splitline[6]) cost.append(splitline[7]) continue if (file_version < 0.9): if (error_bars): raise Warning("Cannot plot error bars -- no value of N in file") error_bars = False # Compute variance of variance ( correct up to O(1/N) ) if (error_bars): vvr1 = [ v**2 * (kur - 1.0) for (v, kur) in zip(var1,kur1)] # # plot figures # # Fudge to get comparable size to default MATLAB fig size width_MATLAB = 0.9*8; height_MATLAB = 0.9*6.5; plt.figure(figsize=([width_MATLAB, height_MATLAB*0.75*nvert])) plt.rc('axes', prop_cycle=(cycler('color', ['k']) * cycler('linestyle', ['--', ':']) * cycler('marker', ['*']))) # Var[P_l - P_{l-1}] per level plt.subplot(nvert, 2, 1) plt.plot(l, numpy.log2(var2), label=r'$P_\ell$', clip_on=False) plt.plot(l[1:], numpy.log2(var1[1:]), label=r'$P_\ell - P_{\ell-1}$', clip_on=False) plt.xlabel('level $\ell$') plt.ylabel(r'$\mathrm{log}_2(\mathrm{variance})$') plt.legend(loc='lower left', fontsize='medium') axis = plt.axis(); plt.axis([0, max(l), axis[2], axis[3]]) if (error_bars): plt.plot(l[1:], numpy.log2(numpy.maximum(numpy.abs(numpy.array(var1[1:]) - 3.0*numpy.sqrt(vvr1[1:])/numpy.sqrt(N)), 1e-10)), '-r.', clip_on=False) plt.plot(l[1:], numpy.log2( numpy.abs(numpy.array(var1[1:]) + 3.0*numpy.sqrt(vvr1[1:])/numpy.sqrt(N)) ), '-r.', clip_on=False) # E[|P_l - P_{l-1}|] per level plt.subplot(nvert, 2, 2) plt.plot(l, numpy.log2(numpy.abs(del2)), label=r'$P_\ell$', clip_on=False) plt.plot(l[1:], numpy.log2(numpy.abs(del1[1:])), label=r'$P_\ell - P_{\ell-1}$', clip_on=False) plt.xlabel('level $\ell$') plt.ylabel(r'$\mathrm{log}_2(|\mathrm{mean}|)$') plt.legend(loc='lower left', fontsize='medium') axis = plt.axis(); plt.axis([0, max(l), axis[2], axis[3]]) if (error_bars): plt.plot(l[1:], numpy.log2(numpy.maximum(numpy.abs(numpy.array(del1[1:]) - 3.0*numpy.sqrt(var1[1:])/numpy.sqrt(N)), 1e-10)), '-r.', clip_on=False) plt.plot(l[1:], numpy.log2( numpy.abs(numpy.array(del1[1:]) + 3.0*numpy.sqrt(var1[1:])/numpy.sqrt(N)) ), '-r.', clip_on=False) if nvert == 3: # consistency check # plt.subplot(nvert, 2, 3) # plt.plot(l[1:], chk1[1:], '*--') # plt.xlabel('level $\ell$') # plt.ylabel(r'consistency check') # axis = plt.axis(); plt.axis([0, max(l), axis[2], axis[3]]) # cost per level plt.subplot(nvert, 2, 3) plt.plot(l, numpy.log2(cost), '*--', clip_on=False) plt.xlabel('level $\ell$') plt.ylabel(r'$\log_2$ cost per sample') axis = plt.axis(); plt.axis([0, max(l), axis[2], axis[3]]) # kurtosis per level plt.subplot(nvert, 2, 4) plt.plot(l[1:], kur1[1:], '*--', clip_on=False) plt.xlabel('level $\ell$') plt.ylabel(r'kurtosis') axis = plt.axis(); plt.axis([0, max(l), axis[2], axis[3]]) if nvert == 1: # Fix subplot spacing plt.subplots_adjust(wspace=0.3) plt.subplots_adjust(hspace=0.4) plt.figure(figsize=(width_MATLAB, height_MATLAB*0.75*nvert)) marker_styles = ['o', 'x', 'd', '*', 's'] plt.rc('axes', prop_cycle=(cycler('color', ['k']) * cycler('linestyle', ['--']) * cycler('marker', marker_styles))) # number of samples per level plt.subplot(nvert, 2, 2*nvert-1) for (eps, ll, n) in zip(epss, ls, Ns): plt.semilogy(ll, n, label=eps, markerfacecolor='none', clip_on=False) plt.xlabel('level $\ell$') plt.ylabel('$N_\ell$') plt.legend(loc='upper right', frameon=True, fontsize='medium') axis = plt.axis(); plt.axis([0, max([max(x) for x in ls]), axis[2], axis[3]]) plt.rc('axes', prop_cycle=(cycler('color', ['k']) * cycler('linestyle', ['--', ':']) * cycler('marker', ['*']))) # normalised cost for given accuracy eps = numpy.array(epss) std_cost = numpy.array(std_cost) mlmc_cost = numpy.array(mlmc_cost) I = numpy.argsort(eps) plt.subplot(nvert, 2, 2*nvert) plt.loglog(eps[I], eps[I]**2 * std_cost[I], '*-', label='Std MC', clip_on=False) plt.loglog(eps[I], eps[I]**2 * mlmc_cost[I], '*--', label='MLMC', clip_on=False) plt.xlabel(r'accuracy $\varepsilon$') plt.ylabel(r'$\varepsilon^2$ cost') plt.legend(fontsize='medium') axis = plt.axis(); plt.axis([min(eps), max(eps), axis[2], axis[3]]) # Fix subplot spacing plt.subplots_adjust(wspace=0.3) plt.subplots_adjust(hspace=0.4) if __name__ == "__main__": import sys mlmc_plot(sys.argv[1], nvert=3) plt.savefig(sys.argv[1].replace(".txt", ".eps"))
[ "matplotlib.pyplot.loglog", "matplotlib.pyplot.subplot", "cycler.cycler", "numpy.abs", "matplotlib.pyplot.plot", "numpy.log2", "matplotlib.pyplot.legend", "matplotlib.pyplot.axis", "numpy.argsort", "matplotlib.pyplot.figure", "numpy.array", "matplotlib.pyplot.rc", "os.path.splitext", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.semilogy", "matplotlib.pyplot.xlabel", "numpy.sqrt" ]
[((175, 208), 'matplotlib.pyplot.rc', 'plt.rc', (['"""legend"""'], {'framealpha': 'None'}), "('legend', framealpha=None)\n", (181, 208), True, 'import matplotlib.pyplot as plt\n'), ((209, 244), 'matplotlib.pyplot.rc', 'plt.rc', (['"""legend"""'], {'edgecolor': '"""black"""'}), "('legend', edgecolor='black')\n", (215, 244), True, 'import matplotlib.pyplot as plt\n'), ((245, 275), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""'}), "('font', family='serif')\n", (251, 275), True, 'import matplotlib.pyplot as plt\n'), ((4217, 4281), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[width_MATLAB, height_MATLAB * 0.75 * nvert]'}), '(figsize=[width_MATLAB, height_MATLAB * 0.75 * nvert])\n', (4227, 4281), True, 'import matplotlib.pyplot as plt\n'), ((4500, 4524), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nvert', '(2)', '(1)'], {}), '(nvert, 2, 1)\n', (4511, 4524), True, 'import matplotlib.pyplot as plt\n'), ((4694, 4721), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""level $\\\\ell$"""'], {}), "('level $\\\\ell$')\n", (4704, 4721), True, 'import matplotlib.pyplot as plt\n'), ((4725, 4776), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\mathrm{log}_2(\\\\mathrm{variance})$"""'], {}), "('$\\\\mathrm{log}_2(\\\\mathrm{variance})$')\n", (4735, 4776), True, 'import matplotlib.pyplot as plt\n'), ((4780, 4827), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower left"""', 'fontsize': '"""medium"""'}), "(loc='lower left', fontsize='medium')\n", (4790, 4827), True, 'import matplotlib.pyplot as plt\n'), ((4839, 4849), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (4847, 4849), True, 'import matplotlib.pyplot as plt\n'), ((5287, 5311), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nvert', '(2)', '(2)'], {}), '(nvert, 2, 2)\n', (5298, 5311), True, 'import matplotlib.pyplot as plt\n'), ((5503, 5530), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""level $\\\\ell$"""'], {}), "('level $\\\\ell$')\n", (5513, 5530), True, 'import matplotlib.pyplot as plt\n'), ((5534, 5583), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\mathrm{log}_2(|\\\\mathrm{mean}|)$"""'], {}), "('$\\\\mathrm{log}_2(|\\\\mathrm{mean}|)$')\n", (5544, 5583), True, 'import matplotlib.pyplot as plt\n'), ((5587, 5634), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower left"""', 'fontsize': '"""medium"""'}), "(loc='lower left', fontsize='medium')\n", (5597, 5634), True, 'import matplotlib.pyplot as plt\n'), ((5646, 5656), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (5654, 5656), True, 'import matplotlib.pyplot as plt\n'), ((7313, 7349), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nvert', '(2)', '(2 * nvert - 1)'], {}), '(nvert, 2, 2 * nvert - 1)\n', (7324, 7349), True, 'import matplotlib.pyplot as plt\n'), ((7471, 7498), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""level $\\\\ell$"""'], {}), "('level $\\\\ell$')\n", (7481, 7498), True, 'import matplotlib.pyplot as plt\n'), ((7502, 7525), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$N_\\\\ell$"""'], {}), "('$N_\\\\ell$')\n", (7512, 7525), True, 'import matplotlib.pyplot as plt\n'), ((7529, 7591), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'frameon': '(True)', 'fontsize': '"""medium"""'}), "(loc='upper right', frameon=True, fontsize='medium')\n", (7539, 7591), True, 'import matplotlib.pyplot as plt\n'), ((7603, 7613), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (7611, 7613), True, 'import matplotlib.pyplot as plt\n'), ((7907, 7924), 'numpy.array', 'numpy.array', (['epss'], {}), '(epss)\n', (7918, 7924), False, 'import numpy\n'), ((7940, 7961), 'numpy.array', 'numpy.array', (['std_cost'], {}), '(std_cost)\n', (7951, 7961), False, 'import numpy\n'), ((7978, 8000), 'numpy.array', 'numpy.array', (['mlmc_cost'], {}), '(mlmc_cost)\n', (7989, 8000), False, 'import numpy\n'), ((8009, 8027), 'numpy.argsort', 'numpy.argsort', (['eps'], {}), '(eps)\n', (8022, 8027), False, 'import numpy\n'), ((8032, 8064), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nvert', '(2)', '(2 * nvert)'], {}), '(nvert, 2, 2 * nvert)\n', (8043, 8064), True, 'import matplotlib.pyplot as plt\n'), ((8067, 8154), 'matplotlib.pyplot.loglog', 'plt.loglog', (['eps[I]', '(eps[I] ** 2 * std_cost[I])', '"""*-"""'], {'label': '"""Std MC"""', 'clip_on': '(False)'}), "(eps[I], eps[I] ** 2 * std_cost[I], '*-', label='Std MC', clip_on\n =False)\n", (8077, 8154), True, 'import matplotlib.pyplot as plt\n'), ((8154, 8241), 'matplotlib.pyplot.loglog', 'plt.loglog', (['eps[I]', '(eps[I] ** 2 * mlmc_cost[I])', '"""*--"""'], {'label': '"""MLMC"""', 'clip_on': '(False)'}), "(eps[I], eps[I] ** 2 * mlmc_cost[I], '*--', label='MLMC', clip_on\n =False)\n", (8164, 8241), True, 'import matplotlib.pyplot as plt\n'), ((8241, 8278), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""accuracy $\\\\varepsilon$"""'], {}), "('accuracy $\\\\varepsilon$')\n", (8251, 8278), True, 'import matplotlib.pyplot as plt\n'), ((8283, 8318), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\varepsilon^2$ cost"""'], {}), "('$\\\\varepsilon^2$ cost')\n", (8293, 8318), True, 'import matplotlib.pyplot as plt\n'), ((8323, 8352), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '"""medium"""'}), "(fontsize='medium')\n", (8333, 8352), True, 'import matplotlib.pyplot as plt\n'), ((8364, 8374), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (8372, 8374), True, 'import matplotlib.pyplot as plt\n'), ((8456, 8487), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.3)'}), '(wspace=0.3)\n', (8475, 8487), True, 'import matplotlib.pyplot as plt\n'), ((8492, 8523), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.4)'}), '(hspace=0.4)\n', (8511, 8523), True, 'import matplotlib.pyplot as plt\n'), ((4545, 4561), 'numpy.log2', 'numpy.log2', (['var2'], {}), '(var2)\n', (4555, 4561), False, 'import numpy\n'), ((4621, 4641), 'numpy.log2', 'numpy.log2', (['var1[1:]'], {}), '(var1[1:])\n', (4631, 4641), False, 'import numpy\n'), ((6358, 6382), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nvert', '(2)', '(3)'], {}), '(nvert, 2, 3)\n', (6369, 6382), True, 'import matplotlib.pyplot as plt\n'), ((6451, 6478), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""level $\\\\ell$"""'], {}), "('level $\\\\ell$')\n", (6461, 6478), True, 'import matplotlib.pyplot as plt\n'), ((6486, 6525), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\log_2$ cost per sample"""'], {}), "('$\\\\log_2$ cost per sample')\n", (6496, 6525), True, 'import matplotlib.pyplot as plt\n'), ((6541, 6551), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (6549, 6551), True, 'import matplotlib.pyplot as plt\n'), ((6631, 6655), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nvert', '(2)', '(4)'], {}), '(nvert, 2, 4)\n', (6642, 6655), True, 'import matplotlib.pyplot as plt\n'), ((6664, 6711), 'matplotlib.pyplot.plot', 'plt.plot', (['l[1:]', 'kur1[1:]', '"""*--"""'], {'clip_on': '(False)'}), "(l[1:], kur1[1:], '*--', clip_on=False)\n", (6672, 6711), True, 'import matplotlib.pyplot as plt\n'), ((6720, 6747), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""level $\\\\ell$"""'], {}), "('level $\\\\ell$')\n", (6730, 6747), True, 'import matplotlib.pyplot as plt\n'), ((6755, 6777), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""kurtosis"""'], {}), "('kurtosis')\n", (6765, 6777), True, 'import matplotlib.pyplot as plt\n'), ((6794, 6804), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (6802, 6804), True, 'import matplotlib.pyplot as plt\n'), ((6904, 6935), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.3)'}), '(wspace=0.3)\n', (6923, 6935), True, 'import matplotlib.pyplot as plt\n'), ((6944, 6975), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.4)'}), '(hspace=0.4)\n', (6963, 6975), True, 'import matplotlib.pyplot as plt\n'), ((6984, 7048), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(width_MATLAB, height_MATLAB * 0.75 * nvert)'}), '(figsize=(width_MATLAB, height_MATLAB * 0.75 * nvert))\n', (6994, 7048), True, 'import matplotlib.pyplot as plt\n'), ((7397, 7466), 'matplotlib.pyplot.semilogy', 'plt.semilogy', (['ll', 'n'], {'label': 'eps', 'markerfacecolor': '"""none"""', 'clip_on': '(False)'}), "(ll, n, label=eps, markerfacecolor='none', clip_on=False)\n", (7409, 7466), True, 'import matplotlib.pyplot as plt\n'), ((1515, 1541), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (1531, 1541), False, 'import os\n'), ((5343, 5358), 'numpy.abs', 'numpy.abs', (['del2'], {}), '(del2)\n', (5352, 5358), False, 'import numpy\n'), ((5430, 5449), 'numpy.abs', 'numpy.abs', (['del1[1:]'], {}), '(del1[1:])\n', (5439, 5449), False, 'import numpy\n'), ((6403, 6419), 'numpy.log2', 'numpy.log2', (['cost'], {}), '(cost)\n', (6413, 6419), False, 'import numpy\n'), ((4434, 4457), 'cycler.cycler', 'cycler', (['"""marker"""', "['*']"], {}), "('marker', ['*'])\n", (4440, 4457), False, 'from cycler import cycler\n'), ((7240, 7271), 'cycler.cycler', 'cycler', (['"""marker"""', 'marker_styles'], {}), "('marker', marker_styles)\n", (7246, 7271), False, 'from cycler import cycler\n'), ((7829, 7852), 'cycler.cycler', 'cycler', (['"""marker"""', "['*']"], {}), "('marker', ['*'])\n", (7835, 7852), False, 'from cycler import cycler\n'), ((4312, 4334), 'cycler.cycler', 'cycler', (['"""color"""', "['k']"], {}), "('color', ['k'])\n", (4318, 4334), False, 'from cycler import cycler\n'), ((4368, 4400), 'cycler.cycler', 'cycler', (['"""linestyle"""', "['--', ':']"], {}), "('linestyle', ['--', ':'])\n", (4374, 4400), False, 'from cycler import cycler\n'), ((7123, 7145), 'cycler.cycler', 'cycler', (['"""color"""', "['k']"], {}), "('color', ['k'])\n", (7129, 7145), False, 'from cycler import cycler\n'), ((7179, 7206), 'cycler.cycler', 'cycler', (['"""linestyle"""', "['--']"], {}), "('linestyle', ['--'])\n", (7185, 7206), False, 'from cycler import cycler\n'), ((7707, 7729), 'cycler.cycler', 'cycler', (['"""color"""', "['k']"], {}), "('color', ['k'])\n", (7713, 7729), False, 'from cycler import cycler\n'), ((7763, 7795), 'cycler.cycler', 'cycler', (['"""linestyle"""', "['--', ':']"], {}), "('linestyle', ['--', ':'])\n", (7769, 7795), False, 'from cycler import cycler\n'), ((5139, 5160), 'numpy.array', 'numpy.array', (['var1[1:]'], {}), '(var1[1:])\n', (5150, 5160), False, 'import numpy\n'), ((5946, 5967), 'numpy.array', 'numpy.array', (['del1[1:]'], {}), '(del1[1:])\n', (5957, 5967), False, 'import numpy\n'), ((4972, 4993), 'numpy.array', 'numpy.array', (['var1[1:]'], {}), '(var1[1:])\n', (4983, 4993), False, 'import numpy\n'), ((5200, 5213), 'numpy.sqrt', 'numpy.sqrt', (['N'], {}), '(N)\n', (5210, 5213), False, 'import numpy\n'), ((5779, 5800), 'numpy.array', 'numpy.array', (['del1[1:]'], {}), '(del1[1:])\n', (5790, 5800), False, 'import numpy\n'), ((6007, 6020), 'numpy.sqrt', 'numpy.sqrt', (['N'], {}), '(N)\n', (6017, 6020), False, 'import numpy\n'), ((5033, 5046), 'numpy.sqrt', 'numpy.sqrt', (['N'], {}), '(N)\n', (5043, 5046), False, 'import numpy\n'), ((5179, 5199), 'numpy.sqrt', 'numpy.sqrt', (['vvr1[1:]'], {}), '(vvr1[1:])\n', (5189, 5199), False, 'import numpy\n'), ((5840, 5853), 'numpy.sqrt', 'numpy.sqrt', (['N'], {}), '(N)\n', (5850, 5853), False, 'import numpy\n'), ((5986, 6006), 'numpy.sqrt', 'numpy.sqrt', (['var1[1:]'], {}), '(var1[1:])\n', (5996, 6006), False, 'import numpy\n'), ((5012, 5032), 'numpy.sqrt', 'numpy.sqrt', (['vvr1[1:]'], {}), '(vvr1[1:])\n', (5022, 5032), False, 'import numpy\n'), ((5819, 5839), 'numpy.sqrt', 'numpy.sqrt', (['var1[1:]'], {}), '(var1[1:])\n', (5829, 5839), False, 'import numpy\n')]
import os import numpy as np import matplotlib.pyplot as plt from skimage.color import rgb2xyz import cv2 import warnings def svd_trunc(I): U, S, V_T = np.linalg.svd(I, full_matrices=False) U = U * S U = U[:,:3] V_T = V_T[:3,:] return U, V_T def set_mesh(px_size=7e-4, res=(100, 100)): [X, Y] = np.meshgrid(np.arange(res[0]), np.arange(res[1])) X = (X - res[0]/2) * px_size Y = (Y - res[1]/2) * px_size return X, Y def render_sphere(X, Y, light, r_ratio): """ center: Sphere center light: Direction of point light source rad: Sphere radius in centimeters pxSize: Size of pixel in micrometers res: Image resolution """ x_max = np.max(X) y_max = np.max(Y) min_max = np.min([x_max, y_max]) rad = min_max * r_ratio Z = np.sqrt(rad**2+0j-X**2-Y**2) X[np.real(Z) == 0] = 0 Y[np.real(Z) == 0] = 0 Z = np.real(Z) F = np.array([X, Y, Z]) if light is None: return F image = np.einsum('ijk,i->jk', F, light) image[image < 0] = 0 return image def norm_lights(lights): N = lights.shape[0] norm = np.linalg.norm(lights, axis=1) norm = np.tile(norm, (1, 3)).reshape(N, 3) lights = np.divide(lights, norm) return lights def get_lights(N = 10): """ N: Number of light sources lights: N light sources set equidistant on a circle about z = 1 with radius sqrt(2) """ lights = np.zeros((N, 3)) M = N - 1 base = 2 * np.pi / M for k in range(M): x = np.cos(base * k) y = np.sin(base * k) z = 1 lights[k] = [x, y, z] lights[M] = [0, 0, np.sqrt(2)] lights = norm_lights(lights) return lights def get_data(sphere = True): """ Sphere: """ if sphere: I, L_T, s = get_data_sphere() else: I, L_T, s = get_data_face() return I, L_T, s def get_data_sphere(path="./output/", N=9, px_size=7e-4, res=(300, 300), r_ratio=0.9): lights = get_lights(N) spheres = [] X, Y = set_mesh(px_size, res) for i, light in enumerate(lights): name = "sphere_" + str(i) + ".png" X, Y = set_mesh(px_size, res) sphere = render_sphere(X, Y, light, r_ratio) spheres.append(sphere.ravel()) out_path = path + name if not os.path.isdir(path): os.mkdir(path) plt.imsave(out_path, sphere, cmap='gray') if i == 0: s = sphere.shape spheres = np.array(spheres) return spheres, lights, s def get_data_face(path='../../Data/FaceData/'): path_files = os.listdir(path) imgs = sorted([''.join([path, _]) for _ in path_files if _.endswith('.tif')]) L_file = [''.join([path, _]) for _ in path_files if _.endswith('.npy')][0] L = np.load(L_file) Img = cv2.imread(imgs[0], -1) s = Img.shape[:2] P = Img[:,:,0].flatten().shape[0] I = np.zeros((7, P)) for k, img in enumerate(imgs): i = rgb2xyz(cv2.imread(img, -1)) lum = i[:,:,1].flatten() I[k,:] = lum return I, L, s def integrateFrankot(zx, zy, pad = 512): """ Question 1 (j) Implement the Frankot-Chellappa algorithm for enforcing integrability and normal integration Parameters ---------- zx : numpy.ndarray The image of derivatives of the depth along the x image dimension zy : tuple The image of derivatives of the depth along the y image dimension pad : float The size of the full FFT used for the reconstruction Returns ---------- z: numpy.ndarray The image, of the same size as the derivatives, of estimated depths at each point """ # Raise error if the shapes of the gradients don't match if not zx.shape == zy.shape: raise ValueError('Sizes of both gradients must match!') # Pad the array FFT with a size we specify h, w = pad, pad # Fourier transform of gradients for projection Zx = np.fft.fftshift(np.fft.fft2(zx, (h, w))) Zy = np.fft.fftshift(np.fft.fft2(zy, (h, w))) j = 1j # Frequency grid [wx, wy] = np.meshgrid(np.linspace(-np.pi, np.pi, w), np.linspace(-np.pi, np.pi, h)) absFreq = wx**2 + wy**2 # Perform the actual projection with warnings.catch_warnings(): warnings.simplefilter('ignore') z = (-j*wx*Zx-j*wy*Zy)/absFreq # Set (undefined) mean value of the surface depth to 0 z[0, 0] = 0. z = np.fft.ifftshift(z) # Invert the Fourier transform for the depth z = np.real(np.fft.ifft2(z)) z = z[:zx.shape[0], :zx.shape[1]] return z
[ "os.mkdir", "numpy.load", "numpy.einsum", "numpy.linalg.svd", "numpy.linalg.norm", "numpy.arange", "numpy.sin", "matplotlib.pyplot.imsave", "numpy.tile", "numpy.fft.ifft2", "numpy.fft.ifftshift", "warnings.simplefilter", "numpy.max", "warnings.catch_warnings", "numpy.real", "numpy.linspace", "numpy.divide", "numpy.min", "numpy.fft.fft2", "numpy.cos", "os.listdir", "os.path.isdir", "numpy.zeros", "cv2.imread", "numpy.array", "numpy.sqrt" ]
[((157, 194), 'numpy.linalg.svd', 'np.linalg.svd', (['I'], {'full_matrices': '(False)'}), '(I, full_matrices=False)\n', (170, 194), True, 'import numpy as np\n'), ((701, 710), 'numpy.max', 'np.max', (['X'], {}), '(X)\n', (707, 710), True, 'import numpy as np\n'), ((723, 732), 'numpy.max', 'np.max', (['Y'], {}), '(Y)\n', (729, 732), True, 'import numpy as np\n'), ((747, 769), 'numpy.min', 'np.min', (['[x_max, y_max]'], {}), '([x_max, y_max])\n', (753, 769), True, 'import numpy as np\n'), ((806, 848), 'numpy.sqrt', 'np.sqrt', (['(rad ** 2 + 0.0j - X ** 2 - Y ** 2)'], {}), '(rad ** 2 + 0.0j - X ** 2 - Y ** 2)\n', (813, 848), True, 'import numpy as np\n'), ((897, 907), 'numpy.real', 'np.real', (['Z'], {}), '(Z)\n', (904, 907), True, 'import numpy as np\n'), ((921, 940), 'numpy.array', 'np.array', (['[X, Y, Z]'], {}), '([X, Y, Z])\n', (929, 940), True, 'import numpy as np\n'), ((994, 1026), 'numpy.einsum', 'np.einsum', (['"""ijk,i->jk"""', 'F', 'light'], {}), "('ijk,i->jk', F, light)\n", (1003, 1026), True, 'import numpy as np\n'), ((1132, 1162), 'numpy.linalg.norm', 'np.linalg.norm', (['lights'], {'axis': '(1)'}), '(lights, axis=1)\n', (1146, 1162), True, 'import numpy as np\n'), ((1223, 1246), 'numpy.divide', 'np.divide', (['lights', 'norm'], {}), '(lights, norm)\n', (1232, 1246), True, 'import numpy as np\n'), ((1443, 1459), 'numpy.zeros', 'np.zeros', (['(N, 3)'], {}), '((N, 3))\n', (1451, 1459), True, 'import numpy as np\n'), ((2494, 2511), 'numpy.array', 'np.array', (['spheres'], {}), '(spheres)\n', (2502, 2511), True, 'import numpy as np\n'), ((2610, 2626), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (2620, 2626), False, 'import os\n'), ((2796, 2811), 'numpy.load', 'np.load', (['L_file'], {}), '(L_file)\n', (2803, 2811), True, 'import numpy as np\n'), ((2823, 2846), 'cv2.imread', 'cv2.imread', (['imgs[0]', '(-1)'], {}), '(imgs[0], -1)\n', (2833, 2846), False, 'import cv2\n'), ((2915, 2931), 'numpy.zeros', 'np.zeros', (['(7, P)'], {}), '((7, P))\n', (2923, 2931), True, 'import numpy as np\n'), ((4502, 4521), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['z'], {}), '(z)\n', (4518, 4521), True, 'import numpy as np\n'), ((334, 351), 'numpy.arange', 'np.arange', (['res[0]'], {}), '(res[0])\n', (343, 351), True, 'import numpy as np\n'), ((353, 370), 'numpy.arange', 'np.arange', (['res[1]'], {}), '(res[1])\n', (362, 370), True, 'import numpy as np\n'), ((1535, 1551), 'numpy.cos', 'np.cos', (['(base * k)'], {}), '(base * k)\n', (1541, 1551), True, 'import numpy as np\n'), ((1564, 1580), 'numpy.sin', 'np.sin', (['(base * k)'], {}), '(base * k)\n', (1570, 1580), True, 'import numpy as np\n'), ((1649, 1659), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (1656, 1659), True, 'import numpy as np\n'), ((2385, 2426), 'matplotlib.pyplot.imsave', 'plt.imsave', (['out_path', 'sphere'], {'cmap': '"""gray"""'}), "(out_path, sphere, cmap='gray')\n", (2395, 2426), True, 'import matplotlib.pyplot as plt\n'), ((4013, 4036), 'numpy.fft.fft2', 'np.fft.fft2', (['zx', '(h, w)'], {}), '(zx, (h, w))\n', (4024, 4036), True, 'import numpy as np\n'), ((4063, 4086), 'numpy.fft.fft2', 'np.fft.fft2', (['zy', '(h, w)'], {}), '(zy, (h, w))\n', (4074, 4086), True, 'import numpy as np\n'), ((4148, 4177), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', 'w'], {}), '(-np.pi, np.pi, w)\n', (4159, 4177), True, 'import numpy as np\n'), ((4206, 4235), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', 'h'], {}), '(-np.pi, np.pi, h)\n', (4217, 4235), True, 'import numpy as np\n'), ((4311, 4336), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (4334, 4336), False, 'import warnings\n'), ((4346, 4377), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (4367, 4377), False, 'import warnings\n'), ((4588, 4603), 'numpy.fft.ifft2', 'np.fft.ifft2', (['z'], {}), '(z)\n', (4600, 4603), True, 'import numpy as np\n'), ((841, 851), 'numpy.real', 'np.real', (['Z'], {}), '(Z)\n', (848, 851), True, 'import numpy as np\n'), ((868, 878), 'numpy.real', 'np.real', (['Z'], {}), '(Z)\n', (875, 878), True, 'import numpy as np\n'), ((1174, 1195), 'numpy.tile', 'np.tile', (['norm', '(1, 3)'], {}), '(norm, (1, 3))\n', (1181, 1195), True, 'import numpy as np\n'), ((2329, 2348), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (2342, 2348), False, 'import os\n'), ((2362, 2376), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (2370, 2376), False, 'import os\n'), ((2988, 3007), 'cv2.imread', 'cv2.imread', (['img', '(-1)'], {}), '(img, -1)\n', (2998, 3007), False, 'import cv2\n')]
""" Utililities =========== This module holds all the core utility functions used throughout the library. These functions are intended to simplify common tasks and to make their output and functionality consistent where needed. """ import json import os from typing import Dict, List import numpy as np # type: ignore from comtypes.client import CreateObject # type: ignore from _ctypes import COMError # type: ignore from frewpy.models.exceptions import FrewError, NodeError def _check_frew_path(file_path) -> None: if not isinstance(file_path, str): raise FrewError("The path must be a string.") if not os.path.exists(file_path): raise FrewError("Path to Frew model does not exist.") if not file_path.lower().endswith(".fwd"): raise FrewError("Path must be to a valid Frew model.") def model_to_json(file_path) -> str: """ Converts a `.fwd` Frew model to a `.json` Frew model. Parameters ---------- file_path : str Absolute file path to the '.fwd' Frew model. Returns ------- json_path : str The new file path of the json file. """ _check_frew_path(file_path) json_path: str = f'{file_path.rsplit(".", 1)[0]}.json' try: model = CreateObject("frewLib.FrewComAuto") except OSError: os.remove(file_path) raise FrewError("Failed to create a COM object.") try: model.Open(file_path) except COMError: raise FrewError("Failed to open the Frew model.") model.SaveAs(json_path) model.Close() return json_path def check_json_path(file_path: str) -> None: """ Checks whether the path is a valid json path. Parameters ---------- file_path : str Absolute file path to the Frew model. Raises ------ FrewError If the path is not a string, doesn't exists or is not to a json file. """ if not isinstance(file_path, str): raise FrewError( f""" File path must be a string. Value {file_path} of type {type (file_path)} given. """ ) if not os.path.exists(file_path): raise FrewError("Frew model file path does not exists.") if not file_path.lower().endswith(".json"): raise FrewError( """ File extension must be a .json. Please use model_to_json to convert it. Import this function from frewpy.utils. """ ) def load_data(file_path: str) -> Dict[str, list]: """ Loads the json file in as a Python dictionary. Parameters ---------- file_path : str Absolute file path to the Frew model. Returns ------- json_data : Dict[str, list] A Python dictionary of the data held within the json model file. """ with open(file_path) as file: return json.loads(file.read()) def clear_results(json_data: dict) -> dict: """ Clears the results in the json file so that it can be analysed using the COM interface. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- json_data : dict A Python dictionary of the data held within the json model file without the results. """ if json_data.get("Frew Results", False): del json_data["Frew Results"] return json_data def get_titles(json_data: dict) -> Dict[str, str]: """ Returns the titles within the json model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- titles : Dict[str, str] The project titles including Job Number, Job Title, Sub Title, Calculation Heading, Initials, and Notes. """ try: return json_data["OasysHeader"][0]["Titles"][0] except KeyError: raise FrewError("Unable to retreive title information.") except IndexError: raise FrewError("Unable to retreive title information.") def get_file_history(json_data: dict) -> List[Dict[str, str]]: """ Returns the file history of the Frew model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- file_history : List[Dict[str, str]] Records of when the file has been opened in Frew and by which user. """ try: return json_data["File history"] except KeyError: raise FrewError("Unable to retreive file history.") def get_file_version(json_data: Dict[str, list]) -> str: """ Returns the file version of the Frew model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- file_version : str The version of the model file showing the exact build of Frew. """ try: return json_data["OasysHeader"][0]["Program title"][0]["FileVersion"] except KeyError: raise FrewError("Unable to retreive file version.") except IndexError: raise FrewError("Unable to retreive file version.") def get_frew_version(json_data: dict) -> str: """ Returns the frew version required for the Frew model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- frew_version : str The overall Frew version in which the model was created. """ try: return json_data["OasysHeader"][0]["Program title"][0]["Version"] except KeyError: raise FrewError("Unable to retreive Frew model version.") except IndexError: raise FrewError("Unable to retreive Frew model version.") def get_num_stages(json_data: dict) -> int: """ Returns the number of stages in the model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- num_stages : int The number of stages in the Frew model. """ try: return len(json_data["Stages"]) except KeyError: raise FrewError("Unable to retrieve the number of stages.") def get_stage_names(json_data: dict) -> List[str]: """ Returns the names of the stages within the Frew model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- stage_names : List[str] A list of the names of stages within the Frew model. """ num_stages: int = get_num_stages(json_data) return [json_data["Stages"][stage]["Name"] for stage in range(num_stages)] def get_num_nodes(json_data: dict) -> int: """ Returns the number of nodes in the Frew model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- num_nodes : int The number of nodes present in each stage. This will always just be 1 integer, and the function will raise an error if it is not the same for every stage. """ num_stages = get_num_stages(json_data) num_nodes: List[int] = [] for stage in range(num_stages): if not json_data["Stages"][stage].get("GeoFrewNodes", False): return 0 num_nodes.append(len(json_data["Stages"][stage]["GeoFrewNodes"])) unique_num_nodes = np.unique(np.array(num_nodes)) if len(unique_num_nodes) == 1: return unique_num_nodes[0] raise NodeError("Number of nodes is not unique for every stage.") def get_num_design_cases(json_data: dict) -> int: """ Returns the number of design cases present in the model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- num_design_cases : int The number of design cases in the Frew model. """ check_results_present(json_data) return len(json_data["Frew Results"]) def get_design_case_names(json_data: dict) -> List[str]: """ Returns the names of the design cases present in the model. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- design_case_names : List[str] The names of the design cases in the Frew model. """ check_results_present(json_data) return [ design_case["GeoPartialFactorSet"]["Name"] for design_case in json_data["Frew Results"] ] def check_results_present(json_data: dict): if not json_data.get("Frew Results", False): raise FrewError( """ No results in the model, please analyse the model first. """ )
[ "os.remove", "frewpy.models.exceptions.FrewError", "os.path.exists", "numpy.array", "comtypes.client.CreateObject", "frewpy.models.exceptions.NodeError" ]
[((7631, 7690), 'frewpy.models.exceptions.NodeError', 'NodeError', (['"""Number of nodes is not unique for every stage."""'], {}), "('Number of nodes is not unique for every stage.')\n", (7640, 7690), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((580, 619), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""The path must be a string."""'], {}), "('The path must be a string.')\n", (589, 619), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((631, 656), 'os.path.exists', 'os.path.exists', (['file_path'], {}), '(file_path)\n', (645, 656), False, 'import os\n'), ((672, 719), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Path to Frew model does not exist."""'], {}), "('Path to Frew model does not exist.')\n", (681, 719), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((781, 829), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Path must be to a valid Frew model."""'], {}), "('Path must be to a valid Frew model.')\n", (790, 829), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((1249, 1284), 'comtypes.client.CreateObject', 'CreateObject', (['"""frewLib.FrewComAuto"""'], {}), "('frewLib.FrewComAuto')\n", (1261, 1284), False, 'from comtypes.client import CreateObject\n'), ((2117, 2142), 'os.path.exists', 'os.path.exists', (['file_path'], {}), '(file_path)\n', (2131, 2142), False, 'import os\n'), ((2158, 2208), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Frew model file path does not exists."""'], {}), "('Frew model file path does not exists.')\n", (2167, 2208), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((2271, 2443), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""\n File extension must be a .json. Please use model_to_json to\n convert it. Import this function from frewpy.utils.\n """'], {}), '(\n """\n File extension must be a .json. Please use model_to_json to\n convert it. Import this function from frewpy.utils.\n """\n )\n', (2280, 2443), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((8773, 8878), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""\n No results in the model, please analyse the model first.\n """'], {}), '(\n """\n No results in the model, please analyse the model first.\n """\n )\n', (8782, 8878), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((1313, 1333), 'os.remove', 'os.remove', (['file_path'], {}), '(file_path)\n', (1322, 1333), False, 'import os\n'), ((1348, 1391), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Failed to create a COM object."""'], {}), "('Failed to create a COM object.')\n", (1357, 1391), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((1466, 1509), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Failed to open the Frew model."""'], {}), "('Failed to open the Frew model.')\n", (1475, 1509), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((3914, 3964), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Unable to retreive title information."""'], {}), "('Unable to retreive title information.')\n", (3923, 3964), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((4002, 4052), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Unable to retreive title information."""'], {}), "('Unable to retreive title information.')\n", (4011, 4052), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((4530, 4575), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Unable to retreive file history."""'], {}), "('Unable to retreive file history.')\n", (4539, 4575), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((5062, 5107), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Unable to retreive file version."""'], {}), "('Unable to retreive file version.')\n", (5071, 5107), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((5145, 5190), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Unable to retreive file version."""'], {}), "('Unable to retreive file version.')\n", (5154, 5190), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((5666, 5717), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Unable to retreive Frew model version."""'], {}), "('Unable to retreive Frew model version.')\n", (5675, 5717), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((5755, 5806), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Unable to retreive Frew model version."""'], {}), "('Unable to retreive Frew model version.')\n", (5764, 5806), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((6216, 6269), 'frewpy.models.exceptions.FrewError', 'FrewError', (['"""Unable to retrieve the number of stages."""'], {}), "('Unable to retrieve the number of stages.')\n", (6225, 6269), False, 'from frewpy.models.exceptions import FrewError, NodeError\n'), ((7530, 7549), 'numpy.array', 'np.array', (['num_nodes'], {}), '(num_nodes)\n', (7538, 7549), True, 'import numpy as np\n')]
#!/usr/bin/env python # Author: <NAME> (<EMAIL>) ########################## # Plotting configuration ########################## from XtDac.DivideAndConquer import matplotlibConfig # Use a matplotlib backend which does not show plots to the user # (they will be saved in files) import matplotlib matplotlib.use("Agg") rcParams = matplotlibConfig.getConfig() for k, v in rcParams.iteritems(): matplotlib.rcParams[k] = v ########################### import argparse import os import sys import functools import numpy import warnings import math import logging import multiprocessing import scipy.stats import time as timemod try: import astropy.io.fits as pyfits except: # If this fail there is no way out import pyfits pass from XtDac.DivideAndConquer import GridGen from XtDac.DivideAndConquer import HardwareUnit from XtDac.DivideAndConquer import InterestingRegion from XtDac.DivideAndConquer import Results from XtDac.DivideAndConquer import TimeIntervalConsolidator from XtDac.DivideAndConquer import XMMWCS from XtDac.DivideAndConquer import Box from XtDac.FixedBinSearch import Likelihood from XtDac.FixedBinSearch import fitsRegions time, X, Y, tstart, tstop, event_header = (None, None, None, None, None, None) # Set up the logger (its verbosity level will be changed later on # using the value provided by the user) logging.basicConfig(level=logging.DEBUG) log = logging.getLogger("XtDac") def validFITSfile(arg): if not os.path.isfile(arg): log.error("The file %s does not exist!" % arg) sys.exit() # Try to open it to see if it is a FITS file try: fits_file = pyfits.open(arg) except: log.error("The file %s is not a valid FITS file" % arg) sys.exit() else: fits_file.close() return arg # def _initProcess(count, eventFile): # # global counter # global time, X, Y, tstart, tstop # # counter = count # # # Read these here, so they will be read only one time for each of the # # processes spawn by multiprocessing # with pyfits.open(eventFile) as fitsFile: # # time = fitsFile['EVENTS'].data.field("TIME") # X = fitsFile['EVENTS'].data.field("X") # Y = fitsFile['EVENTS'].data.field("Y") # # # Sort by time # idx = numpy.argsort(time) # time = time[idx] # X = X[idx] # Y = Y[idx] # # tstart = fitsFile['EVENTS'].header.get("TSTART") # tstop = fitsFile['EVENTS'].header.get("TSTOP") # def trueWorker(box_def, eventFile, nullHypProb, totRegions, bkgIdx=None): box = Box.Box(*box_def) box.setEventfile(eventFile) box.readEvents(True, time, X, Y, tstart, tstop) if (bkgIdx is not None): # Use custom background (usually when looking in regions close to # bright sources) box.setBackground(bkgIdx) # sys.stderr.write(str(box.nOutOfRegion)) if (box.isEmpty() or box.nInRegion < 2 or box.filledArea < 0.5): results = [] else: results = box.findExcesses(nullHypProb) # box.clearMemory() return results def array2string(array): return ",".join(map(lambda x: "%s" % x, array)) # from memory_profiler import profile def _process_regions(eventfile, typeIerror, regions, n_cpus, log): # Define a wrapper for the trueWorker to avoid duplicating all arguments workerWrapper = functools.partial(trueWorker, eventFile=eventfile, nullHypProb=typeIerror, totRegions=len(regions), bkgIdx=None) # Send each region to one worker to be processed, # and collect the results n_regions = len(regions) results = [] # This is the unit for reporting progress chunk_size = 30 progress_unit = max(chunk_size * n_cpus, n_regions / 20) #progress_unit = max(n_cpus, int(float(n_regions) / 10.0)) if n_cpus > 1: # Parallel version log.debug("Starting a pool of %s python processes" % n_cpus) pool = multiprocessing.Pool(n_cpus, # initializer=_initProcess, # initargs=(counter, args.eventfile) ) log.debug("Feeding the regions to the processes...") for i, result in enumerate(pool.imap(workerWrapper, regions, chunksize=chunk_size)): if (i + 1) % progress_unit == 0 or (i + 1) == n_regions: log.info("%s out of %s regions completed (%.0f percent)" % (i + 1, n_regions, (i + 1) / float(n_regions) * 100)) results.append(result) pool.close() pool.join() else: # Serial version log.debug("Using serial version (only 1 CPU)") for i, region in enumerate(regions): results.append(workerWrapper(region)) if (i + 1) % progress_unit == 0 or (i + 1) == n_regions: log.info("%s out of %s regions completed (%.0f percent)" % (i + 1, n_regions, (i + 1) / float(n_regions) * 100)) assert len(results) == n_regions, "Something went wrong in the computation. The number of results doesn't match " \ "the number of regions" return results # @profile def go(args): global time, X, Y, tstart, tstop, event_header # Set up the logger levels = {'info': logging.INFO, 'debug': logging.DEBUG} log.level = levels[args.verbosity] log.debug("Command line: %s" % (" ".join(sys.argv))) # Instantiate the HardwareUnit class log.debug("Probing Hardware Unit...") hwu = HardwareUnit.hardwareUnitFactory(args.eventfile) log.debug("probed %s" % hwu.getName()) log.debug("done") log.debug("Reading event file...") # Remember: X, Y, tstart, tstop, time, event_header are global variables (module-level) with pyfits.open(args.eventfile) as fitsFile: # Get events X_ = fitsFile['EVENTS'].data.field("X") Y_ = fitsFile['EVENTS'].data.field("Y") time_ = fitsFile['EVENTS'].data.field("TIME") # Order them by time # Note that this is advanced slicing, hence it returns a COPY of X_, Y_ and time_. # That's why we delete them explicitly immediately after, to save memory idx = numpy.argsort(time_) time = time_[idx] X = X_[idx] Y = Y_[idx] event_header = fitsFile['EVENTS'].header # Get the start of the first GTI and the stop of the last one gti_starts = [] gti_stops = [] for ext in fitsFile[1:]: if ext.header['EXTNAME'] == 'GTI': gti_starts.append(ext.data.field("START").min()) gti_stops.append(ext.data.field("STOP").max()) # Since we might have randomized the times (in the Chandra pipeline, in the xtc_filter_event_file script), # we need to make sure that the tstart is either the beginning of the first GTI or the time of the first event tstart = min(min(gti_starts), time_.min() - 1e-3) tstop = max(max(gti_stops), time_.max() + 1e-3) # Now make arrays read-only so they will never be copied X.setflags(write=False) Y.setflags(write=False) time.setflags(write=False) # Save memory del X_, Y_, time_ log.debug("done") # Instantiate the GridGen class and generate the grid # of regions log.debug("Generating grid...") if hwu.getName().find("ACIS")==0: # Chandra. Automatically compute the step size, as the average # size of the PSF in the detector try: import psf import caldb4 from astropy.coordinates import SkyCoord import astropy.units as u except ImportError: raise RuntimeError("Cannot import psf and/or caldb4 and or astropy module from CIAO. " "Is CIAO python configured?") cdb = caldb4.Caldb(telescope="CHANDRA", product="REEF") reef = cdb.search[0] extno = cdb.extno() # Replace the trailing '[..]' block number specifier reef = reef.split('[')[0] + "[{}]".format(extno + 1) pdata = psf.psfInit(reef) # Get the coordinates of the events at the corners of the CCD # (don't use the minimum and maximum of X and Y because the CCD is rotated # with respect to sky coordinates) # Get the corners minx = X.min() maxx = X.max() miny = Y.min() maxy = Y.max() corner_1 = [minx, Y[X == minx].max()] corner_2 = [X[Y == maxy].max(), maxy] corner_3 = [X[Y == miny].max(), miny] corner_4 = [maxx, Y[X == maxx].max()] # Get the aim point ra_pointing = event_header.get('RA_PNT') dec_pointing = event_header.get('DEC_PNT') system = event_header.get("RADECSYS") if system is None: system = 'ICRS' wcs = XMMWCS.XMMWCS(args.eventfile, X, Y) x_pointing, y_pointing = wcs.sky2xy([[ra_pointing, dec_pointing]])[0] # Computing maximum distance between corners and the pointing distances_to_corners = numpy.linalg.norm(numpy.array([x_pointing, y_pointing]) - numpy.array([corner_1, corner_2, corner_3, corner_4]), axis=1) max_distance = distances_to_corners.max() pointing = SkyCoord(ra=ra_pointing * u.degree, dec=dec_pointing * u.degree, frame=system.lower()) def get_theta(x_, y_): point = wcs.xy2sky([[x_, y_]])[0] c1 = SkyCoord(ra=point[0] * u.degree, dec=point[1] * u.degree, frame=system.lower()) this_theta = c1.separation(pointing) # Return it in arcmin return this_theta.to(u.arcmin).value def get_psf_size(x_, y_): theta = get_theta(x_, y_) return psf.psfSize(pdata, 1.5, theta, 0.0, 0.68) gg = GridGen.GridGenChandra(hwu) gg.makeGrid(x_pointing, y_pointing, get_psf_size, max_distance) else: # Something else. Use provided step size gg = GridGen.GridGen(hwu) gg.makeGrid(args.regionsize, 'sky', args.multiplicity) log.debug("done") # Get the boxes definitions regions = gg.getBoxes() # with open('test_variable_size.reg','w+') as f: # # for spec in regions: # # reg = Box.Box(*spec) # # f.write("%s" % "".join(reg.getDs9Region())) #sys.exit(0) n_events = time.shape[0] log.info("Processing interval %s - %s (duration: %s s, %s events)" % (tstart, tstop, tstop - tstart, n_events)) results = _process_regions(args.eventfile, args.typeIerror, regions, args.ncpus, log) log.debug("done") log.debug("Selecting interesting regions with more than one interval...") interesting_regions = [] for i, intervals in enumerate(results): # Remember: intervals contains the edges of the intervals if len(intervals) > 2: box = Box.Box(*regions[i]) box.setEventfile(args.eventfile) box.readEvents(preLoaded=True, time=time, X=X, Y=Y, tstart=tstart, tstop=tstop) #if args.writeRegionFiles == 'yes': # box.writeRegion("%s_exc%i.reg" % (root_filename, i + 1)) # box.writeRegion("%s_exc%i.reg" % (root_filename, i + 1)) log.debug("Region %i has %i intervals" % (i+1, len(intervals)-1)) box.writeRegion("interesting_region_%i.reg" % (i+1)) for j,(t1,t2) in enumerate(zip(intervals[:-1],intervals[1:])): log.debug(" %i : %s - %s (%s s long)" % (j+1, t1, t2, t2-t1)) thisInterestingRegion = InterestingRegion.InterestingRegion(box, intervals, time, X, Y, tstart, tstop) interesting_regions.append(thisInterestingRegion) log.debug("done") log.debug("Removing overlapping intervals...") consolidator = TimeIntervalConsolidator.TimeIntervalConsolidator(interesting_regions) cleanedIntervals = consolidator.consolidate() log.debug("done") log.info("Kept %s intervals" % len(cleanedIntervals)) if args.sigmaThreshold > 0: # Import here to avoid to override the .use directive in xtdac import matplotlib.pyplot as plt # Now for each cleaned interval perform a likelihood analysis on a region # larger than the box. This is needed otherwise it is too difficult to distinguish # a PSF-like excess and a flat-like excess log.info("Computing final significance...") finalCandidates = [] for i, interval in enumerate(cleanedIntervals): log.info("Processing interval %s of %s" % (i + 1, len(cleanedIntervals))) this_interval_duration = interval.tstop - interval.tstart log.info("duration: %.1f s" % this_interval_duration) if this_interval_duration > args.max_duration: log.info("Duration is longer than the maximum allowed of %.1f" % (args.max_duration)) continue if interval.nEvents < args.min_number_of_events: log.info("Less than %s events, discarding candidate with %s events" % (args.min_number_of_events, interval.nEvents)) continue boxx, boxy = interval.interestingRegion.getCenterPhysicalCoordinates() boxw, boxh = interval.interestingRegion.box.width, interval.interestingRegion.box.height # Search region is 25 arcsec of radius if hwu.getName().find("ACIS")==0: # For Chandra, let's adapt to the size of the PSF (but keep a minimum size of # at least 50 px) box_size_arcsec = max([boxw, boxh]) * hwu.getPixelScale() radius = max(20.0, (box_size_arcsec /2.0) * 1.5 / hwu.getPixelScale()) log.info("Radius for search region: %s px" % radius) else: radius = 40.0 / hwu.getPixelScale() searchRegionStr = 'physical;circle(%s,%s,%s)' % (boxx, boxy, radius) log.info("Search region string: %s" % searchRegionStr) idx = (time >= interval.tstart) & (time <= interval.tstop) assert X[idx].shape[0] > 0 assert Y[idx].shape[0] > 0 with warnings.catch_warnings(): # Cause all warnings to be ignored warnings.simplefilter("ignore") searchRegionDef = fitsRegions.FitsRegion(X[idx], Y[idx], time[idx], event_header, searchRegionStr) # This is actually a loop of only one iteration for x, y, t, regfilter, reg in searchRegionDef.iteritems(): xmin = boxx - radius xmax = boxx + radius ymin = boxy - radius ymax = boxy + radius if hwu.getName().find("ACIS") == 0: # For Chandra, let's adapt to the size of the PSF, but make at least # twice the size of the pixel (remember, this is in pixels) r_binsize = max(radius / 60.0, 2.0) else: r_binsize = 40.0 / hwu.getPixelScale() / 10.0 assert (xmax-xmin) / r_binsize > 3.0, "Not enough bins for likelihood!" searchRegion = Likelihood.Region(xmin, xmax, ymin, ymax, r_binsize, regfilter, args.expomap, args.eventfile) ls = Likelihood.Likelihood(x, y, searchRegion) # Build the likelihood model # Bkg model (isotropic) iso = Likelihood.Isotropic("bkg", 1.0) m = Likelihood.GlobalModel("likeModel") + iso try: ls.setModel(m) except UnboundLocalError: import pdb;pdb.set_trace() # Minimize the mlogLike to get the background level like0 = ls.minimize(verbose=0) # Small TS map to figure out the source position trial_x = numpy.linspace(boxx - boxw / 2.0, boxx + boxw / 2.0, 16) trial_y = numpy.linspace(boxy - boxh / 2.0, boxy + boxh / 2.0, 16) ra, dec = interval.interestingRegion.getCenterSkyCoordinates() maxTS = 0 _best_x = None _best_y = None TSmap = numpy.zeros([trial_y.shape[0], trial_x.shape[0]]) # import cProfile, pstats, StringIO # pr = cProfile.Profile() # pr.enable() for k, srcx in enumerate(trial_x): for h, srcy in enumerate(trial_y): sys.stderr.write(".") # Now fit adding a source at the position of the maximum of the # image of this region # srcx, srcy = ls.getMaximumPosition() if h == 0: # This is the very first loop. Make the image of the PSF. # We assume that the PSF does not change much within the region, so we # will use the same image for all the next iterations thisSrc = Likelihood.PointSource("testSrc", srcx, srcy, args.eventfile, hwu) psffile = thisSrc.outfile else: # Re-use the psf file already computed thisSrc = Likelihood.PointSource("testSrc", srcx, srcy, args.eventfile, hwu, psffile) pass m += thisSrc ls.setModel(m) like1 = ls.minimize(verbose=0) TS = 2 * (like0 - like1) TSmap[h, k] = TS if TS > maxTS: maxTS = TS _best_x = srcx _best_y = srcy with warnings.catch_warnings(): # Cause all warnings to be ignored warnings.simplefilter("ignore") this_fig = ls.plot() this_fig.savefig("c_%.4f_%.4f_%i.png" % (ra,dec,i)) plt.close(this_fig) m.removeSource("testSrc") # pr.disable() # s = StringIO.StringIO() # sortby = 'cumulative' # ps = pstats.Stats(pr, stream=s).sort_stats(sortby) # ps.print_stats() # print s.getvalue() # sys.exit(0) sys.stderr.write("\n") significance = math.sqrt(max(TSmap.max(), 0)) log.info("number of events: %s" % interval.nEvents) log.info("Region @ (RA,Dec) = (%.4f,%.4f) (%.3f - %.3f s) " "-> %.1f sigma" % (ra, dec, interval.tstart, interval.tstop, significance)) if significance >= args.sigmaThreshold: log.debug("Keeping candidate") # One-sided probability of a n sigma effect prob = scipy.stats.norm().sf(significance) / 2.0 interval.probability = prob interval._best_localization = (_best_x, _best_y) finalCandidates.append(interval) plt.imshow(TSmap, interpolation='none', origin='lower') plt.colorbar() plt.savefig("exc%s_tsmap.png" % i, tight_layout=True) plt.close() else: log.debug("Discarding candidate") # plt.imshow(TSmap, interpolation='none', origin='lower') # plt.savefig("exc%s.png" % i, tight_layout=True) log.debug("done") else: log.debug("Threshold for final significance is <= 0, no likelihood analysis will be performed") finalCandidates = cleanedIntervals # The probability has not been computed, so let's assign -1 for c in finalCandidates: c.probability = -1 pass log.debug("Preparing the summary Ascii file...") root_filename = ".".join(os.path.basename(args.eventfile).split(".")[:-1]) # I need to read the WCS from the event file, if transient_pos is true wcs = None if args.transient_pos: wcs = XMMWCS.XMMWCS(args.eventfile, X, Y) with open("%s_res.txt" % root_filename, "w+") as f: f.write("#RA Dec Tstart Tstop Probability\n") for i, interval in enumerate(finalCandidates): if args.transient_pos: # Write the position of the transient points = wcs.xy2sky([list(interval._best_localization)]) ra, dec = points[0] else: # Write the position of the center of the region containing the transient ra, dec = interval.interestingRegion.getCenterSkyCoordinates() # Find the first and last event in the interval idx = (time >= interval.tstart) & (time <= interval.tstop) first_event_timestamp = time[idx].min() last_event_timestamp = time[idx].max() f.write("%.4f %.4f %.3f %.3f %.3g\n" % (ra, dec, first_event_timestamp - 1e-2, last_event_timestamp + 1e-2, interval.probability)) if args.writeRegionFiles == 'yes': interval.interestingRegion.box.writeRegion("%s_candidate_%i.reg" % (root_filename, i + 1)) log.debug("done") jobStop = timemod.time() if args.html_summary: log.debug("Preparing the summary HTML file...") # Summarize the results in a HTML file resultsSummary = Results.Summary() resultsSummary.addJobInfo(jobStop - jobStart, args.ncpus, args.typeIerror) resultsSummary.addObsInfo(args.eventfile, hwu.getName(), tstart, tstop, n_events) resultsSummary.addWholeHWUlightCurve(time, tstart, tstop, figsize=(8, 8)) resultsSummary.addResults(map(lambda interval: interval.interestingRegion, finalCandidates)) root_filename = ".".join(os.path.basename(args.eventfile).split(".")[:-1]) resultsSummary.write("%s_res.html" % root_filename) log.debug("done") pass if __name__ == "__main__": jobStart = timemod.time() # Define and parse input arguments desc = '''EXTraS Divide-and-Conquer algorithm to find transients.''' parser = argparse.ArgumentParser(description=desc) parser.add_argument("-e", "--eventfile", help="Event file to use (already cleaned and selected in" + " energy and quadrant/CCD)", required=True, type=validFITSfile) parser.add_argument("-x", "--expomap", help="Exposure map for the whole observation. It is only" + " needed to figure out gaps and masked pixels", required=True, type=validFITSfile) parser.add_argument("-b", "--backgroundRegion", help="Custom background circle. To be" + " specified as ra,dec,radius. For example '-b 187.5," + "-23.2,10' corresponds to a circle with 10 arcsec " + "radius centered on R.A., Dec. = (187.5, -23.2)", required=False, default=None) parser.add_argument("-m", "--multiplicity", help="Control the overlap of the regions." + " A multiplicity of 2 means the centers of the regions are" + " shifted by 1/2 of the region size (they overlap by 50 percent)," + " a multiplicity of 4 means they are shifted by 1/4 of " + " their size (they overlap by 75 percent), and so on.", required=False, default=2.0, type=float) parser.add_argument("-c", "--ncpus", help="Number of CPUs to use (default=1)", type=int, default=1, required=False) parser.add_argument("-p", "--typeIerror", help="Type I error probability for the Bayesian Blocks " + "algorithm.", type=float, default=1e-5, required=False) parser.add_argument("-s", "--sigmaThreshold", help="Threshold for the final significance. All intervals found " + "by the bayesian blocks " + "algorithm which does not surpass this threshold will not be saved in the " + "final file.", type=float, default=5.0, required=False) parser.add_argument("-r", "--regionsize", help="Approximate side for the square regions in which the" + " search will be performed (Default: 60 arcsec)", type=float, default=60, required=False) parser.add_argument("--max_duration", help="Do not consider candidate transients with a duration longer then max_duration", type=float, default=1e9, required=False) parser.add_argument("--min_number_of_events", help="Do not consider candidate transients with less than this number of events", type=int, default=0, required=False) parser.add_argument("-w", "--writeRegionFiles", help="Write a ds9 region file for each region with excesses?", type=str, default='yes', required=False, choices=['yes', 'no']) parser.add_argument('--transient_pos', dest='transient_pos', action='store_true') parser.set_defaults(transient_pos=False) parser.add_argument('--no-html', dest='html_summary', action='store_false') parser.set_defaults(html_summary=True) parser.add_argument("-v", "--verbosity", required=False, default='info', choices=['info', 'debug']) args = parser.parse_args() go(args)
[ "matplotlib.pyplot.savefig", "argparse.ArgumentParser", "XtDac.FixedBinSearch.Likelihood.PointSource", "numpy.argsort", "XtDac.DivideAndConquer.XMMWCS.XMMWCS", "os.path.isfile", "XtDac.DivideAndConquer.TimeIntervalConsolidator.TimeIntervalConsolidator", "XtDac.DivideAndConquer.Results.Summary", "XtDac.DivideAndConquer.GridGen.GridGenChandra", "XtDac.FixedBinSearch.Likelihood.GlobalModel", "warnings.simplefilter", "matplotlib.pyplot.imshow", "matplotlib.pyplot.close", "matplotlib.pyplot.colorbar", "caldb4.Caldb", "XtDac.DivideAndConquer.HardwareUnit.hardwareUnitFactory", "warnings.catch_warnings", "numpy.linspace", "XtDac.DivideAndConquer.InterestingRegion.InterestingRegion", "XtDac.DivideAndConquer.Box.Box", "psf.psfSize", "XtDac.DivideAndConquer.matplotlibConfig.getConfig", "XtDac.DivideAndConquer.GridGen.GridGen", "os.path.basename", "pyfits.open", "XtDac.FixedBinSearch.fitsRegions.FitsRegion", "XtDac.FixedBinSearch.Likelihood.Region", "matplotlib.use", "multiprocessing.Pool", "sys.exit", "logging.basicConfig", "XtDac.FixedBinSearch.Likelihood.Isotropic", "numpy.zeros", "time.time", "psf.psfInit", "numpy.array", "XtDac.FixedBinSearch.Likelihood.Likelihood", "pdb.set_trace", "sys.stderr.write", "logging.getLogger" ]
[((300, 321), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (314, 321), False, 'import matplotlib\n'), ((334, 362), 'XtDac.DivideAndConquer.matplotlibConfig.getConfig', 'matplotlibConfig.getConfig', ([], {}), '()\n', (360, 362), False, 'from XtDac.DivideAndConquer import matplotlibConfig\n'), ((1353, 1393), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (1372, 1393), False, 'import logging\n'), ((1400, 1426), 'logging.getLogger', 'logging.getLogger', (['"""XtDac"""'], {}), "('XtDac')\n", (1417, 1426), False, 'import logging\n'), ((2596, 2613), 'XtDac.DivideAndConquer.Box.Box', 'Box.Box', (['*box_def'], {}), '(*box_def)\n', (2603, 2613), False, 'from XtDac.DivideAndConquer import Box\n'), ((5862, 5910), 'XtDac.DivideAndConquer.HardwareUnit.hardwareUnitFactory', 'HardwareUnit.hardwareUnitFactory', (['args.eventfile'], {}), '(args.eventfile)\n', (5894, 5910), False, 'from XtDac.DivideAndConquer import HardwareUnit\n'), ((12414, 12484), 'XtDac.DivideAndConquer.TimeIntervalConsolidator.TimeIntervalConsolidator', 'TimeIntervalConsolidator.TimeIntervalConsolidator', (['interesting_regions'], {}), '(interesting_regions)\n', (12463, 12484), False, 'from XtDac.DivideAndConquer import TimeIntervalConsolidator\n'), ((22482, 22496), 'time.time', 'timemod.time', ([], {}), '()\n', (22494, 22496), True, 'import time as timemod\n'), ((23246, 23260), 'time.time', 'timemod.time', ([], {}), '()\n', (23258, 23260), True, 'import time as timemod\n'), ((23425, 23466), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desc'}), '(description=desc)\n', (23448, 23466), False, 'import argparse\n'), ((1465, 1484), 'os.path.isfile', 'os.path.isfile', (['arg'], {}), '(arg)\n', (1479, 1484), False, 'import os\n'), ((1550, 1560), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1558, 1560), False, 'import sys\n'), ((1641, 1657), 'pyfits.open', 'pyfits.open', (['arg'], {}), '(arg)\n', (1652, 1657), False, 'import pyfits\n'), ((4122, 4150), 'multiprocessing.Pool', 'multiprocessing.Pool', (['n_cpus'], {}), '(n_cpus)\n', (4142, 4150), False, 'import multiprocessing\n'), ((6120, 6147), 'pyfits.open', 'pyfits.open', (['args.eventfile'], {}), '(args.eventfile)\n', (6131, 6147), False, 'import pyfits\n'), ((6552, 6572), 'numpy.argsort', 'numpy.argsort', (['time_'], {}), '(time_)\n', (6565, 6572), False, 'import numpy\n'), ((8234, 8283), 'caldb4.Caldb', 'caldb4.Caldb', ([], {'telescope': '"""CHANDRA"""', 'product': '"""REEF"""'}), "(telescope='CHANDRA', product='REEF')\n", (8246, 8283), False, 'import caldb4\n'), ((8480, 8497), 'psf.psfInit', 'psf.psfInit', (['reef'], {}), '(reef)\n', (8491, 8497), False, 'import psf\n'), ((9248, 9283), 'XtDac.DivideAndConquer.XMMWCS.XMMWCS', 'XMMWCS.XMMWCS', (['args.eventfile', 'X', 'Y'], {}), '(args.eventfile, X, Y)\n', (9261, 9283), False, 'from XtDac.DivideAndConquer import XMMWCS\n'), ((10304, 10331), 'XtDac.DivideAndConquer.GridGen.GridGenChandra', 'GridGen.GridGenChandra', (['hwu'], {}), '(hwu)\n', (10326, 10331), False, 'from XtDac.DivideAndConquer import GridGen\n'), ((10480, 10500), 'XtDac.DivideAndConquer.GridGen.GridGen', 'GridGen.GridGen', (['hwu'], {}), '(hwu)\n', (10495, 10500), False, 'from XtDac.DivideAndConquer import GridGen\n'), ((21260, 21295), 'XtDac.DivideAndConquer.XMMWCS.XMMWCS', 'XMMWCS.XMMWCS', (['args.eventfile', 'X', 'Y'], {}), '(args.eventfile, X, Y)\n', (21273, 21295), False, 'from XtDac.DivideAndConquer import XMMWCS\n'), ((22653, 22670), 'XtDac.DivideAndConquer.Results.Summary', 'Results.Summary', ([], {}), '()\n', (22668, 22670), False, 'from XtDac.DivideAndConquer import Results\n'), ((1744, 1754), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1752, 1754), False, 'import sys\n'), ((10248, 10289), 'psf.psfSize', 'psf.psfSize', (['pdata', '(1.5)', 'theta', '(0.0)', '(0.68)'], {}), '(pdata, 1.5, theta, 0.0, 0.68)\n', (10259, 10289), False, 'import psf\n'), ((11410, 11430), 'XtDac.DivideAndConquer.Box.Box', 'Box.Box', (['*regions[i]'], {}), '(*regions[i])\n', (11417, 11430), False, 'from XtDac.DivideAndConquer import Box\n'), ((12106, 12184), 'XtDac.DivideAndConquer.InterestingRegion.InterestingRegion', 'InterestingRegion.InterestingRegion', (['box', 'intervals', 'time', 'X', 'Y', 'tstart', 'tstop'], {}), '(box, intervals, time, X, Y, tstart, tstop)\n', (12141, 12184), False, 'from XtDac.DivideAndConquer import InterestingRegion\n'), ((16367, 16399), 'XtDac.FixedBinSearch.Likelihood.Isotropic', 'Likelihood.Isotropic', (['"""bkg"""', '(1.0)'], {}), "('bkg', 1.0)\n", (16387, 16399), False, 'from XtDac.FixedBinSearch import Likelihood\n'), ((16785, 16841), 'numpy.linspace', 'numpy.linspace', (['(boxx - boxw / 2.0)', '(boxx + boxw / 2.0)', '(16)'], {}), '(boxx - boxw / 2.0, boxx + boxw / 2.0, 16)\n', (16799, 16841), False, 'import numpy\n'), ((16864, 16920), 'numpy.linspace', 'numpy.linspace', (['(boxy - boxh / 2.0)', '(boxy + boxh / 2.0)', '(16)'], {}), '(boxy - boxh / 2.0, boxy + boxh / 2.0, 16)\n', (16878, 16920), False, 'import numpy\n'), ((17095, 17144), 'numpy.zeros', 'numpy.zeros', (['[trial_y.shape[0], trial_x.shape[0]]'], {}), '([trial_y.shape[0], trial_x.shape[0]])\n', (17106, 17144), False, 'import numpy\n'), ((19405, 19427), 'sys.stderr.write', 'sys.stderr.write', (['"""\n"""'], {}), "('\\n')\n", (19421, 19427), False, 'import sys\n'), ((9483, 9520), 'numpy.array', 'numpy.array', (['[x_pointing, y_pointing]'], {}), '([x_pointing, y_pointing])\n', (9494, 9520), False, 'import numpy\n'), ((9572, 9625), 'numpy.array', 'numpy.array', (['[corner_1, corner_2, corner_3, corner_4]'], {}), '([corner_1, corner_2, corner_3, corner_4])\n', (9583, 9625), False, 'import numpy\n'), ((14890, 14915), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (14913, 14915), False, 'import warnings\n'), ((14986, 15017), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (15007, 15017), False, 'import warnings\n'), ((15053, 15138), 'XtDac.FixedBinSearch.fitsRegions.FitsRegion', 'fitsRegions.FitsRegion', (['X[idx]', 'Y[idx]', 'time[idx]', 'event_header', 'searchRegionStr'], {}), '(X[idx], Y[idx], time[idx], event_header, searchRegionStr\n )\n', (15075, 15138), False, 'from XtDac.FixedBinSearch import fitsRegions\n'), ((15965, 16063), 'XtDac.FixedBinSearch.Likelihood.Region', 'Likelihood.Region', (['xmin', 'xmax', 'ymin', 'ymax', 'r_binsize', 'regfilter', 'args.expomap', 'args.eventfile'], {}), '(xmin, xmax, ymin, ymax, r_binsize, regfilter, args.\n expomap, args.eventfile)\n', (15982, 16063), False, 'from XtDac.FixedBinSearch import Likelihood\n'), ((16228, 16269), 'XtDac.FixedBinSearch.Likelihood.Likelihood', 'Likelihood.Likelihood', (['x', 'y', 'searchRegion'], {}), '(x, y, searchRegion)\n', (16249, 16269), False, 'from XtDac.FixedBinSearch import Likelihood\n'), ((16417, 16452), 'XtDac.FixedBinSearch.Likelihood.GlobalModel', 'Likelihood.GlobalModel', (['"""likeModel"""'], {}), "('likeModel')\n", (16439, 16452), False, 'from XtDac.FixedBinSearch import Likelihood\n'), ((20247, 20302), 'matplotlib.pyplot.imshow', 'plt.imshow', (['TSmap'], {'interpolation': '"""none"""', 'origin': '"""lower"""'}), "(TSmap, interpolation='none', origin='lower')\n", (20257, 20302), True, 'import matplotlib.pyplot as plt\n'), ((20319, 20333), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (20331, 20333), True, 'import matplotlib.pyplot as plt\n'), ((20350, 20403), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('exc%s_tsmap.png' % i)"], {'tight_layout': '(True)'}), "('exc%s_tsmap.png' % i, tight_layout=True)\n", (20361, 20403), True, 'import matplotlib.pyplot as plt\n'), ((20420, 20431), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (20429, 20431), True, 'import matplotlib.pyplot as plt\n'), ((16576, 16591), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (16589, 16591), False, 'import pdb\n'), ((17379, 17400), 'sys.stderr.write', 'sys.stderr.write', (['"""."""'], {}), "('.')\n", (17395, 17400), False, 'import sys\n'), ((21076, 21108), 'os.path.basename', 'os.path.basename', (['args.eventfile'], {}), '(args.eventfile)\n', (21092, 21108), False, 'import os\n'), ((17912, 17978), 'XtDac.FixedBinSearch.Likelihood.PointSource', 'Likelihood.PointSource', (['"""testSrc"""', 'srcx', 'srcy', 'args.eventfile', 'hwu'], {}), "('testSrc', srcx, srcy, args.eventfile, hwu)\n", (17934, 17978), False, 'from XtDac.FixedBinSearch import Likelihood\n'), ((18154, 18229), 'XtDac.FixedBinSearch.Likelihood.PointSource', 'Likelihood.PointSource', (['"""testSrc"""', 'srcx', 'srcy', 'args.eventfile', 'hwu', 'psffile'], {}), "('testSrc', srcx, srcy, args.eventfile, hwu, psffile)\n", (18176, 18229), False, 'from XtDac.FixedBinSearch import Likelihood\n'), ((23060, 23092), 'os.path.basename', 'os.path.basename', (['args.eventfile'], {}), '(args.eventfile)\n', (23076, 23092), False, 'import os\n'), ((18757, 18782), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (18780, 18782), False, 'import warnings\n'), ((18877, 18908), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (18898, 18908), False, 'import warnings\n'), ((19068, 19087), 'matplotlib.pyplot.close', 'plt.close', (['this_fig'], {}), '(this_fig)\n', (19077, 19087), True, 'import matplotlib.pyplot as plt\n')]
from numpy.core.numeric import outer import torch from torch import log, mean, nn import torch.nn.functional as F import numpy as np class VGAE_Encoder(nn.Module): def __init__(self, n_in, n_hid, n_out, adj=None): super(VGAE_Encoder, self).__init__() self.n_out = n_out self.base_gcn = GraphConv2(n_in, n_hid, adj=adj) self.gcn1 = GraphConv2(n_hid, n_out, activation=F.elu, adj=adj) self.gcn2 = GraphConv2(n_out, n_out, activation=F.elu, adj=adj) self.gcn3 = GraphConv2(n_out, n_out*2, activation=lambda x:x, adj=adj) def forward(self, x): hidden = self.base_gcn(x) out = self.gcn1(hidden) out = self.gcn2(out) out = self.gcn3(out) mean = out[:, :self.n_out] std = out[:, self.n_out:] return mean, std def set_gcn_adj(self, adj): self.base_gcn.adj = adj self.gcn1.adj = adj self.gcn2.adj = adj self.gcn3.adj = adj class VAE_Encoder(nn.Module): def __init__(self, n_in, n_hidden, n_out, keep_prob=1.0) -> None: super(VAE_Encoder, self).__init__() self.n_out = n_out self.layer1 = nn.Linear(n_in, n_hidden) self.layer2 = nn.Linear(n_hidden, n_out) self.layer3 = nn.Linear(n_hidden, n_out) self._init_weight() def _init_weight(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.fill_(0.01) def forward(self, inputs): h0 = self.layer1(inputs) h0 = F.relu(h0) mean = self.layer2(h0) logvar = self.layer3(h0) # logvar = F.hardtanh(logvar, min_val=0, max_val=30) return mean, logvar class VAE_Bernulli_Decoder(nn.Module): def __init__(self, n_in, n_hidden, n_out, keep_prob=1.0) -> None: super(VAE_Bernulli_Decoder, self).__init__() self.layer1 = nn.Linear(n_in, n_hidden) self.layer2 = nn.Linear(n_hidden, n_out) self._init_weight() def _init_weight(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.fill_(0.01) def forward(self, inputs): h0 = self.layer1(inputs) h0 = F.relu(h0) x_hat = self.layer2(h0) return x_hat class Encoder(nn.Module): def __init__(self, n_in, n_hid, n_out, adj=None): super(Encoder,self).__init__() self.n_out = n_out self.base_gcn = GraphConv2(n_in, n_hid, adj=adj) self.gcn1 = GraphConv2(n_hid, n_out, activation=F.elu, adj=adj) self.gcn2 = GraphConv2(n_out, n_out, activation=F.elu, adj=adj) self.gcn3 = GraphConv2(n_out, n_out, activation=lambda x:x, adj=adj) def forward(self, x): hidden = self.base_gcn(x) out = self.gcn1(hidden) out = self.gcn2(out) out = self.gcn3(out) alpha = torch.exp(out/4) alpha = F.hardtanh(alpha, min_val=1e-2, max_val=30) return alpha def set_gcn_adj(self, adj): self.base_gcn.adj = adj self.gcn1.adj = adj self.gcn2.adj = adj self.gcn3.adj = adj class Encoder2(nn.Module): def __init__(self, n_in, n_hidden, n_out, keep_prob=1.0) -> None: super(Encoder2, self).__init__() self.n_out = n_out self.layer1 = nn.Linear(n_in, n_hidden) self.layer2 = nn.Linear(n_hidden, n_out) self._init_weight() def _init_weight(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.fill_(0.01) def forward(self, inputs): h0 = self.layer1(inputs) h0 = F.relu(h0) out = self.layer2(h0) alpha = torch.exp(out/4) alpha = F.hardtanh(alpha, min_val=1e-2, max_val=30) return alpha class Encoder3(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, keep_prob=1.0) -> None: super(Encoder3, self).__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) self.relu1 = nn.ReLU() self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.relu2 = nn.ReLU() self.fc3 = nn.Linear(hidden_dim, hidden_dim) self.relu3 = nn.ReLU() self.fc4 = nn.Linear(hidden_dim, output_dim) # self._init_weight() # def _init_weight(self): # for m in self.modules(): # if isinstance(m, nn.Linear): # nn.init.xavier_normal_(m.weight.data) # m.bias.data.fill_(0.01) def forward(self, x): out = x.view(x.size(0), -1) out = self.fc1(out) out = self.relu1(out) out = self.fc2(out) out = self.relu2(out) out = self.fc3(out) out = self.relu3(out) out = self.fc4(out) # out = torch.exp(out/4) # out = F.hardtanh(out, min_val=1e-2, max_val=30) return out class VGAE_Decoder(nn.Module): def __init__(self, n_in, n_hid, n_out, n_label, keep_prob=1.0): super(VGAE_Decoder,self).__init__() self.n_label = n_label self.layer1 = nn.Sequential(nn.Linear(n_in,n_hid), nn.Tanh(), nn.Dropout(1-keep_prob)) self.layer2 = nn.Sequential(nn.Linear(n_hid,n_hid), nn.ELU(), nn.Dropout(1-keep_prob)) self.fc_out = nn.Linear(n_hid,n_out) self._init_weight() def _init_weight(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.fill_(0.01) def forward(self, z): h0 = self.layer1(z) h1 = self.layer2(h0) features_hat = self.fc_out(h1) labels_hat = z[:, -self.n_label:] adj_hat = dot_product_decode(z) return features_hat, labels_hat, adj_hat class Decoder(nn.Module): def __init__(self, n_in, n_hid, n_out, n_label, keep_prob=1.0): super(Decoder,self).__init__() self.n_label = n_label self.layer1 = nn.Sequential(nn.Linear(n_in,n_hid), nn.Tanh(), nn.Dropout(1-keep_prob)) self.layer2 = nn.Sequential(nn.Linear(n_hid,n_hid), nn.ELU(), nn.Dropout(1-keep_prob)) self.layer3 = nn.Sequential(nn.Linear(n_in,n_hid), nn.Tanh(), nn.Dropout(1-keep_prob)) self.layer4 = nn.Sequential(nn.Linear(n_hid,n_label), nn.ELU(), nn.Dropout(1-keep_prob)) self.fc_out = nn.Linear(n_hid,n_out) self._init_weight() def _init_weight(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.fill_(0.01) def forward(self, z): h0 = self.layer1(z) h1 = self.layer2(h0) features_hat = self.fc_out(h1) h2 = self.layer3(z) h3 = self.layer4(h2) labels_hat = h3 adj_hat = dot_product_decode(z) return features_hat, labels_hat, adj_hat class GraphConv(nn.Module): def __init__(self, n_in, n_out, adj, activation = F.relu, **kwargs): super(GraphConv, self).__init__(**kwargs) self.weight = glorot_init(n_in, n_out) self.adj = adj self.activation = activation def forward(self, inputs): x = inputs x = torch.mm(x,self.weight) x = torch.mm(self.adj, x) outputs = self.activation(x) return outputs class GraphConv2(nn.Module): def __init__(self, n_in, n_out, activation = F.relu, adj=None, **kwargs): super(GraphConv2, self).__init__(**kwargs) self.weight = glorot_init(n_in, n_out) self.adj = adj self.activation = activation def forward(self, inputs): x = inputs x = torch.mm(x,self.weight) x = torch.spmm(self.adj, x) outputs = self.activation(x) return outputs def dot_product_decode(Z): A_pred = torch.sigmoid(torch.matmul(Z,Z.t())) return A_pred def glorot_init(input_dim, output_dim): init_range = np.sqrt(6.0/(input_dim + output_dim)) initial = torch.rand(input_dim, output_dim)*2*init_range - init_range return nn.Parameter(initial)
[ "torch.nn.Parameter", "torch.nn.Dropout", "torch.nn.ReLU", "torch.rand", "torch.nn.Tanh", "torch.nn.init.xavier_normal_", "torch.mm", "torch.spmm", "torch.exp", "torch.nn.ELU", "torch.nn.functional.hardtanh", "torch.nn.Linear", "torch.nn.functional.relu", "numpy.sqrt" ]
[((8286, 8325), 'numpy.sqrt', 'np.sqrt', (['(6.0 / (input_dim + output_dim))'], {}), '(6.0 / (input_dim + output_dim))\n', (8293, 8325), True, 'import numpy as np\n'), ((8409, 8430), 'torch.nn.Parameter', 'nn.Parameter', (['initial'], {}), '(initial)\n', (8421, 8430), False, 'from torch import log, mean, nn\n'), ((1170, 1195), 'torch.nn.Linear', 'nn.Linear', (['n_in', 'n_hidden'], {}), '(n_in, n_hidden)\n', (1179, 1195), False, 'from torch import log, mean, nn\n'), ((1218, 1244), 'torch.nn.Linear', 'nn.Linear', (['n_hidden', 'n_out'], {}), '(n_hidden, n_out)\n', (1227, 1244), False, 'from torch import log, mean, nn\n'), ((1267, 1293), 'torch.nn.Linear', 'nn.Linear', (['n_hidden', 'n_out'], {}), '(n_hidden, n_out)\n', (1276, 1293), False, 'from torch import log, mean, nn\n'), ((1605, 1615), 'torch.nn.functional.relu', 'F.relu', (['h0'], {}), '(h0)\n', (1611, 1615), True, 'import torch.nn.functional as F\n'), ((1954, 1979), 'torch.nn.Linear', 'nn.Linear', (['n_in', 'n_hidden'], {}), '(n_in, n_hidden)\n', (1963, 1979), False, 'from torch import log, mean, nn\n'), ((2002, 2028), 'torch.nn.Linear', 'nn.Linear', (['n_hidden', 'n_out'], {}), '(n_hidden, n_out)\n', (2011, 2028), False, 'from torch import log, mean, nn\n'), ((2332, 2342), 'torch.nn.functional.relu', 'F.relu', (['h0'], {}), '(h0)\n', (2338, 2342), True, 'import torch.nn.functional as F\n'), ((2992, 3010), 'torch.exp', 'torch.exp', (['(out / 4)'], {}), '(out / 4)\n', (3001, 3010), False, 'import torch\n'), ((3025, 3068), 'torch.nn.functional.hardtanh', 'F.hardtanh', (['alpha'], {'min_val': '(0.01)', 'max_val': '(30)'}), '(alpha, min_val=0.01, max_val=30)\n', (3035, 3068), True, 'import torch.nn.functional as F\n'), ((3428, 3453), 'torch.nn.Linear', 'nn.Linear', (['n_in', 'n_hidden'], {}), '(n_in, n_hidden)\n', (3437, 3453), False, 'from torch import log, mean, nn\n'), ((3476, 3502), 'torch.nn.Linear', 'nn.Linear', (['n_hidden', 'n_out'], {}), '(n_hidden, n_out)\n', (3485, 3502), False, 'from torch import log, mean, nn\n'), ((3814, 3824), 'torch.nn.functional.relu', 'F.relu', (['h0'], {}), '(h0)\n', (3820, 3824), True, 'import torch.nn.functional as F\n'), ((3871, 3889), 'torch.exp', 'torch.exp', (['(out / 4)'], {}), '(out / 4)\n', (3880, 3889), False, 'import torch\n'), ((3904, 3947), 'torch.nn.functional.hardtanh', 'F.hardtanh', (['alpha'], {'min_val': '(0.01)', 'max_val': '(30)'}), '(alpha, min_val=0.01, max_val=30)\n', (3914, 3947), True, 'import torch.nn.functional as F\n'), ((4140, 4172), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'hidden_dim'], {}), '(input_dim, hidden_dim)\n', (4149, 4172), False, 'from torch import log, mean, nn\n'), ((4194, 4203), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4201, 4203), False, 'from torch import log, mean, nn\n'), ((4223, 4256), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'hidden_dim'], {}), '(hidden_dim, hidden_dim)\n', (4232, 4256), False, 'from torch import log, mean, nn\n'), ((4278, 4287), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4285, 4287), False, 'from torch import log, mean, nn\n'), ((4307, 4340), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'hidden_dim'], {}), '(hidden_dim, hidden_dim)\n', (4316, 4340), False, 'from torch import log, mean, nn\n'), ((4362, 4371), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4369, 4371), False, 'from torch import log, mean, nn\n'), ((4391, 4424), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'output_dim'], {}), '(hidden_dim, output_dim)\n', (4400, 4424), False, 'from torch import log, mean, nn\n'), ((5498, 5521), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_out'], {}), '(n_hid, n_out)\n', (5507, 5521), False, 'from torch import log, mean, nn\n'), ((6697, 6720), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_out'], {}), '(n_hid, n_out)\n', (6706, 6720), False, 'from torch import log, mean, nn\n'), ((7562, 7586), 'torch.mm', 'torch.mm', (['x', 'self.weight'], {}), '(x, self.weight)\n', (7570, 7586), False, 'import torch\n'), ((7598, 7619), 'torch.mm', 'torch.mm', (['self.adj', 'x'], {}), '(self.adj, x)\n', (7606, 7619), False, 'import torch\n'), ((8011, 8035), 'torch.mm', 'torch.mm', (['x', 'self.weight'], {}), '(x, self.weight)\n', (8019, 8035), False, 'import torch\n'), ((8047, 8070), 'torch.spmm', 'torch.spmm', (['self.adj', 'x'], {}), '(self.adj, x)\n', (8057, 8070), False, 'import torch\n'), ((5258, 5280), 'torch.nn.Linear', 'nn.Linear', (['n_in', 'n_hid'], {}), '(n_in, n_hid)\n', (5267, 5280), False, 'from torch import log, mean, nn\n'), ((5297, 5306), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (5304, 5306), False, 'from torch import log, mean, nn\n'), ((5324, 5349), 'torch.nn.Dropout', 'nn.Dropout', (['(1 - keep_prob)'], {}), '(1 - keep_prob)\n', (5334, 5349), False, 'from torch import log, mean, nn\n'), ((5385, 5408), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_hid'], {}), '(n_hid, n_hid)\n', (5394, 5408), False, 'from torch import log, mean, nn\n'), ((5425, 5433), 'torch.nn.ELU', 'nn.ELU', ([], {}), '()\n', (5431, 5433), False, 'from torch import log, mean, nn\n'), ((5451, 5476), 'torch.nn.Dropout', 'nn.Dropout', (['(1 - keep_prob)'], {}), '(1 - keep_prob)\n', (5461, 5476), False, 'from torch import log, mean, nn\n'), ((6201, 6223), 'torch.nn.Linear', 'nn.Linear', (['n_in', 'n_hid'], {}), '(n_in, n_hid)\n', (6210, 6223), False, 'from torch import log, mean, nn\n'), ((6240, 6249), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (6247, 6249), False, 'from torch import log, mean, nn\n'), ((6267, 6292), 'torch.nn.Dropout', 'nn.Dropout', (['(1 - keep_prob)'], {}), '(1 - keep_prob)\n', (6277, 6292), False, 'from torch import log, mean, nn\n'), ((6328, 6351), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_hid'], {}), '(n_hid, n_hid)\n', (6337, 6351), False, 'from torch import log, mean, nn\n'), ((6368, 6376), 'torch.nn.ELU', 'nn.ELU', ([], {}), '()\n', (6374, 6376), False, 'from torch import log, mean, nn\n'), ((6394, 6419), 'torch.nn.Dropout', 'nn.Dropout', (['(1 - keep_prob)'], {}), '(1 - keep_prob)\n', (6404, 6419), False, 'from torch import log, mean, nn\n'), ((6455, 6477), 'torch.nn.Linear', 'nn.Linear', (['n_in', 'n_hid'], {}), '(n_in, n_hid)\n', (6464, 6477), False, 'from torch import log, mean, nn\n'), ((6494, 6503), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (6501, 6503), False, 'from torch import log, mean, nn\n'), ((6521, 6546), 'torch.nn.Dropout', 'nn.Dropout', (['(1 - keep_prob)'], {}), '(1 - keep_prob)\n', (6531, 6546), False, 'from torch import log, mean, nn\n'), ((6582, 6607), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_label'], {}), '(n_hid, n_label)\n', (6591, 6607), False, 'from torch import log, mean, nn\n'), ((6624, 6632), 'torch.nn.ELU', 'nn.ELU', ([], {}), '()\n', (6630, 6632), False, 'from torch import log, mean, nn\n'), ((6650, 6675), 'torch.nn.Dropout', 'nn.Dropout', (['(1 - keep_prob)'], {}), '(1 - keep_prob)\n', (6660, 6675), False, 'from torch import log, mean, nn\n'), ((1445, 1482), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['m.weight.data'], {}), '(m.weight.data)\n', (1467, 1482), False, 'from torch import log, mean, nn\n'), ((2176, 2213), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['m.weight.data'], {}), '(m.weight.data)\n', (2198, 2213), False, 'from torch import log, mean, nn\n'), ((3654, 3691), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['m.weight.data'], {}), '(m.weight.data)\n', (3676, 3691), False, 'from torch import log, mean, nn\n'), ((5668, 5705), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['m.weight.data'], {}), '(m.weight.data)\n', (5690, 5705), False, 'from torch import log, mean, nn\n'), ((6867, 6904), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['m.weight.data'], {}), '(m.weight.data)\n', (6889, 6904), False, 'from torch import log, mean, nn\n'), ((8338, 8371), 'torch.rand', 'torch.rand', (['input_dim', 'output_dim'], {}), '(input_dim, output_dim)\n', (8348, 8371), False, 'import torch\n')]
""" Find a nearby root of the coupled radial/angular Teukolsky equations. TODO Documentation. """ from __future__ import division, print_function, absolute_import import logging import numpy as np from scipy import optimize from .angular import sep_const_closest, C_and_sep_const_closest from . import radial # TODO some documentation here, better documentation throughout class NearbyRootFinder(object): """Object to find and store results from simultaneous roots of radial and angular QNM equations, following the Leaver and Cook-Zalutskiy approach. Parameters ---------- a: float [default: 0.] Dimensionless spin of black hole, 0 <= a < 1. s: int [default: -2] Spin of field of interest m: int [default: 2] Azimuthal number of mode of interest A_closest_to: complex [default: 4.+0.j] Complex value close to desired separation constant. This is intended for tracking the l-number of a sequence starting from the analytically-known value at a=0 l_max: int [default: 20] Maximum value of l to include in the spherical-spheroidal matrix for finding separation constant and mixing coefficients. Must be sufficiently larger than l of interest that angular spectral method can converge. The number of l's needed for convergence depends on a. omega_guess: complex [default: .5-.5j] Initial guess of omega for root-finding tol: float [default: sqrt(double epsilon)] Tolerance for root-finding omega cf_tol: float [defailt: 1e-10] Tolerance for continued fraction calculation n_inv: int [default: 0] Inversion number of radial infinite continued fraction, which selects overtone number of interest Nr: int [default: 300] Truncation number of radial infinite continued fraction. Must be sufficiently large for convergence. Nr_min: int [default: 300] Floor for Nr (for dynamic control of Nr) Nr_max: int [default: 4000] Ceiling for Nr (for dynamic control of Nr) r_N: complex [default: 1.] Seed value taken for truncation of infinite continued fraction. UNUSED, REMOVE """ def __init__(self, *args, **kwargs): # Set defaults before using values in kwargs self.a = 0. self.s = -2 self.m = 2 self.A0 = 4.+0.j self.l_max = 20 self.omega_guess = .5-.5j self.tol = np.sqrt(np.finfo(float).eps) self.cf_tol = 1e-10 self.n_inv = 0 self.Nr = 300 self.Nr_min = 300 self.Nr_max = 4000 self.r_N = 1. self.set_params(**kwargs) def set_params(self, *args, **kwargs): """Set the parameters for root finding. Parameters are described in the class documentation. Finally calls :meth:`clear_results`. """ # TODO This violates DRY, do better. self.a = kwargs.get('a', self.a) self.s = kwargs.get('s', self.s) self.m = kwargs.get('m', self.m) self.A0 = kwargs.get('A_closest_to', self.A0) self.l_max = kwargs.get('l_max', self.l_max) self.omega_guess = kwargs.get('omega_guess', self.omega_guess) self.tol = kwargs.get('tol', self.tol) self.cf_tol = kwargs.get('cf_tol', self.cf_tol) self.n_inv = kwargs.get('n_inv', self.n_inv) self.Nr = kwargs.get('Nr', self.Nr) self.Nr_min = kwargs.get('Nr_min', self.Nr_min) self.Nr_max = kwargs.get('Nr_max', self.Nr_max) self.r_N = kwargs.get('r_N', self.r_N) # Optional pole factors self.poles = np.array([]) # TODO: Check that values make sense self.clear_results() def clear_results(self): """Clears the stored results from last call of :meth:`do_solve`""" self.solved = False self.opt_res = None self.omega = None self.A = None self.C = None self.cf_err = None self.n_frac = None self.poles = np.array([]) def __call__(self, x): """Internal function for usage with optimize.root, for an instance of this class to act like a function for root-finding. optimize.root only works with reals so we pack and unpack complexes into float[2] """ omega = x[0] + 1.j*x[1] # oblateness parameter c = self.a * omega # Separation constant at this a*omega A = sep_const_closest(self.A0, self.s, c, self.m, self.l_max) # We are trying to find a root of this function: # inv_err = radial.leaver_cf_trunc_inversion(omega, self.a, # self.s, self.m, A, # self.n_inv, # self.Nr, self.r_N) # TODO! # Determine the value to use for cf_tol based on # the Jacobian, cf_tol = |d cf(\omega)/d\omega| tol. inv_err, self.cf_err, self.n_frac = radial.leaver_cf_inv_lentz(omega, self.a, self.s, self.m, A, self.n_inv, self.cf_tol, self.Nr_min, self.Nr_max) # logging.info("Lentz terminated with cf_err={}, n_frac={}".format(self.cf_err, self.n_frac)) # Insert optional poles pole_factors = np.prod(omega - self.poles) supp_err = inv_err / pole_factors return [np.real(supp_err), np.imag(supp_err)] def do_solve(self): """Try to find a root of the continued fraction equation, using the parameters that have been set in :meth:`set_params`.""" # For the default (hybr) method, tol sets 'xtol', the # tolerance on omega. self.opt_res = optimize.root(self, [np.real(self.omega_guess), np.imag(self.omega_guess)], method = 'hybr', tol = self.tol) if (not self.opt_res.success): tmp_opt_res = self.opt_res self.clear_results() self.opt_res = tmp_opt_res return None self.solved = True self.omega = self.opt_res.x[0] + 1.j*self.opt_res.x[1] c = self.a * self.omega # As far as I can tell, scipy.linalg.eig already normalizes # the eigenvector to unit norm, and the coefficient with the # largest norm is real self.A, self.C = C_and_sep_const_closest(self.A0, self.s, c, self.m, self.l_max) return self.omega def get_cf_err(self): """Return the continued fraction error and the number of iterations in the last evaluation of the continued fraction. Returns ------- cf_err: float n_frac: int """ return self.cf_err, self.n_frac def set_poles(self, poles=[]): """ Set poles to multiply error function. Parameters ---------- poles: array_like as complex numbers [default: []] """ self.poles = np.array(poles).astype(complex)
[ "numpy.finfo", "numpy.imag", "numpy.array", "numpy.real", "numpy.prod" ]
[((3914, 3926), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3922, 3926), True, 'import numpy as np\n'), ((4322, 4334), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4330, 4334), True, 'import numpy as np\n'), ((5821, 5848), 'numpy.prod', 'np.prod', (['(omega - self.poles)'], {}), '(omega - self.poles)\n', (5828, 5848), True, 'import numpy as np\n'), ((5908, 5925), 'numpy.real', 'np.real', (['supp_err'], {}), '(supp_err)\n', (5915, 5925), True, 'import numpy as np\n'), ((5927, 5944), 'numpy.imag', 'np.imag', (['supp_err'], {}), '(supp_err)\n', (5934, 5944), True, 'import numpy as np\n'), ((2511, 2526), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (2519, 2526), True, 'import numpy as np\n'), ((6285, 6310), 'numpy.real', 'np.real', (['self.omega_guess'], {}), '(self.omega_guess)\n', (6292, 6310), True, 'import numpy as np\n'), ((6312, 6337), 'numpy.imag', 'np.imag', (['self.omega_guess'], {}), '(self.omega_guess)\n', (6319, 6337), True, 'import numpy as np\n'), ((7600, 7615), 'numpy.array', 'np.array', (['poles'], {}), '(poles)\n', (7608, 7615), True, 'import numpy as np\n')]
import glob, os, pickle, datetime, time, re, pprint import matplotlib.pyplot as plt import numpy as np from src import plotter, graphs from src.mltoolbox.metrics import METRICS from src.utils import * from shutil import copyfile, rmtree def main(): # SETUP BEGIN """ x01 : reg only uniform edges avg on 8 tests x02 : reg cycles avg on 8 tests x03 : reg all with avg on 16 tests x04 : svm """ test_suite_root = './test_log/paper/' test_suite_code = 'conv_real_reg' test_suite_pattern = 'test_*n_exp*' log_pattern = re.compile(r'.*') # re.compile(r'.*mse_log\.gz$') excluded_graphs = [] # SETUP END # list paths of all folders of tests that satisfy the setting pattern test_folder_paths = [s.replace('\\', '/') for s in list(glob.iglob( os.path.normpath("{}{}/{}".format( test_suite_root, test_suite_code, test_suite_pattern ).replace('\\', '/')))) ] # if paths list if empty abort with error if len(test_folder_paths) == 0: raise Exception("Empty test folder paths list") # setup file and metrics (are initially taken from the first simulation in the path list) setup = None setup_metrics = set([]) setup_real_metrics = set([]) """ logs = { $TEST_FOLDER_PATH : { $TEST_LOG_FILENAME : $LOG_ARRAY } } """ logs = {} for test_folder_path in test_folder_paths[:]: if re.match(r'.*.AVG$', test_folder_path): # if the folder is result of a previous merge then skip it test_folder_paths.remove(test_folder_path) continue try: # open current test setup file with open("{}/.setup.pkl".format(test_folder_path), 'rb') as setup_file: _setup = pickle.load(setup_file) except: print("No setup file to open") raise if setup is None: # is setup variable is not set then set setup and setup metrics equal to those # of the current opened test folder setup = _setup setup_metrics = set(setup['metrics']) setup_real_metrics = set(setup['real_metrics']) else: # is setup is already set then intersect metrics and real metrics to keep only # those shared among all test folders setup_metrics &= set(setup['metrics']) setup_real_metrics &= set(setup['real_metrics']) logs[test_folder_path] = {} # list all logs inside current test folder escaping problematic characters test_logs_paths = [s.replace('\\', '/') for s in list( glob.iglob( os.path.normpath(os.path.join(glob.escape(test_folder_path), '*.gz')).replace('\\', '/')) ) ] print("Extract logs from {}".format(test_folder_path)) # loop through all logs inside current test folder for test_log_path in test_logs_paths: # take only the name of the log file test_log_filename = test_log_path.split('/')[-1] # split graph's name and log name test_log_graph, test_log_name = test_log_filename.split('_', 1) if "avg_iter_time_log" in test_log_name or "max_iter_time_log" in test_log_name: # avg_iter_time and max_iter_time need to be treated in a particular way since made # by tuples and not by single float values logs[test_folder_path][test_log_filename] = [ tuple([float(s.split(",")[0]), float(s.split(",")[1])]) for s in np.loadtxt(test_log_path, str) ] elif log_pattern.match(test_log_filename) or test_log_name in ['iter_time.gz', 'iter_time.txt.gz']: # load log into dict normally without preprocessing values logs[test_folder_path][test_log_filename] = np.loadtxt(test_log_path) # get the list of all logs' names of the first test folder without duplicates avg_log_names = set(logs[test_folder_paths[0]].keys()) for i in range(1, len(test_folder_paths)): # intersect with all other folders' logs' names avg_log_names &= set(logs[test_folder_paths[i]].keys()) """ avg_logs = { $LOG_X_NAME : [$LOG_X_TEST#1, $LOG_X_TEST#2, ...], ... $LOG_Y_NAME : [$LOG_Y_TEST#1, $LOG_Y_TEST#2, ...], ... } """ avg_logs = {} min_log_lengths = {} # $LOG_NAME : $MIN_LOG_LENGTH new_setup_graphs_names = set([]) for test_folder_path in logs: for log_name in list(avg_log_names): new_setup_graphs_names.add(log_name.split('_', maxsplit=1)[0]) if log_name not in avg_logs: avg_logs[log_name] = [] min_log_lengths[log_name] = math.inf avg_logs[log_name].append(logs[test_folder_path][log_name]) min_log_lengths[log_name] = min(min_log_lengths[log_name], len(logs[test_folder_path][log_name])) for log_name in list(avg_log_names): print("Create merged {}".format(log_name)) avg_logs[log_name] = [l[0:min_log_lengths[log_name]] for l in avg_logs[log_name]] avg_logs[log_name] = np.array(np.sum(avg_logs[log_name], axis=0)) / len(avg_logs[log_name]) new_ordered_setup_graphs_names = [] for graph in setup['graphs']: if graph in list(new_setup_graphs_names): new_ordered_setup_graphs_names.append(graph) setup['graphs'] = graphs.generate_n_nodes_graphs_list(setup['n'], new_ordered_setup_graphs_names) setup['metrics'] = list(setup_metrics) setup['real_metrics'] = list(setup_real_metrics) avg_output_dir = os.path.normpath(os.path.join( test_folder_paths[0].rsplit('/', maxsplit=1)[0], test_folder_paths[0].rsplit('/', maxsplit=1)[1].split('conflict')[0] + '.AVG' )) if os.path.exists(avg_output_dir): if input( "Folder {} already exists, continuing will cause the loss of all data already inside it, continue " "anyway? (type 'y' or 'yes' to continue or any other key to abort)".format(avg_output_dir)) not in [ 'y', 'yes']: raise Exception("Script aborted") rmtree(avg_output_dir) os.makedirs(avg_output_dir) for log_name in avg_logs: dest = os.path.normpath(os.path.join( avg_output_dir, log_name )) np.savetxt(dest, avg_logs[log_name], delimiter=',') print('Saved {}'.format(log_name, dest)) with open(os.path.join(avg_output_dir, '.setup.pkl'), "wb") as f: pickle.dump(setup, f, pickle.HIGHEST_PROTOCOL) print('Setup dumped into {}'.format(os.path.join(avg_output_dir, '.setup.pkl'))) # Fill descriptor with setup dictionary descriptor = """>>> Test Descriptor File AVERAGE TEST OUTPUT FILE Date: {} Tests merged: {}\n """.format(str(datetime.datetime.fromtimestamp(time.time())), pprint.PrettyPrinter(indent=4).pformat(test_folder_paths)) for k, v in setup.items(): descriptor += "{} = {}\n".format(k, v) descriptor += "\n" with open(os.path.join(avg_output_dir, '.descriptor.txt'), "w") as f: f.write(descriptor) print('Descriptor file created at {}'.format(os.path.join(avg_output_dir, '.descriptor.txt'))) if __name__ == '__main__': main()
[ "pickle.dump", "numpy.sum", "os.makedirs", "numpy.savetxt", "os.path.exists", "re.match", "time.time", "src.graphs.generate_n_nodes_graphs_list", "pprint.PrettyPrinter", "pickle.load", "glob.escape", "numpy.loadtxt", "shutil.rmtree", "os.path.join", "re.compile" ]
[((562, 578), 're.compile', 're.compile', (['""".*"""'], {}), "('.*')\n", (572, 578), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((5525, 5604), 'src.graphs.generate_n_nodes_graphs_list', 'graphs.generate_n_nodes_graphs_list', (["setup['n']", 'new_ordered_setup_graphs_names'], {}), "(setup['n'], new_ordered_setup_graphs_names)\n", (5560, 5604), False, 'from src import plotter, graphs\n'), ((5912, 5942), 'os.path.exists', 'os.path.exists', (['avg_output_dir'], {}), '(avg_output_dir)\n', (5926, 5942), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((6301, 6328), 'os.makedirs', 'os.makedirs', (['avg_output_dir'], {}), '(avg_output_dir)\n', (6312, 6328), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((1479, 1516), 're.match', 're.match', (['""".*.AVG$"""', 'test_folder_path'], {}), "('.*.AVG$', test_folder_path)\n", (1487, 1516), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((6274, 6296), 'shutil.rmtree', 'rmtree', (['avg_output_dir'], {}), '(avg_output_dir)\n', (6280, 6296), False, 'from shutil import copyfile, rmtree\n'), ((6474, 6525), 'numpy.savetxt', 'np.savetxt', (['dest', 'avg_logs[log_name]'], {'delimiter': '""","""'}), "(dest, avg_logs[log_name], delimiter=',')\n", (6484, 6525), True, 'import numpy as np\n'), ((6654, 6700), 'pickle.dump', 'pickle.dump', (['setup', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(setup, f, pickle.HIGHEST_PROTOCOL)\n', (6665, 6700), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((6392, 6430), 'os.path.join', 'os.path.join', (['avg_output_dir', 'log_name'], {}), '(avg_output_dir, log_name)\n', (6404, 6430), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((6590, 6632), 'os.path.join', 'os.path.join', (['avg_output_dir', '""".setup.pkl"""'], {}), "(avg_output_dir, '.setup.pkl')\n", (6602, 6632), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((7195, 7242), 'os.path.join', 'os.path.join', (['avg_output_dir', '""".descriptor.txt"""'], {}), "(avg_output_dir, '.descriptor.txt')\n", (7207, 7242), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((1832, 1855), 'pickle.load', 'pickle.load', (['setup_file'], {}), '(setup_file)\n', (1843, 1855), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((5258, 5292), 'numpy.sum', 'np.sum', (['avg_logs[log_name]'], {'axis': '(0)'}), '(avg_logs[log_name], axis=0)\n', (5264, 5292), True, 'import numpy as np\n'), ((6745, 6787), 'os.path.join', 'os.path.join', (['avg_output_dir', '""".setup.pkl"""'], {}), "(avg_output_dir, '.setup.pkl')\n", (6757, 6787), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((6996, 7007), 'time.time', 'time.time', ([], {}), '()\n', (7005, 7007), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((7019, 7049), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (7039, 7049), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((7336, 7383), 'os.path.join', 'os.path.join', (['avg_output_dir', '""".descriptor.txt"""'], {}), "(avg_output_dir, '.descriptor.txt')\n", (7348, 7383), False, 'import glob, os, pickle, datetime, time, re, pprint\n'), ((3940, 3965), 'numpy.loadtxt', 'np.loadtxt', (['test_log_path'], {}), '(test_log_path)\n', (3950, 3965), True, 'import numpy as np\n'), ((3644, 3674), 'numpy.loadtxt', 'np.loadtxt', (['test_log_path', 'str'], {}), '(test_log_path, str)\n', (3654, 3674), True, 'import numpy as np\n'), ((2758, 2787), 'glob.escape', 'glob.escape', (['test_folder_path'], {}), '(test_folder_path)\n', (2769, 2787), False, 'import glob, os, pickle, datetime, time, re, pprint\n')]
import numpy as np from skimage.metrics import structural_similarity, peak_signal_noise_ratio import functools # Data format: H W C __all__ = [ 'psnr', 'ssim', 'sam', 'ergas', 'mpsnr', 'mssim', 'mpsnr_max' ] def psnr(output, target, data_range=1): return peak_signal_noise_ratio(target, output, data_range=data_range) def ssim(img1, img2, **kwargs): return structural_similarity(img1, img2, channel_axis=2, **kwargs) def sam(img1, img2, eps=1e-8): """ Spectral Angle Mapper which defines the spectral similarity between two spectra """ tmp1 = np.sum(img1*img2, axis=2) + eps tmp2 = np.sqrt(np.sum(img1**2, axis=2)) + eps tmp3 = np.sqrt(np.sum(img2**2, axis=2)) + eps tmp4 = tmp1 / tmp2 / tmp3 angle = np.arccos(tmp4.clip(-1, 1)) return np.mean(np.real(angle)) def ergas(output, target, r=1): b = target.shape[-1] ergas = 0 for i in range(b): ergas += np.mean((target[:, :, i]-output[:, :, i])**2) / (np.mean(target[:, :, i])**2) ergas = 100*r*np.sqrt(ergas/b) return ergas # ---------------------------------------------------------------------------- # # BandWise Metrics # # ---------------------------------------------------------------------------- # def bandwise(func): @functools.wraps(func) def warpped(output, target, *args, **kwargs): C = output.shape[-1] total = 0 for ch in range(C): x = output[:, :, ch] y = target[:, :, ch] total += func(x, y, *args, **kwargs) return total / C return warpped @bandwise def mpsnr(output, target, data_range=1): return psnr(target, output, data_range=data_range) def mssim(img1, img2, **kwargs): return ssim(img1, img2, **kwargs) def mpsnr_max(output, target): """ Different from mpsnr, this function use max value of each channel (instead of 1 or 255) as the peak signal. """ total = 0. for k in range(target.shape[-1]): peak = np.amax(target[:, :, k])**2 mse = np.mean((output[:, :, k]-target[:, :, k])**2) total += 10*np.log10(peak / mse) return total / target.shape[-1]
[ "numpy.sum", "numpy.amax", "skimage.metrics.structural_similarity", "numpy.mean", "numpy.real", "functools.wraps", "numpy.log10", "skimage.metrics.peak_signal_noise_ratio", "numpy.sqrt" ]
[((291, 353), 'skimage.metrics.peak_signal_noise_ratio', 'peak_signal_noise_ratio', (['target', 'output'], {'data_range': 'data_range'}), '(target, output, data_range=data_range)\n', (314, 353), False, 'from skimage.metrics import structural_similarity, peak_signal_noise_ratio\n'), ((399, 458), 'skimage.metrics.structural_similarity', 'structural_similarity', (['img1', 'img2'], {'channel_axis': '(2)'}), '(img1, img2, channel_axis=2, **kwargs)\n', (420, 458), False, 'from skimage.metrics import structural_similarity, peak_signal_noise_ratio\n'), ((1354, 1375), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (1369, 1375), False, 'import functools\n'), ((603, 630), 'numpy.sum', 'np.sum', (['(img1 * img2)'], {'axis': '(2)'}), '(img1 * img2, axis=2)\n', (609, 630), True, 'import numpy as np\n'), ((824, 838), 'numpy.real', 'np.real', (['angle'], {}), '(angle)\n', (831, 838), True, 'import numpy as np\n'), ((1049, 1067), 'numpy.sqrt', 'np.sqrt', (['(ergas / b)'], {}), '(ergas / b)\n', (1056, 1067), True, 'import numpy as np\n'), ((2117, 2166), 'numpy.mean', 'np.mean', (['((output[:, :, k] - target[:, :, k]) ** 2)'], {}), '((output[:, :, k] - target[:, :, k]) ** 2)\n', (2124, 2166), True, 'import numpy as np\n'), ((654, 679), 'numpy.sum', 'np.sum', (['(img1 ** 2)'], {'axis': '(2)'}), '(img1 ** 2, axis=2)\n', (660, 679), True, 'import numpy as np\n'), ((704, 729), 'numpy.sum', 'np.sum', (['(img2 ** 2)'], {'axis': '(2)'}), '(img2 ** 2, axis=2)\n', (710, 729), True, 'import numpy as np\n'), ((953, 1002), 'numpy.mean', 'np.mean', (['((target[:, :, i] - output[:, :, i]) ** 2)'], {}), '((target[:, :, i] - output[:, :, i]) ** 2)\n', (960, 1002), True, 'import numpy as np\n'), ((2075, 2099), 'numpy.amax', 'np.amax', (['target[:, :, k]'], {}), '(target[:, :, k])\n', (2082, 2099), True, 'import numpy as np\n'), ((2183, 2203), 'numpy.log10', 'np.log10', (['(peak / mse)'], {}), '(peak / mse)\n', (2191, 2203), True, 'import numpy as np\n'), ((1002, 1026), 'numpy.mean', 'np.mean', (['target[:, :, i]'], {}), '(target[:, :, i])\n', (1009, 1026), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on %(date)s @author: <NAME> """ import pandas as pd import numpy as np from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.metrics import mean_squared_error # Power outage class def f(row): """function that categories days with more than 8 outages as extreme, 3-8 outages as bad, and 0-2 as normal""" if row['Total_outages'] > 8: val = 2 elif row['Total_outages'] > 2: val = 1 else: val = 0 return val # Load data function: load data for neural network training # Input: None # Output: x_train, y_train, x_test, y_test def load_data(): data = pd.read_csv('../../Data/WeatherOutagesAllJerry.csv') data = data.dropna(how = 'all') data['category'] = data.apply(f, axis=1) data.head() # Seperate training and testing dataset train,test=train_test_split(data,test_size=0.1,random_state=567) x_train = train[['Day_length_hr','Avg_Temp_F','Avg_humidity_percent','Avg_windspeed_mph','Max_windspeed_mph', 'Precipitation_in','Event_thunderstorm']] y_train = train['category'] x_test = test[['Day_length_hr','Avg_Temp_F','Avg_humidity_percent','Avg_windspeed_mph','Max_windspeed_mph', 'Precipitation_in','Event_thunderstorm']] y_test = test['category'] # data normalization x_train = preprocessing.normalize(x_train) # training dataset x_test = preprocessing.normalize(x_test) #testing dataset return x_train, y_train, x_test, y_test # Oversample algoritm # This function oversample from under-reprented class # Input: X-feature, y-response, R1-oversample ratio for bad case, R2-oversample ratio for extreme case # Output: X_resam, y_resam def balance_sample(X, y, R1, R2): from imblearn.over_sampling import RandomOverSampler # Apply the random over-sampling ros = RandomOverSampler(ratio=R1,random_state=6) x_res, y_res = ros.fit_sample(X[y!=2], y[y!=2]) ros2 = RandomOverSampler(ratio=R2,random_state=6) x_res2, y_res2 = ros2.fit_sample(X[y!=1], y[y!=1]) X_resam = np.concatenate((x_res,x_res2[y_res2==2]), axis=0) y_resam = np.concatenate((y_res, y_res2[y_res2==2]),axis=0) return X_resam, y_resam def neural_network_clf(x_train, y_train, x_test, y_test): clf = MLPClassifier(max_iter=1000,activation='identity', solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5, 3), random_state=1) clf.fit(x_train, y_train) y_train_pred = clf.predict(x_train) y_test_pred = clf.predict(x_test) print("Train error for normalized data",mean_squared_error(y_train,y_train_pred)) print("Test error for normalized data",mean_squared_error(y_test,y_test_pred))
[ "pandas.read_csv", "sklearn.model_selection.train_test_split", "imblearn.over_sampling.RandomOverSampler", "sklearn.preprocessing.normalize", "sklearn.neural_network.MLPClassifier", "sklearn.metrics.mean_squared_error", "numpy.concatenate" ]
[((787, 839), 'pandas.read_csv', 'pd.read_csv', (['"""../../Data/WeatherOutagesAllJerry.csv"""'], {}), "('../../Data/WeatherOutagesAllJerry.csv')\n", (798, 839), True, 'import pandas as pd\n'), ((997, 1052), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data'], {'test_size': '(0.1)', 'random_state': '(567)'}), '(data, test_size=0.1, random_state=567)\n', (1013, 1052), False, 'from sklearn.model_selection import train_test_split\n'), ((1498, 1530), 'sklearn.preprocessing.normalize', 'preprocessing.normalize', (['x_train'], {}), '(x_train)\n', (1521, 1530), False, 'from sklearn import preprocessing\n'), ((1563, 1594), 'sklearn.preprocessing.normalize', 'preprocessing.normalize', (['x_test'], {}), '(x_test)\n', (1586, 1594), False, 'from sklearn import preprocessing\n'), ((2002, 2045), 'imblearn.over_sampling.RandomOverSampler', 'RandomOverSampler', ([], {'ratio': 'R1', 'random_state': '(6)'}), '(ratio=R1, random_state=6)\n', (2019, 2045), False, 'from imblearn.over_sampling import RandomOverSampler\n'), ((2108, 2151), 'imblearn.over_sampling.RandomOverSampler', 'RandomOverSampler', ([], {'ratio': 'R2', 'random_state': '(6)'}), '(ratio=R2, random_state=6)\n', (2125, 2151), False, 'from imblearn.over_sampling import RandomOverSampler\n'), ((2221, 2273), 'numpy.concatenate', 'np.concatenate', (['(x_res, x_res2[y_res2 == 2])'], {'axis': '(0)'}), '((x_res, x_res2[y_res2 == 2]), axis=0)\n', (2235, 2273), True, 'import numpy as np\n'), ((2285, 2337), 'numpy.concatenate', 'np.concatenate', (['(y_res, y_res2[y_res2 == 2])'], {'axis': '(0)'}), '((y_res, y_res2[y_res2 == 2]), axis=0)\n', (2299, 2337), True, 'import numpy as np\n'), ((2435, 2563), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'max_iter': '(1000)', 'activation': '"""identity"""', 'solver': '"""lbfgs"""', 'alpha': '(1e-05)', 'hidden_layer_sizes': '(5, 3)', 'random_state': '(1)'}), "(max_iter=1000, activation='identity', solver='lbfgs', alpha=\n 1e-05, hidden_layer_sizes=(5, 3), random_state=1)\n", (2448, 2563), False, 'from sklearn.neural_network import MLPClassifier\n'), ((2735, 2776), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_train', 'y_train_pred'], {}), '(y_train, y_train_pred)\n', (2753, 2776), False, 'from sklearn.metrics import mean_squared_error\n'), ((2820, 2859), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_test', 'y_test_pred'], {}), '(y_test, y_test_pred)\n', (2838, 2859), False, 'from sklearn.metrics import mean_squared_error\n')]
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # 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. # The author of this file is: https://github.com/mg2015started import numpy as np def get_split_batch(batch): """memory.sample() returns a batch of experiences, but we want an array for each element in the memory (s, a, r, s', done)""" states_mb = np.array([each[0][0] for each in batch]) # print(states_mb.shape) actions_mb = np.array([each[0][1] for each in batch]) # print(actions_mb.shape) rewards_mb = np.array([each[0][2] for each in batch]) # print(rewards_mb.shape) next_states_mb = np.array([each[0][3] for each in batch]) # print(next_states_mb.shape) dones_mb = np.array([each[0][4] for each in batch]) return states_mb, actions_mb, rewards_mb, next_states_mb, dones_mb def OU(action, mu=0, theta=0.15, sigma=0.3): # noise = np.ones(action_dim) * mu noise = theta * (mu - action) + sigma * np.random.randn(1) # noise = noise + d_noise return noise def calculate_angle(ego_location, goal_location, ego_direction): # calculate vector direction goal_location = np.array(goal_location) ego_location = np.array(ego_location) goal_vector = goal_location - ego_location L_g_vector = np.sqrt(goal_vector.dot(goal_vector)) ego_vector = np.array( [np.cos(ego_direction * np.pi / 180), np.sin(ego_direction * np.pi / 180)] ) L_e_vector = np.sqrt(ego_vector.dot(ego_vector)) cos_angle = goal_vector.dot(ego_vector) / (L_g_vector * L_e_vector) angle = (np.arccos(cos_angle)) * 180 / np.pi if np.cross(goal_vector, ego_vector) > 0: angle = -angle return angle def calculate_distance(location_a, location_b): """ calculate distance between a and b""" return np.linalg.norm(location_a - location_b)
[ "numpy.random.randn", "numpy.cross", "numpy.sin", "numpy.linalg.norm", "numpy.array", "numpy.cos", "numpy.arccos" ]
[((1393, 1433), 'numpy.array', 'np.array', (['[each[0][0] for each in batch]'], {}), '([each[0][0] for each in batch])\n', (1401, 1433), True, 'import numpy as np\n'), ((1480, 1520), 'numpy.array', 'np.array', (['[each[0][1] for each in batch]'], {}), '([each[0][1] for each in batch])\n', (1488, 1520), True, 'import numpy as np\n'), ((1568, 1608), 'numpy.array', 'np.array', (['[each[0][2] for each in batch]'], {}), '([each[0][2] for each in batch])\n', (1576, 1608), True, 'import numpy as np\n'), ((1660, 1700), 'numpy.array', 'np.array', (['[each[0][3] for each in batch]'], {}), '([each[0][3] for each in batch])\n', (1668, 1700), True, 'import numpy as np\n'), ((1750, 1790), 'numpy.array', 'np.array', (['[each[0][4] for each in batch]'], {}), '([each[0][4] for each in batch])\n', (1758, 1790), True, 'import numpy as np\n'), ((2179, 2202), 'numpy.array', 'np.array', (['goal_location'], {}), '(goal_location)\n', (2187, 2202), True, 'import numpy as np\n'), ((2222, 2244), 'numpy.array', 'np.array', (['ego_location'], {}), '(ego_location)\n', (2230, 2244), True, 'import numpy as np\n'), ((2830, 2869), 'numpy.linalg.norm', 'np.linalg.norm', (['(location_a - location_b)'], {}), '(location_a - location_b)\n', (2844, 2869), True, 'import numpy as np\n'), ((2644, 2677), 'numpy.cross', 'np.cross', (['goal_vector', 'ego_vector'], {}), '(goal_vector, ego_vector)\n', (2652, 2677), True, 'import numpy as np\n'), ((1993, 2011), 'numpy.random.randn', 'np.random.randn', (['(1)'], {}), '(1)\n', (2008, 2011), True, 'import numpy as np\n'), ((2383, 2418), 'numpy.cos', 'np.cos', (['(ego_direction * np.pi / 180)'], {}), '(ego_direction * np.pi / 180)\n', (2389, 2418), True, 'import numpy as np\n'), ((2420, 2455), 'numpy.sin', 'np.sin', (['(ego_direction * np.pi / 180)'], {}), '(ego_direction * np.pi / 180)\n', (2426, 2455), True, 'import numpy as np\n'), ((2601, 2621), 'numpy.arccos', 'np.arccos', (['cos_angle'], {}), '(cos_angle)\n', (2610, 2621), True, 'import numpy as np\n')]
# coding=utf-8 # Copyright 2018 The DisentanglementLib Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """translation dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import cv2 from disentanglement_lib.data.ground_truth import ground_truth_data from disentanglement_lib.data.ground_truth import util import numpy as np import gin from six.moves import range def to_honeycomb(x): x1 = np.zeros(x.shape) x1[:, 0] = x[:, 0] + (x[:, 1] % 2) * 0.5 x1[:, 1] = x[:, 1] / 2 * np.sqrt(3) return x1 @gin.configurable("translation") class Translation(ground_truth_data.GroundTruthData): """Translation dataset. """ def __init__(self, pos_type: int, radius=10): # By default, all factors (including shape) are considered ground truth # factors. factors = np.zeros((22 * 22, 2)) factors[:, 0] = np.arange(22 * 22) // 22 factors[:, 1] = np.arange(22 * 22) % 22 factors = factors if pos_type == 0: pos = factors * 2 # cartesian elif pos_type == 1: pos = to_honeycomb(factors) * 2 elif pos_type == 2: r = 1 + factors[:, 0] / 22 * 20 theta = factors[:, 1] / 22 * 2 * np.pi pos = np.zeros((22 * 22, 2)) pos[:, 1] = r * np.cos(theta) + 32 pos[:, 0] = r * np.sin(theta) + 32 else: raise NotImplementedError() self.data_shape = [64, 64, 1] self.factor_sizes = [22, 22] self.pos = pos self.latent_factor_indices = np.zeros(self.factor_sizes, dtype=np.int) for i in range(self.factor_sizes[0]): self.latent_factor_indices[i] = self.factor_sizes[0] * i + np.arange(self.factor_sizes[1]) self.data = np.zeros([len(self)] + self.data_shape, dtype=np.float32) index = 0 for i in range(self.factor_sizes[0]): for j in range(self.factor_sizes[1]): img = np.zeros(self.data_shape) cv2.circle(img, (10, 10), radius, (1.0,), -1) M = np.float32([[1, 0, pos[index, 0]], [0, 1, pos[index, 1]]]) self.data[index, :, :, 0] = cv2.warpAffine(img, M, (64, 64)) index += 1 @property def num_factors(self): return len(self.factor_sizes) @property def factors_num_values(self): return self.factor_sizes @property def observation_shape(self): return self.data_shape def sample_factors(self, num, random_state): """Sample a batch of factors Y.""" factors = [random_state.randint(i, size=num) for i in self.factors_num_values] return np.stack(factors, axis=1) def sample_observations_from_factors(self, factors, random_state): indices = self.latent_factor_indices[factors[:, 0], factors[:, 1]] return self.data[indices] def _sample_factor(self, i, num, random_state): return random_state.randint(self.factor_sizes[i], size=num) def set_img(original, i, j, img): h, w, _ = img.shape if i + h > 64: original[i:i + h, j:j + w] = img[:min(-1, 64 - i - h)] else: original[i:i + h, j:j + w] = img return original
[ "numpy.stack", "cv2.circle", "six.moves.range", "numpy.float32", "numpy.zeros", "cv2.warpAffine", "numpy.sin", "numpy.arange", "numpy.cos", "gin.configurable", "numpy.sqrt" ]
[((1125, 1156), 'gin.configurable', 'gin.configurable', (['"""translation"""'], {}), "('translation')\n", (1141, 1156), False, 'import gin\n'), ((1005, 1022), 'numpy.zeros', 'np.zeros', (['x.shape'], {}), '(x.shape)\n', (1013, 1022), True, 'import numpy as np\n'), ((1097, 1107), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (1104, 1107), True, 'import numpy as np\n'), ((1415, 1437), 'numpy.zeros', 'np.zeros', (['(22 * 22, 2)'], {}), '((22 * 22, 2))\n', (1423, 1437), True, 'import numpy as np\n'), ((2150, 2191), 'numpy.zeros', 'np.zeros', (['self.factor_sizes'], {'dtype': 'np.int'}), '(self.factor_sizes, dtype=np.int)\n', (2158, 2191), True, 'import numpy as np\n'), ((2209, 2236), 'six.moves.range', 'range', (['self.factor_sizes[0]'], {}), '(self.factor_sizes[0])\n', (2214, 2236), False, 'from six.moves import range\n'), ((2457, 2484), 'six.moves.range', 'range', (['self.factor_sizes[0]'], {}), '(self.factor_sizes[0])\n', (2462, 2484), False, 'from six.moves import range\n'), ((3266, 3291), 'numpy.stack', 'np.stack', (['factors'], {'axis': '(1)'}), '(factors, axis=1)\n', (3274, 3291), True, 'import numpy as np\n'), ((1462, 1480), 'numpy.arange', 'np.arange', (['(22 * 22)'], {}), '(22 * 22)\n', (1471, 1480), True, 'import numpy as np\n'), ((1511, 1529), 'numpy.arange', 'np.arange', (['(22 * 22)'], {}), '(22 * 22)\n', (1520, 1529), True, 'import numpy as np\n'), ((2507, 2534), 'six.moves.range', 'range', (['self.factor_sizes[1]'], {}), '(self.factor_sizes[1])\n', (2512, 2534), False, 'from six.moves import range\n'), ((2309, 2340), 'numpy.arange', 'np.arange', (['self.factor_sizes[1]'], {}), '(self.factor_sizes[1])\n', (2318, 2340), True, 'import numpy as np\n'), ((2558, 2583), 'numpy.zeros', 'np.zeros', (['self.data_shape'], {}), '(self.data_shape)\n', (2566, 2583), True, 'import numpy as np\n'), ((2600, 2645), 'cv2.circle', 'cv2.circle', (['img', '(10, 10)', 'radius', '(1.0,)', '(-1)'], {}), '(img, (10, 10), radius, (1.0,), -1)\n', (2610, 2645), False, 'import cv2\n'), ((2666, 2724), 'numpy.float32', 'np.float32', (['[[1, 0, pos[index, 0]], [0, 1, pos[index, 1]]]'], {}), '([[1, 0, pos[index, 0]], [0, 1, pos[index, 1]]])\n', (2676, 2724), True, 'import numpy as np\n'), ((2769, 2801), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'M', '(64, 64)'], {}), '(img, M, (64, 64))\n', (2783, 2801), False, 'import cv2\n'), ((1843, 1865), 'numpy.zeros', 'np.zeros', (['(22 * 22, 2)'], {}), '((22 * 22, 2))\n', (1851, 1865), True, 'import numpy as np\n'), ((1894, 1907), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (1900, 1907), True, 'import numpy as np\n'), ((1941, 1954), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1947, 1954), True, 'import numpy as np\n')]
import PyQt5 import os import imutils import cv2 import numpy as np from PIL import Image as im from PyQt5 import QtWidgets, uic, QtGui from PyQt5.QtGui import QGuiApplication import sys #Image augmentation GUI App def contour_crop_no_resize(image,dim): ''' Contour and crop the image (generally used in brain mri images and object detection) :param image: cv2 object ''' resized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA) return resized def contour_crop_resize(image,dim): ''' Contour and crop the image (generally used in brain mri images and object detection) :param image: cv2 object ''' grayscale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) grayscale=cv2.GaussianBlur(grayscale,(5,5),0) threshold_image=cv2.threshold(grayscale,45,255,cv2.THRESH_BINARY)[1] threshold_image=cv2.erode(threshold_image,None,iterations=2) threshold_image=cv2.dilate(threshold_image,None,iterations=2) contour=cv2.findContours(threshold_image.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) contour=imutils.grab_contours(contour) c=max(contour,key=cv2.contourArea) extreme_pnts_left=tuple(c[c[:,:,0].argmin()][0]) extreme_pnts_right=tuple(c[c[:,:,0].argmax()][0]) extreme_pnts_top=tuple(c[c[:,:,1].argmin()][0]) extreme_pnts_bot=tuple(c[c[:,:,1].argmax()][0]) new_image=image[extreme_pnts_top[1]:extreme_pnts_bot[1],extreme_pnts_left[0]:extreme_pnts_right[0]] resized = cv2.resize(new_image, dim, interpolation = cv2.INTER_AREA) return resized def brightness_increase(image,brightness): ''' increase the brightness of the image :param image: cv2 object :param brightness: brightness increasing level ''' bright=np.ones(image.shape,dtype="uint8")*brightness brightincreased=cv2.add(image,bright) return brightincreased def decrease_brightness(image,brightness): ''' decrease the brightness of the image :param image: cv2 object :param brightness: brightness decreasing level ''' bright=np.ones(image.shape,dtype="uint8")*50 brightdecrease=cv2.subtract(image,bright) return brightdecrease def rotate(image,angle=90, scale=1.0): ''' Rotate the image :param image: cv2 object :param image: image to be processed :param angle: Rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner). :param scale: Isotropic scale factor. ''' w = image.shape[1] h = image.shape[0] #rotate matrix M = cv2.getRotationMatrix2D((w/2,h/2), angle, scale) #rotate image = cv2.warpAffine(image,M,(w,h)) return image def flip(image,axis): ''' Flip the image :param image: cv2 object :param axis: axis to flip ''' flip=cv2.flip(image,axis) return flip def sharpen(image): ''' Sharpen the image :param image: cv2 object ''' sharpening=np.array([ [-1,-1,-1], [-1,10,-1], [-1,-1,-1] ]) sharpened=cv2.filter2D(image,-1,sharpening) return sharpened def shear(image,axis): ''' Shear the image :param image: cv2 object :param axis: axis which image will be sheared ''' rows, cols, dim = image.shape if axis==0: M = np.float32([[1, 0.5, 0], [0, 1 , 0], [0, 0 , 1]]) elif axis==1: M = np.float32([[1, 0, 0], [0.5, 1, 0], [0, 0, 1]]) sheared_img = cv2.warpPerspective(image,M,(int(cols*1.5),int(rows*1.5))) return sheared_img class Ui(QtWidgets.QMainWindow): def __init__(self): super(Ui, self).__init__() uic.loadUi('augmentation.ui', self) self.show() self.setWindowTitle("Image Augmentor") mypixmap=QtGui.QPixmap("2582365.ico") my_icon=QtGui.QIcon(mypixmap) self.setWindowIcon(my_icon) self.lineEdit=self.findChild(QtWidgets.QLineEdit,'lineEdit') self.checkBox = self.findChild(QtWidgets.QCheckBox,'checkBox_1') self.checkBox_2=self.findChild(QtWidgets.QCheckBox,'checkBox_2') self.checkBox_3=self.findChild(QtWidgets.QCheckBox,'checkBox_3') self.checkBox_4=self.findChild(QtWidgets.QCheckBox,'checkBox_4') self.checkBox_5=self.findChild(QtWidgets.QCheckBox,'checkBox_5') self.checkBox_6=self.findChild(QtWidgets.QCheckBox,'checkBox_6') self.checkBox_7=self.findChild(QtWidgets.QCheckBox,'checkBox_7') self.button=self.findChild(QtWidgets.QPushButton,'pushButton') self.button2=self.findChild(QtWidgets.QPushButton,'pushButton_2') self.button3=self.findChild(QtWidgets.QPushButton,'pushButton_3') self.button2.clicked.connect(self.clear) self.button3.clicked.connect(self.clearline) self.progress=self.findChild(QtWidgets.QProgressBar,'progressBar') self.spin1=self.findChild(QtWidgets.QSpinBox,'spinBox') self.spin2=self.findChild(QtWidgets.QSpinBox,'spinBox_2') self.button.clicked.connect(self.submit) def clearline(self): self.lineEdit.clear() def clear(self): if self.button2.text()=="Clear Choices": self.button2.setText("Toggle") self.checkBox.setChecked(False) self.checkBox_2.setChecked(False) self.checkBox_3.setChecked(False) self.checkBox_4.setChecked(False) self.checkBox_5.setChecked(False) self.checkBox_6.setChecked(False) self.checkBox_7.setChecked(False) elif self.button2.text()=="Toggle": self.button2.setText("Clear Choices") self.checkBox.setChecked(True) self.checkBox_2.setChecked(True) self.checkBox_3.setChecked(True) self.checkBox_4.setChecked(True) self.checkBox_5.setChecked(True) self.checkBox_6.setChecked(True) self.checkBox_7.setChecked(True) def submit(self): counter=0 dim=(int(self.spin1.value()),int(self.spin2.value())) path=self.lineEdit.text() if str(path).startswith('"') and str(path).endswith('"'): path=path[1:-1] my_path=str(path).split("\\") folder_name=my_path.copy().pop() my_path_popped=my_path[:-1] # using list comprehension def listToString(s): # initialize an empty string str1 = "" # traverse in the string for ele in s: str1 += ele str1 += "/" # return string return str1 poppedString=listToString(my_path_popped) if not os.path.exists(poppedString): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Critical) msg.setText("Error") msg.setInformativeText("Change your path!") msg.setWindowTitle("Error!") msg.setDetailedText("Program could not find the path you provided.") msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel) msg.exec_() String=listToString(my_path) i=float(0.000001) aug_path=poppedString+"/augmented_"+folder_name if not os.path.exists(aug_path): os.makedirs(aug_path) for subdir, dirs, files in os.walk(String): for file in files: QGuiApplication.processEvents() filepath = subdir + "/" + file imagem=cv2.imread(filepath) resized=0 if self.checkBox.isChecked(): cv2.imwrite(aug_path+"/cntrdrszd_"+file,contour_crop_resize(imagem,dim)) resized=contour_crop_resize(imagem,dim) else: cv2.imwrite(aug_path+"/rszd_"+file,contour_crop_no_resize(imagem,dim)) resized=contour_crop_no_resize(imagem,dim) if self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/brinc_"+file,brightness_increase(resized,50)) if self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/brdec_"+file,decrease_brightness(resized,50)) if self.checkBox_4.isChecked(): cv2.imwrite(aug_path+"/rtd90_"+file,rotate(resized,90,1)) cv2.imwrite(aug_path+"/rtd45_"+file,rotate(resized,45,1)) cv2.imwrite(aug_path+"/rtd30_"+file,rotate(resized,30,1)) cv2.imwrite(aug_path+"/rtd270_"+file,rotate(resized,270,1)) cv2.imwrite(aug_path+"/rtd315_"+file,rotate(resized,315,1)) cv2.imwrite(aug_path+"/rtd330_"+file,rotate(resized,330,1)) if self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_rtd90_"+file,rotate(brightness_increase(resized,50),90,1)) cv2.imwrite(aug_path+"/binc_rtd45_"+file,rotate(brightness_increase(resized,50),45,1)) cv2.imwrite(aug_path+"/binc_rtd30_"+file,rotate(brightness_increase(resized,50),30,1)) cv2.imwrite(aug_path+"/binc_rtd270_"+file,rotate(brightness_increase(resized,50),270,1)) cv2.imwrite(aug_path+"/binc_rtd315_"+file,rotate(brightness_increase(resized,50),315,1)) cv2.imwrite(aug_path+"/binc_rtd330_"+file,rotate(brightness_increase(resized,50),330,1)) if self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_rtd90_"+file,rotate(decrease_brightness(resized,50),90,1)) cv2.imwrite(aug_path+"/bdec_rtd45_"+file,rotate(decrease_brightness(resized,50),45,1)) cv2.imwrite(aug_path+"/bdec_rtd30_"+file,rotate(decrease_brightness(resized,50),30,1)) cv2.imwrite(aug_path+"/bdec_rtd270_"+file,rotate(decrease_brightness(resized,50),270,1)) cv2.imwrite(aug_path+"/bdec_rtd315_"+file,rotate(decrease_brightness(resized,50),315,1)) cv2.imwrite(aug_path+"/bdec_rtd330_"+file,rotate(decrease_brightness(resized,50),330,1)) if self.checkBox_5.isChecked(): cv2.imwrite(aug_path+"/flipxy_"+file,flip(resized,-1)) cv2.imwrite(aug_path+"/flipx_"+file,flip(resized,0)) cv2.imwrite(aug_path+"/flipy_"+file,flip(resized,1)) if self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_flipxy_"+file,flip(brightness_increase(resized,50),-1)) cv2.imwrite(aug_path+"/binc_flipx_"+file,flip(brightness_increase(resized,50),0)) cv2.imwrite(aug_path+"/bdec_flipy_"+file,flip(brightness_increase(resized,50),1)) if self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_flipxy_"+file,flip(decrease_brightness(resized,50),-1)) cv2.imwrite(aug_path+"/bdec_flipx_"+file,flip(decrease_brightness(resized,50),0)) cv2.imwrite(aug_path+"/bdec_flipy_"+file,flip(decrease_brightness(resized,50),1)) if self.checkBox_4.isChecked(): cv2.imwrite(aug_path+"/rtd90_flipxy_"+file,flip(rotate(resized,90,1),-1)) cv2.imwrite(aug_path+"/rtd45_flipxy_"+file,flip(rotate(resized,45,1),-1)) cv2.imwrite(aug_path+"/rtd30_flipxy_"+file,flip(rotate(resized,30,1),-1)) cv2.imwrite(aug_path+"/rtd270_flipxy_"+file,flip(rotate(resized,270,1),-1)) cv2.imwrite(aug_path+"/rtd315_flipxy_"+file,flip(rotate(resized,315,1),-1)) cv2.imwrite(aug_path+"/rtd330_flipxy_"+file,flip(rotate(resized,330,1),-1)) cv2.imwrite(aug_path+"/rtd90_flipx_"+file,flip(rotate(resized,90,1),0)) cv2.imwrite(aug_path+"/rtd45_flipx_"+file,flip(rotate(resized,45,1),0)) cv2.imwrite(aug_path+"/rtd30_flipx_"+file,flip(rotate(resized,30,1),0)) cv2.imwrite(aug_path+"/rtd270_flipx_"+file,flip(rotate(resized,270,1),0)) cv2.imwrite(aug_path+"/rtd315_flipx_"+file,flip(rotate(resized,315,1),0)) cv2.imwrite(aug_path+"/rtd330_flipx_"+file,flip(rotate(resized,330,1),0)) cv2.imwrite(aug_path+"/rtd90_flipy_"+file,flip(rotate(resized,90,1),1)) cv2.imwrite(aug_path+"/rtd45_flipy_"+file,flip(rotate(resized,45,1),1)) cv2.imwrite(aug_path+"/rtd30_flipy_"+file,flip(rotate(resized,30,1),1)) cv2.imwrite(aug_path+"/rtd270_flipy_"+file,flip(rotate(resized,270,1),1)) cv2.imwrite(aug_path+"/rtd315_flipy_"+file,flip(rotate(resized,315,1),1)) cv2.imwrite(aug_path+"/rtd330_flipy_"+file,flip(rotate(resized,330,1),1)) if self.checkBox_4.isChecked() and self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_rtd90_flipxy_"+file,flip(rotate(brightness_increase(resized,50),90,1),-1)) cv2.imwrite(aug_path+"/binc_rtd45_flipxy_"+file,flip(rotate(brightness_increase(resized,50),45,1),-1)) cv2.imwrite(aug_path+"/binc_rtd30_flipxy_"+file,flip(rotate(brightness_increase(resized,50),30,1),-1)) cv2.imwrite(aug_path+"/binc_rtd270_flipxy_"+file,flip(rotate(brightness_increase(resized,50),270,1),-1)) cv2.imwrite(aug_path+"/binc_rtd315_flipxy_"+file,flip(rotate(brightness_increase(resized,50),315,1),-1)) cv2.imwrite(aug_path+"/binc_rtd330_flipxy_"+file,flip(rotate(brightness_increase(resized,50),330,1),-1)) cv2.imwrite(aug_path+"/binc_rtd90_flipx_"+file,flip(rotate(brightness_increase(resized,50),90,1),0)) cv2.imwrite(aug_path+"/binc_rtd45_flipx_"+file,flip(rotate(brightness_increase(resized,50),45,1),0)) cv2.imwrite(aug_path+"/binc_rtd30_flipx_"+file,flip(rotate(brightness_increase(resized,50),30,1),0)) cv2.imwrite(aug_path+"/binc_rtd270_flipx_"+file,flip(rotate(brightness_increase(resized,50),270,1),0)) cv2.imwrite(aug_path+"/binc_rtd315_flipx_"+file,flip(rotate(brightness_increase(resized,50),315,1),0)) cv2.imwrite(aug_path+"/binc_rtd330_flipx_"+file,flip(rotate(brightness_increase(resized,50),330,1),0)) cv2.imwrite(aug_path+"/binc_rtd90_flipy_"+file,flip(rotate(brightness_increase(resized,50),90,1),1)) cv2.imwrite(aug_path+"/binc_rtd45_flipy_"+file,flip(rotate(brightness_increase(resized,50),45,1),1)) cv2.imwrite(aug_path+"/binc_rtd30_flipy_"+file,flip(rotate(brightness_increase(resized,50),30,1),1)) cv2.imwrite(aug_path+"/binc_rtd270_flipy_"+file,flip(rotate(brightness_increase(resized,50),270,1),1)) cv2.imwrite(aug_path+"/binc_rtd315_flipy_"+file,flip(rotate(brightness_increase(resized,50),315,1),1)) cv2.imwrite(aug_path+"/binc_rtd330_flipy_"+file,flip(rotate(brightness_increase(resized,50),330,1),1)) if self.checkBox_4.isChecked() and self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_rtd90_flipxy_"+file,flip(rotate(decrease_brightness(resized,50),90,1),-1)) cv2.imwrite(aug_path+"/bdec_rtd45_flipxy_"+file,flip(rotate(decrease_brightness(resized,50),45,1),-1)) cv2.imwrite(aug_path+"/bdec_rtd30_flipxy_"+file,flip(rotate(decrease_brightness(resized,50),30,1),-1)) cv2.imwrite(aug_path+"/bdec_rtd270_flipxy_"+file,flip(rotate(decrease_brightness(resized,50),270,1),-1)) cv2.imwrite(aug_path+"/bdec_rtd315_flipxy_"+file,flip(rotate(decrease_brightness(resized,50),315,1),-1)) cv2.imwrite(aug_path+"/bdec_rtd330_flipxy_"+file,flip(rotate(decrease_brightness(resized,50),330,1),-1)) cv2.imwrite(aug_path+"/bdec_rtd90_flipx_"+file,flip(rotate(decrease_brightness(resized,50),90,1),0)) cv2.imwrite(aug_path+"/bdec_rtd45_flipx_"+file,flip(rotate(decrease_brightness(resized,50),45,1),0)) cv2.imwrite(aug_path+"/bdec_rtd30_flipx_"+file,flip(rotate(decrease_brightness(resized,50),30,1),0)) cv2.imwrite(aug_path+"/bdec_rtd270_flipx_"+file,flip(rotate(decrease_brightness(resized,50),270,1),0)) cv2.imwrite(aug_path+"/bdec_rtd315_flipx_"+file,flip(rotate(decrease_brightness(resized,50),315,1),0)) cv2.imwrite(aug_path+"/bdec_rtd330_flipx_"+file,flip(rotate(decrease_brightness(resized,50),330,1),0)) cv2.imwrite(aug_path+"/bdec_rtd90_flipy_"+file,flip(rotate(decrease_brightness(resized,50),90,1),1)) cv2.imwrite(aug_path+"/bdec_rtd45_flipy_"+file,flip(rotate(decrease_brightness(resized,50),45,1),1)) cv2.imwrite(aug_path+"/bdec_rtd30_flipy_"+file,flip(rotate(decrease_brightness(resized,50),30,1),1)) cv2.imwrite(aug_path+"/bdec_rtd270_flipy_"+file,flip(rotate(decrease_brightness(resized,50),270,1),1)) cv2.imwrite(aug_path+"/bdec_rtd315_flipy_"+file,flip(rotate(decrease_brightness(resized,50),315,1),1)) cv2.imwrite(aug_path+"/bdec_rtd330_flipy_"+file,flip(rotate(decrease_brightness(resized,50),330,1),1)) if self.checkBox_6.isChecked(): cv2.imwrite(aug_path+"/shrpnd_"+file,sharpen(resized)) if self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_shrpnd_"+file,sharpen(brightness_increase(resized,50))) if self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_shrpnd_"+file,sharpen(decrease_brightness(resized,50))) if self.checkBox_4.isChecked(): cv2.imwrite(aug_path+"/rtd90_shrpnd_"+file,sharpen(rotate(resized,90,1))) cv2.imwrite(aug_path+"/rtd45_shrpnd_"+file,sharpen(rotate(resized,45,1))) cv2.imwrite(aug_path+"/rtd30_shrpnd_"+file,sharpen(rotate(resized,30,1))) cv2.imwrite(aug_path+"/rtd270_shrpnd_"+file,sharpen(rotate(resized,270,1))) cv2.imwrite(aug_path+"/rtd315_shrpnd_"+file,sharpen(rotate(resized,315,1))) cv2.imwrite(aug_path+"/rtd330_shrpnd_"+file,sharpen(rotate(resized,330,1))) if self.checkBox_5.isChecked(): cv2.imwrite(aug_path+"/flipxy_shrpnd_"+file,sharpen(flip(resized,-1))) cv2.imwrite(aug_path+"/flipx_shrpnd_"+file,sharpen(flip(resized,0))) cv2.imwrite(aug_path+"/flipy_shrpnd"+file,sharpen(flip(resized,1))) if self.checkBox_4.isChecked() and self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_rtd90_shrpnd_"+file,sharpen(rotate(brightness_increase(resized,50),90,1))) cv2.imwrite(aug_path+"/binc_rtd45_shrpnd_"+file,sharpen(rotate(brightness_increase(resized,50),45,1))) cv2.imwrite(aug_path+"/binc_rtd30_shrpnd_"+file,sharpen(rotate(brightness_increase(resized,50),30,1))) cv2.imwrite(aug_path+"/binc_rtd270_shrpnd_"+file,sharpen(rotate(brightness_increase(resized,50),270,1))) cv2.imwrite(aug_path+"/binc_rtd315_shrpnd_"+file,sharpen(rotate(brightness_increase(resized,50),315,1))) cv2.imwrite(aug_path+"/binc_rtd330_shrpnd_"+file,sharpen(rotate(brightness_increase(resized,50),330,1))) if self.checkBox_4.isChecked() and self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_rtd90_shrpnd_"+file,sharpen(rotate(decrease_brightness(resized,50),90,1))) cv2.imwrite(aug_path+"/bdec_rtd45_shrpnd_"+file,sharpen(rotate(decrease_brightness(resized,50),45,1))) cv2.imwrite(aug_path+"/bdec_rtd30_shrpnd_"+file,sharpen(rotate(decrease_brightness(resized,50),30,1))) cv2.imwrite(aug_path+"/bdec_rtd270_shrpnd_"+file,sharpen(rotate(decrease_brightness(resized,50),270,1))) cv2.imwrite(aug_path+"/bdec_rtd315_shrpnd_"+file,sharpen(rotate(decrease_brightness(resized,50),315,1))) cv2.imwrite(aug_path+"/bdec_rtd330_shrpnd_"+file,sharpen(rotate(decrease_brightness(resized,50),330,1))) if self.checkBox_5.isChecked() and self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_flipxy_shrpnd_"+file,sharpen(flip(brightness_increase(resized,50),-1))) cv2.imwrite(aug_path+"/binc_flipx_shrpnd_"+file,sharpen(flip(brightness_increase(resized,50),0))) cv2.imwrite(aug_path+"/binc_flipy_shrpnd_"+file,sharpen(flip(brightness_increase(resized,50),1))) if self.checkBox_5.isChecked() and self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_flipxy_shrpnd_"+file,sharpen(flip(decrease_brightness(resized,50),-1))) cv2.imwrite(aug_path+"/bdec_flipx_shrpnd_"+file,sharpen(flip(decrease_brightness(resized,50),0))) cv2.imwrite(aug_path+"/bdec_flipy_shrpnd_"+file,sharpen(flip(decrease_brightness(resized,50),1))) if self.checkBox_5.isChecked() and self.checkBox_4.isChecked(): cv2.imwrite(aug_path+"/rtd90_flipxy_shrpnd_"+file,sharpen(flip(rotate(resized,90,1),-1))) cv2.imwrite(aug_path+"/rtd45_flipxy_shrpnd_"+file,sharpen(flip(rotate(resized,45,1),-1))) cv2.imwrite(aug_path+"/rtd30_flipxy_shrpnd_"+file,sharpen(flip(rotate(resized,30,1),-1))) cv2.imwrite(aug_path+"/rtd270_flipxy_shrpnd_"+file,sharpen(flip(rotate(resized,270,1),-1))) cv2.imwrite(aug_path+"/rtd315_flipxy_shrpnd_"+file,sharpen(flip(rotate(resized,315,1),-1))) cv2.imwrite(aug_path+"/rtd330_flipxy_shrpnd_"+file,sharpen(flip(rotate(resized,330,1),-1))) cv2.imwrite(aug_path+"/rtd90_flipx_shrpnd_"+file,sharpen(flip(rotate(resized,90,1),0))) cv2.imwrite(aug_path+"/rtd45_flipx_shrpnd_"+file,sharpen(flip(rotate(resized,45,1),0))) cv2.imwrite(aug_path+"/rtd30_flipx_shrpnd_"+file,sharpen(flip(rotate(resized,30,1),0))) cv2.imwrite(aug_path+"/rtd270_flipx_shrpnd_"+file,sharpen(flip(rotate(resized,270,1),0))) cv2.imwrite(aug_path+"/rtd315_flipx_shrpnd_"+file,sharpen(flip(rotate(resized,315,1),0))) cv2.imwrite(aug_path+"/rtd330_flipx_shrpnd_"+file,sharpen(flip(rotate(resized,330,1),0))) cv2.imwrite(aug_path+"/rtd90_flipy_shrpnd_"+file,sharpen(flip(rotate(resized,90,1),1))) cv2.imwrite(aug_path+"/rtd45_flipy_shrpnd_"+file,sharpen(flip(rotate(resized,45,1),1))) cv2.imwrite(aug_path+"/rtd30_flipy_shrpnd_"+file,sharpen(flip(rotate(resized,30,1),1))) cv2.imwrite(aug_path+"/rtd270_flipy_shrpnd_"+file,sharpen(flip(rotate(resized,270,1),1))) cv2.imwrite(aug_path+"/rtd315_flipy_shrpnd_"+file,sharpen(flip(rotate(resized,315,1),1))) cv2.imwrite(aug_path+"/rtd330_flipy_shrpnd_"+file,sharpen(flip(rotate(resized,330,1),1))) if self.checkBox_7.isChecked(): cv2.imwrite(aug_path+"/shrdx_"+file,shear(resized,0)) cv2.imwrite(aug_path+"/shrdy_"+file,shear(resized,1)) if self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_shrdx_"+file,shear(brightness_increase(resized,50),0)) cv2.imwrite(aug_path+"/binc_shrdy_"+file,shear(brightness_increase(resized,50),1)) if self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_shrdx_"+file,shear(decrease_brightness(resized,50),0)) cv2.imwrite(aug_path+"/bdec_shrdy_"+file,shear(decrease_brightness(resized,50),1)) if self.checkBox_4.isChecked(): cv2.imwrite(aug_path+"/rtd90_shrdx_"+file,shear(rotate(resized,90,1),0)) cv2.imwrite(aug_path+"/rtd45_shrdx_"+file,shear(rotate(resized,45,1),0)) cv2.imwrite(aug_path+"/rtd30_shrdx_"+file,shear(rotate(resized,30,1),0)) cv2.imwrite(aug_path+"/rtd270_shrdx_"+file,shear(rotate(resized,270,1),0)) cv2.imwrite(aug_path+"/rtd315_shrdx_"+file,shear(rotate(resized,315,1),0)) cv2.imwrite(aug_path+"/rtd330_shrdx_"+file,shear(rotate(resized,330,1),0)) cv2.imwrite(aug_path+"/rtd90_shrdy_"+file,shear(rotate(resized,90,1),1)) cv2.imwrite(aug_path+"/rtd45_shrdy_"+file,shear(rotate(resized,45,1),1)) cv2.imwrite(aug_path+"/rtd30_shrdy_"+file,shear(rotate(resized,30,1),1)) cv2.imwrite(aug_path+"/rtd270_shrdy_"+file,shear(rotate(resized,270,1),1)) cv2.imwrite(aug_path+"/rtd315_shrdy_"+file,shear(rotate(resized,315,1),1)) cv2.imwrite(aug_path+"/rtd330_shrdy_"+file,shear(rotate(resized,330,1),1)) if self.checkBox_5.isChecked(): cv2.imwrite(aug_path+"/flipxy_shrdx_"+file,shear(flip(resized,-1),0)) cv2.imwrite(aug_path+"/flipx_shrdx_"+file,shear(flip(resized,0),0)) cv2.imwrite(aug_path+"/flipy_shrdx"+file,shear(flip(resized,1),0)) cv2.imwrite(aug_path+"/flipxy_shrdy_"+file,shear(flip(resized,-1),1)) cv2.imwrite(aug_path+"/flipx_shrdy_"+file,shear(flip(resized,0),1)) cv2.imwrite(aug_path+"/flipy_shrdy"+file,shear(flip(resized,1),1)) if self.checkBox_6.isChecked(): cv2.imwrite(aug_path+"/shrpnd_shrdx"+file,shear(sharpen(resized),0)) cv2.imwrite(aug_path+"/shrpnd_shrdy"+file,shear(sharpen(resized),1)) if self.checkBox_4.isChecked() and self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_rtd90_shrdx_"+file,shear(rotate(brightness_increase(resized,50),90,1),0)) cv2.imwrite(aug_path+"/binc_rtd45_shrdx_"+file,shear(rotate(brightness_increase(resized,50),45,1),0)) cv2.imwrite(aug_path+"/binc_rtd30_shrdx_"+file,shear(rotate(brightness_increase(resized,50),30,1),0)) cv2.imwrite(aug_path+"/binc_rtd270_shrdx_"+file,shear(rotate(brightness_increase(resized,50),270,1),0)) cv2.imwrite(aug_path+"/binc_rtd315_shrdx_"+file,shear(rotate(brightness_increase(resized,50),315,1),0)) cv2.imwrite(aug_path+"/binc_rtd330_shrdx_"+file,shear(rotate(brightness_increase(resized,50),330,1),0)) cv2.imwrite(aug_path+"/binc_rtd90_shrdy_"+file,shear(rotate(brightness_increase(resized,50),90,1),1)) cv2.imwrite(aug_path+"/binc_rtd45_shrdy_"+file,shear(rotate(brightness_increase(resized,50),45,1),1)) cv2.imwrite(aug_path+"/binc_rtd30_shrdy_"+file,shear(rotate(brightness_increase(resized,50),30,1),1)) cv2.imwrite(aug_path+"/binc_rtd270_shrdy_"+file,shear(rotate(brightness_increase(resized,50),270,1),1)) cv2.imwrite(aug_path+"/binc_rtd315_shrdy_"+file,shear(rotate(brightness_increase(resized,50),315,1),1)) cv2.imwrite(aug_path+"/binc_rtd330_shrdy_"+file,shear(rotate(brightness_increase(resized,50),330,1),1)) if self.checkBox_4.isChecked() and self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_rtd90_shrdx_"+file,shear(rotate(decrease_brightness(resized,50),90,1),0)) cv2.imwrite(aug_path+"/bdec_rtd45_shrdx_"+file,shear(rotate(decrease_brightness(resized,50),45,1),0)) cv2.imwrite(aug_path+"/bdec_rtd30_shrdx_"+file,shear(rotate(decrease_brightness(resized,50),30,1),0)) cv2.imwrite(aug_path+"/bdec_rtd270_shrdx_"+file,shear(rotate(decrease_brightness(resized,50),270,1),0)) cv2.imwrite(aug_path+"/bdec_rtd315_shrdx_"+file,shear(rotate(decrease_brightness(resized,50),315,1),0)) cv2.imwrite(aug_path+"/bdec_rtd330_shrdx_"+file,shear(rotate(decrease_brightness(resized,50),330,1),0)) cv2.imwrite(aug_path+"/bdec_rtd90_shrdy_"+file,shear(rotate(decrease_brightness(resized,50),90,1),1)) cv2.imwrite(aug_path+"/bdec_rtd45_shrdy_"+file,shear(rotate(decrease_brightness(resized,50),45,1),1)) cv2.imwrite(aug_path+"/bdec_rtd30_shrdy_"+file,shear(rotate(decrease_brightness(resized,50),30,1),1)) cv2.imwrite(aug_path+"/bdec_rtd270_shrdy_"+file,shear(rotate(decrease_brightness(resized,50),270,1),1)) cv2.imwrite(aug_path+"/bdec_rtd315_shrdy_"+file,shear(rotate(decrease_brightness(resized,50),315,1),1)) cv2.imwrite(aug_path+"/bdec_rtd330_shrdy_"+file,shear(rotate(decrease_brightness(resized,50),330,1),1)) if self.checkBox_5.isChecked() and self.checkBox_2.isChecked(): cv2.imwrite(aug_path+"/binc_flipxy_shrdx_"+file,shear(flip(brightness_increase(resized,50),-1),0)) cv2.imwrite(aug_path+"/binc_flipx_shrdx_"+file,shear(flip(brightness_increase(resized,50),0),0)) cv2.imwrite(aug_path+"/binc_flipy_shrdx_"+file,shear(flip(brightness_increase(resized,50),1),0)) cv2.imwrite(aug_path+"/binc_flipxy_shrdy_"+file,shear(flip(brightness_increase(resized,50),-1),1)) cv2.imwrite(aug_path+"/binc_flipx_shrdy_"+file,shear(flip(brightness_increase(resized,50),0),1)) cv2.imwrite(aug_path+"/binc_flipy_shrdy_"+file,shear(flip(brightness_increase(resized,50),1),1)) if self.checkBox_5.isChecked() and self.checkBox_3.isChecked(): cv2.imwrite(aug_path+"/bdec_flipxy_shrdx_"+file,shear(flip(decrease_brightness(resized,50),-1),0)) cv2.imwrite(aug_path+"/bdec_flipx_shrdx_"+file,shear(flip(decrease_brightness(resized,50),0),0)) cv2.imwrite(aug_path+"/bdec_flipy_shrdx_"+file,shear(flip(decrease_brightness(resized,50),1),0)) cv2.imwrite(aug_path+"/bdec_flipxy_shrdy_"+file,shear(flip(decrease_brightness(resized,50),-1),1)) cv2.imwrite(aug_path+"/bdec_flipx_shrdy_"+file,shear(flip(decrease_brightness(resized,50),0),1)) cv2.imwrite(aug_path+"/bdec_flipy_shrdy_"+file,shear(flip(decrease_brightness(resized,50),1),1)) if self.checkBox_5.isChecked() and self.checkBox_4.isChecked(): cv2.imwrite(aug_path+"/rtd90_flipxy_shrdx_"+file,shear(flip(rotate(resized,90,1),-1),0)) cv2.imwrite(aug_path+"/rtd45_flipxy_shrdx_"+file,shear(flip(rotate(resized,45,1),-1),0)) cv2.imwrite(aug_path+"/rtd30_flipxy_shrdx_"+file,shear(flip(rotate(resized,30,1),-1),0)) cv2.imwrite(aug_path+"/rtd270_flipxy_shrdx_"+file,shear(flip(rotate(resized,270,1),-1),0)) cv2.imwrite(aug_path+"/rtd315_flipxy_shrdx_"+file,shear(flip(rotate(resized,315,1),-1),0)) cv2.imwrite(aug_path+"/rtd330_flipxy_shrdx_"+file,shear(flip(rotate(resized,330,1),-1),0)) cv2.imwrite(aug_path+"/rtd90_flipx_shrdx_"+file,shear(flip(rotate(resized,90,1),0),0)) cv2.imwrite(aug_path+"/rtd45_flipx_shrdx_"+file,shear(flip(rotate(resized,45,1),0),0)) cv2.imwrite(aug_path+"/rtd30_flipx_shrdx_"+file,shear(flip(rotate(resized,30,1),0),0)) cv2.imwrite(aug_path+"/rtd270_flipx_shrdx_"+file,shear(flip(rotate(resized,270,1),0),0)) cv2.imwrite(aug_path+"/rtd315_flipx_shrdx_"+file,shear(flip(rotate(resized,315,1),0),0)) cv2.imwrite(aug_path+"/rtd330_flipx_shrdx_"+file,shear(flip(rotate(resized,330,1),0),0)) cv2.imwrite(aug_path+"/rtd90_flipy_shrdx_"+file,shear(flip(rotate(resized,90,1),1),0)) cv2.imwrite(aug_path+"/rtd45_flipy_shrdx_"+file,shear(flip(rotate(resized,45,1),1),0)) cv2.imwrite(aug_path+"/rtd30_flipy_shrdx_"+file,shear(flip(rotate(resized,30,1),1),0)) cv2.imwrite(aug_path+"/rtd270_flipy_shrdx_"+file,shear(flip(rotate(resized,270,1),1),0)) cv2.imwrite(aug_path+"/rtd315_flipy_shrdx_"+file,shear(flip(rotate(resized,315,1),1),0)) cv2.imwrite(aug_path+"/rtd330_flipy_shrdx_"+file,shear(flip(rotate(resized,330,1),1),0)) cv2.imwrite(aug_path+"/rtd90_flipxy_shrdy_"+file,shear(flip(rotate(resized,90,1),-1),1)) cv2.imwrite(aug_path+"/rtd45_flipxy_shrdy_"+file,shear(flip(rotate(resized,45,1),-1),1)) cv2.imwrite(aug_path+"/rtd30_flipxy_shrdy_"+file,shear(flip(rotate(resized,30,1),-1),1)) cv2.imwrite(aug_path+"/rtd270_flipxy_shrdy_"+file,shear(flip(rotate(resized,270,1),-1),1)) cv2.imwrite(aug_path+"/rtd315_flipxy_shrdy_"+file,shear(flip(rotate(resized,315,1),-1),1)) cv2.imwrite(aug_path+"/rtd330_flipxy_shrdy_"+file,shear(flip(rotate(resized,330,1),-1),1)) cv2.imwrite(aug_path+"/rtd90_flipx_shrdy_"+file,shear(flip(rotate(resized,90,1),0),1)) cv2.imwrite(aug_path+"/rtd45_flipx_shrdy_"+file,shear(flip(rotate(resized,45,1),0),1)) cv2.imwrite(aug_path+"/rtd30_flipx_shrdy_"+file,shear(flip(rotate(resized,30,1),0),1)) cv2.imwrite(aug_path+"/rtd270_flipx_shrdy_"+file,shear(flip(rotate(resized,270,1),0),1)) cv2.imwrite(aug_path+"/rtd315_flipx_shrdy_"+file,shear(flip(rotate(resized,315,1),0),1)) cv2.imwrite(aug_path+"/rtd330_flipx_shrdy_"+file,shear(flip(rotate(resized,330,1),0),1)) cv2.imwrite(aug_path+"/rtd90_flipy_shrdy_"+file,shear(flip(rotate(resized,90,1),1),1)) cv2.imwrite(aug_path+"/rtd45_flipy_shrdy_"+file,shear(flip(rotate(resized,45,1),1),1)) cv2.imwrite(aug_path+"/rtd30_flipy_shrdy_"+file,shear(flip(rotate(resized,30,1),1),1)) cv2.imwrite(aug_path+"/rtd270_flipy_shrdy_"+file,shear(flip(rotate(resized,270,1),1),1)) cv2.imwrite(aug_path+"/rtd315_flipy_shrdy_"+file,shear(flip(rotate(resized,315,1),1),1)) cv2.imwrite(aug_path+"/rtd330_flipy_shrdy_"+file,shear(flip(rotate(resized,330,1),1),1)) if self.progress.value!=0 and counter==0: i+=float(float(100)/float(len(files))) self.progress.setValue(i) print(counter,self.progress.value()) if 99==self.progress.value() and counter==0: self.progress.setValue(0) counter+=1 msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Information") msg.setInformativeText("Completed!") msg.setWindowTitle("Finished") msg.setDetailedText("Your process has been succesfully completed.") msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel) msg.exec_() elif 100<=self.progress.value() and counter==0: counter+=1 self.progress.setValue(0) msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("Information") msg.setInformativeText("Completed!") msg.setWindowTitle("Finished") msg.setDetailedText("Your process has been succesfully completed.") msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel) msg.exec_() app = QtWidgets.QApplication(sys.argv) app.setStyle('Fusion') window = Ui() app.exec_()
[ "cv2.GaussianBlur", "os.walk", "numpy.ones", "PyQt5.uic.loadUi", "cv2.warpAffine", "PyQt5.QtWidgets.QApplication", "cv2.erode", "cv2.getRotationMatrix2D", "cv2.subtract", "cv2.filter2D", "cv2.dilate", "cv2.cvtColor", "os.path.exists", "cv2.resize", "PyQt5.QtGui.QPixmap", "imutils.grab_contours", "cv2.flip", "cv2.add", "PyQt5.QtGui.QIcon", "PyQt5.QtWidgets.QMessageBox", "os.makedirs", "cv2.threshold", "numpy.float32", "cv2.imread", "numpy.array", "PyQt5.QtGui.QGuiApplication.processEvents" ]
[((38929, 38961), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (38951, 38961), False, 'from PyQt5 import QtWidgets, uic, QtGui\n'), ((422, 474), 'cv2.resize', 'cv2.resize', (['image', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(image, dim, interpolation=cv2.INTER_AREA)\n', (432, 474), False, 'import cv2\n'), ((689, 728), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (701, 728), False, 'import cv2\n'), ((743, 781), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['grayscale', '(5, 5)', '(0)'], {}), '(grayscale, (5, 5), 0)\n', (759, 781), False, 'import cv2\n'), ((874, 920), 'cv2.erode', 'cv2.erode', (['threshold_image', 'None'], {'iterations': '(2)'}), '(threshold_image, None, iterations=2)\n', (883, 920), False, 'import cv2\n'), ((940, 987), 'cv2.dilate', 'cv2.dilate', (['threshold_image', 'None'], {'iterations': '(2)'}), '(threshold_image, None, iterations=2)\n', (950, 987), False, 'import cv2\n'), ((1097, 1127), 'imutils.grab_contours', 'imutils.grab_contours', (['contour'], {}), '(contour)\n', (1118, 1127), False, 'import imutils\n'), ((1507, 1563), 'cv2.resize', 'cv2.resize', (['new_image', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(new_image, dim, interpolation=cv2.INTER_AREA)\n', (1517, 1563), False, 'import cv2\n'), ((1859, 1881), 'cv2.add', 'cv2.add', (['image', 'bright'], {}), '(image, bright)\n', (1866, 1881), False, 'import cv2\n'), ((2169, 2196), 'cv2.subtract', 'cv2.subtract', (['image', 'bright'], {}), '(image, bright)\n', (2181, 2196), False, 'import cv2\n'), ((2656, 2709), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['(w / 2, h / 2)', 'angle', 'scale'], {}), '((w / 2, h / 2), angle, scale)\n', (2679, 2709), False, 'import cv2\n'), ((2731, 2763), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'M', '(w, h)'], {}), '(image, M, (w, h))\n', (2745, 2763), False, 'import cv2\n'), ((2913, 2934), 'cv2.flip', 'cv2.flip', (['image', 'axis'], {}), '(image, axis)\n', (2921, 2934), False, 'import cv2\n'), ((3063, 3115), 'numpy.array', 'np.array', (['[[-1, -1, -1], [-1, 10, -1], [-1, -1, -1]]'], {}), '([[-1, -1, -1], [-1, 10, -1], [-1, -1, -1]])\n', (3071, 3115), True, 'import numpy as np\n'), ((3177, 3212), 'cv2.filter2D', 'cv2.filter2D', (['image', '(-1)', 'sharpening'], {}), '(image, -1, sharpening)\n', (3189, 3212), False, 'import cv2\n'), ((800, 852), 'cv2.threshold', 'cv2.threshold', (['grayscale', '(45)', '(255)', 'cv2.THRESH_BINARY'], {}), '(grayscale, 45, 255, cv2.THRESH_BINARY)\n', (813, 852), False, 'import cv2\n'), ((1792, 1827), 'numpy.ones', 'np.ones', (['image.shape'], {'dtype': '"""uint8"""'}), "(image.shape, dtype='uint8')\n", (1799, 1827), True, 'import numpy as np\n'), ((2111, 2146), 'numpy.ones', 'np.ones', (['image.shape'], {'dtype': '"""uint8"""'}), "(image.shape, dtype='uint8')\n", (2118, 2146), True, 'import numpy as np\n'), ((3448, 3495), 'numpy.float32', 'np.float32', (['[[1, 0.5, 0], [0, 1, 0], [0, 0, 1]]'], {}), '([[1, 0.5, 0], [0, 1, 0], [0, 0, 1]])\n', (3458, 3495), True, 'import numpy as np\n'), ((3898, 3933), 'PyQt5.uic.loadUi', 'uic.loadUi', (['"""augmentation.ui"""', 'self'], {}), "('augmentation.ui', self)\n", (3908, 3933), False, 'from PyQt5 import QtWidgets, uic, QtGui\n'), ((4025, 4053), 'PyQt5.QtGui.QPixmap', 'QtGui.QPixmap', (['"""2582365.ico"""'], {}), "('2582365.ico')\n", (4038, 4053), False, 'from PyQt5 import QtWidgets, uic, QtGui\n'), ((4071, 4092), 'PyQt5.QtGui.QIcon', 'QtGui.QIcon', (['mypixmap'], {}), '(mypixmap)\n', (4082, 4092), False, 'from PyQt5 import QtWidgets, uic, QtGui\n'), ((7775, 7790), 'os.walk', 'os.walk', (['String'], {}), '(String)\n', (7782, 7790), False, 'import os\n'), ((3584, 3631), 'numpy.float32', 'np.float32', (['[[1, 0, 0], [0.5, 1, 0], [0, 0, 1]]'], {}), '([[1, 0, 0], [0.5, 1, 0], [0, 0, 1]])\n', (3594, 3631), True, 'import numpy as np\n'), ((7047, 7075), 'os.path.exists', 'os.path.exists', (['poppedString'], {}), '(poppedString)\n', (7061, 7075), False, 'import os\n'), ((7096, 7119), 'PyQt5.QtWidgets.QMessageBox', 'QtWidgets.QMessageBox', ([], {}), '()\n', (7117, 7119), False, 'from PyQt5 import QtWidgets, uic, QtGui\n'), ((7655, 7679), 'os.path.exists', 'os.path.exists', (['aug_path'], {}), '(aug_path)\n', (7669, 7679), False, 'import os\n'), ((7704, 7725), 'os.makedirs', 'os.makedirs', (['aug_path'], {}), '(aug_path)\n', (7715, 7725), False, 'import os\n'), ((7859, 7890), 'PyQt5.QtGui.QGuiApplication.processEvents', 'QGuiApplication.processEvents', ([], {}), '()\n', (7888, 7890), False, 'from PyQt5.QtGui import QGuiApplication\n'), ((7983, 8003), 'cv2.imread', 'cv2.imread', (['filepath'], {}), '(filepath)\n', (7993, 8003), False, 'import cv2\n'), ((37695, 37718), 'PyQt5.QtWidgets.QMessageBox', 'QtWidgets.QMessageBox', ([], {}), '()\n', (37716, 37718), False, 'from PyQt5 import QtWidgets, uic, QtGui\n'), ((38381, 38404), 'PyQt5.QtWidgets.QMessageBox', 'QtWidgets.QMessageBox', ([], {}), '()\n', (38402, 38404), False, 'from PyQt5 import QtWidgets, uic, QtGui\n')]
"""Testing for Showalter Index only. While MetPy handles all five parameters, the Showalter Index was contributed to MetPy by the GeoCAT team because of the skewt_params function. Additionally, a discrepancy between NCL and MetPy calculations of CAPE has been identified. After validating the CAPE value by hand using the method outlined in Hobbs 2006, it was determined that the MetPy calculation was closer to the CAPE value than the NCL calculation. To overcome any issues with validating the dataset, it was decided that skewt_params would only test against the Showalter Index for validation and not against all five parameters. Citation: <NAME>., and <NAME>, 2006: Atmospheric Science: An Introductory Survey. 2nd ed. Academic Press, pg 345 """ import sys import metpy.calc as mpcalc import numpy as np import xarray as xr import numpy.testing as nt from metpy.units import units import geocat.datafiles as gdf import pandas as pd # Import from directory structure if coverage test, or from installed # packages otherwise if "--cov" in str(sys.argv): from src.geocat.comp import get_skewt_vars, showalter_index else: from geocat.comp import get_skewt_vars, showalter_index ds = pd.read_csv(gdf.get('ascii_files/sounding.testdata'), delimiter='\\s+', header=None) # get ground truth from ncl run netcdf file try: out = xr.open_dataset( "skewt_params_output.nc" ) # Generated by running ncl_tests/skewt_params_test.ncl except: out = xr.open_dataset("test/skewt_params_output.nc") # Extract the data from ds p = ds[1].values * units.hPa # Pressure [mb/hPa] tc = (ds[5].values + 2) * units.degC # Temperature [C] tdc = ds[9].values * units.degC # Dew pt temp [C] pro = mpcalc.parcel_profile(p, tc[0], tdc[0]).to('degC') # Extract Showalter Index from NCL out file and convert to int Shox = np.round(out['Shox']) # Use np.round to avoid rounding issues NCL_shox = int(Shox[0]) # Convert to int def test_shox_vals(): # Showalter index shox = showalter_index(p, tc, tdc) shox = shox[0].magnitude # Place calculated values in iterable list vals = np.round(shox).astype(int) # Compare calculated values with expected nt.assert_equal(vals, NCL_shox) def test_get_skewt_vars(): """With respect to the note in test_vars, the MetPy calculated values for Plcl, Tlcl, Pwat, and CAPE along with the tested value for Showalter Index are pre-defined in this test. This test is to ensure that the values of each are being read, assigned, and placed correctly in get_skewt_vars. """ expected = 'Plcl= 927 Tlcl[C]= 24 Shox= 3 Pwat[cm]= 5 Cape[J]= 2958' result = get_skewt_vars(p, tc, tdc, pro) nt.assert_equal(result, expected)
[ "metpy.calc.parcel_profile", "xarray.open_dataset", "geocat.datafiles.get", "geocat.comp.showalter_index", "geocat.comp.get_skewt_vars", "numpy.testing.assert_equal", "numpy.round" ]
[((1864, 1885), 'numpy.round', 'np.round', (["out['Shox']"], {}), "(out['Shox'])\n", (1872, 1885), True, 'import numpy as np\n'), ((1207, 1247), 'geocat.datafiles.get', 'gdf.get', (['"""ascii_files/sounding.testdata"""'], {}), "('ascii_files/sounding.testdata')\n", (1214, 1247), True, 'import geocat.datafiles as gdf\n'), ((1373, 1414), 'xarray.open_dataset', 'xr.open_dataset', (['"""skewt_params_output.nc"""'], {}), "('skewt_params_output.nc')\n", (1388, 1414), True, 'import xarray as xr\n'), ((2027, 2054), 'geocat.comp.showalter_index', 'showalter_index', (['p', 'tc', 'tdc'], {}), '(p, tc, tdc)\n', (2042, 2054), False, 'from geocat.comp import get_skewt_vars, showalter_index\n'), ((2221, 2252), 'numpy.testing.assert_equal', 'nt.assert_equal', (['vals', 'NCL_shox'], {}), '(vals, NCL_shox)\n', (2236, 2252), True, 'import numpy.testing as nt\n'), ((2690, 2721), 'geocat.comp.get_skewt_vars', 'get_skewt_vars', (['p', 'tc', 'tdc', 'pro'], {}), '(p, tc, tdc, pro)\n', (2704, 2721), False, 'from geocat.comp import get_skewt_vars, showalter_index\n'), ((2726, 2759), 'numpy.testing.assert_equal', 'nt.assert_equal', (['result', 'expected'], {}), '(result, expected)\n', (2741, 2759), True, 'import numpy.testing as nt\n'), ((1503, 1549), 'xarray.open_dataset', 'xr.open_dataset', (['"""test/skewt_params_output.nc"""'], {}), "('test/skewt_params_output.nc')\n", (1518, 1549), True, 'import xarray as xr\n'), ((1742, 1781), 'metpy.calc.parcel_profile', 'mpcalc.parcel_profile', (['p', 'tc[0]', 'tdc[0]'], {}), '(p, tc[0], tdc[0])\n', (1763, 1781), True, 'import metpy.calc as mpcalc\n'), ((2143, 2157), 'numpy.round', 'np.round', (['shox'], {}), '(shox)\n', (2151, 2157), True, 'import numpy as np\n')]
import grblas import numba import numpy as np from typing import Union, Tuple from .container import Flat, Pivot from .schema import SchemaMismatchError from .oputils import jitted_op class SizeMismatchError(Exception): pass # Sentinel to indicate the fill values come from the object to which we are aligning _fill_like = object() def align(a: Union[Flat, Pivot], b: Union[Flat, Pivot], op=None, afill=None, bfill=None): """ Dispatched to align_pivots if both a and b and Pivots. Otherwise dispatches to align_flats, converting any Pivots to Flats using .flatten() """ if a.schema is not b.schema: raise SchemaMismatchError("Objects have different schemas") if afill is not None and afill is b: afill = _fill_like if bfill is not None and bfill is a: bfill = _fill_like a_type = type(a) b_type = type(b) if a_type is Pivot and b_type is Pivot: return align_pivots(a, b, op=op, afill=afill, bfill=bfill) elif a_type is Flat and b_type is Flat: return align_flats(a, b, op=op, afill=afill, bfill=bfill) elif a_type is Pivot: return align_flats(a.flatten(), b, op=op, afill=afill, bfill=bfill) else: return align_flats(a, b.flatten(), op=op, afill=afill, bfill=bfill) def align_flats(a: Flat, b: Flat, op=None, afill=None, bfill=None): """ Aligns two Flats, returning two Pivots with matching left and top dimensions. If a and b are already aligned, returns Flats instead of Pivots. If op is provided, returns a single Pivot. Otherwise returns a 2-tuple of Pivots afill and bfill are used to determine the kind of alignment afill=None, bfill=None -> inner join afill!=None, bfill=None -> left join afill=None, bfill!=None -> right join afill!=None, bfill!=None -> outer join :param a: Flat :param b: Flat :param op: grblas.BinaryOp (default None) :param afill: scalar or Flat (default None) :param bfill: scalar or Flat (default None) :return: Pivot or (Pivot, Pivot) """ if a.schema is not b.schema: raise SchemaMismatchError("Objects have different schemas") if afill is not None and afill is b: afill = _fill_like if bfill is not None and bfill is a: bfill = _fill_like # Determine which object is a subset of the other, or if they are fully disjoint mismatched_dims = a.dims ^ b.dims if not mismatched_dims: result = _already_aligned_flats(a, b, op, afill, bfill) elif a.dims - b.dims == mismatched_dims: # b is the subset a = a.pivot(top=mismatched_dims) result = _align_subset(a, b, op, afill, bfill) elif b.dims - a.dims == mismatched_dims: # a is the subset b = b.pivot(top=mismatched_dims) result = _align_subset(b, a, op, bfill, afill, reversed=True) else: # disjoint matched_dims = a.dims & b.dims if matched_dims: # partial disjoint a = a.pivot(left=matched_dims) b = b.pivot(left=matched_dims) result = _align_partial_disjoint(a, b, op, afill, bfill) else: # full disjoint result = _align_fully_disjoint(a, b, op) return result def align_pivots(a: Pivot, b: Pivot, op=None, afill=None, bfill=None): """ Aligns two Pivots, returning two Pivots with matching left and top dimensions. If op is provided, returns a single Pivot. Otherwise returns a 2-tuple of Pivots afill and bfill are used to determine the kind of alignment afill=None, bfill=None -> inner join afill!=None, bfill=None -> left join afill=None, bfill!=None -> right join afill!=None, bfill!=None -> outer join :param a: Pivot :param b: Pivot :param op: grblas.BinaryOp (default None) :param afill: scalar or Flat (default None) :param bfill: scalar or Flat (default None) :return: Pivot or (Pivot, Pivot) """ if a.schema is not b.schema: raise SchemaMismatchError("Objects have different schemas") if afill is not None and afill is b: afill = _fill_like if bfill is not None and bfill is a: bfill = _fill_like # Determine which object is a subset of the other, or if they are fully disjoint a_dims = a.left | a.top b_dims = b.left | b.top mismatched_dims = a_dims ^ b_dims if not mismatched_dims: result = _already_aligned_pivots(a, b.pivot(left=a.left), op, afill, bfill) elif a_dims - b_dims == mismatched_dims: # b is the subset a = a.pivot(top=mismatched_dims) result = _align_subset(a, b.flatten(), op, afill, bfill) elif b_dims - a_dims == mismatched_dims: # a is the subset b = b.pivot(top=mismatched_dims) result = _align_subset(b, a.flatten(), op, bfill, afill, reversed=True) else: # disjoint matched_dims = a_dims & b_dims if matched_dims: # partial disjoint a = a.pivot(left=matched_dims) b = b.pivot(left=matched_dims) result = _align_partial_disjoint(a, b, op, afill, bfill) else: # full disjoint result = _align_fully_disjoint(a.flatten(), b.flatten(), op) return result def _already_aligned_flats(a: Flat, b: Flat, op=None, afill=None, bfill=None) -> Union[Flat, Tuple[Flat, Flat]]: """ a.dims must equal b.dims """ assert a.dims == b.dims, f"Mismatching dimensions {a.dims ^ b.dims}" # Create a2 and b2 as expanded, filled vectors a2, b2 = a.vector, b.vector if afill is _fill_like: a2 = a2.dup() a2(~a2.S) << b2 elif afill is not None: a2 = grblas.Vector.new(a2.dtype, size=a2.size) a2(b2.S) << afill a2(a.vector.S) << a.vector if bfill is _fill_like: b2 = b2.dup() b2(~b2.S) << a2 elif bfill is not None: b2 = grblas.Vector.new(b2.dtype, size=b2.size) b2(a2.S) << bfill b2(b.vector.S) << b.vector # Handle op if op is None: return Flat(a2, a.schema, a.dims), Flat(b2, b.schema, b.dims) else: result = a2.ewise_mult(b2, op=op) return Flat(result.new(), a.schema, a.dims) def _already_aligned_pivots(a: Pivot, b: Pivot, op=None, afill=None, bfill=None) -> Union[Pivot, Tuple[Pivot, Pivot]]: """ a.left must equal b.left a.top must equal b.top """ assert a.left == b.left, f"Mismatching left dimensions {a.left ^ b.left}" assert a.top == b.top, f"Mismatching top dimensions {a.top ^ b.top}" # Create a2 and b2 as expanded, filled matrices a2, b2 = a.matrix, b.matrix if afill is _fill_like: a2 = a2.dup() a2(~a2.S) << b2 elif afill is not None: a2 = grblas.Matrix.new(a2.dtype, nrows=a2.nrows, ncols=a2.ncols) a2(b2.S) << afill a2(a.matrix.S) << a.matrix if bfill is _fill_like: b2 = b2.dup() b2(~b2.S) << a2 elif bfill is not None: b2 = grblas.Matrix.new(b2.dtype, nrows=b2.nrows, ncols=b2.ncols) b2(a2.S) << bfill b2(b.matrix.S) << b.matrix # Handle op if op is None: return Pivot(a2, a.schema, a.left, a.top), Pivot(b2, b.schema, b.left, b.top) else: result = a2.ewise_mult(b2, op=op) return Pivot(result.new(), a.schema, a.left, a.top) def _align_subset(x: Pivot, sub: Flat, op=None, afill=None, bfill=None, reversed=False) -> Union[Pivot, Tuple[Pivot, Pivot]]: """ x must have mismatched dims on top sub must have dims exactly matching x.left """ x2 = x.matrix size = sub.vector.size if x2.nrows != size: raise SizeMismatchError(f"nrows {x2.nrows} != size {size}") # Convert sub's values into the diagonal of a matrix index, vals = sub.vector.to_values() diag = grblas.Matrix.from_values(index, index, vals, nrows=size, ncols=size) # Multiply the diagonal matrix by the shape of x (any_first will only take values from diag) # This performs a broadcast of sub's values to the corresponding locations in x y2 = diag.mxm(x2, grblas.semiring.any_first).new() # mxm is an intersection operation, so mismatched codes are missing in m_broadcast if op is None or afill is not None: # Check if sub contained more rows than are present in m_broadcast v_x = y2.reduce_rows(grblas.monoid.any).new() if v_x.nvals < sub.vector.nvals: # Find mismatched codes and add them in with the NULL v_x(~v_x.S, replace=True)[:] << sub.vector # Update y2 with values lost from mxm y2[:, 0] << v_x # Column 0 is the code for all_dims == NULL if afill is not None: # Fill corresponding elements of x2 if afill if afill is not _fill_like: v_x(v_x.S) << afill x2 = x2.dup() x2(v_x.S)[:, 0] << v_x if bfill is _fill_like: y2(~y2.S) << x2 elif bfill is not None: ybackup = y2 y2 = grblas.Matrix.new(y2.dtype, nrows=y2.nrows, ncols=y2.ncols) y2(x2.S) << bfill y2(ybackup.S) << ybackup # Handle op if op is None: x = Pivot(x2, x.schema, x.left, x.top) y = Pivot(y2, x.schema, x.left, x.top) return (y, x) if reversed else (x, y) else: result = y2.ewise_mult(x2, op=op) if reversed else x2.ewise_mult(y2, op=op) return Pivot(result.new(), x.schema, x.left, x.top) def _align_fully_disjoint(x: Flat, y: Flat, op=None) -> Union[Pivot, Tuple[Pivot, Pivot]]: """ x.dims must have no overlap with y.dims """ xm = grblas.Matrix.new(x.vector.dtype, x.vector.size, 1) xm[:, 0] << x.vector ym = grblas.Matrix.new(y.vector.dtype, y.vector.size, 1) ym[:, 0] << y.vector # Perform the cross-joins. Values from only a single input are used per calculation xr = xm.mxm(ym.T, grblas.semiring.any_first) yr = xm.mxm(ym.T, grblas.semiring.any_second) if op is None: return ( Pivot(xr.new(), x.schema, left=x.dims, top=y.dims), Pivot(yr.new(), x.schema, left=x.dims, top=y.dims) ) else: result = xr.new() result(accum=op) << yr return Pivot(result, x.schema, left=x.dims, top=y.dims) def _align_partial_disjoint(x: Pivot, y: Pivot, op=None, afill=None, bfill=None) -> Union[Pivot, Tuple[Pivot, Pivot]]: """ x.left must match y.left x.top must have no overlap with y.top """ assert x.left == y.left matched_dims = x.left mismatched_dims = x.top | y.top top_mask = x.schema.build_bitmask(mismatched_dims) # Compute the size and offsets of the cross join computation x1 = x.matrix.apply(grblas.unary.one).new().reduce_rows(grblas.monoid.plus['INT64']).new() y1 = y.matrix.apply(grblas.unary.one).new().reduce_rows(grblas.monoid.plus['INT64']).new() combo = x1.ewise_add(y1, grblas.monoid.times).new() # Mask back into x1 and y1 to contain only what applies to each (unless filling to match) if op is None: xmask = x1.S if afill is None else None ymask = y1.S if bfill is None else None x1(mask=xmask) << combo y1(mask=ymask) << combo x1_size = int(x1.reduce().value) y1_size = int(y1.reduce().value) else: # op is provided, will only have a single return object # Trim x1 to final size, then compute result_size if afill is None and bfill is None: # intersecting values only x1 << x1.ewise_mult(y1, grblas.monoid.times) elif afill is None: # size same as x x1(x1.S, replace=True) << combo elif bfill is None: # size same as y x1(y1.S, replace=True) << combo else: x1 = combo result_size = int(x1.reduce().value) combo_idx, combo_offset = combo.to_values() # Extract input arrays in hypercsr format xs = x.matrix.ss.export(format='hypercsr', sort=True) xs_rows = xs['rows'] xs_indptr = xs['indptr'] xs_col_indices = xs['col_indices'] xs_values = xs['values'] ys = y.matrix.ss.export(format='hypercsr', sort=True) ys_rows = ys['rows'] ys_indptr = ys['indptr'] ys_col_indices = ys['col_indices'] ys_values = ys['values'] if op is None: # Build output data structures r1_rows = np.zeros((x1_size,), dtype=np.uint64) r1_cols = np.zeros((x1_size,), dtype=np.uint64) r1_vals = np.zeros((x1_size,), dtype=xs['values'].dtype) r2_rows = np.zeros((y1_size,), dtype=np.uint64) r2_cols = np.zeros((y1_size,), dtype=np.uint64) r2_vals = np.zeros((y1_size,), dtype=ys['values'].dtype) _align_partial_disjoint_numba( combo_idx, xs_rows, xs_indptr, xs_col_indices, xs_values, ys_rows, ys_indptr, ys_col_indices, ys_values, r1_rows, r1_cols, r1_vals, r2_rows, r2_cols, r2_vals, afill is not None, bfill is not None, afill if afill is not None and afill is not _fill_like else None, bfill if bfill is not None and bfill is not _fill_like else None ) return ( Pivot(grblas.Matrix.from_values(r1_rows, r1_cols, r1_vals, nrows=x.matrix.nrows, ncols=top_mask + 1), x.schema, matched_dims, mismatched_dims), Pivot(grblas.Matrix.from_values(r2_rows, r2_cols, r2_vals, nrows=x.matrix.nrows, ncols=top_mask + 1), x.schema, matched_dims, mismatched_dims) ) else: unified_input_dtype = grblas.dtypes.unify( grblas.dtypes.lookup_dtype(xs['values'].dtype), grblas.dtypes.lookup_dtype(ys['values'].dtype) ) output_dtype_str = op.types[grblas.dtypes.lookup_dtype(unified_input_dtype).name] op = jitted_op(op) # Build output data structures r_rows = np.zeros((result_size,), dtype=np.uint64) r_cols = np.zeros((result_size,), dtype=np.uint64) r_vals = np.zeros((result_size,), dtype=grblas.dtypes.lookup_dtype(output_dtype_str).np_type) _align_partial_disjoint_numba_op( op, combo_idx, xs_rows, xs_indptr, xs_col_indices, xs_values, ys_rows, ys_indptr, ys_col_indices, ys_values, r_rows, r_cols, r_vals, afill is not None, bfill is not None, afill if afill is not None and afill is not _fill_like else None, bfill if bfill is not None and bfill is not _fill_like else None ) return ( Pivot(grblas.Matrix.from_values(r_rows, r_cols, r_vals), x.schema, matched_dims, mismatched_dims) ) @numba.njit def _align_partial_disjoint_numba( combo_idx, xs_rows, xs_indptr, xs_col_indices, xs_values, ys_rows, ys_indptr, ys_col_indices, ys_values, r1_rows, r1_cols, r1_vals, r2_rows, r2_cols, r2_vals, fill_x, fill_y, # boolean x_fillval, y_fillval, # scalar or None ): # xi/yi are the current index of xs/ys, not necessarily in sync with combo_idx due to mismatched codes xi = 0 yi = 0 xoffset = 0 yoffset = 0 for row in combo_idx: # Find xrow and yrow, if available xrow, yrow = -1, -1 if xi < len(xs_rows) and xs_rows[xi] == row: xrow = xi xi += 1 if yi < len(ys_rows) and ys_rows[yi] == row: yrow = yi yi += 1 # Iterate over x and y indices for this row if xrow >= 0 and yrow >= 0: for xj in range(xs_indptr[xrow], xs_indptr[xrow + 1]): for yj in range(ys_indptr[yrow], ys_indptr[yrow + 1]): r1_rows[xoffset] = row r2_rows[yoffset] = row col_idx = xs_col_indices[xj] + ys_col_indices[yj] r1_cols[xoffset] = col_idx r2_cols[yoffset] = col_idx r1_vals[xoffset] = xs_values[xj] r2_vals[yoffset] = ys_values[yj] xoffset += 1 yoffset += 1 elif xrow >= 0: for xj in range(xs_indptr[xrow], xs_indptr[xrow + 1]): r1_rows[xoffset] = row r1_cols[xoffset] = xs_col_indices[xj] r1_vals[xoffset] = xs_values[xj] xoffset += 1 if fill_y: r2_rows[yoffset] = row r2_cols[yoffset] = xs_col_indices[xj] if y_fillval is None: r2_vals[yoffset] = xs_values[xj] else: r2_vals[yoffset] = y_fillval yoffset += 1 elif yrow >= 0: for yj in range(ys_indptr[yrow], ys_indptr[yrow + 1]): r2_rows[yoffset] = row r2_cols[yoffset] = ys_col_indices[yj] r2_vals[yoffset] = ys_values[yj] yoffset += 1 if fill_x: r1_rows[xoffset] = row r1_cols[xoffset] = ys_col_indices[yj] if x_fillval is None: r1_vals[xoffset] = ys_values[yj] else: r1_vals[xoffset] = x_fillval xoffset += 1 else: raise Exception("Unhandled row") @numba.njit def _align_partial_disjoint_numba_op( op, combo_idx, xs_rows, xs_indptr, xs_col_indices, xs_values, ys_rows, ys_indptr, ys_col_indices, ys_values, r_rows, r_cols, r_vals, fill_x, fill_y, # boolean x_fillval, y_fillval, # scalar or None ): # xi/yi are the current index of xs/ys, not necessarily in sync with combo_idx due to mismatched codes xi = 0 yi = 0 offset = 0 for row in combo_idx: # Find xrow and yrow, if available xrow, yrow = -1, -1 if xi < len(xs_rows) and xs_rows[xi] == row: xrow = xi xi += 1 if yi < len(ys_rows) and ys_rows[yi] == row: yrow = yi yi += 1 # Iterate over x and y indices for this row if xrow >= 0 and yrow >= 0: for xj in range(xs_indptr[xrow], xs_indptr[xrow + 1]): for yj in range(ys_indptr[yrow], ys_indptr[yrow + 1]): r_rows[offset] = row col_idx = xs_col_indices[xj] + ys_col_indices[yj] r_cols[offset] = col_idx # Could do the computation here between r1 and r2 rather than keeping them separate r_vals[offset] = op(xs_values[xj], ys_values[yj]) offset += 1 elif xrow >= 0: if not fill_y: continue for xj in range(xs_indptr[xrow], xs_indptr[xrow + 1]): r_rows[offset] = row r_cols[offset] = xs_col_indices[xj] other_val = xs_values[xj] if y_fillval is None else y_fillval r_vals[offset] = op(xs_values[xj], other_val) offset += 1 elif yrow >= 0: if not fill_x: continue for yj in range(ys_indptr[yrow], ys_indptr[yrow + 1]): r_rows[offset] = row r_cols[offset] = ys_col_indices[yj] other_val = ys_values[yj] if x_fillval is None else x_fillval r_vals[offset] = op(ys_values[yj], other_val) offset += 1 else: raise Exception("Unhandled row")
[ "grblas.Vector.new", "numpy.zeros", "grblas.Matrix.new", "grblas.dtypes.lookup_dtype", "grblas.Matrix.from_values" ]
[((7765, 7834), 'grblas.Matrix.from_values', 'grblas.Matrix.from_values', (['index', 'index', 'vals'], {'nrows': 'size', 'ncols': 'size'}), '(index, index, vals, nrows=size, ncols=size)\n', (7790, 7834), False, 'import grblas\n'), ((9584, 9635), 'grblas.Matrix.new', 'grblas.Matrix.new', (['x.vector.dtype', 'x.vector.size', '(1)'], {}), '(x.vector.dtype, x.vector.size, 1)\n', (9601, 9635), False, 'import grblas\n'), ((9670, 9721), 'grblas.Matrix.new', 'grblas.Matrix.new', (['y.vector.dtype', 'y.vector.size', '(1)'], {}), '(y.vector.dtype, y.vector.size, 1)\n', (9687, 9721), False, 'import grblas\n'), ((12307, 12344), 'numpy.zeros', 'np.zeros', (['(x1_size,)'], {'dtype': 'np.uint64'}), '((x1_size,), dtype=np.uint64)\n', (12315, 12344), True, 'import numpy as np\n'), ((12363, 12400), 'numpy.zeros', 'np.zeros', (['(x1_size,)'], {'dtype': 'np.uint64'}), '((x1_size,), dtype=np.uint64)\n', (12371, 12400), True, 'import numpy as np\n'), ((12419, 12465), 'numpy.zeros', 'np.zeros', (['(x1_size,)'], {'dtype': "xs['values'].dtype"}), "((x1_size,), dtype=xs['values'].dtype)\n", (12427, 12465), True, 'import numpy as np\n'), ((12484, 12521), 'numpy.zeros', 'np.zeros', (['(y1_size,)'], {'dtype': 'np.uint64'}), '((y1_size,), dtype=np.uint64)\n', (12492, 12521), True, 'import numpy as np\n'), ((12540, 12577), 'numpy.zeros', 'np.zeros', (['(y1_size,)'], {'dtype': 'np.uint64'}), '((y1_size,), dtype=np.uint64)\n', (12548, 12577), True, 'import numpy as np\n'), ((12596, 12642), 'numpy.zeros', 'np.zeros', (['(y1_size,)'], {'dtype': "ys['values'].dtype"}), "((y1_size,), dtype=ys['values'].dtype)\n", (12604, 12642), True, 'import numpy as np\n'), ((13858, 13899), 'numpy.zeros', 'np.zeros', (['(result_size,)'], {'dtype': 'np.uint64'}), '((result_size,), dtype=np.uint64)\n', (13866, 13899), True, 'import numpy as np\n'), ((13917, 13958), 'numpy.zeros', 'np.zeros', (['(result_size,)'], {'dtype': 'np.uint64'}), '((result_size,), dtype=np.uint64)\n', (13925, 13958), True, 'import numpy as np\n'), ((5621, 5662), 'grblas.Vector.new', 'grblas.Vector.new', (['a2.dtype'], {'size': 'a2.size'}), '(a2.dtype, size=a2.size)\n', (5638, 5662), False, 'import grblas\n'), ((5840, 5881), 'grblas.Vector.new', 'grblas.Vector.new', (['b2.dtype'], {'size': 'b2.size'}), '(b2.dtype, size=b2.size)\n', (5857, 5881), False, 'import grblas\n'), ((6696, 6755), 'grblas.Matrix.new', 'grblas.Matrix.new', (['a2.dtype'], {'nrows': 'a2.nrows', 'ncols': 'a2.ncols'}), '(a2.dtype, nrows=a2.nrows, ncols=a2.ncols)\n', (6713, 6755), False, 'import grblas\n'), ((6933, 6992), 'grblas.Matrix.new', 'grblas.Matrix.new', (['b2.dtype'], {'nrows': 'b2.nrows', 'ncols': 'b2.ncols'}), '(b2.dtype, nrows=b2.nrows, ncols=b2.ncols)\n', (6950, 6992), False, 'import grblas\n'), ((8974, 9033), 'grblas.Matrix.new', 'grblas.Matrix.new', (['y2.dtype'], {'nrows': 'y2.nrows', 'ncols': 'y2.ncols'}), '(y2.dtype, nrows=y2.nrows, ncols=y2.ncols)\n', (8991, 9033), False, 'import grblas\n'), ((13566, 13612), 'grblas.dtypes.lookup_dtype', 'grblas.dtypes.lookup_dtype', (["xs['values'].dtype"], {}), "(xs['values'].dtype)\n", (13592, 13612), False, 'import grblas\n'), ((13626, 13672), 'grblas.dtypes.lookup_dtype', 'grblas.dtypes.lookup_dtype', (["ys['values'].dtype"], {}), "(ys['values'].dtype)\n", (13652, 13672), False, 'import grblas\n'), ((14536, 14585), 'grblas.Matrix.from_values', 'grblas.Matrix.from_values', (['r_rows', 'r_cols', 'r_vals'], {}), '(r_rows, r_cols, r_vals)\n', (14561, 14585), False, 'import grblas\n'), ((13153, 13251), 'grblas.Matrix.from_values', 'grblas.Matrix.from_values', (['r1_rows', 'r1_cols', 'r1_vals'], {'nrows': 'x.matrix.nrows', 'ncols': '(top_mask + 1)'}), '(r1_rows, r1_cols, r1_vals, nrows=x.matrix.nrows,\n ncols=top_mask + 1)\n', (13178, 13251), False, 'import grblas\n'), ((13327, 13425), 'grblas.Matrix.from_values', 'grblas.Matrix.from_values', (['r2_rows', 'r2_cols', 'r2_vals'], {'nrows': 'x.matrix.nrows', 'ncols': '(top_mask + 1)'}), '(r2_rows, r2_cols, r2_vals, nrows=x.matrix.nrows,\n ncols=top_mask + 1)\n', (13352, 13425), False, 'import grblas\n'), ((13719, 13766), 'grblas.dtypes.lookup_dtype', 'grblas.dtypes.lookup_dtype', (['unified_input_dtype'], {}), '(unified_input_dtype)\n', (13745, 13766), False, 'import grblas\n'), ((14007, 14051), 'grblas.dtypes.lookup_dtype', 'grblas.dtypes.lookup_dtype', (['output_dtype_str'], {}), '(output_dtype_str)\n', (14033, 14051), False, 'import grblas\n')]
import torch import librosa import numpy as np import mlflow.pytorch import torch.nn.functional as F import matplotlib.pyplot as plt from librosa.feature import mfcc def predict(model, x): n_mfcc = 40 sample_rate = 22050 mel_coefficients = mfcc(x, sample_rate, n_mfcc=n_mfcc) time_frames = mel_coefficients.shape[-1] chunks = int(np.ceil(time_frames / 160)) pad_size = (chunks * 160) - time_frames mfcc_pad = np.pad(mel_coefficients, ((0, 0), (0, pad_size)), mode="wrap") mfcc_split = np.split(mfcc_pad, 160, axis=1) mfcc_batch = np.stack(mfcc_split) probabilities = model(torch.FloatTensor(mfcc_batch).to("cuda")) classifications = torch.argmax(probabilities, dim=-1) sequence = torch.reshape(classifications, (1, -1)) original_length = x.size predictions = F.interpolate(sequence.unsqueeze(0).to(torch.float), original_length, mode='linear') predictions = torch.squeeze(predictions).to(torch.int64) return predictions def main(): model_path = "mlruns/0/ec90ba732dec470492d3d6e7089e644b/artifacts/model" model = mlflow.pytorch.load_model(model_path) audio, _ = librosa.load("data/reddit/1vtdusf08us21-DASH_240.wav") predictions = predict(model, audio) predictions = predictions.cpu().detach().numpy() fig, ax = plt.subplots() ax.plot(audio) ax.fill_between(np.arange(len(predictions)), 0, 1, color="green", where=predictions==1, alpha=0.3, transform=ax.get_xaxis_transform()) ax.fill_between(np.arange(len(predictions)), 0, 1, color="red", where=predictions==2, alpha=0.3, transform=ax.get_xaxis_transform()) plt.show() if __name__ == "__main__": main()
[ "numpy.pad", "numpy.stack", "matplotlib.pyplot.show", "numpy.ceil", "torch.argmax", "torch.FloatTensor", "matplotlib.pyplot.subplots", "numpy.split", "torch.squeeze", "librosa.load", "torch.reshape", "librosa.feature.mfcc" ]
[((257, 292), 'librosa.feature.mfcc', 'mfcc', (['x', 'sample_rate'], {'n_mfcc': 'n_mfcc'}), '(x, sample_rate, n_mfcc=n_mfcc)\n', (261, 292), False, 'from librosa.feature import mfcc\n'), ((443, 505), 'numpy.pad', 'np.pad', (['mel_coefficients', '((0, 0), (0, pad_size))'], {'mode': '"""wrap"""'}), "(mel_coefficients, ((0, 0), (0, pad_size)), mode='wrap')\n", (449, 505), True, 'import numpy as np\n'), ((523, 554), 'numpy.split', 'np.split', (['mfcc_pad', '(160)'], {'axis': '(1)'}), '(mfcc_pad, 160, axis=1)\n', (531, 554), True, 'import numpy as np\n'), ((573, 593), 'numpy.stack', 'np.stack', (['mfcc_split'], {}), '(mfcc_split)\n', (581, 593), True, 'import numpy as np\n'), ((684, 719), 'torch.argmax', 'torch.argmax', (['probabilities'], {'dim': '(-1)'}), '(probabilities, dim=-1)\n', (696, 719), False, 'import torch\n'), ((735, 774), 'torch.reshape', 'torch.reshape', (['classifications', '(1, -1)'], {}), '(classifications, (1, -1))\n', (748, 774), False, 'import torch\n'), ((1150, 1204), 'librosa.load', 'librosa.load', (['"""data/reddit/1vtdusf08us21-DASH_240.wav"""'], {}), "('data/reddit/1vtdusf08us21-DASH_240.wav')\n", (1162, 1204), False, 'import librosa\n'), ((1312, 1326), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1324, 1326), True, 'import matplotlib.pyplot as plt\n'), ((1628, 1638), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1636, 1638), True, 'import matplotlib.pyplot as plt\n'), ((355, 381), 'numpy.ceil', 'np.ceil', (['(time_frames / 160)'], {}), '(time_frames / 160)\n', (362, 381), True, 'import numpy as np\n'), ((926, 952), 'torch.squeeze', 'torch.squeeze', (['predictions'], {}), '(predictions)\n', (939, 952), False, 'import torch\n'), ((620, 649), 'torch.FloatTensor', 'torch.FloatTensor', (['mfcc_batch'], {}), '(mfcc_batch)\n', (637, 649), False, 'import torch\n')]
import numpy as np from sklearn.preprocessing import Imputer, StandardScaler from matplotlib import pyplot as plt data = np.load('sample.npy') # Plot raw data. plt.figure(1) plt.plot(data) # Impute missing values. imputer = Imputer() data = imputer.fit_transform(data) plt.figure(2) plt.plot(data) # Scale data. scaler = StandardScaler() data = scaler.fit_transform(data) plt.figure(3) plt.plot(data) plt.show()
[ "numpy.load", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "sklearn.preprocessing.Imputer", "matplotlib.pyplot.figure" ]
[((122, 143), 'numpy.load', 'np.load', (['"""sample.npy"""'], {}), "('sample.npy')\n", (129, 143), True, 'import numpy as np\n'), ((162, 175), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (172, 175), True, 'from matplotlib import pyplot as plt\n'), ((176, 190), 'matplotlib.pyplot.plot', 'plt.plot', (['data'], {}), '(data)\n', (184, 190), True, 'from matplotlib import pyplot as plt\n'), ((227, 236), 'sklearn.preprocessing.Imputer', 'Imputer', ([], {}), '()\n', (234, 236), False, 'from sklearn.preprocessing import Imputer, StandardScaler\n'), ((273, 286), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (283, 286), True, 'from matplotlib import pyplot as plt\n'), ((287, 301), 'matplotlib.pyplot.plot', 'plt.plot', (['data'], {}), '(data)\n', (295, 301), True, 'from matplotlib import pyplot as plt\n'), ((326, 342), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (340, 342), False, 'from sklearn.preprocessing import Imputer, StandardScaler\n'), ((378, 391), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (388, 391), True, 'from matplotlib import pyplot as plt\n'), ((392, 406), 'matplotlib.pyplot.plot', 'plt.plot', (['data'], {}), '(data)\n', (400, 406), True, 'from matplotlib import pyplot as plt\n'), ((408, 418), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (416, 418), True, 'from matplotlib import pyplot as plt\n')]
# 3rd party modules import gym import numpy as np import subprocess import os from gym import spaces from basilisk_env.simulators import opNavSimulator class opNavEnv(gym.Env): """ OpNav scenario. The spacecraft must decide when to point at the ground (which generates a reward) versus pointing at the sun (which increases the sim duration). """ def __init__(self): self.__version__ = "0.0.2" print("Basilisk OpNav Mode Management Sim - Version {}".format(self.__version__)) # General variables defining the environment self.max_length =int(40) # Specify the maximum number of planning intervals # Tell the environment that it doesn't have a sim attribute... self.sim_init = 0 self.simulator = None self.reward_total = 0 # Set up options, constants for this environment self.step_duration = 50. # Set step duration equal to 60 minute self.reward_mult = 1. low = -1e16 high = 1e16 self.observation_space = spaces.Box(low, high,shape=(4,1)) self.obs = np.zeros([4,]) self.debug_states = np.zeros([12,]) ## Action Space description # 0 - earth pointing (mission objective) # 1 - sun pointing (power objective) # 2 - desaturation (required for long-term pointing) self.action_space = spaces.Discrete(2) # Store what the agent tried self.curr_episode = -1 self.action_episode_memory = [] self.curr_step = 0 self.episode_over = False def _seed(self): np.random.seed() return def step(self, action): """ The agent takes a step in the environment. Parameters ---------- action : int Returns ------- ob, reward, episode_over, info : tuple ob (object) : an environment-specific object representing your observation of the environment. reward (float) : amount of reward achieved by the previous action. The scale varies between environments, but the goal is always to increase your total reward. episode_over (bool) : whether it's time to reset the environment again. Most (but not all) tasks are divided up into well-defined episodes, and done being True indicates the episode has terminated. (For example, perhaps the pole tipped too far, or you lost your last life.) info (dict) : diagnostic information useful for debugging. It can sometimes be useful for learning (for example, it might contain the raw probabilities behind the environment's last state change). However, official evaluations of your agent are not allowed to use this for learning. """ if self.sim_init == 0: self.simulator = opNavSimulator.scenario_OpNav(1., 1., self.step_duration) self.sim_init = 1 if self.curr_step%10 == 0: print("At step ", self.curr_step, " of ", self.max_length) if self.curr_step >= self.max_length: self.episode_over = True prev_ob = self._get_state() self._take_action(action) reward = self._get_reward() self.reward_total += reward ob = self._get_state() if self.sim_over: self.episode_over = True print("End of episode") if self.episode_over: info = {'episode':{ 'r': self.reward_total, 'l': self.curr_step}, 'full_states': self.debug_states, 'obs': ob } self.simulator.close_gracefully() # Stop spice from blowing up self.sim_init = 0 else: info={ 'full_states': self.debug_states, 'obs': ob } self.curr_step += 1 return ob, reward, self.episode_over, info def _take_action(self, action): ''' Interfaces with the simulator to :param action: :return: ''' self.action_episode_memory[self.curr_episode].append(action) # Let the simulator handle action management: self.obs, self.debug_states, self.sim_over = self.simulator.run_sim(action) def _get_reward(self): """ Reward is based on time spent with the inertial attitude pointed towards the ground within a given tolerance. """ reward = 0 real = np.array([self.debug_states[3],self.debug_states[4], self.debug_states[5]]) nav = np.array([self.debug_states[0],self.debug_states[1], self.debug_states[2]]) nav -= real nav *= 1./np.linalg.norm(real) if self.action_episode_memory[self.curr_episode][-1] == 1: reward = np.linalg.norm(self.reward_mult / (1. + np.linalg.norm(nav)**2.0)) return reward def reset(self): """ Reset the state of the environment and returns an initial observation. Returns ------- observation (object): the initial observation of the space. """ self.action_episode_memory.append([]) self.episode_over = False self.curr_step = 0 self.reward_total = 0 self.simulator = opNavSimulator.scenario_OpNav(1., 1., self.step_duration) self.sim_init=1 return self.simulator.obs def _render(self, mode='human', close=False): return def _get_state(self): """Get the observation. WIP: Work out which error representation to give the algo.""" return self.simulator.obs
[ "numpy.random.seed", "basilisk_env.simulators.opNavSimulator.scenario_OpNav", "gym.spaces.Discrete", "numpy.zeros", "numpy.array", "gym.spaces.Box", "numpy.linalg.norm" ]
[((1050, 1085), 'gym.spaces.Box', 'spaces.Box', (['low', 'high'], {'shape': '(4, 1)'}), '(low, high, shape=(4, 1))\n', (1060, 1085), False, 'from gym import spaces\n'), ((1103, 1116), 'numpy.zeros', 'np.zeros', (['[4]'], {}), '([4])\n', (1111, 1116), True, 'import numpy as np\n'), ((1146, 1160), 'numpy.zeros', 'np.zeros', (['[12]'], {}), '([12])\n', (1154, 1160), True, 'import numpy as np\n'), ((1389, 1407), 'gym.spaces.Discrete', 'spaces.Discrete', (['(2)'], {}), '(2)\n', (1404, 1407), False, 'from gym import spaces\n'), ((1608, 1624), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (1622, 1624), True, 'import numpy as np\n'), ((4719, 4795), 'numpy.array', 'np.array', (['[self.debug_states[3], self.debug_states[4], self.debug_states[5]]'], {}), '([self.debug_states[3], self.debug_states[4], self.debug_states[5]])\n', (4727, 4795), True, 'import numpy as np\n'), ((4809, 4885), 'numpy.array', 'np.array', (['[self.debug_states[0], self.debug_states[1], self.debug_states[2]]'], {}), '([self.debug_states[0], self.debug_states[1], self.debug_states[2]])\n', (4817, 4885), True, 'import numpy as np\n'), ((5510, 5569), 'basilisk_env.simulators.opNavSimulator.scenario_OpNav', 'opNavSimulator.scenario_OpNav', (['(1.0)', '(1.0)', 'self.step_duration'], {}), '(1.0, 1.0, self.step_duration)\n', (5539, 5569), False, 'from basilisk_env.simulators import opNavSimulator\n'), ((3045, 3104), 'basilisk_env.simulators.opNavSimulator.scenario_OpNav', 'opNavSimulator.scenario_OpNav', (['(1.0)', '(1.0)', 'self.step_duration'], {}), '(1.0, 1.0, self.step_duration)\n', (3074, 3104), False, 'from basilisk_env.simulators import opNavSimulator\n'), ((4923, 4943), 'numpy.linalg.norm', 'np.linalg.norm', (['real'], {}), '(real)\n', (4937, 4943), True, 'import numpy as np\n'), ((5073, 5092), 'numpy.linalg.norm', 'np.linalg.norm', (['nav'], {}), '(nav)\n', (5087, 5092), True, 'import numpy as np\n')]
import os import random import sys import numpy as np import pytest sys.path.append(os.path.join(os.path.dirname(__file__))) sys.path.append("\\".join(os.path.dirname(__file__).split("\\")[:-2])) sys.path.append(os.path.join(os.path.dirname(__file__), "../../")) from src.distributed_reflectors.reflector import Reflector SEED = 0 PI = np.pi straight_collision_and_clear_miss = ( np.array([[-3, 0, 0], [-3, 0, PI / 2]]), 1.0, np.array([0, 0, PI / 2]), np.array([1, 0]), np.array([[0, 0, PI], [-3, 0, PI / 2]]), ) barely_misses = ( np.array([[-1.0, 0, PI / 4], [-1.0, 0, -PI / 4]]), 1.0, np.array([0, 0, PI / 2]), np.array([0, 0]), np.array([[-1.0, 0, PI / 4], [-1.0, 0, -PI / 4]]), ) near_misses_but_hit = ( np.array([[-0.99, 0, PI / 4], [-0.99, 0, -PI / 4]]), 1.0, np.array([0, 0, PI / 2]), np.array([1, 1]), np.array([[0.0, 0.99, 3 * PI / 4], [0.0, -0.99, 5 * PI / 4]]), ) hit = ( np.array([[-np.sqrt(3) / 2, 0, PI / 6], [-np.sqrt(3) / 2, 0, -PI / 6]]), 1.0, np.array([0, 0, PI / 2]), np.array([1, 1]), np.array([[0, 0.5, 5 * PI / 6], [0.0, -0.5, 7 * PI / 6]]), ) def test_reflector_instantiation(): length = 2.0 coordinates = 5 * np.random.randn(3) reflector = Reflector(length, coordinates) assert isinstance(reflector, Reflector) assert 0 <= reflector.angle <= np.pi @pytest.mark.parametrize( "particle_coordinates,length,reflector_coordinates,expected_collisions,expected_new_coordinates", [straight_collision_and_clear_miss, barely_misses, near_misses_but_hit, hit], ) def test_correct_collision_detections( particle_coordinates, length, reflector_coordinates, expected_collisions, expected_new_coordinates, ): reflector = Reflector(length, reflector_coordinates) collisions = reflector.will_collide(particle_coordinates) np.testing.assert_equal(collisions, expected_collisions) @pytest.mark.parametrize( "particle_coordinates,length,reflector_coordinates,expected_collisions,expected_new_coordinates", [straight_collision_and_clear_miss, barely_misses, near_misses_but_hit, hit], ) def test_correct_collision_coordinates( particle_coordinates, length, reflector_coordinates, expected_collisions, expected_new_coordinates, ): reflector = Reflector(length, reflector_coordinates) particle_collisions = reflector.will_collide(particle_coordinates) new_coordinates = reflector.get_new_coordinates( particle_coordinates, particle_collisions ) np.testing.assert_allclose(new_coordinates, expected_new_coordinates, atol=10 ** -5)
[ "src.distributed_reflectors.reflector.Reflector", "numpy.random.randn", "os.path.dirname", "numpy.testing.assert_allclose", "numpy.array", "numpy.testing.assert_equal", "pytest.mark.parametrize", "numpy.sqrt" ]
[((1387, 1600), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""particle_coordinates,length,reflector_coordinates,expected_collisions,expected_new_coordinates"""', '[straight_collision_and_clear_miss, barely_misses, near_misses_but_hit, hit]'], {}), "(\n 'particle_coordinates,length,reflector_coordinates,expected_collisions,expected_new_coordinates'\n , [straight_collision_and_clear_miss, barely_misses,\n near_misses_but_hit, hit])\n", (1410, 1600), False, 'import pytest\n'), ((1945, 2158), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""particle_coordinates,length,reflector_coordinates,expected_collisions,expected_new_coordinates"""', '[straight_collision_and_clear_miss, barely_misses, near_misses_but_hit, hit]'], {}), "(\n 'particle_coordinates,length,reflector_coordinates,expected_collisions,expected_new_coordinates'\n , [straight_collision_and_clear_miss, barely_misses,\n near_misses_but_hit, hit])\n", (1968, 2158), False, 'import pytest\n'), ((391, 430), 'numpy.array', 'np.array', (['[[-3, 0, 0], [-3, 0, PI / 2]]'], {}), '([[-3, 0, 0], [-3, 0, PI / 2]])\n', (399, 430), True, 'import numpy as np\n'), ((445, 469), 'numpy.array', 'np.array', (['[0, 0, PI / 2]'], {}), '([0, 0, PI / 2])\n', (453, 469), True, 'import numpy as np\n'), ((475, 491), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (483, 491), True, 'import numpy as np\n'), ((497, 536), 'numpy.array', 'np.array', (['[[0, 0, PI], [-3, 0, PI / 2]]'], {}), '([[0, 0, PI], [-3, 0, PI / 2]])\n', (505, 536), True, 'import numpy as np\n'), ((563, 612), 'numpy.array', 'np.array', (['[[-1.0, 0, PI / 4], [-1.0, 0, -PI / 4]]'], {}), '([[-1.0, 0, PI / 4], [-1.0, 0, -PI / 4]])\n', (571, 612), True, 'import numpy as np\n'), ((627, 651), 'numpy.array', 'np.array', (['[0, 0, PI / 2]'], {}), '([0, 0, PI / 2])\n', (635, 651), True, 'import numpy as np\n'), ((657, 673), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (665, 673), True, 'import numpy as np\n'), ((679, 728), 'numpy.array', 'np.array', (['[[-1.0, 0, PI / 4], [-1.0, 0, -PI / 4]]'], {}), '([[-1.0, 0, PI / 4], [-1.0, 0, -PI / 4]])\n', (687, 728), True, 'import numpy as np\n'), ((761, 812), 'numpy.array', 'np.array', (['[[-0.99, 0, PI / 4], [-0.99, 0, -PI / 4]]'], {}), '([[-0.99, 0, PI / 4], [-0.99, 0, -PI / 4]])\n', (769, 812), True, 'import numpy as np\n'), ((827, 851), 'numpy.array', 'np.array', (['[0, 0, PI / 2]'], {}), '([0, 0, PI / 2])\n', (835, 851), True, 'import numpy as np\n'), ((857, 873), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (865, 873), True, 'import numpy as np\n'), ((879, 940), 'numpy.array', 'np.array', (['[[0.0, 0.99, 3 * PI / 4], [0.0, -0.99, 5 * PI / 4]]'], {}), '([[0.0, 0.99, 3 * PI / 4], [0.0, -0.99, 5 * PI / 4]])\n', (887, 940), True, 'import numpy as np\n'), ((1043, 1067), 'numpy.array', 'np.array', (['[0, 0, PI / 2]'], {}), '([0, 0, PI / 2])\n', (1051, 1067), True, 'import numpy as np\n'), ((1073, 1089), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (1081, 1089), True, 'import numpy as np\n'), ((1095, 1152), 'numpy.array', 'np.array', (['[[0, 0.5, 5 * PI / 6], [0.0, -0.5, 7 * PI / 6]]'], {}), '([[0, 0.5, 5 * PI / 6], [0.0, -0.5, 7 * PI / 6]])\n', (1103, 1152), True, 'import numpy as np\n'), ((1268, 1298), 'src.distributed_reflectors.reflector.Reflector', 'Reflector', (['length', 'coordinates'], {}), '(length, coordinates)\n', (1277, 1298), False, 'from src.distributed_reflectors.reflector import Reflector\n'), ((1777, 1817), 'src.distributed_reflectors.reflector.Reflector', 'Reflector', (['length', 'reflector_coordinates'], {}), '(length, reflector_coordinates)\n', (1786, 1817), False, 'from src.distributed_reflectors.reflector import Reflector\n'), ((1885, 1941), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['collisions', 'expected_collisions'], {}), '(collisions, expected_collisions)\n', (1908, 1941), True, 'import numpy as np\n'), ((2336, 2376), 'src.distributed_reflectors.reflector.Reflector', 'Reflector', (['length', 'reflector_coordinates'], {}), '(length, reflector_coordinates)\n', (2345, 2376), False, 'from src.distributed_reflectors.reflector import Reflector\n'), ((2562, 2651), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['new_coordinates', 'expected_new_coordinates'], {'atol': '(10 ** -5)'}), '(new_coordinates, expected_new_coordinates, atol=\n 10 ** -5)\n', (2588, 2651), True, 'import numpy as np\n'), ((99, 124), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (114, 124), False, 'import os\n'), ((227, 252), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (242, 252), False, 'import os\n'), ((1233, 1251), 'numpy.random.randn', 'np.random.randn', (['(3)'], {}), '(3)\n', (1248, 1251), True, 'import numpy as np\n'), ((153, 178), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (168, 178), False, 'import os\n'), ((969, 979), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (976, 979), True, 'import numpy as np\n'), ((999, 1009), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (1006, 1009), True, 'import numpy as np\n')]
import random from typing import List, Tuple, Union import numpy as np from srl.base.define import ContinuousAction, DiscreteAction, DiscreteSpaceType, RLObservation from srl.base.env.spaces.box import BoxSpace class ArrayContinuousSpace(BoxSpace): def __init__( self, size: int, low: Union[float, np.ndarray] = -np.inf, high: Union[float, np.ndarray] = np.inf, ) -> None: self._size = size super().__init__((self.size,), low, high) @property def size(self): return self._size def sample(self, invalid_actions: List[DiscreteSpaceType] = []) -> List[float]: return super().sample(invalid_actions).tolist() # --- action discrete def get_action_discrete_info(self) -> int: return self._n def action_discrete_encode(self, val: List[float]) -> DiscreteAction: raise NotImplementedError def action_discrete_decode(self, val: DiscreteAction) -> List[float]: return super().action_discrete_decode(val).tolist() # --- action continuous def get_action_continuous_info(self) -> Tuple[int, np.ndarray, np.ndarray]: return super().get_action_continuous_info() # def action_continuous_encode(self, val: float) -> ContinuousAction: # raise NotImplementedError def action_continuous_decode(self, val: ContinuousAction) -> List[float]: return val # --- observation discrete def get_observation_discrete_info(self) -> Tuple[Tuple[int, ...], np.ndarray, np.ndarray]: return super().get_observation_discrete_info() def observation_discrete_encode(self, val: List[float]) -> RLObservation: return super().observation_discrete_encode(np.asarray(val)) # --- observation continuous def get_observation_continuous_info(self) -> Tuple[Tuple[int, ...], np.ndarray, np.ndarray]: return super().get_observation_continuous_info() def observation_continuous_encode(self, val: List[float]) -> RLObservation: return super().observation_continuous_encode(np.asarray(val))
[ "numpy.asarray" ]
[((1716, 1731), 'numpy.asarray', 'np.asarray', (['val'], {}), '(val)\n', (1726, 1731), True, 'import numpy as np\n'), ((2055, 2070), 'numpy.asarray', 'np.asarray', (['val'], {}), '(val)\n', (2065, 2070), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import collections import glob import os import pandas as pd import numpy as np import torch.nn.functional as F import PIL.Image as Image from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params from inference.metrics.fid.fid_score import _compute_statistics_of_images, \ calculate_frechet_distance from inference.metrics.fid.inception import InceptionV3 from inference.metrics.lpips import LPIPSLossWrapper from inference.perspective import load_video_frames_from_folder, FlowPredictor from inference.segmentation import SegmentationModule from inference.encode_and_animate import calc_segmentation_posterior_error, sum_dicts from inference.metrics.ssim import SSIM import constants MOVABLE_CLASSES = [2, 21] def calc_optical_flow_metrics(flow_predictor, frames, movable_mask): if not movable_mask.any(): return dict(flow_l2=float('nan')) assert not (frames < 0).any() and not (frames > 1).any() flows = flow_predictor.predict_flow(frames * 2 - 1)[1] flows_x, flows_y = flows[:, [0]], flows[:, [1]] flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean()) flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean()) result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5) return result def batch2pil(batch): np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu().numpy().astype('uint8') return [Image.fromarray(ar) for ar in np_batch] def main(args): segmentation_network = SegmentationModule(os.path.expandvars(args.segm_network)).cuda() segmentation_network.eval() lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda() flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network)) all_metrics = [] all_metrics_idx = [] # load generated images gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.gen_images), '*.jpg'))) gen_frames_as_img = [] for fname in gen_frame_paths: frame = Image.open(fname).convert('RGB') frame_batch = image2batch(frame).cuda() / 2 + 0.5 assert not (frame_batch < 0).any() and not (frame_batch > 1).any() frame_img = batch2pil(frame_batch)[0] gen_frames_as_img.append(frame_img) # load gt-images, scale, crop and segment gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.gt_images), '*.jpg'))) gt_frames_as_img = [] for fname in gt_frame_paths: frame = Image.open(fname).convert('RGB') frame = frame.resize(get_scale_size(args.resolution, frame.size)) frame_batch = image2batch(frame).cuda() / 2 + 0.5 assert not (frame_batch < 0).any() and not (frame_batch > 1).any() scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:]) frame_batch = F.interpolate(frame_batch, size=scaled_size, mode='bilinear', align_corners=False) crop_y1, crop_y2, crop_x1, crop_x2 = choose_center_full_size_crop_params(*frame_batch.shape[2:]) frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2] frame_img = batch2pil(frame_batch)[0] gt_frames_as_img.append(frame_img) # compute FID between generated images and gt print('Calculating FID for images...') block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048] fid_model = InceptionV3([block_idx]).cuda() fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img, fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False) fid_gen_means, fid_gen_std = _compute_statistics_of_images(gen_frames_as_img, fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False) fid = dict() fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means, fid_gt_std, fid_gen_means, fid_gen_std)) # load generated videos for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))): if not os.path.isdir(src_path): continue print(f'Processing {src_path}') if src_path.endswith('/'): src_path = src_path[:-1] vname = os.path.basename(src_path) frames = load_video_frames_from_folder(src_path, frame_template=args.frametemplate) / 2 + 0.5 assert not (frames < 0).any() and not (frames > 1).any() # get mask from the first frame cur_segm_scores = segmentation_network.predict(frames[:1].cuda(), imgSizes=[args.resolution]) cur_segm_proba = F.softmax(cur_segm_scores, dim=1) movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True)[0] immovable_scores = cur_segm_proba[:, [c for c in range(cur_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(1, keepdim=True)[0] shift_mask = (movable_scores > immovable_scores).float() print('Flow metrics...') flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, shift_mask > 0) print('LPIPS metrics...') cur_metrics = collections.defaultdict(float) lpips = [] for l in range(1, frames.shape[0], args.batch): r = min(l + args.batch, frames.shape[0]) lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 - shift_mask), frames[0].cuda() * (1 - shift_mask)))) cur_metrics['lpips_gen'] = np.mean(lpips) sum_dicts(cur_metrics, flow_metrics) all_metrics.append(cur_metrics) all_metrics_idx.append(vname) # load real images, from which the videos were generated, scale, crop and segment real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.real_images), '*.jpg'))) real_frames_as_img = [] real_frames_with_segm = {} for fname in real_frame_paths: frame = Image.open(fname).convert('RGB') frame = frame.resize(get_scale_size(args.resolution, frame.size)) # check the interval of stored numbers: 0..1 || -1..1 || 0..255 frame_batch = image2batch(frame).cuda() frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max() - frame_batch.min()) assert not (frame_batch < 0).any() and not (frame_batch > 1).any() scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:]) frame_batch = F.interpolate(frame_batch, size=scaled_size, mode='bilinear', align_corners=False) crop_y1, crop_y2, crop_x1, crop_x2 = choose_center_full_size_crop_params(*frame_batch.shape[2:]) frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2] frame_img = batch2pil(frame_batch)[0] real_frames_as_img.append(frame_img) cur_segm_scores = segmentation_network.predict(frame_batch, imgSizes=[args.resolution]) cur_segm_proba = F.softmax(cur_segm_scores, dim=1) f_id = os.path.splitext(os.path.basename(fname))[0] real_frames_with_segm[f_id] = (frame_batch, cur_segm_proba) # load videos -- animated real images animated_frames_by_i = collections.defaultdict(list) for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))): if not os.path.isdir(src_path): continue print(f'Processing {src_path}') if src_path.endswith('/'): src_path = src_path[:-1] vname = os.path.basename(src_path) frames = load_video_frames_from_folder(src_path, frame_template=args.frametemplate) / 2 + 0.5 assert not (frames < 0).any() and not (frames > 1).any() for i, fr in enumerate(batch2pil(frames)): animated_frames_by_i[i].append(fr) cur_real_frame = None cur_real_segm_proba = None for frname, (fr, segm) in real_frames_with_segm.items(): if vname.startswith(frname): cur_real_frame = fr cur_real_segm_proba = segm break assert cur_real_frame is not None, (vname, real_frames_with_segm.keys()) movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True)[0] immovable_scores = cur_real_segm_proba[:, [c for c in range(cur_real_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(1, keepdim=True)[0] shift_mask = (movable_scores > immovable_scores).float() print('Flow metrics...') flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, shift_mask > 0) print('LPIPS metrics...') cur_metrics = collections.defaultdict(float) cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1], cur_real_frame)) lpips = [] for l in range(0, frames.shape[0], args.batch): r = min(l + args.batch, frames.shape[0]) lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 - shift_mask), cur_real_frame.cuda() * (1 - shift_mask)))) cur_metrics['lpips_anim'] = np.mean(lpips) sum_dicts(cur_metrics, flow_metrics) all_metrics.append(cur_metrics) all_metrics_idx.append(vname) print('Calculating FID...') block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048] fid_model = InceptionV3([block_idx]).cuda() fid_real_means, fid_real_std = _compute_statistics_of_images(real_frames_as_img, fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False) for i, cur_gen_frames in animated_frames_by_i.items(): if i % args.skipframe != 0: continue cur_fid_means, cur_fid_std = _compute_statistics_of_images(cur_gen_frames, fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False) fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means, fid_real_std, cur_fid_means, cur_fid_std)) all_metrics.append(fid) all_metrics_idx.append('global_metrics') os.makedirs(os.path.dirname(args.outpath), exist_ok=True) sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx) sum_metrics.to_csv(args.outpath, sep='\t') if __name__ == '__main__': import argparse aparser = argparse.ArgumentParser() aparser.add_argument('--outpath', type=str, default='results/metrics.csv', help='Path to file to write metrics to') aparser.add_argument('--gen-images', type=str, default='results/generated/256/images', help='Path to generated images') aparser.add_argument('--gt-images', type=str, default='results/gt_images', help='Path to gt-images') aparser.add_argument('--gen-videos', type=str, default='results/generated/256/noise', help='Path to generated videos (separate folder with frames for each video)') aparser.add_argument('--animated-images', type=str, default='results/encode_and_animate_results/test_images/02_eoif', help='Path to animated images (separate folder with frames for each video)') aparser.add_argument('--real-images', type=str, default='results/test_images', help='Path to real input images') aparser.add_argument('--frametemplate', type=str, default='{:05}.jpg', help='Template to generate frame file names') aparser.add_argument('--resolution', type=int, default=256, help='Resolution of generated frames') aparser.add_argument('--skipframe', type=int, default=10, help='How many frames to skip before evaluating FID') aparser.add_argument('--batch', type=int, default=69, help='Batch size for FID and LPIPS calculation') aparser.add_argument('--segm-network', type=str, default=os.path.join(constants.RESULT_DIR, 'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'), help='Path to ade20k-resnet50dilated-ppm_deepsup') aparser.add_argument('--flow-network', type=str, default=os.path.join(constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'), help='Path to SuperSloMo.ckpt') aparser.add_argument('--lpips-network', type=str, default=os.path.join(constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'), help='Path to vgg.pth') main(aparser.parse_args())
[ "inference.base_image_utils.image2batch", "inference.perspective.load_video_frames_from_folder", "argparse.ArgumentParser", "collections.defaultdict", "numpy.mean", "inference.encode_and_animate.sum_dicts", "os.path.join", "pandas.DataFrame", "inference.base_image_utils.get_scale_size", "os.path.dirname", "inference.metrics.fid.inception.InceptionV3", "os.path.basename", "os.path.expandvars", "inference.base_image_utils.choose_center_full_size_crop_params", "os.path.isdir", "inference.metrics.fid.fid_score._compute_statistics_of_images", "torch.nn.functional.softmax", "PIL.Image.open", "inference.metrics.lpips.LPIPSLossWrapper", "PIL.Image.fromarray", "torch.nn.functional.interpolate", "inference.metrics.fid.fid_score.calculate_frechet_distance" ]
[((3471, 3596), 'inference.metrics.fid.fid_score._compute_statistics_of_images', '_compute_statistics_of_images', (['gt_frames_as_img', 'fid_model'], {'batch_size': 'args.batch', 'dims': '(2048)', 'cuda': '(True)', 'keep_size': '(False)'}), '(gt_frames_as_img, fid_model, batch_size=args.\n batch, dims=2048, cuda=True, keep_size=False)\n', (3500, 3596), False, 'from inference.metrics.fid.fid_score import _compute_statistics_of_images, calculate_frechet_distance\n'), ((3747, 3873), 'inference.metrics.fid.fid_score._compute_statistics_of_images', '_compute_statistics_of_images', (['gen_frames_as_img', 'fid_model'], {'batch_size': 'args.batch', 'dims': '(2048)', 'cuda': '(True)', 'keep_size': '(False)'}), '(gen_frames_as_img, fid_model, batch_size=args\n .batch, dims=2048, cuda=True, keep_size=False)\n', (3776, 3873), False, 'from inference.metrics.fid.fid_score import _compute_statistics_of_images, calculate_frechet_distance\n'), ((7309, 7338), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (7332, 7338), False, 'import collections\n'), ((9520, 9647), 'inference.metrics.fid.fid_score._compute_statistics_of_images', '_compute_statistics_of_images', (['real_frames_as_img', 'fid_model'], {'batch_size': 'args.batch', 'dims': '(2048)', 'cuda': '(True)', 'keep_size': '(False)'}), '(real_frames_as_img, fid_model, batch_size=\n args.batch, dims=2048, cuda=True, keep_size=False)\n', (9549, 9647), False, 'from inference.metrics.fid.fid_score import _compute_statistics_of_images, calculate_frechet_distance\n'), ((10516, 10564), 'pandas.DataFrame', 'pd.DataFrame', (['all_metrics'], {'index': 'all_metrics_idx'}), '(all_metrics, index=all_metrics_idx)\n', (10528, 10564), True, 'import pandas as pd\n'), ((10676, 10701), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10699, 10701), False, 'import argparse\n'), ((1504, 1523), 'PIL.Image.fromarray', 'Image.fromarray', (['ar'], {}), '(ar)\n', (1519, 1523), True, 'import PIL.Image as Image\n'), ((1788, 1825), 'os.path.expandvars', 'os.path.expandvars', (['args.flow_network'], {}), '(args.flow_network)\n', (1806, 1825), False, 'import os\n'), ((2815, 2869), 'inference.base_image_utils.get_scale_size', 'get_scale_size', (['args.resolution', 'frame_batch.shape[2:]'], {}), '(args.resolution, frame_batch.shape[2:])\n', (2829, 2869), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n'), ((2892, 2979), 'torch.nn.functional.interpolate', 'F.interpolate', (['frame_batch'], {'size': 'scaled_size', 'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(frame_batch, size=scaled_size, mode='bilinear', align_corners\n =False)\n", (2905, 2979), True, 'import torch.nn.functional as F\n'), ((3021, 3080), 'inference.base_image_utils.choose_center_full_size_crop_params', 'choose_center_full_size_crop_params', (['*frame_batch.shape[2:]'], {}), '(*frame_batch.shape[2:])\n', (3056, 3080), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n'), ((4042, 4127), 'inference.metrics.fid.fid_score.calculate_frechet_distance', 'calculate_frechet_distance', (['fid_gt_means', 'fid_gt_std', 'fid_gen_means', 'fid_gen_std'], {}), '(fid_gt_means, fid_gt_std, fid_gen_means, fid_gen_std\n )\n', (4068, 4127), False, 'from inference.metrics.fid.fid_score import _compute_statistics_of_images, calculate_frechet_distance\n'), ((4418, 4444), 'os.path.basename', 'os.path.basename', (['src_path'], {}), '(src_path)\n', (4434, 4444), False, 'import os\n'), ((4780, 4813), 'torch.nn.functional.softmax', 'F.softmax', (['cur_segm_scores'], {'dim': '(1)'}), '(cur_segm_scores, dim=1)\n', (4789, 4813), True, 'import torch.nn.functional as F\n'), ((5345, 5375), 'collections.defaultdict', 'collections.defaultdict', (['float'], {}), '(float)\n', (5368, 5375), False, 'import collections\n'), ((5664, 5678), 'numpy.mean', 'np.mean', (['lpips'], {}), '(lpips)\n', (5671, 5678), True, 'import numpy as np\n'), ((5687, 5723), 'inference.encode_and_animate.sum_dicts', 'sum_dicts', (['cur_metrics', 'flow_metrics'], {}), '(cur_metrics, flow_metrics)\n', (5696, 5723), False, 'from inference.encode_and_animate import calc_segmentation_posterior_error, sum_dicts\n'), ((6523, 6577), 'inference.base_image_utils.get_scale_size', 'get_scale_size', (['args.resolution', 'frame_batch.shape[2:]'], {}), '(args.resolution, frame_batch.shape[2:])\n', (6537, 6577), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n'), ((6600, 6687), 'torch.nn.functional.interpolate', 'F.interpolate', (['frame_batch'], {'size': 'scaled_size', 'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(frame_batch, size=scaled_size, mode='bilinear', align_corners\n =False)\n", (6613, 6687), True, 'import torch.nn.functional as F\n'), ((6729, 6788), 'inference.base_image_utils.choose_center_full_size_crop_params', 'choose_center_full_size_crop_params', (['*frame_batch.shape[2:]'], {}), '(*frame_batch.shape[2:])\n', (6764, 6788), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n'), ((7077, 7110), 'torch.nn.functional.softmax', 'F.softmax', (['cur_segm_scores'], {'dim': '(1)'}), '(cur_segm_scores, dim=1)\n', (7086, 7110), True, 'import torch.nn.functional as F\n'), ((7610, 7636), 'os.path.basename', 'os.path.basename', (['src_path'], {}), '(src_path)\n', (7626, 7636), False, 'import os\n'), ((8795, 8825), 'collections.defaultdict', 'collections.defaultdict', (['float'], {}), '(float)\n', (8818, 8825), False, 'import collections\n'), ((9211, 9225), 'numpy.mean', 'np.mean', (['lpips'], {}), '(lpips)\n', (9218, 9225), True, 'import numpy as np\n'), ((9235, 9271), 'inference.encode_and_animate.sum_dicts', 'sum_dicts', (['cur_metrics', 'flow_metrics'], {}), '(cur_metrics, flow_metrics)\n', (9244, 9271), False, 'from inference.encode_and_animate import calc_segmentation_posterior_error, sum_dicts\n'), ((9926, 10049), 'inference.metrics.fid.fid_score._compute_statistics_of_images', '_compute_statistics_of_images', (['cur_gen_frames', 'fid_model'], {'batch_size': 'args.batch', 'dims': '(2048)', 'cuda': '(True)', 'keep_size': '(False)'}), '(cur_gen_frames, fid_model, batch_size=args.\n batch, dims=2048, cuda=True, keep_size=False)\n', (9955, 10049), False, 'from inference.metrics.fid.fid_score import _compute_statistics_of_images, calculate_frechet_distance\n'), ((10452, 10481), 'os.path.dirname', 'os.path.dirname', (['args.outpath'], {}), '(args.outpath)\n', (10467, 10481), False, 'import os\n'), ((1709, 1745), 'inference.metrics.lpips.LPIPSLossWrapper', 'LPIPSLossWrapper', (['args.lpips_network'], {}), '(args.lpips_network)\n', (1725, 1745), False, 'from inference.metrics.lpips import LPIPSLossWrapper\n'), ((2614, 2657), 'inference.base_image_utils.get_scale_size', 'get_scale_size', (['args.resolution', 'frame.size'], {}), '(args.resolution, frame.size)\n', (2628, 2657), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n'), ((3408, 3432), 'inference.metrics.fid.inception.InceptionV3', 'InceptionV3', (['[block_idx]'], {}), '([block_idx])\n', (3419, 3432), False, 'from inference.metrics.fid.inception import InceptionV3\n'), ((4190, 4224), 'os.path.join', 'os.path.join', (['args.gen_videos', '"""*"""'], {}), "(args.gen_videos, '*')\n", (4202, 4224), False, 'import os\n'), ((4243, 4266), 'os.path.isdir', 'os.path.isdir', (['src_path'], {}), '(src_path)\n', (4256, 4266), False, 'import os\n'), ((6162, 6205), 'inference.base_image_utils.get_scale_size', 'get_scale_size', (['args.resolution', 'frame.size'], {}), '(args.resolution, frame.size)\n', (6176, 6205), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n'), ((7377, 7416), 'os.path.join', 'os.path.join', (['args.animated_images', '"""*"""'], {}), "(args.animated_images, '*')\n", (7389, 7416), False, 'import os\n'), ((7435, 7458), 'os.path.isdir', 'os.path.isdir', (['src_path'], {}), '(src_path)\n', (7448, 7458), False, 'import os\n'), ((9453, 9477), 'inference.metrics.fid.inception.InceptionV3', 'InceptionV3', (['[block_idx]'], {}), '([block_idx])\n', (9464, 9477), False, 'from inference.metrics.fid.inception import InceptionV3\n'), ((10211, 10299), 'inference.metrics.fid.fid_score.calculate_frechet_distance', 'calculate_frechet_distance', (['fid_real_means', 'fid_real_std', 'cur_fid_means', 'cur_fid_std'], {}), '(fid_real_means, fid_real_std, cur_fid_means,\n cur_fid_std)\n', (10237, 10299), False, 'from inference.metrics.fid.fid_score import _compute_statistics_of_images, calculate_frechet_distance\n'), ((12195, 12289), 'os.path.join', 'os.path.join', (['constants.RESULT_DIR', '"""pretrained_models/ade20k-resnet50dilated-ppm_deepsup"""'], {}), "(constants.RESULT_DIR,\n 'pretrained_models/ade20k-resnet50dilated-ppm_deepsup')\n", (12207, 12289), False, 'import os\n'), ((12449, 12520), 'os.path.join', 'os.path.join', (['constants.RESULT_DIR', '"""pretrained_models/SuperSloMo.ckpt"""'], {}), "(constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt')\n", (12461, 12520), False, 'import os\n'), ((12666, 12742), 'os.path.join', 'os.path.join', (['constants.RESULT_DIR', '"""pretrained_models/lpips_models/vgg.pth"""'], {}), "(constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth')\n", (12678, 12742), False, 'import os\n'), ((1608, 1645), 'os.path.expandvars', 'os.path.expandvars', (['args.segm_network'], {}), '(args.segm_network)\n', (1626, 1645), False, 'import os\n'), ((1953, 1988), 'os.path.expandvars', 'os.path.expandvars', (['args.gen_images'], {}), '(args.gen_images)\n', (1971, 1988), False, 'import os\n'), ((2078, 2095), 'PIL.Image.open', 'Image.open', (['fname'], {}), '(fname)\n', (2088, 2095), True, 'import PIL.Image as Image\n'), ((2430, 2464), 'os.path.expandvars', 'os.path.expandvars', (['args.gt_images'], {}), '(args.gt_images)\n', (2448, 2464), False, 'import os\n'), ((2552, 2569), 'PIL.Image.open', 'Image.open', (['fname'], {}), '(fname)\n', (2562, 2569), True, 'import PIL.Image as Image\n'), ((4462, 4536), 'inference.perspective.load_video_frames_from_folder', 'load_video_frames_from_folder', (['src_path'], {'frame_template': 'args.frametemplate'}), '(src_path, frame_template=args.frametemplate)\n', (4491, 4536), False, 'from inference.perspective import load_video_frames_from_folder, FlowPredictor\n'), ((5941, 5977), 'os.path.expandvars', 'os.path.expandvars', (['args.real_images'], {}), '(args.real_images)\n', (5959, 5977), False, 'import os\n'), ((6100, 6117), 'PIL.Image.open', 'Image.open', (['fname'], {}), '(fname)\n', (6110, 6117), True, 'import PIL.Image as Image\n'), ((6302, 6320), 'inference.base_image_utils.image2batch', 'image2batch', (['frame'], {}), '(frame)\n', (6313, 6320), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n'), ((7143, 7166), 'os.path.basename', 'os.path.basename', (['fname'], {}), '(fname)\n', (7159, 7166), False, 'import os\n'), ((7654, 7728), 'inference.perspective.load_video_frames_from_folder', 'load_video_frames_from_folder', (['src_path'], {'frame_template': 'args.frametemplate'}), '(src_path, frame_template=args.frametemplate)\n', (7683, 7728), False, 'from inference.perspective import load_video_frames_from_folder, FlowPredictor\n'), ((2133, 2151), 'inference.base_image_utils.image2batch', 'image2batch', (['frame'], {}), '(frame)\n', (2144, 2151), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n'), ((2682, 2700), 'inference.base_image_utils.image2batch', 'image2batch', (['frame'], {}), '(frame)\n', (2693, 2700), False, 'from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\n')]
import numpy as np def CheckScore(board): Win = Loss = Tie = False zeros = np.where(board == 0) if np.all(board[0,0:3] == 1) or np.all(board[1,0:3] == 1) or np.all(board[2,0:3] == 1): Win = True elif np.all(board[0:3,0] == 1) or np.all(board[0:3,1] == 1) or np.all(board[0:3,2] == 1): Win = True elif board[0,0] == 1 and board[1,1] == 1 and board[2,2] == 1: Win = True elif board[2,0] == 1 and board[1,1] == 1 and board[0,2] == 1: Win = True elif np.all(board[0,0:3] == 2) or np.all(board[1,0:3] == 2) or np.all(board[2,0:3] == 2): Loss = True elif np.all(board[0:3,0] == 2) or np.all(board[0:3,1] == 2) or np.all(board[0:3,2] == 2): Loss = True elif board[0,0] == 2 and board[1,1] == 2 and board[2,2] == 2: Loss = True elif board[2,0] == 2 and board[1,1] == 2 and board[0,2] == 2: Loss = True elif len(zeros[0]) == 0: Tie = True else: print("board:",board) return Win, Loss, Tie
[ "numpy.where", "numpy.all" ]
[((84, 104), 'numpy.where', 'np.where', (['(board == 0)'], {}), '(board == 0)\n', (92, 104), True, 'import numpy as np\n'), ((112, 138), 'numpy.all', 'np.all', (['(board[0, 0:3] == 1)'], {}), '(board[0, 0:3] == 1)\n', (118, 138), True, 'import numpy as np\n'), ((141, 167), 'numpy.all', 'np.all', (['(board[1, 0:3] == 1)'], {}), '(board[1, 0:3] == 1)\n', (147, 167), True, 'import numpy as np\n'), ((170, 196), 'numpy.all', 'np.all', (['(board[2, 0:3] == 1)'], {}), '(board[2, 0:3] == 1)\n', (176, 196), True, 'import numpy as np\n'), ((225, 251), 'numpy.all', 'np.all', (['(board[0:3, 0] == 1)'], {}), '(board[0:3, 0] == 1)\n', (231, 251), True, 'import numpy as np\n'), ((254, 280), 'numpy.all', 'np.all', (['(board[0:3, 1] == 1)'], {}), '(board[0:3, 1] == 1)\n', (260, 280), True, 'import numpy as np\n'), ((283, 309), 'numpy.all', 'np.all', (['(board[0:3, 2] == 1)'], {}), '(board[0:3, 2] == 1)\n', (289, 309), True, 'import numpy as np\n'), ((517, 543), 'numpy.all', 'np.all', (['(board[0, 0:3] == 2)'], {}), '(board[0, 0:3] == 2)\n', (523, 543), True, 'import numpy as np\n'), ((546, 572), 'numpy.all', 'np.all', (['(board[1, 0:3] == 2)'], {}), '(board[1, 0:3] == 2)\n', (552, 572), True, 'import numpy as np\n'), ((575, 601), 'numpy.all', 'np.all', (['(board[2, 0:3] == 2)'], {}), '(board[2, 0:3] == 2)\n', (581, 601), True, 'import numpy as np\n'), ((631, 657), 'numpy.all', 'np.all', (['(board[0:3, 0] == 2)'], {}), '(board[0:3, 0] == 2)\n', (637, 657), True, 'import numpy as np\n'), ((660, 686), 'numpy.all', 'np.all', (['(board[0:3, 1] == 2)'], {}), '(board[0:3, 1] == 2)\n', (666, 686), True, 'import numpy as np\n'), ((689, 715), 'numpy.all', 'np.all', (['(board[0:3, 2] == 2)'], {}), '(board[0:3, 2] == 2)\n', (695, 715), True, 'import numpy as np\n')]
#!/usr/bin/python3 # # Monitor GUI for an array of CBRS boards to watch power levels # and temperature across time along with a user-controlled # value for frequency, gain, and others. # # 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. # # (c) <EMAIL> 2018 ######################################################################## ## Main window ######################################################################## from PyQt5.QtWidgets import QMainWindow from PyQt5.QtWidgets import QSplashScreen from PyQt5.QtWidgets import QWidget from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap class MainWindow(QMainWindow): def __init__(self, irises, settings, parent=None, chan=None, **kwargs): QMainWindow.__init__(self, parent) self._splash = QSplashScreen(self, QPixmap('data/logo.tif')) self._splash.show() self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle("CBRS Array Monitor") self.setMinimumSize(800, 600) self._settings = settings self.addDockWidget(Qt.TopDockWidgetArea, TopLevelControlPanel(irises=irises, settings=settings, parent=self)) #start the window self.setCentralWidget(MainStatusWindow(irises=irises, parent=self, chan=chan)) #load previous settings print("Loading %s"%self._settings.fileName()) if self._settings.contains("MainWindow/geometry"): self.restoreGeometry(self._settings.value("MainWindow/geometry")) if self._settings.contains("MainWindow/state"): self.restoreState(self._settings.value("MainWindow/state")) #load complete self._splash.finish(self) def closeEvent(self, event): #stash settings self._settings.setValue("MainWindow/geometry", self.saveGeometry()) self._settings.setValue("MainWindow/state", self.saveState()) ######################################################################## ## Status window ######################################################################## from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QFormLayout from PyQt5.QtWidgets import QHBoxLayout class MainStatusWindow(QWidget): def __init__(self, irises, parent=None, chan=None): QWidget.__init__(self, parent) hbox = QHBoxLayout(self) for i, iris in enumerate(irises): if i%8 == 0: form = QFormLayout() hbox.addLayout(form) serial = iris.getHardwareInfo()['serial'] statusDisplay = SingleIrisStatus(iris, self, chan) form.addRow(serial, statusDisplay) ######################################################################## ## Single status display ######################################################################## from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QProgressBar from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QLabel from PyQt5.QtCore import QTimer from PyQt5.QtCore import pyqtSignal import numpy as np class SingleIrisStatus(QWidget): parserComplete = pyqtSignal(dict) def __init__(self, iris, parent=None, chan=None): self.chan = [0,1] if chan is None else [chan] QWidget.__init__(self, parent) self._iris = iris layout = QHBoxLayout(self) vbox = QVBoxLayout() layout.addLayout(vbox) self._progressBars = list() self._errorMessages = list() for ch in [0,1]: pbar = QProgressBar(self) vbox.addWidget(pbar) pbar.setRange(-100, 0) pbar.setFormat("Ch%s %%v dBfs"%("AB"[ch])) pbar.setValue(-100) self._progressBars.append(pbar) txt = QLabel(self) vbox.addWidget(txt) self._errorMessages.append(txt) self._txt = QLabel(self) layout.addWidget(self._txt) self._timer = QTimer(self) self._timer.setSingleShot(True) self._timer.setInterval(1000) self._timer.timeout.connect(self._handleTimeout) self._timer.start() self.parserComplete.connect(self._handleParserComplete) def _handleParserComplete(self, results): self._thread.join() self._thread = None for ch in self.chan: self._progressBars[ch].setValue(results[ch]['pwr']) if 'err' in results[ch]: self._errorMessages[ch].setText('<font color="red">%s</font>'%(results[ch]['err'])) else: self._errorMessages[ch].setText(' ') self._txt.setText('%g C'%results['temp']) #print('_handleParserComplete %s'%str(results)) self._timer.start() def _handleTimeout(self): self._thread = threading.Thread(target=self._workThread) self._thread.start() def _workThread(self): results = dict() for ch in self.chan: samps = self._iris.readRegisters('RX_SNOOPER', ch, 1024) samps = np.array([complex(float(np.int16(s & 0xffff)), float(np.int16(s >> 16))) for s in samps])/float(1 << 15) result = toneGood(samps) results[ch] = result results['temp'] = float(self._iris.readSensor('LMS7_TEMP')) self.parserComplete.emit(results) ######################################################################## ## tone parsing logic ######################################################################## from sklk_widgets import LogPowerFFT SAMP_RATE = 10e6 TONE_FS = 1e6 FILT_BW = 30e6 def toneGood(samps, tone=TONE_FS, fs=SAMP_RATE, low_thresh=0.01, high_thresh=0.7, spur_threshes=[10,12,15,20], ignore_dc=False, suppress=100e3): """ Check to see if a tone is received as expected, e.g., for testing boards by transmitting a tone and receiving it in loopback mode. Rejects if receive power is too low or too high, or if the next n spurious tones are higher than spur_threshes. Suppress DC and carriers adjacent to tone, according to ignore_dc and suppress. """ result = dict(ret=False) ps = LogPowerFFT(samps) dc_bin = len(samps)//2 tone_bin = dc_bin + int(np.round(len(samps)*tone/fs)) #todo: check result['pwr'] = ps[tone_bin] avg = np.mean(np.abs(samps)) result['avg'] = avg if avg < low_thresh: result['err'] = "Tone power too low." return result if avg > high_thresh or np.amax(np.abs(samps)) > 1.0: result['err'] = "Tone power too high -- likely clipping." return result if np.argmax(ps) != tone_bin: result['err'] = "Tone is not highest signal." return result if(ignore_dc): #ignore DC ps[dc_bin] = np.min(ps) #-100 n_suppress = int(np.round(len(samps)*suppress/fs)) #print(n_suppress, np.min(ps),tone_bin) ps[tone_bin+1:tone_bin+1+n_suppress] = np.min(ps) ps[tone_bin-n_suppress:tone_bin] = np.min(ps) s_power = np.sort(ps) for i,thresh in enumerate(spur_threshes): if s_power[-i-2] > ps[tone_bin] - thresh: result['err'] = 'Spur %d is too high! It is %f, tone is %f' % (i+1, s_power[-i-2], ps[tone_bin]) return result result['ret'] = True return result def setupIris(iris, chan): for ch in [0, 1]: iris.setSampleRate(SOAPY_SDR_RX, ch, SAMP_RATE) iris.setSampleRate(SOAPY_SDR_TX, ch, SAMP_RATE) iris.setBandwidth(SOAPY_SDR_RX, ch, FILT_BW) iris.setBandwidth(SOAPY_SDR_TX, ch, FILT_BW) iris.writeSetting(SOAPY_SDR_TX, ch, 'TSP_TSG_CONST', str(1 << 12)) iris.setFrequency(SOAPY_SDR_TX, ch, 'BB', TONE_FS) iris.writeSetting('FE_ENABLE_CAL_PATH', 'true') if chan is not None: iris.writeSetting(SOAPY_SDR_TX, int(not chan), "ENABLE_CHANNEL","false") iris.writeSetting(SOAPY_SDR_RX, int(not chan), "ENABLE_CHANNEL","false") ######################################################################## ## Top level control panel ######################################################################## from PyQt5.QtWidgets import QDockWidget from PyQt5.QtWidgets import QDoubleSpinBox from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QFormLayout from PyQt5.QtWidgets import QGroupBox from PyQt5.QtWidgets import QWidget from sklk_widgets import FreqEntryWidget from SoapySDR import * import functools import threading class TopLevelControlPanel(QDockWidget): def __init__(self, irises, settings, parent = None): QDockWidget.__init__(self, "Control panel", parent) self.setObjectName("TopLevelControlPanel") self._irises = irises self._settings = settings widget = QWidget(self) self.setWidget(widget) layout = QHBoxLayout(widget) form = QFormLayout() layout.addLayout(form) freq = self._settings.value('TopLevelControlPanel/tddFrequency', 3.6e9, float) self._handleTddFreqChange(freq) tddFrequencyEntry = FreqEntryWidget(widget) tddFrequencyEntry.setValue(freq) tddFrequencyEntry.valueChanged.connect(self._handleTddFreqChange) form.addRow("TDD Frequency", tddFrequencyEntry) for dirName, direction in (("Tx controls", SOAPY_SDR_TX), ("Rx controls", SOAPY_SDR_RX)): groupBox = QGroupBox(dirName, widget) hbox = QHBoxLayout(groupBox) layout.addWidget(groupBox) for i, gainName in enumerate(irises[0].listGains(direction, 0)): if i%2 == 0: form = QFormLayout() hbox.addLayout(form) value = self._settings.value('TopLevelControlPanel/%sGain%s'%('Rx' if direction == SOAPY_SDR_RX else 'Tx', gainName), 0.0, float) self._handleGainChange(direction, gainName, value) edit = QDoubleSpinBox(widget) form.addRow(gainName, edit) r = irises[0].getGainRange(direction, 0, gainName) edit.setRange(r.minimum(), r.maximum()) if r.step() != 0: edit.setSingleStep(r.step()) edit.setSuffix(' dB') edit.setValue(value) edit.valueChanged.connect(functools.partial(self._handleGainChange, direction, gainName)) def _handleTddFreqChange(self, newFreq): for direction in (SOAPY_SDR_RX, SOAPY_SDR_TX): threads = [threading.Thread(target=functools.partial(iris.setFrequency, direction, 0, "RF", newFreq)) for iris in self._irises] for t in threads: t.start() for t in threads: t.join() self._settings.setValue('TopLevelControlPanel/tddFrequency', newFreq) def _handleGainChange(self, direction, gainName, newValue): for ch in [0, 1]: threads = [threading.Thread(target=functools.partial(iris.setGain, direction, ch, gainName, newValue)) for iris in self._irises] for t in threads: t.start() for t in threads: t.join() self._settings.setValue('TopLevelControlPanel/%sGain%s'%('Rx' if direction == SOAPY_SDR_RX else 'Tx', gainName), newValue) ######################################################################## ## Invoke the application ######################################################################## from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QSettings from sklk_widgets import DeviceSelectionDialog import SoapySDR import argparse import threading import sys if __name__ == '__main__': app = QApplication(sys.argv) #parser = argparse.ArgumentParser() #args = parser.parse_args() chan = None #set to 0 or 1 for only testing one channel (better performance in CBRS) serials = sys.argv[1:] if serials: handles = [dict(driver='iris',serial=s) for s in serials] else: handles = [h for h in SoapySDR.Device.enumerate(dict(driver='iris')) if 'CBRS' in h['frontend']] irises = SoapySDR.Device(handles) threads = [threading.Thread(target=setupIris, args=[iris,chan]) for iris in irises] for t in threads: t.start() for t in threads: t.join() settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "Skylark", "CBRSArrayMonitor") w = MainWindow(irises=irises, settings=settings, chan=chan) w.show() sys.exit(app.exec_())
[ "PyQt5.QtCore.pyqtSignal", "numpy.abs", "PyQt5.QtWidgets.QMainWindow.__init__", "numpy.argmax", "PyQt5.QtWidgets.QDockWidget.__init__", "PyQt5.QtWidgets.QVBoxLayout", "PyQt5.QtWidgets.QApplication", "sklk_widgets.FreqEntryWidget", "PyQt5.QtWidgets.QLabel", "PyQt5.QtWidgets.QWidget", "PyQt5.QtCore.QSettings", "PyQt5.QtWidgets.QWidget.__init__", "PyQt5.QtCore.QTimer", "threading.Thread", "functools.partial", "PyQt5.QtWidgets.QHBoxLayout", "PyQt5.QtWidgets.QGroupBox", "sklk_widgets.LogPowerFFT", "numpy.sort", "numpy.min", "PyQt5.QtWidgets.QDoubleSpinBox", "PyQt5.QtGui.QPixmap", "SoapySDR.Device", "PyQt5.QtWidgets.QProgressBar", "numpy.int16", "PyQt5.QtWidgets.QFormLayout" ]
[((3545, 3561), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', (['dict'], {}), '(dict)\n', (3555, 3561), False, 'from PyQt5.QtCore import pyqtSignal\n'), ((6522, 6540), 'sklk_widgets.LogPowerFFT', 'LogPowerFFT', (['samps'], {}), '(samps)\n', (6533, 6540), False, 'from sklk_widgets import LogPowerFFT\n'), ((7292, 7302), 'numpy.min', 'np.min', (['ps'], {}), '(ps)\n', (7298, 7302), True, 'import numpy as np\n'), ((7342, 7352), 'numpy.min', 'np.min', (['ps'], {}), '(ps)\n', (7348, 7352), True, 'import numpy as np\n'), ((7368, 7379), 'numpy.sort', 'np.sort', (['ps'], {}), '(ps)\n', (7375, 7379), True, 'import numpy as np\n'), ((11913, 11935), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (11925, 11935), False, 'from PyQt5.QtWidgets import QApplication\n'), ((12328, 12352), 'SoapySDR.Device', 'SoapySDR.Device', (['handles'], {}), '(handles)\n', (12343, 12352), False, 'import SoapySDR\n'), ((12520, 12606), 'PyQt5.QtCore.QSettings', 'QSettings', (['QSettings.IniFormat', 'QSettings.UserScope', '"""Skylark"""', '"""CBRSArrayMonitor"""'], {}), "(QSettings.IniFormat, QSettings.UserScope, 'Skylark',\n 'CBRSArrayMonitor')\n", (12529, 12606), False, 'from PyQt5.QtCore import QSettings\n'), ((1167, 1201), 'PyQt5.QtWidgets.QMainWindow.__init__', 'QMainWindow.__init__', (['self', 'parent'], {}), '(self, parent)\n', (1187, 1201), False, 'from PyQt5.QtWidgets import QMainWindow\n'), ((2670, 2700), 'PyQt5.QtWidgets.QWidget.__init__', 'QWidget.__init__', (['self', 'parent'], {}), '(self, parent)\n', (2686, 2700), False, 'from PyQt5.QtWidgets import QWidget\n'), ((2716, 2733), 'PyQt5.QtWidgets.QHBoxLayout', 'QHBoxLayout', (['self'], {}), '(self)\n', (2727, 2733), False, 'from PyQt5.QtWidgets import QHBoxLayout\n'), ((3679, 3709), 'PyQt5.QtWidgets.QWidget.__init__', 'QWidget.__init__', (['self', 'parent'], {}), '(self, parent)\n', (3695, 3709), False, 'from PyQt5.QtWidgets import QWidget\n'), ((3753, 3770), 'PyQt5.QtWidgets.QHBoxLayout', 'QHBoxLayout', (['self'], {}), '(self)\n', (3764, 3770), False, 'from PyQt5.QtWidgets import QHBoxLayout\n'), ((3786, 3799), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (3797, 3799), False, 'from PyQt5.QtWidgets import QVBoxLayout\n'), ((4293, 4305), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['self'], {}), '(self)\n', (4299, 4305), False, 'from PyQt5.QtWidgets import QLabel\n'), ((4365, 4377), 'PyQt5.QtCore.QTimer', 'QTimer', (['self'], {}), '(self)\n', (4371, 4377), False, 'from PyQt5.QtCore import QTimer\n'), ((5201, 5242), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._workThread'}), '(target=self._workThread)\n', (5217, 5242), False, 'import threading\n'), ((6691, 6704), 'numpy.abs', 'np.abs', (['samps'], {}), '(samps)\n', (6697, 6704), True, 'import numpy as np\n'), ((6977, 6990), 'numpy.argmax', 'np.argmax', (['ps'], {}), '(ps)\n', (6986, 6990), True, 'import numpy as np\n'), ((7132, 7142), 'numpy.min', 'np.min', (['ps'], {}), '(ps)\n', (7138, 7142), True, 'import numpy as np\n'), ((8914, 8965), 'PyQt5.QtWidgets.QDockWidget.__init__', 'QDockWidget.__init__', (['self', '"""Control panel"""', 'parent'], {}), "(self, 'Control panel', parent)\n", (8934, 8965), False, 'from PyQt5.QtWidgets import QDockWidget\n'), ((9099, 9112), 'PyQt5.QtWidgets.QWidget', 'QWidget', (['self'], {}), '(self)\n', (9106, 9112), False, 'from PyQt5.QtWidgets import QWidget\n'), ((9161, 9180), 'PyQt5.QtWidgets.QHBoxLayout', 'QHBoxLayout', (['widget'], {}), '(widget)\n', (9172, 9180), False, 'from PyQt5.QtWidgets import QHBoxLayout\n'), ((9196, 9209), 'PyQt5.QtWidgets.QFormLayout', 'QFormLayout', ([], {}), '()\n', (9207, 9209), False, 'from PyQt5.QtWidgets import QFormLayout\n'), ((9397, 9420), 'sklk_widgets.FreqEntryWidget', 'FreqEntryWidget', (['widget'], {}), '(widget)\n', (9412, 9420), False, 'from sklk_widgets import FreqEntryWidget\n'), ((12368, 12421), 'threading.Thread', 'threading.Thread', ([], {'target': 'setupIris', 'args': '[iris, chan]'}), '(target=setupIris, args=[iris, chan])\n', (12384, 12421), False, 'import threading\n'), ((1245, 1269), 'PyQt5.QtGui.QPixmap', 'QPixmap', (['"""data/logo.tif"""'], {}), "('data/logo.tif')\n", (1252, 1269), False, 'from PyQt5.QtGui import QPixmap\n'), ((3948, 3966), 'PyQt5.QtWidgets.QProgressBar', 'QProgressBar', (['self'], {}), '(self)\n', (3960, 3966), False, 'from PyQt5.QtWidgets import QProgressBar\n'), ((4184, 4196), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['self'], {}), '(self)\n', (4190, 4196), False, 'from PyQt5.QtWidgets import QLabel\n'), ((9714, 9740), 'PyQt5.QtWidgets.QGroupBox', 'QGroupBox', (['dirName', 'widget'], {}), '(dirName, widget)\n', (9723, 9740), False, 'from PyQt5.QtWidgets import QGroupBox\n'), ((9760, 9781), 'PyQt5.QtWidgets.QHBoxLayout', 'QHBoxLayout', (['groupBox'], {}), '(groupBox)\n', (9771, 9781), False, 'from PyQt5.QtWidgets import QHBoxLayout\n'), ((2824, 2837), 'PyQt5.QtWidgets.QFormLayout', 'QFormLayout', ([], {}), '()\n', (2835, 2837), False, 'from PyQt5.QtWidgets import QFormLayout\n'), ((6859, 6872), 'numpy.abs', 'np.abs', (['samps'], {}), '(samps)\n', (6865, 6872), True, 'import numpy as np\n'), ((10245, 10267), 'PyQt5.QtWidgets.QDoubleSpinBox', 'QDoubleSpinBox', (['widget'], {}), '(widget)\n', (10259, 10267), False, 'from PyQt5.QtWidgets import QDoubleSpinBox\n'), ((9954, 9967), 'PyQt5.QtWidgets.QFormLayout', 'QFormLayout', ([], {}), '()\n', (9965, 9967), False, 'from PyQt5.QtWidgets import QFormLayout\n'), ((10615, 10677), 'functools.partial', 'functools.partial', (['self._handleGainChange', 'direction', 'gainName'], {}), '(self._handleGainChange, direction, gainName)\n', (10632, 10677), False, 'import functools\n'), ((10827, 10892), 'functools.partial', 'functools.partial', (['iris.setFrequency', 'direction', '(0)', '"""RF"""', 'newFreq'], {}), "(iris.setFrequency, direction, 0, 'RF', newFreq)\n", (10844, 10892), False, 'import functools\n'), ((11215, 11281), 'functools.partial', 'functools.partial', (['iris.setGain', 'direction', 'ch', 'gainName', 'newValue'], {}), '(iris.setGain, direction, ch, gainName, newValue)\n', (11232, 11281), False, 'import functools\n'), ((5467, 5486), 'numpy.int16', 'np.int16', (['(s & 65535)'], {}), '(s & 65535)\n', (5475, 5486), True, 'import numpy as np\n'), ((5496, 5513), 'numpy.int16', 'np.int16', (['(s >> 16)'], {}), '(s >> 16)\n', (5504, 5513), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import numpy as np from computeCostMulti import computeCostMulti def gradientDescentMulti(X, y, theta, alpha, num_iters): #GRADIENTDESCENTMULTI Performs gradient descent to learn theta # theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by # taking num_iters gradient steps with learning rate alpha # Initialize some useful values m = y.shape[0] # number of training examples J_history = np.reshape(np.zeros((num_iters, 1)), (num_iters, 1)) for i in range(num_iters): # ====================== YOUR CODE HERE ====================== # Instructions: Perform a single gradient step on the parameter vector # theta. # # Hint: While debugging, it can be useful to print out the values # of the cost function (computeCostMulti) and gradient here. # theta = np.subtract(theta, (alpha / m) * np.dot(np.subtract(np.dot(X, theta), y).T, X).T) # ============================================================ # Save the cost J in every iteration J_history[i, 0] = computeCostMulti(X, y, theta) return (theta, J_history)
[ "numpy.dot", "numpy.zeros", "computeCostMulti.computeCostMulti" ]
[((479, 503), 'numpy.zeros', 'np.zeros', (['(num_iters, 1)'], {}), '((num_iters, 1))\n', (487, 503), True, 'import numpy as np\n'), ((1147, 1176), 'computeCostMulti.computeCostMulti', 'computeCostMulti', (['X', 'y', 'theta'], {}), '(X, y, theta)\n', (1163, 1176), False, 'from computeCostMulti import computeCostMulti\n'), ((973, 989), 'numpy.dot', 'np.dot', (['X', 'theta'], {}), '(X, theta)\n', (979, 989), True, 'import numpy as np\n')]
##technically, this means that I don't have to force floats in my division from __future__ import division, absolute_import ##this makes the plot lines thicker, darker, etc. from matplotlib import rc,rcParams rc('text', usetex=True) rc('axes', linewidth=2) rc('font', weight='bold') ##importing the needed modules import astropy.stats import glob import math import matplotlib.pyplot as plt from matplotlib import ticker from matplotlib.ticker import FormatStrFormatter import numpy as np import os import pandas as pd from scipy import integrate,optimize,spatial ##for plotting 3D from mpl_toolkits.mplot3d import Axes3D ##making global-like text sizes class Vars(object): size_xlabel = 22 size_ylabel = 22 size_text = 20 size_tick = 20 size_legend = 20 va = Vars() ##Victor's functions ##used for importing the needed data files ##used for creating bins for histograms, etc. automatically (not hard coding) __author__ =['<NAME>'] __copyright__ =["Copyright 2016 <NAME>, Index function"] __email__ =['<EMAIL>'] __maintainer__ =['<NAME>'] def Index(directory, datatype): """ Indexes the files in a directory `directory' with a specific data type. Parameters ---------- directory: str Absolute path to the folder that is indexed. datatype: str Data type of the files to be indexed in the folder. Returns ------- file_array: array_like np.array of indexed files in the folder 'directory' with specific datatype. Examples -------- >>> Index('~/data', '.txt') >>> array(['A.txt', 'Z'.txt', ...]) """ assert(os.path.exists(directory)) files = np.array(glob.glob('{0}/*{1}'.format(directory, datatype))) return files def myceil(x, base=10): """ Returns the upper-bound integer of 'x' in base 'base'. Parameters ---------- x: float number to be approximated to closest number to 'base' base: float base used to calculate the closest 'largest' number Returns ------- n_high: float Closest float number to 'x', i.e. upper-bound float. Example ------- >>>> myceil(12,10) 20 >>>> >>>> myceil(12.05, 0.1) 12.10000 """ n_high = float(base*math.ceil(float(x)/base)) return n_high def myfloor(x, base=10): """ Returns the lower-bound integer of 'x' in base 'base' Parameters ---------- x: float number to be approximated to closest number of 'base' base: float base used to calculate the closest 'smallest' number Returns ------- n_low: float Closest float number to 'x', i.e. lower-bound float. Example ------- >>>> myfloor(12, 5) >>>> 10 """ n_low = float(base*math.floor(float(x)/base)) return n_low def Bins_array_create(arr, base=10): """ Generates array between [arr.min(), arr.max()] in steps of `base`. Parameters ---------- arr: array_like, Shape (N,...), One-dimensional Array of numerical elements base: float, optional (default=10) Interval between bins Returns ------- bins_arr: array_like Array of bin edges for given arr """ base = float(base) arr = np.array(arr) assert(arr.ndim==1) arr_min = myfloor(arr.min(), base=base) arr_max = myceil( arr.max(), base=base) bins_arr = np.arange(arr_min, arr_max+0.5*base, base) return bins_arr ############################################################################### def sph_to_cart(ra,dec,cz,h): """ Converts spherical coordinates to Cartesian coordinates. Parameters ---------- ra: array-like right-ascension of galaxies in degrees dec: array-like declination of galaxies in degrees cz: array-like velocity of galaxies in km/s h: float-like the Hubble constant; 70 for experimental, 100 for theoretical Returns ------- coords: array-like, shape = N by 3 x, y, and z coordinates """ cz_dist = cz/float(h) #converts velocity into distance x_arr = cz_dist*np.cos(np.radians(ra))*np.cos(np.radians(dec)) y_arr = cz_dist*np.sin(np.radians(ra))*np.cos(np.radians(dec)) z_arr = cz_dist*np.sin(np.radians(dec)) coords = np.column_stack((x_arr,y_arr,z_arr)) return coords ############################################################################### ##actually a rather obsolete function, as I could just sort by distance, since ##N is the same for all cases ##Need something like this for Density in a Sphere method def calc_dens_nn(n_val,r_val): """ Returns densities of spheres with radius being the distance to the nth nearest neighbor. Parameters ---------- n_val = integer The 'N' from Nth nearest neighbor r_val = array-like An array with the distances to the Nth nearest neighbor for each galaxy Returns ------- dens: array-like An array with the densities of the spheres created with radii to the Nth nearest neighbor. """ dens = np.array([(3.*(n_val+1)/(4.*np.pi*r_val[hh]**3))\ for hh in xrange(len(r_val))]) return dens ############################################################################### def plot_calcs(mass,bins,dlogM): """ Returns values for plotting the stellar mass function and mass ratios Parameters ---------- mass: array-like A 1D array with mass values, assumed to be in order based on the density of the environment bins: array-like A 1D array with the values which will be used as the bin edges by the histogram function dlogM: float-like The log difference between bin edges Returns ------- bin_centers: array-like An array with the medians mass values of the mass bins mass_freq: array-like Contains the number density values of each mass bin ratio_dict: dictionary-like A dictionary with three keys, corresponding to the divisors 2,4, and 10 (as the percentile cuts are based on these divisions). Each key has the density-cut, mass ratios for that specific cut (50/50 for 2; 25/75 for 4; 10/90 for 10). bin_centers_fin: array-like An array with the mean mass values of the galaxies in each mass bin """ mass_counts, edges = np.histogram(mass,bins) bin_centers = 0.5*(edges[:-1]+edges[1:]) mass_freq = mass_counts/float(len(mass))/dlogM ratio_dict = {} frac_val = [2,4,10] yerr = [] bin_centers_fin = [] for ii in frac_val: ratio_dict[ii] = {} frac_data = int(len(mass)/ii) # Calculations for the lower density cut frac_mass = mass[0:frac_data] counts, edges = np.histogram(frac_mass,bins) # Calculations for the higher density cut frac_mass_2 = mass[-frac_data:] counts_2, edges_2 = np.histogram(frac_mass_2,bins) # Ratio determination ratio_counts = (1.*counts_2)/(1.*counts) non_zero = np.isfinite(ratio_counts) ratio_counts_1 = ratio_counts[non_zero] # print 'len ratio_counts: {0}'.format(len(ratio_counts_1)) ratio_dict[ii] = ratio_counts_1 temp_yerr = (counts_2*1.)/(counts*1.)* \ np.sqrt(1./counts + 1./counts_2) temp_yerr_1 = temp_yerr[non_zero] # print 'len yerr: {0}'.format(len(temp_yerr_1)) yerr.append(temp_yerr_1) bin_centers_1 = bin_centers[non_zero] # print 'len bin_cens: {0}'.format(len(bin_centers_1)) bin_centers_fin.append(bin_centers_1) mass_freq_list = [[] for xx in xrange(2)] mass_freq_list[0] = mass_freq mass_freq_list[1] = np.sqrt(mass_counts)/float(len(mass))/dlogM mass_freq = np.array(mass_freq_list) ratio_dict_list = [[] for xx in xrange(2)] ratio_dict_list[0] = ratio_dict ratio_dict_list[1] = yerr ratio_dict = ratio_dict_list return bin_centers, mass_freq, ratio_dict, bin_centers_fin ############################################################################### def bin_func(mass_dist,bins,kk,bootstrap=False): """ Returns median distance to Nth nearest neighbor Parameters ---------- mass_dist: array-like An array with mass values in at index 0 (when transformed) and distance to the Nth nearest neighbor in the others Example: 6239 by 7 Has mass values and distances to 6 Nth nearest neighbors bins: array-like A 1D array with the values which will be used as the bin edges kk: integer-like The index of mass_dist (transformed) where the appropriate distance array may be found Optional -------- bootstrap == True Calculates the bootstrap errors associated with each median distance value. Creates an array housing arrays containing the actual distance values associated with every galaxy in a specific bin. Bootstrap error is then performed using astropy, and upper and lower one sigma values are found for each median value. These are added to a list with the median distances, and then converted to an array and returned in place of just 'medians.' Returns ------- medians: array-like An array with the median distance to the Nth nearest neighbor from all the galaxies in each of the bins """ edges = bins bin_centers = 0.5*(edges[:-1]+edges[1:]) # print 'length bins:' # print len(bins) digitized = np.digitize(mass_dist.T[0],edges) digitized -= int(1) bin_nums = np.unique(digitized) bin_nums_list = list(bin_nums) if (len(bin_centers)) in bin_nums_list: bin_nums_list.remove(len(bin_centers)) bin_nums = np.array(bin_nums_list) medians = np.array([np.nanmedian(mass_dist.T[kk][digitized==ii])\ for ii in bin_nums]) if bootstrap == True: dist_in_bin = np.array([(mass_dist.T[kk][digitized==ii])\ for ii in bin_nums]) for vv in xrange(len(dist_in_bin)): if len(dist_in_bin[vv]) == 0: # dist_in_bin_list = list(dist_in_bin[vv]) # dist_in_bin[vv] = np.zeros(len(dist_in_bin[0])) dist_in_bin[vv] = np.nan low_err_test = np.array([np.percentile(astropy.stats.bootstrap\ (dist_in_bin[vv],bootnum=1000,bootfunc=np.median),16)\ for vv in xrange(len(dist_in_bin))]) high_err_test = np.array([np.percentile(astropy.stats.bootstrap\ (dist_in_bin[vv],bootnum=1000,bootfunc=np.median),84)\ for vv in xrange(len(dist_in_bin))]) med_list = [[] for yy in xrange(3)] med_list[0] = medians med_list[1] = low_err_test med_list[2] = high_err_test medians = np.array(med_list) # print len(medians) # print len(non_zero_bins) return medians ############################################################################### def hist_calcs(mass,bins,dlogM): """ Returns dictionaries with the counts for the upper and lower density portions; calculates the three different percentile cuts for each mass array given Parameters ---------- mass: array-like A 1D array with log stellar mass values, assumed to be an order which corresponds to the ascending densities; (necessary, as the index cuts are based on this) bins: array-like A 1D array with the values which will be used as the bin edges dlogM: float-like The log difference between bin edges Returns ------- hist_dict_low: dictionary-like A dictionary with three keys (the frac vals), with arrays as values. The values for the lower density cut; also has three error keys hist_dict_high: dictionary-like A dictionary with three keys (the frac vals), with arrays as values. The values for the higher density cut; also has three error keys """ hist_dict_low = {} hist_dict_high = {} bin_cens_low = {} bin_cens_high = {} frac_val = np.array([2,4,10]) ##given the fractional value, returns the index frac_dict = {2:0,4:1,10:2} edges = bins bin_centers = 0.5 * (edges[:-1]+edges[1:]) low_err = [[] for xx in xrange(len(frac_val))] high_err = [[] for xx in xrange(len(frac_val))] for ii in frac_val: frac_data = int(len(mass)/ii) frac_mass = mass[0:frac_data] counts, edges = np.histogram(frac_mass,bins) low_counts = (counts/float(len(frac_mass))/dlogM) non_zero = (low_counts!=0) low_counts_1 = low_counts[non_zero] hist_dict_low[ii] = low_counts_1 bin_cens_low[ii] = bin_centers[non_zero] ##So... I don't actually know if I need to be calculating error ##on the mocks. I thought I didn't, but then, I swear someone ##*ahem (Victor)* said to. So I am. Guess I'm not sure they're ##useful. But I'll have them if necessary. And ECO at least ##needs them. low_err = np.sqrt(counts)/len(frac_mass)/dlogM low_err_1 = low_err[non_zero] err_key = 'err_{0}'.format(ii) hist_dict_low[err_key] = low_err_1 frac_mass_2 = mass[-frac_data:] counts_2, edges_2 = np.histogram(frac_mass_2,bins) high_counts = counts_2/float(len(frac_mass_2))/dlogM non_zero = (high_counts!=0) high_counts_1 = high_counts[non_zero] hist_dict_high[ii] = high_counts_1 bin_cens_high[ii] = bin_centers[non_zero] high_err = np.sqrt(counts_2)/len(frac_mass_2)/dlogM high_err_1 = high_err[non_zero] hist_dict_high[err_key] = high_err_1 return hist_dict_low, hist_dict_high, bin_cens_low, bin_cens_high ############################################################################### def plot_halo_frac(bin_centers,y_vals,ax,plot_idx,text=False): titles = [1,2,3,5,10,20] ax.set_xlim(9.1,11.9) ax.set_xticks(np.arange(9.5,12.,0.5)) ax.tick_params(axis='x', which='major', labelsize=16) if text == True: title_here = 'n = {0}'.format(titles[plot_idx]) ax.text(0.05, 0.95, title_here,horizontalalignment='left', \ verticalalignment='top',transform=ax.transAxes,fontsize=18) if plot_idx == 4: ax.set_xlabel('$\log\ (M_{*}/M_{\odot})$',fontsize=20) ax.plot(bin_centers,y_vals,color='silver') def plot_mean_halo_frac(bin_centers,mean_vals,ax,std): ax.errorbar(bin_centers,mean_vals,yerr=std,color='darkmagenta') ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### ##Importing the ECO Data!!! eco_path = r"C:\Users\Hannah\Desktop\Vanderbilt_REU\Stellar_mass_env_density" eco_path += r"\Catalogs\ECO_true" eco_cols = np.array([2,4,10,15,16,19,20,21]) ##the newest file from the online database ECO_true = (Index(eco_path,'.csv')) names = ['logMhalo','dec','cent_sat','group_ID','Mr','cz','ra','logMstar'] ##the [0] is necessary for it to take the string. Otherwise, ECO_true is a ##numpy array PD_eco = pd.read_csv(ECO_true[0], usecols=(eco_cols),header=None, \ skiprows=1,names=names) eco_comp = PD_eco[PD_eco.logMstar >= 9.1] ra_eco = eco_comp.ra dec_eco = eco_comp.dec cz_eco = eco_comp.cz mass_eco = eco_comp.logMstar logMhalo = eco_comp.logMhalo cent_sat = eco_comp.cent_sat group_ID = eco_comp.group_ID Mr_eco = eco_comp.Mr ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### ##Importing mock data!!! dirpath = r"C:\Users\Hannah\Desktop\Vanderbilt_REU\Stellar_mass_env_Density" dirpath+= r"\Catalogs\Beta_M1_Behroozi\ab_matching" dirpath+= r"\Resolve_plk_5001_so_mvir_hod1_scatter0p2_mock1_ECO_Mocks" ECO_cats = (Index(dirpath,'.dat')) usecols = (0,1,2,4,7,13,20,25) names = ['ra','dec','cz','Halo_ID','halo_cent_sat','logMstar', 'group_ID','group_cent_sat'] PD = [[] for ii in xrange(len(ECO_cats))] ##creating a list of panda dataframes for ii in xrange(len(ECO_cats)): temp_PD = (pd.read_csv(ECO_cats[ii],sep="\s+", usecols= usecols, header=None, skiprows=2,names=names)) PD[ii] = temp_PD ##making stellar mass cuts, with stellar mass completeness limit (all should ##pass, but just in case), and max limit being that of ECO's most massive ##galaxy PD_comp_1 = [(PD[ii][PD[ii].logMstar >= 9.1]) for ii in xrange(len(ECO_cats))] PD_comp = [(PD_comp_1[ii][PD_comp_1[ii].logMstar <=11.77]) for ii in xrange(len(ECO_cats))] ##this resets the indices in the pd dataframe, meaning they will be ##counted/indexed as if the galaxies with stellar masses outside of the limit ##were never there [(PD_comp[ii].reset_index(drop=True,inplace=True)) for ii in xrange(len(ECO_cats))] ##finding the min and max stellar mass galaxy of each catalog ##not necessary for the abundance matched mocks, but useful to have in here ##in case I have to run non ABD matched ##I was thinking to use the maximum min value and the minumum max value, so ##that there would be no empty bins on either side, but I think it's a moot ##point. Also, I already set a min and max on all the stellar masses. ##There could possibly be one mock at some point that would have less than ##the normal number of bins, but my other code should make up for that min_max_mass_arr = [] for ii in xrange(len(PD_comp)): min_max_mass_arr.append(max(PD_comp[ii].logMstar)) min_max_mass_arr.append(min(PD_comp[ii].logMstar)) min_max_mass_arr = np.array(min_max_mass_arr) ##could change this at some point dlogM = 0.2 ##bins inherently use even decimal points, so this forces odd bins = Bins_array_create(min_max_mass_arr,dlogM) bins+= 0.1 bins_list = list(bins) ##double checking to make sure that there is no mass bin edge past 11.7 for ii in bins: if ii > 11.77: bins_list.remove(ii) bins = np.array(bins_list) ra_arr = np.array([(PD_comp[ii].ra) for ii in xrange(len(PD_comp))]) dec_arr = np.array([(PD_comp[ii].dec) for ii in xrange(len(PD_comp))]) cz_arr = np.array([(PD_comp[ii].cz) for ii in xrange(len(PD_comp))]) mass_arr = np.array([(PD_comp[ii].logMstar) for ii in xrange(len(PD_comp))]) halo_id_arr = np.array([(PD_comp[ii].Halo_ID) for ii in xrange(len(PD_comp))]) halo_cent_sat_arr = np.array([(PD_comp[ii].halo_cent_sat) for ii in xrange(len(PD_comp))]) group_id_arr = np.array([(PD_comp[ii].group_ID) for ii in xrange(len(PD_comp))]) group_cent_sat_arr = np.array([(PD_comp[ii].group_cent_sat) for ii in xrange(len(PD_comp))]) ############################################################################### ############################################################################### ############################################################################### ##Variables and dictionaries for later use throughout. ##calulating the number of bins for later reference num_of_mocks = len(PD_comp) num_of_bins = int(len(bins) - 1) neigh_dict = {1:0,2:1,3:2,5:3,10:4,20:5} frac_dict = {2:0,4:1,10:2} neigh_vals = np.array([1,2,3,5,10,20]) frac_vals = np.array([2,4,10]) ############################################################################### ############################################################################### ############################################################################### ##Setting up ECO first coords_eco = sph_to_cart(ra_eco,dec_eco,cz_eco,70) eco_neigh_tree = spatial.cKDTree(coords_eco) ##neigh_vals index seems weird, but is so that if neighbor values change, the ##code is dynamic ##I believe the zero index is getting the distances to the neighbors ##the 1st index gives the index of the neighbor eco_tree_dist = np.array(eco_neigh_tree.query(coords_eco,neigh_vals[-1]+1)[0]) ##I'm not sure that I'll need this, but here's an array with the indices eco_neigh_idx = np.array(eco_neigh_tree.query(coords_eco,neigh_vals[-1]+1)[1]) ##some explaining: eco_tree_dist is number of galaxies by number of neighbors ##in shape. For example, 6000 by 21. Using T makes it 21 by 6000. Then, using ##[neigh_vals], I choose only the rows which are relevant. This makes it, for ##example, 6 by 6000. Then, I use T again, returning it to 6000 by 6. ##Added in front of all of this is the log mass of each galaxy. None of the ##orders changed, so it's fine. There are now len(neigh_vals)+1 columns eco_mass_dist = np.column_stack((mass_eco,eco_tree_dist.T[neigh_vals].T)) ##the xrange is directing to which column the indices are to be sorted by ##start with one, since the first column is mass ##the total number of columns will be 1+len(neigh_vals) ##sorted from smallest distance to largest ##[::-1] reversed the indices, so those with the largest distances to their ##nearest neighbors, and thus in the least dense areas, are listed first eco_idx = [np.argsort(eco_mass_dist.T[kk])[::-1] for kk in \ xrange(1,len(neigh_vals)+1)] ##should have all of the masses put in order depending on the environment of ##their galaxy (from least dense to most) eco_mass_dat = np.array([eco_mass_dist.T[0][eco_idx[kk]] for kk in \ xrange(len(neigh_vals))]) ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### ##Changing the data from degrees and velocity to Cartesian system coords_test = np.array([sph_to_cart(ra_arr[vv],dec_arr[vv],cz_arr[vv],70)\ for vv in xrange(len(ECO_cats))]) ##Lists which will house information from the cKD tree nn_arr_temp = [[] for uu in xrange(len(coords_test))] nn_arr = [[] for xx in xrange(len(coords_test))] nn_idx = [[] for zz in xrange(len(coords_test))] ##Creating the cKD tree for nearest neighbors, and having it find the distances ##nn_arr houses the actual distances ##nn_idx houses the index of the galaxy which is the nth nearest neighbor for vv in xrange(num_of_mocks): nn_arr_temp[vv] = spatial.cKDTree(coords_test[vv]) nn_arr[vv] = np.array(nn_arr_temp[vv].query(coords_test[vv],\ neigh_vals[-1]+1)[0]) nn_idx[vv] = np.array(nn_arr_temp[vv].query(coords_test[vv],\ neigh_vals[-1]+1)[1]) ##nn_specs is a list, with 8 elements, one for each mock ##each list has a series of numpy arrays, however many galaxies there are in ##that mock ##these arrays give the distances to the nearest neighbors of interest nn_specs = [(np.array(nn_arr).T[ii].T[neigh_vals].T) for ii in\ xrange(num_of_mocks)] ##houses the same info as nn_specs, except now, the logMstar of each galaxy is ##the first term of the numpy array nn_mass_dist = np.array([(np.column_stack((mass_arr[qq],nn_specs[qq])))\ for qq in xrange(num_of_mocks)]) ##houses the indexes of the neighbors of interest for each galaxy nn_neigh_idx = np.array([(np.array(nn_idx).T[ii].T[neigh_vals].T) \ for ii in xrange(num_of_mocks)]) ############################################################################### ##nn_dist_sorting is a dictionary which has a key for every mock, and then keys for ##each nn value. Each nn_dist_sorting[mock][nn] has however many elements as there are galaxies in ##that specific mock. These elements are 1 by 2 arrays, with the logMstar of the ##galaxy and the distance to its nth nearest neighbor ##dist_sort_mass is the dictionary of mocks of nn's with the logMstars sorted ##according to the distance to the nth nearest neighbor. This was sorted using ##large to small distance, so low to high density. nn_dist_sorting = {} dist_sort_mass = {} ##for use with density in a sphere # nn_dens = {} # mass_dat = {} ratio_info = {} bin_cens_diff = {} # mass_freq = [[] for xx in xrange(len(coords_test))] mass_freq = {} for ii in xrange(num_of_mocks): nn_dist_sorting[ii] = {} dist_sort_mass[ii] = {} ##for use with density in a sphere # nn_dens[ii] = {} # mass_dat[ii] = {} ratio_info[ii] = {} bin_cens_diff[ii] = {} for jj in xrange(len(neigh_vals)): nn_dist_sorting[ii][(neigh_vals[jj])] = np.column_stack((nn_mass_dist[ii].T\ [0],np.array(nn_mass_dist[ii].T[xrange(1,len(neigh_vals)+1)[jj]]))) ##smallest distance to largest (before reverse) Reversed, so then the ##largest distances are first, meaning the least dense environments ##gives indices of the sorted distances dist_sort_idx = np.argsort(np.array(nn_dist_sorting[ii][neigh_vals[jj]].T\ [1]))[::-1] ##using the index to sort the masses for each mock according to each nn dist_sort_mass[ii][(neigh_vals[jj])] = (nn_dist_sorting[ii][neigh_vals\ [jj]][dist_sort_idx].T[0]) ##this created a dictionary with arrays containing the logMstar and ##environment densities . a moot point for nn environment, but this may ##be useful when I switch out nn for density of a sphere # nn_dens[ii][(neigh_vals[jj])] = np.column_stack((nn_mass_dist[ii].T\ # [0],calc_dens_nn(neigh_vals[jj],\ # nn_mass_dist[ii].T[range(1,len(neigh_vals)+1)[jj]]))) ##lowest density to highest # idx = np.array(nn_dens[ii][neigh_vals[jj]].T[1].argsort()) # mass_dat[ii][(neigh_vals[jj])] = (nn_dens[ii][neigh_vals[jj]]\ # [idx].T[0]) ##bin_centers is the median mass value of each bin; good for plotting ##to make things seem equally spaced ##mass_freq is now a dictionary with keys for each mock. Each key ##houses two arrays. one with the frequency values and another with ##Poisson errors ##ratio_info is a dictionary with mock number of keys to other ##dictionaries. Then, there are keys for each nn. These give back a ##list. The first list item is a dictionary with three keys (2,4,10), ##corresponding to the fractional cuts that we made ##The next item is a list of three arrays, housing the corresponding ##errors ##bin_cens_diff is so that, for the off chance of empty bins, we have ##the proper bins to plot the ratio_info with (actually, this is ##probably useful for the ratio cuts and larger mass bins. idk) bin_centers, mass_freq[ii], ratio_info[ii][neigh_vals[jj]],\ bin_cens_diff[ii][neigh_vals[jj]] = \ plot_calcs(dist_sort_mass[ii][neigh_vals[jj]],bins,dlogM) ##all_mock_meds is a dictionary with 6 keys, for the nn vals. These have keys ##for each mock. These keys gve back arrays with the median distance ##values to the nth neighbor for each mass bins ##this previously had some code to give back the appropriate x-coordinates for ##plotting, but the number of medians is all the same... on the off chance that ##for some reason this throws an error in the future, the original code is in ##pickling. all_mock_meds = {} for jj in xrange(len(nn_mass_dist[vv].T)-1): all_mock_meds[neigh_vals[jj]] = {} for vv in xrange(num_of_mocks): all_mock_meds[neigh_vals[jj]][vv] = (bin_func(nn_mass_dist[vv],\ bins,(jj+1))) ##this is for debugging; shows the number of medians listed for each nn for ##each mock. if these are not all the same, there is a problem, and the ##extra code may, in fact, be needed # for vv in xrange(8): # for jj in xrange(6): # print len(all_mock_meds[neigh_vals[jj]][vv]) ##Bands for median distances ##I am torn about eventually turning this into a function. I think there are ##a fair amount of variables, etc. between the different times that I do this ##that if this were a function, it would need to intake a lot of arguments ##This works by counting the number of columns in one median distance array. ##Then, after making sure there are the same number of medians in each case, ##it begins to make a matrix of arrays, 13 rows by 8 columns. So, it inserted ##the medians of each mock vertically. Then, it can take the max/min of each ##row! This definitely came from Victor. ##Returns a dictionary with keys which are strings of the nn vals. Each key ##gives a list of two numpy arrays, the first being the max for each bin ##and the second being the min. band_for_medians = {} for nn in neigh_vals: for ii in xrange(num_of_mocks): med_str = '{0}'.format(nn) num_of_meds = all_mock_meds[nn][ii] if len(num_of_meds) == num_of_bins: n_elem = len(num_of_meds) else: while len(num_of_meds) < num_of_bins: num_of_meds_list = list(num_of_meds) num_of_meds_list.append(np.nan) num_of_meds = np.array(num_of_meds_list) n_elem = len(num_of_meds) if ii == 0: med_matrix = np.zeros((n_elem,1)) med_matrix = np.insert(med_matrix,len(med_matrix.T),num_of_meds,1) med_matrix = np.array(np.delete(med_matrix,0,axis=1)) med_matrix_max = np.array([np.nanmax(med_matrix[kk]) for kk in \ xrange(len(med_matrix))]) med_matrix_min = np.array([np.nanmin(med_matrix[kk]) for kk in \ xrange(len(med_matrix))]) band_for_medians[med_str] = [med_matrix_max,med_matrix_min] ############################################################################### ##First thing to know: ratio_info. It's a dictionary with a key for each mock ##and then a key for each neighbor value. This gives a list, one with 2 items. ##The first is a dictionary with three keys, one for each frac val. The second ##is a list of three numpy arrays. Each array has the error on the ##corresponding frac val numbers ##Plot_ratio_arr is a dictionary (funny, since you'd think it's an array,right) ##It has a key for each nn, a key for each frac val, and a key for each mock ##We just ignore the error. It was calculated for fun? I'm not sure if it will ##ever be useful for anything, but just in case? I used to have it be an ##option in the function (plot_calcs, I think). plot_ratio_arr = {} for ii in neigh_vals: plot_ratio_arr[ii] = {} for hh in frac_vals: plot_ratio_arr[ii][hh] = {} for jj in xrange(num_of_mocks): plot_ratio_arr[ii][hh][jj] = ratio_info[jj][ii][0][hh] band_for_ratios = {} ##This code works just as the code for the median bands does ##Apparently, there's an all Nan axis encountered somewhere, but that's okay for nn in neigh_vals: for vv in frac_vals: bin_str = '{0}_{1}'.format(nn,vv) for cc in xrange(num_of_mocks): num_of_rats = plot_ratio_arr[nn][vv][cc] if len(num_of_rats) == num_of_bins: n_elem = len(num_of_rats) else: while len(num_of_rats) < num_of_bins: num_of_rats_list = list(num_of_rats) num_of_rats_list.append(np.nan) num_of_rats = np.array(num_of_rats_list) n_elem = len(num_of_rats) if cc == 0: rat_matrix = np.zeros((n_elem,1)) rat_matrix = np.insert(rat_matrix,len(rat_matrix.T),num_of_rats,1) rat_matrix = np.array(np.delete(rat_matrix,0,axis=1)) for kk in xrange(len(rat_matrix)): ##this is kind of a hack, because there was no better way to get ##around the infinities rat_matrix[kk][rat_matrix[kk] == np.inf] = np.nan rat_matrix_max = [np.nanmax(rat_matrix[kk]) \ for kk in xrange(len(rat_matrix))] rat_matrix_min = [np.nanmin(rat_matrix[kk]) \ for kk in xrange(len(rat_matrix))] band_for_ratios[bin_str] = [rat_matrix_max,rat_matrix_min] ###New code for creating the band for the stellar mass function ###I'm just assuming that each mock will have the same number of bins band_for_mass_func = {} for jj in xrange(num_of_mocks): mfunc_arr = mass_freq[jj][0] n_elem = len(mfunc_arr) if jj == 0: mfunc_matrix = np.zeros((n_elem,1)) mfunc_matrix = np.insert(mfunc_matrix,len(mfunc_matrix.T),mfunc_arr,1) mfunc_matrix = np.array(np.delete(mfunc_matrix,0,axis=1)) mfunc_mat_max = [np.max(mfunc_matrix[kk]) for kk in xrange(len(mfunc_matrix))] mfunc_mat_min = [np.min(mfunc_matrix[kk]) for kk in xrange(len(mfunc_matrix))] ############################################################################### ##may need for later... when dealinng with histogram bands nn_keys = np.sort(neigh_dict.keys()) col_keys = np.sort(frac_dict.keys()) ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### ##Beginning the process of calculating how many galaxies in a specific mass bin ##have their nth nearest neighbor in the same halo as them ##truth_vals will be a dictionary with keys for each mock and then keys for ##each nn value; a boolean type array. This structure amazes me and I have a ##difficult time imagining I came up with it myself... truth_vals = {} for ii in xrange(len(halo_id_arr)): truth_vals[ii] = {} for jj in neigh_vals: halo_id_neigh = halo_id_arr[ii][nn_neigh_idx[ii].T[neigh_dict[jj]]].values truth_vals[ii][jj] = halo_id_neigh==halo_id_arr[ii].values ##halo_frac is a dictionary much like the truth values. Number of mocks for keys, ##then number of nearest neighbors. For each mock, neighbor, specific mass bin, ##it lists the fraction of galaxies with nn in their same halo ##I also have a hard time remembering developing this code... I imagine it was ##a messy process. But it worked out in the end! halo_frac = {} for ii in xrange(len(mass_arr)): halo_frac[ii] = {} mass_binning = np.digitize(mass_arr[ii],bins) bins_to_use = list(np.unique(mass_binning)) if (len(bins)-1) not in bins_to_use: bins_to_use.append(len(bins)-1) if len(bins) in bins_to_use: bins_to_use.remove(len(bins)) for jj in neigh_vals: one_zero = truth_vals[ii][jj].astype(int) frac = [] for xx in bins_to_use: truth_binning = one_zero[mass_binning==xx] num_in_bin = len(truth_binning) if num_in_bin == 0: num_in_bin = np.nan num_same_halo = np.count_nonzero(truth_binning==1) frac.append(num_same_halo/(1.*num_in_bin)) halo_frac[ii][jj] = frac ##Finding the mean fraction for each mass bin in the separate mocks. Also ##finding the standard deviation, to use as error mean_mock_halo_frac = {} for ii in neigh_vals: for jj in xrange(len(halo_frac)): bin_str = '{0}'.format(ii) oo_arr = halo_frac[jj][ii] n_o_elem = len(oo_arr) if jj == 0: oo_tot = np.zeros((n_o_elem,1)) oo_tot = np.insert(oo_tot,len(oo_tot.T),oo_arr,1) oo_tot = np.array(np.delete(oo_tot,0,axis=1)) oo_tot_mean = [np.nanmean(oo_tot[uu]) for uu in xrange(len(oo_tot))] oo_tot_std = [np.nanstd(oo_tot[uu])/np.sqrt(len(halo_frac)) \ for uu in xrange(len(oo_tot))] mean_mock_halo_frac[bin_str] = np.array([oo_tot_mean,oo_tot_std]) ############################################################################### ##Plotting the mean halo frac for the mocks for each nn value nrow = int(2) ncol = int(3) fig,axes = plt.subplots(nrows=nrow,ncols=ncol, \ figsize=(12,12),sharex=True,sharey=True) axes_flat = axes.flatten() zz = int(0) while zz <=4: for jj in neigh_vals: for kk in xrange(len(halo_frac)): if kk == 0: value = True else: value = False plot_halo_frac(bin_centers,halo_frac[kk][jj],axes_flat[zz],zz,\ text = value) nn_str = '{0}'.format(jj) plot_mean_halo_frac(bin_centers,mean_mock_halo_frac[nn_str][0],\ axes_flat[zz],mean_mock_halo_frac[nn_str][1]) zz += 1 plt.subplots_adjust(top=0.97,bottom=0.1,left=0.03,right=0.99,hspace=0.10,\ wspace=0.12) plt.show()
[ "matplotlib.rc", "numpy.nanmedian", "pandas.read_csv", "numpy.argsort", "numpy.histogram", "numpy.arange", "scipy.spatial.cKDTree", "numpy.unique", "numpy.nanmean", "os.path.exists", "numpy.isfinite", "numpy.max", "matplotlib.pyplot.subplots", "numpy.radians", "matplotlib.pyplot.show", "numpy.min", "matplotlib.pyplot.subplots_adjust", "numpy.digitize", "numpy.delete", "numpy.nanmax", "numpy.count_nonzero", "numpy.nanstd", "numpy.zeros", "numpy.nanmin", "numpy.array", "numpy.column_stack", "numpy.sqrt" ]
[((210, 233), 'matplotlib.rc', 'rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (212, 233), False, 'from matplotlib import rc, rcParams\n'), ((234, 257), 'matplotlib.rc', 'rc', (['"""axes"""'], {'linewidth': '(2)'}), "('axes', linewidth=2)\n", (236, 257), False, 'from matplotlib import rc, rcParams\n'), ((258, 283), 'matplotlib.rc', 'rc', (['"""font"""'], {'weight': '"""bold"""'}), "('font', weight='bold')\n", (260, 283), False, 'from matplotlib import rc, rcParams\n'), ((15824, 15864), 'numpy.array', 'np.array', (['[2, 4, 10, 15, 16, 19, 20, 21]'], {}), '([2, 4, 10, 15, 16, 19, 20, 21])\n', (15832, 15864), True, 'import numpy as np\n'), ((16117, 16202), 'pandas.read_csv', 'pd.read_csv', (['ECO_true[0]'], {'usecols': 'eco_cols', 'header': 'None', 'skiprows': '(1)', 'names': 'names'}), '(ECO_true[0], usecols=eco_cols, header=None, skiprows=1, names=names\n )\n', (16128, 16202), True, 'import pandas as pd\n'), ((18847, 18873), 'numpy.array', 'np.array', (['min_max_mass_arr'], {}), '(min_max_mass_arr)\n', (18855, 18873), True, 'import numpy as np\n'), ((19213, 19232), 'numpy.array', 'np.array', (['bins_list'], {}), '(bins_list)\n', (19221, 19232), True, 'import numpy as np\n'), ((20394, 20424), 'numpy.array', 'np.array', (['[1, 2, 3, 5, 10, 20]'], {}), '([1, 2, 3, 5, 10, 20])\n', (20402, 20424), True, 'import numpy as np\n'), ((20435, 20455), 'numpy.array', 'np.array', (['[2, 4, 10]'], {}), '([2, 4, 10])\n', (20443, 20455), True, 'import numpy as np\n'), ((20790, 20817), 'scipy.spatial.cKDTree', 'spatial.cKDTree', (['coords_eco'], {}), '(coords_eco)\n', (20805, 20817), False, 'from scipy import integrate, optimize, spatial\n'), ((21740, 21798), 'numpy.column_stack', 'np.column_stack', (['(mass_eco, eco_tree_dist.T[neigh_vals].T)'], {}), '((mass_eco, eco_tree_dist.T[neigh_vals].T))\n', (21755, 21798), True, 'import numpy as np\n'), ((37326, 37411), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': 'nrow', 'ncols': 'ncol', 'figsize': '(12, 12)', 'sharex': '(True)', 'sharey': '(True)'}), '(nrows=nrow, ncols=ncol, figsize=(12, 12), sharex=True, sharey=True\n )\n', (37338, 37411), True, 'import matplotlib.pyplot as plt\n'), ((37943, 38036), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'top': '(0.97)', 'bottom': '(0.1)', 'left': '(0.03)', 'right': '(0.99)', 'hspace': '(0.1)', 'wspace': '(0.12)'}), '(top=0.97, bottom=0.1, left=0.03, right=0.99, hspace=0.1,\n wspace=0.12)\n', (37962, 38036), True, 'import matplotlib.pyplot as plt\n'), ((38041, 38051), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (38049, 38051), True, 'import matplotlib.pyplot as plt\n'), ((1668, 1693), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (1682, 1693), False, 'import os\n'), ((3306, 3319), 'numpy.array', 'np.array', (['arr'], {}), '(arr)\n', (3314, 3319), True, 'import numpy as np\n'), ((3449, 3495), 'numpy.arange', 'np.arange', (['arr_min', '(arr_max + 0.5 * base)', 'base'], {}), '(arr_min, arr_max + 0.5 * base, base)\n', (3458, 3495), True, 'import numpy as np\n'), ((4367, 4405), 'numpy.column_stack', 'np.column_stack', (['(x_arr, y_arr, z_arr)'], {}), '((x_arr, y_arr, z_arr))\n', (4382, 4405), True, 'import numpy as np\n'), ((6498, 6522), 'numpy.histogram', 'np.histogram', (['mass', 'bins'], {}), '(mass, bins)\n', (6510, 6522), True, 'import numpy as np\n'), ((8069, 8093), 'numpy.array', 'np.array', (['mass_freq_list'], {}), '(mass_freq_list)\n', (8077, 8093), True, 'import numpy as np\n'), ((9888, 9922), 'numpy.digitize', 'np.digitize', (['mass_dist.T[0]', 'edges'], {}), '(mass_dist.T[0], edges)\n', (9899, 9922), True, 'import numpy as np\n'), ((9973, 9993), 'numpy.unique', 'np.unique', (['digitized'], {}), '(digitized)\n', (9982, 9993), True, 'import numpy as np\n'), ((10150, 10173), 'numpy.array', 'np.array', (['bin_nums_list'], {}), '(bin_nums_list)\n', (10158, 10173), True, 'import numpy as np\n'), ((12670, 12690), 'numpy.array', 'np.array', (['[2, 4, 10]'], {}), '([2, 4, 10])\n', (12678, 12690), True, 'import numpy as np\n'), ((17391, 17487), 'pandas.read_csv', 'pd.read_csv', (['ECO_cats[ii]'], {'sep': '"""\\\\s+"""', 'usecols': 'usecols', 'header': 'None', 'skiprows': '(2)', 'names': 'names'}), "(ECO_cats[ii], sep='\\\\s+', usecols=usecols, header=None,\n skiprows=2, names=names)\n", (17402, 17487), True, 'import pandas as pd\n'), ((23626, 23658), 'scipy.spatial.cKDTree', 'spatial.cKDTree', (['coords_test[vv]'], {}), '(coords_test[vv])\n', (23641, 23658), False, 'from scipy import integrate, optimize, spatial\n'), ((33868, 33902), 'numpy.delete', 'np.delete', (['mfunc_matrix', '(0)'], {'axis': '(1)'}), '(mfunc_matrix, 0, axis=1)\n', (33877, 33902), True, 'import numpy as np\n'), ((33919, 33943), 'numpy.max', 'np.max', (['mfunc_matrix[kk]'], {}), '(mfunc_matrix[kk])\n', (33925, 33943), True, 'import numpy as np\n'), ((33998, 34022), 'numpy.min', 'np.min', (['mfunc_matrix[kk]'], {}), '(mfunc_matrix[kk])\n', (34004, 34022), True, 'import numpy as np\n'), ((35723, 35754), 'numpy.digitize', 'np.digitize', (['mass_arr[ii]', 'bins'], {}), '(mass_arr[ii], bins)\n', (35734, 35754), True, 'import numpy as np\n'), ((37100, 37135), 'numpy.array', 'np.array', (['[oo_tot_mean, oo_tot_std]'], {}), '([oo_tot_mean, oo_tot_std])\n', (37108, 37135), True, 'import numpy as np\n'), ((6937, 6966), 'numpy.histogram', 'np.histogram', (['frac_mass', 'bins'], {}), '(frac_mass, bins)\n', (6949, 6966), True, 'import numpy as np\n'), ((7091, 7122), 'numpy.histogram', 'np.histogram', (['frac_mass_2', 'bins'], {}), '(frac_mass_2, bins)\n', (7103, 7122), True, 'import numpy as np\n'), ((7232, 7257), 'numpy.isfinite', 'np.isfinite', (['ratio_counts'], {}), '(ratio_counts)\n', (7243, 7257), True, 'import numpy as np\n'), ((10331, 10394), 'numpy.array', 'np.array', (['[mass_dist.T[kk][digitized == ii] for ii in bin_nums]'], {}), '([mass_dist.T[kk][digitized == ii] for ii in bin_nums])\n', (10339, 10394), True, 'import numpy as np\n'), ((11310, 11328), 'numpy.array', 'np.array', (['med_list'], {}), '(med_list)\n', (11318, 11328), True, 'import numpy as np\n'), ((13109, 13138), 'numpy.histogram', 'np.histogram', (['frac_mass', 'bins'], {}), '(frac_mass, bins)\n', (13121, 13138), True, 'import numpy as np\n'), ((13961, 13992), 'numpy.histogram', 'np.histogram', (['frac_mass_2', 'bins'], {}), '(frac_mass_2, bins)\n', (13973, 13992), True, 'import numpy as np\n'), ((14692, 14717), 'numpy.arange', 'np.arange', (['(9.5)', '(12.0)', '(0.5)'], {}), '(9.5, 12.0, 0.5)\n', (14701, 14717), True, 'import numpy as np\n'), ((22181, 22212), 'numpy.argsort', 'np.argsort', (['eco_mass_dist.T[kk]'], {}), '(eco_mass_dist.T[kk])\n', (22191, 22212), True, 'import numpy as np\n'), ((24347, 24392), 'numpy.column_stack', 'np.column_stack', (['(mass_arr[qq], nn_specs[qq])'], {}), '((mass_arr[qq], nn_specs[qq]))\n', (24362, 24392), True, 'import numpy as np\n'), ((30707, 30739), 'numpy.delete', 'np.delete', (['med_matrix', '(0)'], {'axis': '(1)'}), '(med_matrix, 0, axis=1)\n', (30716, 30739), True, 'import numpy as np\n'), ((33746, 33767), 'numpy.zeros', 'np.zeros', (['(n_elem, 1)'], {}), '((n_elem, 1))\n', (33754, 33767), True, 'import numpy as np\n'), ((35777, 35800), 'numpy.unique', 'np.unique', (['mass_binning'], {}), '(mass_binning)\n', (35786, 35800), True, 'import numpy as np\n'), ((36862, 36890), 'numpy.delete', 'np.delete', (['oo_tot', '(0)'], {'axis': '(1)'}), '(oo_tot, 0, axis=1)\n', (36871, 36890), True, 'import numpy as np\n'), ((36909, 36931), 'numpy.nanmean', 'np.nanmean', (['oo_tot[uu]'], {}), '(oo_tot[uu])\n', (36919, 36931), True, 'import numpy as np\n'), ((4221, 4236), 'numpy.radians', 'np.radians', (['dec'], {}), '(dec)\n', (4231, 4236), True, 'import numpy as np\n'), ((4290, 4305), 'numpy.radians', 'np.radians', (['dec'], {}), '(dec)\n', (4300, 4305), True, 'import numpy as np\n'), ((4336, 4351), 'numpy.radians', 'np.radians', (['dec'], {}), '(dec)\n', (4346, 4351), True, 'import numpy as np\n'), ((7510, 7548), 'numpy.sqrt', 'np.sqrt', (['(1.0 / counts + 1.0 / counts_2)'], {}), '(1.0 / counts + 1.0 / counts_2)\n', (7517, 7548), True, 'import numpy as np\n'), ((8000, 8020), 'numpy.sqrt', 'np.sqrt', (['mass_counts'], {}), '(mass_counts)\n', (8007, 8020), True, 'import numpy as np\n'), ((10204, 10250), 'numpy.nanmedian', 'np.nanmedian', (['mass_dist.T[kk][digitized == ii]'], {}), '(mass_dist.T[kk][digitized == ii])\n', (10216, 10250), True, 'import numpy as np\n'), ((30585, 30606), 'numpy.zeros', 'np.zeros', (['(n_elem, 1)'], {}), '((n_elem, 1))\n', (30593, 30606), True, 'import numpy as np\n'), ((30770, 30795), 'numpy.nanmax', 'np.nanmax', (['med_matrix[kk]'], {}), '(med_matrix[kk])\n', (30779, 30795), True, 'import numpy as np\n'), ((30873, 30898), 'numpy.nanmin', 'np.nanmin', (['med_matrix[kk]'], {}), '(med_matrix[kk])\n', (30882, 30898), True, 'import numpy as np\n'), ((32929, 32961), 'numpy.delete', 'np.delete', (['rat_matrix', '(0)'], {'axis': '(1)'}), '(rat_matrix, 0, axis=1)\n', (32938, 32961), True, 'import numpy as np\n'), ((33205, 33230), 'numpy.nanmax', 'np.nanmax', (['rat_matrix[kk]'], {}), '(rat_matrix[kk])\n', (33214, 33230), True, 'import numpy as np\n'), ((33306, 33331), 'numpy.nanmin', 'np.nanmin', (['rat_matrix[kk]'], {}), '(rat_matrix[kk])\n', (33315, 33331), True, 'import numpy as np\n'), ((36274, 36310), 'numpy.count_nonzero', 'np.count_nonzero', (['(truth_binning == 1)'], {}), '(truth_binning == 1)\n', (36290, 36310), True, 'import numpy as np\n'), ((36759, 36782), 'numpy.zeros', 'np.zeros', (['(n_o_elem, 1)'], {}), '((n_o_elem, 1))\n', (36767, 36782), True, 'import numpy as np\n'), ((36982, 37003), 'numpy.nanstd', 'np.nanstd', (['oo_tot[uu]'], {}), '(oo_tot[uu])\n', (36991, 37003), True, 'import numpy as np\n'), ((4198, 4212), 'numpy.radians', 'np.radians', (['ra'], {}), '(ra)\n', (4208, 4212), True, 'import numpy as np\n'), ((4267, 4281), 'numpy.radians', 'np.radians', (['ra'], {}), '(ra)\n', (4277, 4281), True, 'import numpy as np\n'), ((13719, 13734), 'numpy.sqrt', 'np.sqrt', (['counts'], {}), '(counts)\n', (13726, 13734), True, 'import numpy as np\n'), ((14273, 14290), 'numpy.sqrt', 'np.sqrt', (['counts_2'], {}), '(counts_2)\n', (14280, 14290), True, 'import numpy as np\n'), ((26170, 26220), 'numpy.array', 'np.array', (['nn_dist_sorting[ii][neigh_vals[jj]].T[1]'], {}), '(nn_dist_sorting[ii][neigh_vals[jj]].T[1])\n', (26178, 26220), True, 'import numpy as np\n'), ((30475, 30501), 'numpy.array', 'np.array', (['num_of_meds_list'], {}), '(num_of_meds_list)\n', (30483, 30501), True, 'import numpy as np\n'), ((32799, 32820), 'numpy.zeros', 'np.zeros', (['(n_elem, 1)'], {}), '((n_elem, 1))\n', (32807, 32820), True, 'import numpy as np\n'), ((32677, 32703), 'numpy.array', 'np.array', (['num_of_rats_list'], {}), '(num_of_rats_list)\n', (32685, 32703), True, 'import numpy as np\n'), ((24088, 24104), 'numpy.array', 'np.array', (['nn_arr'], {}), '(nn_arr)\n', (24096, 24104), True, 'import numpy as np\n'), ((24544, 24560), 'numpy.array', 'np.array', (['nn_idx'], {}), '(nn_idx)\n', (24552, 24560), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np def plotLine(c0, c1, ax): t = np.linspace(0, 1, 11) c = (c1 - c0) * t + c0 ax.plot(c.real, c.imag) def plotCircle(c0, r, ax): t = np.linspace(0, 1, 1001) * 2 * np.pi s = c0 + r * np.exp(1j * t) ax.plot(s.real, s.imag) def plotEllipse(c0, a, b, phi, ax): t = np.linspace(0, 1, 1001) * 2 * np.pi c = np.exp(1j * t) s = c0 + (c.real * a + 1j * c.imag * b) * np.exp(1j * phi) ax.plot(s.real, s.imag) def plotDistribution(s0, s1, fig=None, axes=None, info=None, hotThresh=10000): from waveforms.math.fit import get_threshold_info, mult_gaussian_pdf if info is None: info = get_threshold_info(s0, s1) thr, phi = info['threshold'], info['phi'] visibility, p0, p1 = info['visibility'] # print( # f"thr={thr:.6f}, phi={phi:.6f}, visibility={visibility:.3f}, {p0}, {1-p1}" # ) if axes is not None: ax1, ax2 = axes else: if fig is None: fig = plt.figure() ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) if (len(s0) + len(s1)) < hotThresh: ax1.plot(np.real(s0), np.imag(s0), '.', alpha=0.2) ax1.plot(np.real(s1), np.imag(s1), '.', alpha=0.2) else: _, *bins = np.histogram2d(np.real(np.hstack([s0, s1])), np.imag(np.hstack([s0, s1])), bins=50) H0, *_ = np.histogram2d(np.real(s0), np.imag(s0), bins=bins, density=True) H1, *_ = np.histogram2d(np.real(s1), np.imag(s1), bins=bins, density=True) vlim = max(np.max(np.abs(H0)), np.max(np.abs(H1))) ax1.imshow(H1.T - H0.T, alpha=(np.fmax(H0.T, H1.T) / vlim).clip(0, 1), interpolation='nearest', origin='lower', cmap='coolwarm', vmin=-vlim, vmax=vlim, extent=(bins[0][0], bins[0][-1], bins[1][0], bins[1][-1])) ax1.axis('equal') ax1.set_xticks([]) ax1.set_yticks([]) for s in ax1.spines.values(): s.set_visible(False) # c0, c1 = info['center'] # a0, b0, a1, b1 = info['std'] params = info['params'] r0, i0, r1, i1 = params[0][0], params[1][0], params[0][1], params[1][1] a0, b0, a1, b1 = params[0][2], params[1][2], params[0][3], params[1][3] c0 = (r0 + 1j * i0) * np.exp(1j * phi) c1 = (r1 + 1j * i1) * np.exp(1j * phi) plotEllipse(c0, 2 * a0, 2 * b0, phi, ax1) plotEllipse(c1, 2 * a1, 2 * b1, phi, ax1) im0, im1 = info['idle'] lim = min(im0.min(), im1.min()), max(im0.max(), im1.max()) t = (np.linspace(lim[0], lim[1], 3) + 1j * thr) * np.exp(-1j * phi) ax1.plot(t.imag, t.real, 'k--') ax1.plot(np.real(c0), np.imag(c0), 'o', color='C3') ax1.plot(np.real(c1), np.imag(c1), 'o', color='C4') re0, re1 = info['signal'] x, a, b, c = info['cdf'] n0, bins0, *_ = ax2.hist(re0, bins=50, alpha=0.5) n1, bins1, *_ = ax2.hist(re1, bins=50, alpha=0.5) ax2.plot( x, np.sum(n0) * (bins0[1] - bins0[0]) * mult_gaussian_pdf( x, [r0, r1], [a0, a1], [params[0][4], 1 - params[0][4]])) ax2.plot( x, np.sum(n1) * (bins1[1] - bins1[0]) * mult_gaussian_pdf( x, [r0, r1], [a0, a1], [params[0][5], 1 - params[0][5]])) ax2.set_ylabel('Count') ax2.set_xlabel('Projection Axes') ax3 = ax2.twinx() ax3.plot(x, a) ax3.plot(x, b) ax3.plot(x, c) ax3.set_ylim(0, 1.1) ax3.vlines(thr, 0, 1.1, 'k') ax3.set_ylabel('Probility') return info ALLXYSeq = [('I', 'I'), ('X', 'X'), ('Y', 'Y'), ('X', 'Y'), ('Y', 'X'), ('X/2', 'I'), ('Y/2', 'I'), ('X/2', 'Y/2'), ('Y/2', 'X/2'), ('X/2', 'Y'), ('Y/2', 'X'), ('X', 'Y/2'), ('Y', 'X/2'), ('X/2', 'X'), ('X', 'X/2'), ('Y/2', 'Y'), ('Y', 'Y/2'), ('X', 'I'), ('Y', 'I'), ('X/2', 'X/2'), ('Y/2', 'Y/2')] def plotALLXY(data, ax=None): assert len(data) % len(ALLXYSeq) == 0 if ax is None: ax = plt.gca() ax.plot(np.array(data), 'o-') repeat = len(data) // len(ALLXYSeq) ax.set_xticks(np.arange(len(ALLXYSeq)) * repeat + 0.5 * (repeat - 1)) ax.set_xticklabels([','.join(seq) for seq in ALLXYSeq], rotation=60) ax.grid(which='major')
[ "numpy.fmax", "numpy.abs", "numpy.sum", "matplotlib.pyplot.gca", "numpy.hstack", "numpy.imag", "matplotlib.pyplot.figure", "numpy.array", "numpy.exp", "numpy.real", "numpy.linspace", "waveforms.math.fit.mult_gaussian_pdf", "waveforms.math.fit.get_threshold_info" ]
[((87, 108), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(11)'], {}), '(0, 1, 11)\n', (98, 108), True, 'import numpy as np\n'), ((387, 403), 'numpy.exp', 'np.exp', (['(1.0j * t)'], {}), '(1.0j * t)\n', (393, 403), True, 'import numpy as np\n'), ((684, 710), 'waveforms.math.fit.get_threshold_info', 'get_threshold_info', (['s0', 's1'], {}), '(s0, s1)\n', (702, 710), False, 'from waveforms.math.fit import get_threshold_info, mult_gaussian_pdf\n'), ((2607, 2625), 'numpy.exp', 'np.exp', (['(1.0j * phi)'], {}), '(1.0j * phi)\n', (2613, 2625), True, 'import numpy as np\n'), ((2650, 2668), 'numpy.exp', 'np.exp', (['(1.0j * phi)'], {}), '(1.0j * phi)\n', (2656, 2668), True, 'import numpy as np\n'), ((2905, 2924), 'numpy.exp', 'np.exp', (['(-1.0j * phi)'], {}), '(-1.0j * phi)\n', (2911, 2924), True, 'import numpy as np\n'), ((2973, 2984), 'numpy.real', 'np.real', (['c0'], {}), '(c0)\n', (2980, 2984), True, 'import numpy as np\n'), ((2986, 2997), 'numpy.imag', 'np.imag', (['c0'], {}), '(c0)\n', (2993, 2997), True, 'import numpy as np\n'), ((3029, 3040), 'numpy.real', 'np.real', (['c1'], {}), '(c1)\n', (3036, 3040), True, 'import numpy as np\n'), ((3042, 3053), 'numpy.imag', 'np.imag', (['c1'], {}), '(c1)\n', (3049, 3053), True, 'import numpy as np\n'), ((4269, 4278), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (4276, 4278), True, 'import matplotlib.pyplot as plt\n'), ((4292, 4306), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (4300, 4306), True, 'import numpy as np\n'), ((201, 224), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1001)'], {}), '(0, 1, 1001)\n', (212, 224), True, 'import numpy as np\n'), ((254, 270), 'numpy.exp', 'np.exp', (['(1.0j * t)'], {}), '(1.0j * t)\n', (260, 270), True, 'import numpy as np\n'), ((343, 366), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1001)'], {}), '(0, 1, 1001)\n', (354, 366), True, 'import numpy as np\n'), ((448, 466), 'numpy.exp', 'np.exp', (['(1.0j * phi)'], {}), '(1.0j * phi)\n', (454, 466), True, 'import numpy as np\n'), ((1009, 1021), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1019, 1021), True, 'import matplotlib.pyplot as plt\n'), ((1150, 1161), 'numpy.real', 'np.real', (['s0'], {}), '(s0)\n', (1157, 1161), True, 'import numpy as np\n'), ((1163, 1174), 'numpy.imag', 'np.imag', (['s0'], {}), '(s0)\n', (1170, 1174), True, 'import numpy as np\n'), ((1209, 1220), 'numpy.real', 'np.real', (['s1'], {}), '(s1)\n', (1216, 1220), True, 'import numpy as np\n'), ((1222, 1233), 'numpy.imag', 'np.imag', (['s1'], {}), '(s1)\n', (1229, 1233), True, 'import numpy as np\n'), ((1465, 1476), 'numpy.real', 'np.real', (['s0'], {}), '(s0)\n', (1472, 1476), True, 'import numpy as np\n'), ((1510, 1521), 'numpy.imag', 'np.imag', (['s0'], {}), '(s0)\n', (1517, 1521), True, 'import numpy as np\n'), ((1644, 1655), 'numpy.real', 'np.real', (['s1'], {}), '(s1)\n', (1651, 1655), True, 'import numpy as np\n'), ((1689, 1700), 'numpy.imag', 'np.imag', (['s1'], {}), '(s1)\n', (1696, 1700), True, 'import numpy as np\n'), ((2860, 2890), 'numpy.linspace', 'np.linspace', (['lim[0]', 'lim[1]', '(3)'], {}), '(lim[0], lim[1], 3)\n', (2871, 2890), True, 'import numpy as np\n'), ((3311, 3385), 'waveforms.math.fit.mult_gaussian_pdf', 'mult_gaussian_pdf', (['x', '[r0, r1]', '[a0, a1]', '[params[0][4], 1 - params[0][4]]'], {}), '(x, [r0, r1], [a0, a1], [params[0][4], 1 - params[0][4]])\n', (3328, 3385), False, 'from waveforms.math.fit import get_threshold_info, mult_gaussian_pdf\n'), ((3470, 3544), 'waveforms.math.fit.mult_gaussian_pdf', 'mult_gaussian_pdf', (['x', '[r0, r1]', '[a0, a1]', '[params[0][5], 1 - params[0][5]]'], {}), '(x, [r0, r1], [a0, a1], [params[0][5], 1 - params[0][5]])\n', (3487, 3544), False, 'from waveforms.math.fit import get_threshold_info, mult_gaussian_pdf\n'), ((1303, 1322), 'numpy.hstack', 'np.hstack', (['[s0, s1]'], {}), '([s0, s1])\n', (1312, 1322), True, 'import numpy as np\n'), ((1367, 1386), 'numpy.hstack', 'np.hstack', (['[s0, s1]'], {}), '([s0, s1])\n', (1376, 1386), True, 'import numpy as np\n'), ((1817, 1827), 'numpy.abs', 'np.abs', (['H0'], {}), '(H0)\n', (1823, 1827), True, 'import numpy as np\n'), ((1837, 1847), 'numpy.abs', 'np.abs', (['H1'], {}), '(H1)\n', (1843, 1847), True, 'import numpy as np\n'), ((3274, 3284), 'numpy.sum', 'np.sum', (['n0'], {}), '(n0)\n', (3280, 3284), True, 'import numpy as np\n'), ((3433, 3443), 'numpy.sum', 'np.sum', (['n1'], {}), '(n1)\n', (3439, 3443), True, 'import numpy as np\n'), ((1909, 1928), 'numpy.fmax', 'np.fmax', (['H0.T', 'H1.T'], {}), '(H0.T, H1.T)\n', (1916, 1928), True, 'import numpy as np\n')]
import lorm from lorm.manif import Sphere2 from lorm.funcs import ManifoldObjectiveFunction from nfft import nfsft import numpy as np import copy as cp class plan(ManifoldObjectiveFunction): def __init__(self, M, N, alpha, L, equality_constraint=False, closed=True): ''' plan for computing the (polynomial) L^2 discrepancy for points measures on the sphere S^2 E(mu,nu_M) = D(mu,nu_M)^2 + alpha/M sum_{i=1}^M (dist(x_i,x_{i-1}) - L)_+^2, (if equality_constraint == False) E(mu,nu_M) = D(mu,nu_M)^2 + alpha/M sum_{i=1}^M (dist(x_i,x_{i-1}) - L)^2, (if equality_constraint == True) M - number of points N - polynomial degree ''' self._M = M self._N = N self._nfsft_plan = nfsft.plan(M, N) self._lambda_hat = nfsft.SphericalFourierCoefficients(N) for n in range(N+1): self._lambda_hat[n,:] = 1./((2*n-1)*(2*n+1)*(2*n+3)) self._mu_hat = nfsft.SphericalFourierCoefficients(N) self._mu_hat[0,0] = 1 self._weights = np.sqrt(4*np.pi) * np.ones([M,1],dtype=float) / M self._alpha = alpha self._L = L self._equality_constraint = equality_constraint self._closed = closed def f(point_array_coords): lengths = self._eval_lengths(point_array_coords) pos_diff_lengths = self._M*lengths-self._L if self._equality_constraint == False: pos_diff_lengths[ pos_diff_lengths < 0] = 0 err_vector = self._eval_error_vector(point_array_coords) return np.real(np.sum(err_vector.array*err_vector.array.conjugate()*self._lambda_hat.array)) + self._alpha * 1./self._M*np.sum((pos_diff_lengths)**2) def grad(point_array_coords): le = self._eval_error_vector(point_array_coords) le *= self._lambda_hat # we already set the point_array_coords in _eval_error_vector grad = 2*np.real(self._nfsft_plan.compute_gradYmatrix_multiplication(le)) * self._weights + self._alpha*1./self._M*self._eval_grad_sum_lengths_squared(point_array_coords) return grad def hess_mult(base_point_array_coords, tangent_array_coords): norm = np.linalg.norm(tangent_array_coords) h = 1e-12 return norm*(self._grad(base_point_array_coords + h*tangent_array_coords/norm) - self._grad(base_point_array_coords))/h ManifoldObjectiveFunction.__init__(self,Sphere2(),f,grad=grad,hess_mult=hess_mult, parameterized=True) def _eval_error_vector(self,point_array_coords): self._nfsft_plan.set_local_coords(point_array_coords) err_vector = self._nfsft_plan.compute_Ymatrix_adjoint_multiplication(self._weights, self._N) err_vector -= self._mu_hat return err_vector def _eval_lengths(self,point_array_coords): lengths = np.zeros([self._M]) theta = point_array_coords[:,0] dp = np.zeros([self._M]) dp[:] = point_array_coords[:,1] dp[0] -= point_array_coords[self._M-1,1] dp[1:self._M] -= point_array_coords[0:self._M-1,1] ct = np.cos(theta) st = np.sin(theta) if self._closed: lengths[0] = np.sqrt(2 * (1 - ct[0]*ct[self._M-1] - np.cos(dp[0])*st[0]*st[self._M-1])) lengths[1:self._M] = np.sqrt(2 * (1 - ct[1:self._M]*ct[0:self._M-1]- np.cos(dp[1:self._M])*st[1:self._M]*st[0:self._M-1])) return lengths def _eval_grad_lengths1(self,point_array_coords): grad_lengths = np.zeros([self._M,2]) theta = point_array_coords[:,0] dp = np.zeros([self._M]) dp[:] = point_array_coords[:,1] dp[0] -= point_array_coords[self._M-1,1] dp[1:self._M] -= point_array_coords[0:self._M-1,1] ct = np.cos(theta) st = np.sin(theta) lengths = self._eval_lengths(point_array_coords) if self._closed: grad_lengths[0,0] = (st[0]*ct[self._M-1] - np.cos(dp[0])*ct[0]*st[self._M-1])/lengths[0] grad_lengths[0,1] = np.sin(dp[0])*st[0]*st[self._M-1]/lengths[0] grad_lengths[1:self._M,0] = (st[1:self._M]*ct[0:self._M-1] - np.cos(dp[1:self._M])*ct[1:self._M]*st[0:self._M-1])/lengths[1:self._M] grad_lengths[1:self._M,1] = np.sin(dp[1:self._M])*st[1:self._M]*st[0:self._M-1]/lengths[1:self._M] return grad_lengths def _eval_grad_lengths2(self,point_array_coords): grad_lengths = np.zeros([self._M,2]) theta = point_array_coords[:,0] dp = np.zeros([self._M]) dp[:] = point_array_coords[:,1] dp[0] -= point_array_coords[self._M-1,1] dp[1:self._M] -= point_array_coords[0:self._M-1,1] ct = np.cos(theta) st = np.sin(theta) lengths = self._eval_lengths(point_array_coords) if self._closed: grad_lengths[self._M-1,0] = (ct[0]*st[self._M-1] - np.cos(dp[0])*st[0]*ct[self._M-1])/lengths[0] grad_lengths[self._M-1,1] = -np.sin(dp[0])*st[0]*st[self._M-1]/lengths[0] grad_lengths[0:self._M-1,0] = (ct[1:self._M]*st[0:self._M-1] - np.cos(dp[1:self._M])*st[1:self._M]*ct[0:self._M-1])/lengths[1:self._M] grad_lengths[0:self._M-1,1] = -np.sin(dp[1:self._M])*st[1:self._M]*st[0:self._M-1]/lengths[1:self._M] return grad_lengths def _eval_grad_sum_lengths_squared(self,point_array_coords): lengths = self._eval_lengths(point_array_coords).reshape([self._M,1]) grad_lengths1 = self._eval_grad_lengths1(point_array_coords) grad_lengths2 = self._eval_grad_lengths2(point_array_coords) grad = np.zeros((self._M,2)) pos_diff_lengths = self._M*lengths-self._L if self._equality_constraint == False: pos_diff_lengths[ pos_diff_lengths < 0] = 0 grad[0,:] += pos_diff_lengths[0]*grad_lengths1[0,:] grad[1:self._M,:] += pos_diff_lengths[1:self._M]*grad_lengths1[1:self._M,:] grad[self._M-1,:] += pos_diff_lengths[0]*grad_lengths2[self._M-1,:] grad[0:self._M-1,:] += pos_diff_lengths[1:self._M]*grad_lengths2[0:self._M-1,:] return 2*self._M*grad
[ "numpy.sum", "nfft.nfsft.plan", "numpy.zeros", "nfft.nfsft.SphericalFourierCoefficients", "lorm.manif.Sphere2", "numpy.ones", "numpy.sin", "numpy.linalg.norm", "numpy.cos", "numpy.sqrt" ]
[((765, 781), 'nfft.nfsft.plan', 'nfsft.plan', (['M', 'N'], {}), '(M, N)\n', (775, 781), False, 'from nfft import nfsft\n'), ((809, 846), 'nfft.nfsft.SphericalFourierCoefficients', 'nfsft.SphericalFourierCoefficients', (['N'], {}), '(N)\n', (843, 846), False, 'from nfft import nfsft\n'), ((964, 1001), 'nfft.nfsft.SphericalFourierCoefficients', 'nfsft.SphericalFourierCoefficients', (['N'], {}), '(N)\n', (998, 1001), False, 'from nfft import nfsft\n'), ((2890, 2909), 'numpy.zeros', 'np.zeros', (['[self._M]'], {}), '([self._M])\n', (2898, 2909), True, 'import numpy as np\n'), ((2963, 2982), 'numpy.zeros', 'np.zeros', (['[self._M]'], {}), '([self._M])\n', (2971, 2982), True, 'import numpy as np\n'), ((3144, 3157), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (3150, 3157), True, 'import numpy as np\n'), ((3171, 3184), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (3177, 3184), True, 'import numpy as np\n'), ((3545, 3567), 'numpy.zeros', 'np.zeros', (['[self._M, 2]'], {}), '([self._M, 2])\n', (3553, 3567), True, 'import numpy as np\n'), ((3620, 3639), 'numpy.zeros', 'np.zeros', (['[self._M]'], {}), '([self._M])\n', (3628, 3639), True, 'import numpy as np\n'), ((3801, 3814), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (3807, 3814), True, 'import numpy as np\n'), ((3828, 3841), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (3834, 3841), True, 'import numpy as np\n'), ((4458, 4480), 'numpy.zeros', 'np.zeros', (['[self._M, 2]'], {}), '([self._M, 2])\n', (4466, 4480), True, 'import numpy as np\n'), ((4533, 4552), 'numpy.zeros', 'np.zeros', (['[self._M]'], {}), '([self._M])\n', (4541, 4552), True, 'import numpy as np\n'), ((4714, 4727), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (4720, 4727), True, 'import numpy as np\n'), ((4741, 4754), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (4747, 4754), True, 'import numpy as np\n'), ((5615, 5637), 'numpy.zeros', 'np.zeros', (['(self._M, 2)'], {}), '((self._M, 2))\n', (5623, 5637), True, 'import numpy as np\n'), ((2241, 2277), 'numpy.linalg.norm', 'np.linalg.norm', (['tangent_array_coords'], {}), '(tangent_array_coords)\n', (2255, 2277), True, 'import numpy as np\n'), ((2482, 2491), 'lorm.manif.Sphere2', 'Sphere2', ([], {}), '()\n', (2489, 2491), False, 'from lorm.manif import Sphere2\n'), ((1056, 1074), 'numpy.sqrt', 'np.sqrt', (['(4 * np.pi)'], {}), '(4 * np.pi)\n', (1063, 1074), True, 'import numpy as np\n'), ((1075, 1103), 'numpy.ones', 'np.ones', (['[M, 1]'], {'dtype': 'float'}), '([M, 1], dtype=float)\n', (1082, 1103), True, 'import numpy as np\n'), ((1704, 1733), 'numpy.sum', 'np.sum', (['(pos_diff_lengths ** 2)'], {}), '(pos_diff_lengths ** 2)\n', (1710, 1733), True, 'import numpy as np\n'), ((4281, 4302), 'numpy.sin', 'np.sin', (['dp[1:self._M]'], {}), '(dp[1:self._M])\n', (4287, 4302), True, 'import numpy as np\n'), ((4059, 4072), 'numpy.sin', 'np.sin', (['dp[0]'], {}), '(dp[0])\n', (4065, 4072), True, 'import numpy as np\n'), ((4173, 4194), 'numpy.cos', 'np.cos', (['dp[1:self._M]'], {}), '(dp[1:self._M])\n', (4179, 4194), True, 'import numpy as np\n'), ((5106, 5127), 'numpy.cos', 'np.cos', (['dp[1:self._M]'], {}), '(dp[1:self._M])\n', (5112, 5127), True, 'import numpy as np\n'), ((5218, 5239), 'numpy.sin', 'np.sin', (['dp[1:self._M]'], {}), '(dp[1:self._M])\n', (5224, 5239), True, 'import numpy as np\n'), ((3389, 3410), 'numpy.cos', 'np.cos', (['dp[1:self._M]'], {}), '(dp[1:self._M])\n', (3395, 3410), True, 'import numpy as np\n'), ((3980, 3993), 'numpy.cos', 'np.cos', (['dp[0]'], {}), '(dp[0])\n', (3986, 3993), True, 'import numpy as np\n'), ((4901, 4914), 'numpy.cos', 'np.cos', (['dp[0]'], {}), '(dp[0])\n', (4907, 4914), True, 'import numpy as np\n'), ((4989, 5002), 'numpy.sin', 'np.sin', (['dp[0]'], {}), '(dp[0])\n', (4995, 5002), True, 'import numpy as np\n'), ((3275, 3288), 'numpy.cos', 'np.cos', (['dp[0]'], {}), '(dp[0])\n', (3281, 3288), True, 'import numpy as np\n')]
# Copyright 2020 The FastEstimator Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import unittest import numpy as np import tensorflow as tf import torch import fastestimator as fe class TestExp(unittest.TestCase): def test_exp_np_input(self): n = np.array([-2., 2, 1]) obj1 = fe.backend.exp(n) obj2 = np.array([0.13533528, 7.3890561, 2.71828183]) self.assertTrue(np.allclose(obj1, obj2)) def test_exp_tf_input(self): t = tf.constant([-2., 2, 1]) obj1 = fe.backend.exp(t) obj2 = np.array([0.13533528, 7.3890561, 2.71828183]) self.assertTrue(np.allclose(obj1, obj2)) def test_exp_torch_input(self): t = torch.tensor([-2., 2, 1]) obj1 = fe.backend.exp(t) obj2 = np.array([0.13533528, 7.3890561, 2.71828183]) self.assertTrue(np.allclose(obj1, obj2))
[ "numpy.allclose", "tensorflow.constant", "fastestimator.backend.exp", "numpy.array", "torch.tensor" ]
[((874, 896), 'numpy.array', 'np.array', (['[-2.0, 2, 1]'], {}), '([-2.0, 2, 1])\n', (882, 896), True, 'import numpy as np\n'), ((911, 928), 'fastestimator.backend.exp', 'fe.backend.exp', (['n'], {}), '(n)\n', (925, 928), True, 'import fastestimator as fe\n'), ((944, 989), 'numpy.array', 'np.array', (['[0.13533528, 7.3890561, 2.71828183]'], {}), '([0.13533528, 7.3890561, 2.71828183])\n', (952, 989), True, 'import numpy as np\n'), ((1085, 1110), 'tensorflow.constant', 'tf.constant', (['[-2.0, 2, 1]'], {}), '([-2.0, 2, 1])\n', (1096, 1110), True, 'import tensorflow as tf\n'), ((1125, 1142), 'fastestimator.backend.exp', 'fe.backend.exp', (['t'], {}), '(t)\n', (1139, 1142), True, 'import fastestimator as fe\n'), ((1158, 1203), 'numpy.array', 'np.array', (['[0.13533528, 7.3890561, 2.71828183]'], {}), '([0.13533528, 7.3890561, 2.71828183])\n', (1166, 1203), True, 'import numpy as np\n'), ((1302, 1328), 'torch.tensor', 'torch.tensor', (['[-2.0, 2, 1]'], {}), '([-2.0, 2, 1])\n', (1314, 1328), False, 'import torch\n'), ((1343, 1360), 'fastestimator.backend.exp', 'fe.backend.exp', (['t'], {}), '(t)\n', (1357, 1360), True, 'import fastestimator as fe\n'), ((1376, 1421), 'numpy.array', 'np.array', (['[0.13533528, 7.3890561, 2.71828183]'], {}), '([0.13533528, 7.3890561, 2.71828183])\n', (1384, 1421), True, 'import numpy as np\n'), ((1014, 1037), 'numpy.allclose', 'np.allclose', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (1025, 1037), True, 'import numpy as np\n'), ((1228, 1251), 'numpy.allclose', 'np.allclose', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (1239, 1251), True, 'import numpy as np\n'), ((1446, 1469), 'numpy.allclose', 'np.allclose', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (1457, 1469), True, 'import numpy as np\n')]
# (c) 2019-2021, <NAME> @ ETH Zurich # Computer-assisted Applications in Medicine (CAiM) Group, Prof. <NAME> import tensorflow as tf import numpy as np import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class DiceLoss(tf.losses.Loss): """ Dice loss References ---------- .. Adapted from https://github.com/baumgach/acdc_segmenter """ def __init__(self, epsilon=1e-10, use_hard_pred=False, **kwargs): super().__init__() self.only_foreground = kwargs.get('only_foreground', False) self.epsilon = epsilon self.use_hard_pred = use_hard_pred mode = kwargs.get('mode', None) if mode == 'macro': self.sum_over_labels = False self.sum_over_batches = False elif mode == 'macro_robust': self.sum_over_labels = False self.sum_over_batches = True elif mode == 'micro': self.sum_over_labels = True self.sum_over_batches = False elif mode is None: self.sum_over_labels = kwargs.get('per_structure') # Intentionally no default value self.sum_over_batches = kwargs.get('sum_over_batches', False) else: raise ValueError("Encountered unexpected 'mode' in dice_loss: '%s'" % mode) def call(self, labels, logits): dice_per_img_per_lab = self.get_dice(logits=logits, labels=labels) if self.only_foreground: if self.sum_over_batches: loss = 1 - tf.reduce_mean(dice_per_img_per_lab[:-1]) else: loss = 1 - tf.reduce_mean(dice_per_img_per_lab[:, :-1]) else: loss = 1 - tf.reduce_mean(dice_per_img_per_lab) return loss def get_dice(self, labels, logits): ndims = logits.get_shape().ndims prediction = logits # prediction = tf.nn.softmax(logits) if self.use_hard_pred: # This casts the predictions to binary 0 or 1 prediction = tf.one_hot(tf.argmax(prediction, axis=-1), depth=tf.shape(prediction)[-1]) intersection = tf.multiply(prediction, labels) if ndims == 5: reduction_axes = [1, 2, 3] else: reduction_axes = [1, 2] if self.sum_over_batches: reduction_axes = [0] + reduction_axes if self.sum_over_labels: reduction_axes += [reduction_axes[-1] + 1] # also sum over the last axis # Reduce the maps over all dimensions except the batch and the label index i = tf.reduce_sum(intersection, axis=reduction_axes) l = tf.reduce_sum(prediction, axis=reduction_axes) r = tf.reduce_sum(labels, axis=reduction_axes) dice_per_img_per_lab = 2 * i / (l + r + self.epsilon) return dice_per_img_per_lab class CrossEntropyWeighted(tf.losses.Loss): """ Weighted cross entropy loss with logits """ def __init__(self, class_weights, key_out=None, name='CrossEntropyWeigthed', **kwargs): super(CrossEntropyWeighted, self).__init__(name=name, **kwargs) self.class_weights = class_weights self.n_class = len(self.class_weights) self.key_out = key_out @tf.function def call(self, labels, logits): flat_logits = tf.reshape(logits, [-1, self.n_class]) flat_labels = tf.reshape(labels, [-1, self.n_class]) class_weights = tf.constant(np.array(self.class_weights, dtype=np.float32)) weight_map = tf.multiply(flat_labels, class_weights) weight_map = tf.reduce_sum(weight_map, axis=1) loss_map = tf.nn.softmax_cross_entropy_with_logits(logits=flat_logits, labels=flat_labels) weighted_loss = tf.multiply(loss_map, weight_map) loss = tf.reduce_mean(weighted_loss) return loss def get_loss(name_loss, class_weights=None): """ Parses the parameters to get the correct loss Parameters ---------- name_loss : str Name of the loss function to use class_weights : list (of floats) or None Weights of the different classes employed Returns ------- tf.losses.Loss Loss function as required by a tf model """ if name_loss == 'dice': return DiceLoss(mode='macro_robust', only_foreground=True) elif name_loss == 'crossentropy': if class_weights is None: raise Exception("class_weights should be declared for weighted cross entropy") return CrossEntropyWeighted(class_weights) else: raise Exception("The loss {} has not been implemented".format(name_loss))
[ "tensorflow.reduce_sum", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.argmax", "tensorflow.reshape", "tensorflow.reduce_mean", "tensorflow.multiply", "tensorflow.shape", "numpy.array", "logging.getLogger" ]
[((181, 208), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (198, 208), False, 'import logging\n'), ((2124, 2155), 'tensorflow.multiply', 'tf.multiply', (['prediction', 'labels'], {}), '(prediction, labels)\n', (2135, 2155), True, 'import tensorflow as tf\n'), ((2570, 2618), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['intersection'], {'axis': 'reduction_axes'}), '(intersection, axis=reduction_axes)\n', (2583, 2618), True, 'import tensorflow as tf\n'), ((2631, 2677), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['prediction'], {'axis': 'reduction_axes'}), '(prediction, axis=reduction_axes)\n', (2644, 2677), True, 'import tensorflow as tf\n'), ((2690, 2732), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['labels'], {'axis': 'reduction_axes'}), '(labels, axis=reduction_axes)\n', (2703, 2732), True, 'import tensorflow as tf\n'), ((3301, 3339), 'tensorflow.reshape', 'tf.reshape', (['logits', '[-1, self.n_class]'], {}), '(logits, [-1, self.n_class])\n', (3311, 3339), True, 'import tensorflow as tf\n'), ((3362, 3400), 'tensorflow.reshape', 'tf.reshape', (['labels', '[-1, self.n_class]'], {}), '(labels, [-1, self.n_class])\n', (3372, 3400), True, 'import tensorflow as tf\n'), ((3508, 3547), 'tensorflow.multiply', 'tf.multiply', (['flat_labels', 'class_weights'], {}), '(flat_labels, class_weights)\n', (3519, 3547), True, 'import tensorflow as tf\n'), ((3569, 3602), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['weight_map'], {'axis': '(1)'}), '(weight_map, axis=1)\n', (3582, 3602), True, 'import tensorflow as tf\n'), ((3623, 3702), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'flat_logits', 'labels': 'flat_labels'}), '(logits=flat_logits, labels=flat_labels)\n', (3662, 3702), True, 'import tensorflow as tf\n'), ((3727, 3760), 'tensorflow.multiply', 'tf.multiply', (['loss_map', 'weight_map'], {}), '(loss_map, weight_map)\n', (3738, 3760), True, 'import tensorflow as tf\n'), ((3777, 3806), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['weighted_loss'], {}), '(weighted_loss)\n', (3791, 3806), True, 'import tensorflow as tf\n'), ((3438, 3484), 'numpy.array', 'np.array', (['self.class_weights'], {'dtype': 'np.float32'}), '(self.class_weights, dtype=np.float32)\n', (3446, 3484), True, 'import numpy as np\n'), ((1699, 1735), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['dice_per_img_per_lab'], {}), '(dice_per_img_per_lab)\n', (1713, 1735), True, 'import tensorflow as tf\n'), ((2036, 2066), 'tensorflow.argmax', 'tf.argmax', (['prediction'], {'axis': '(-1)'}), '(prediction, axis=-1)\n', (2045, 2066), True, 'import tensorflow as tf\n'), ((1530, 1571), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['dice_per_img_per_lab[:-1]'], {}), '(dice_per_img_per_lab[:-1])\n', (1544, 1571), True, 'import tensorflow as tf\n'), ((1617, 1661), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['dice_per_img_per_lab[:, :-1]'], {}), '(dice_per_img_per_lab[:, :-1])\n', (1631, 1661), True, 'import tensorflow as tf\n'), ((2074, 2094), 'tensorflow.shape', 'tf.shape', (['prediction'], {}), '(prediction)\n', (2082, 2094), True, 'import tensorflow as tf\n')]
__version__ = '1.0.0-rc.1' __author__ = '<NAME>, <NAME>, <NAME>, <NAME>' import json import os import random import numpy as np import torch from transformers import AutoTokenizer from rate_severity_of_toxic_comments.dataset import AVAILABLE_DATASET_TYPES from rate_severity_of_toxic_comments.embedding import AVAILABLE_EMBEDDINGS from rate_severity_of_toxic_comments.model import AVAILABLE_ARCHITECTURES from rate_severity_of_toxic_comments.preprocessing import AVAILABLE_PREPROCESSING_PIPELINES from rate_severity_of_toxic_comments.tokenizer import NaiveTokenizer, create_recurrent_model_tokenizer _bad_words = [] AVAILABLE_MODES = ['recurrent', 'pretrained', 'debug'] def fix_random_seed(seed): """ Fix random seed. Parameters ---------- seed : int Seed for random state. """ torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) def obfuscator(text): """ Censors bad words. Parameters ---------- text : str Text to censor. Returns ------- text : str Censored text. """ global _bad_words if len(_bad_words) == 0: with open('res/bad_words.txt') as file: bad_words = [l.rstrip() for l in file.readlines() if len(l) > 2] bad_words = [l for l in bad_words if len(l) > 2] _bad_words = list(sorted(bad_words, key=len, reverse=True)) for word in _bad_words: visible = min(len(word) // 3, 3) censorship = word[0:visible] + \ ((len(word) - visible * 2) * '*') + word[-visible:] text = text.replace(word, censorship) return text def parse_config(default_filepath, local_filepath=None): """ Parses the configuration file. Parameters ---------- default_filepath : str Default configuration filepath. local_filepath : str, optional Local configuration filepath. Returns ------- config : dict Configuration dictionary. """ default = open(default_filepath) config = json.load(default) if os.path.exists(local_filepath): with open(local_filepath) as local: import collections.abc def deep_update(d, u): for k, v in u.items(): if isinstance(v, collections.abc.Mapping): d[k] = deep_update(d.get(k, {}), v) else: d[k] = v return d config = deep_update(config, json.load(local)) validate_config(config) return config def process_config(df, config): """ Parses the configuration dictionary. Parameters ---------- df : pandas.core.frame.DataFrame Dataset. config : dict Configuration dictionary. Returns ------- support_bag : dict Configuration dictionary. """ support_bag = {} if config['options']['run_mode'] == 'pretrained': support_bag['tokenizer'] = AutoTokenizer.from_pretrained( config['pretrained']['model_name']) elif config['options']['run_mode'] == 'recurrent': tokenizer, embedding_matrix = create_recurrent_model_tokenizer( config, df) support_bag['tokenizer'] = tokenizer support_bag['embedding_matrix'] = embedding_matrix elif config['options']['run_mode'] == 'debug': support_bag['tokenizer'] = NaiveTokenizer() support_bag['tokenizer'].set_vocab({'[UNK]': 0, '[PAD]': 1}) if config['options']['seed']: fix_random_seed(config['options']['seed']) return support_bag def validate_config(config): """ Validates the configuration dictionary. Parameters ---------- config : dict Configuration dictionary. """ if config['options']['run_mode'] not in AVAILABLE_MODES: raise ValueError('Invalid configuration! Run Mode not supported') elif config['recurrent']['architecture'] not in AVAILABLE_ARCHITECTURES: raise ValueError( 'Invalid configuration! Recurrent architecture not supported') elif not all([p in AVAILABLE_PREPROCESSING_PIPELINES for p in config['recurrent']['preprocessing']]): raise ValueError( 'Invalid configuration! Preprocessing pipeline not supported') elif (config['recurrent']['embedding_type'], config['recurrent']['embedding_dimension']) not in AVAILABLE_EMBEDDINGS: raise ValueError( 'Invalid configuration! Embedding type and dimension not supported') elif config['training']['dataset']['type'] not in AVAILABLE_DATASET_TYPES: raise ValueError('Invalid configuration! Dataset type not supported') elif config['evaluation']['dataset']['type'] not in AVAILABLE_DATASET_TYPES: raise ValueError('Invalid configuration! Dataset type not supported') if not all(item in config['options'].keys() for item in ['run_mode', 'use_gpu', 'wandb']): raise ValueError( "Invalid configuration! Value missing under 'options'") elif not all(item in config['pretrained'].keys() for item in ['model_name', 'output_features']): raise ValueError( "Invalid configuration! Value missing under 'pretrained'") elif not all(item in config['recurrent'].keys() for item in ['architecture', 'preprocessing', 'vocab_file', 'embedding_type', 'embedding_dimension', 'hidden_dim']): raise ValueError( "Invalid configuration! Value missing under 'recurrent'") elif not all(item in config['training'].keys() for item in ['epochs', 'train_batch_size', 'valid_batch_size', 'learning_rate', 'dataset']): raise ValueError( "Invalid configuration! Value missing under 'training'") elif not all(item in config['evaluation'].keys() for item in ['dataset']): raise ValueError( "Invalid configuration! Value missing under 'evaluation'") elif config['training']['dataset']['type'] == 'pairwise' and 'loss_margin' not in config['training']['dataset']: raise ValueError( 'Pairwise dataset requires a margin attribute!') elif config['evaluation']['dataset']['type'] == 'pairwise' and 'loss_margin' not in config['evaluation']['dataset']: raise ValueError( 'Pairwise dataset requires a margin attribute!')
[ "rate_severity_of_toxic_comments.tokenizer.NaiveTokenizer", "json.load", "numpy.random.seed", "rate_severity_of_toxic_comments.tokenizer.create_recurrent_model_tokenizer", "torch.manual_seed", "os.path.exists", "torch.cuda.manual_seed", "transformers.AutoTokenizer.from_pretrained", "random.seed", "torch.cuda.is_available" ]
[((825, 848), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (842, 848), False, 'import torch\n'), ((853, 873), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (867, 873), True, 'import numpy as np\n'), ((878, 895), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (889, 895), False, 'import random\n'), ((903, 928), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (926, 928), False, 'import torch\n'), ((2114, 2132), 'json.load', 'json.load', (['default'], {}), '(default)\n', (2123, 2132), False, 'import json\n'), ((2140, 2170), 'os.path.exists', 'os.path.exists', (['local_filepath'], {}), '(local_filepath)\n', (2154, 2170), False, 'import os\n'), ((938, 966), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (960, 966), False, 'import torch\n'), ((3059, 3124), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (["config['pretrained']['model_name']"], {}), "(config['pretrained']['model_name'])\n", (3088, 3124), False, 'from transformers import AutoTokenizer\n'), ((3231, 3275), 'rate_severity_of_toxic_comments.tokenizer.create_recurrent_model_tokenizer', 'create_recurrent_model_tokenizer', (['config', 'df'], {}), '(config, df)\n', (3263, 3275), False, 'from rate_severity_of_toxic_comments.tokenizer import NaiveTokenizer, create_recurrent_model_tokenizer\n'), ((2574, 2590), 'json.load', 'json.load', (['local'], {}), '(local)\n', (2583, 2590), False, 'import json\n'), ((3479, 3495), 'rate_severity_of_toxic_comments.tokenizer.NaiveTokenizer', 'NaiveTokenizer', ([], {}), '()\n', (3493, 3495), False, 'from rate_severity_of_toxic_comments.tokenizer import NaiveTokenizer, create_recurrent_model_tokenizer\n')]
from pymc import * from numpy import ones, array n = 5*ones(4,dtype=int) dose=array([-.86,-.3,-.05,.73]) @stochastic def alpha(value=-1.): return 0. @stochastic def beta(value=10.): return 0. @deterministic def theta(a=alpha, b=beta, d=dose): """theta = inv_logit(a+b)""" return invlogit(a+b*d) @observed @stochastic(dtype=int) def deaths(value=array([0,1,3,5],dtype=float), n=n, p=theta): """deaths ~ binomial(n, p)""" return binomial_like(value, n, p)
[ "numpy.array", "numpy.ones" ]
[((79, 112), 'numpy.array', 'array', (['[-0.86, -0.3, -0.05, 0.73]'], {}), '([-0.86, -0.3, -0.05, 0.73])\n', (84, 112), False, 'from numpy import ones, array\n'), ((56, 74), 'numpy.ones', 'ones', (['(4)'], {'dtype': 'int'}), '(4, dtype=int)\n', (60, 74), False, 'from numpy import ones, array\n'), ((366, 398), 'numpy.array', 'array', (['[0, 1, 3, 5]'], {'dtype': 'float'}), '([0, 1, 3, 5], dtype=float)\n', (371, 398), False, 'from numpy import ones, array\n')]
import numpy as np import matplotlib.pyplot as plt import sys pose_file = sys.argv[1] poses = np.load(pose_file) x, y, z = poses[:30, 0, -1], poses[:30, 1, -1], poses[:30, 2, -1] # Creating figure fig = plt.figure(figsize = (10, 7)) ax = plt.axes(projection ="3d") # Creating plot ax.scatter3D(x, y, z, color = "green") plt.title("poses") plt.show()
[ "matplotlib.pyplot.title", "numpy.load", "matplotlib.pyplot.show", "matplotlib.pyplot.axes", "matplotlib.pyplot.figure" ]
[((95, 113), 'numpy.load', 'np.load', (['pose_file'], {}), '(pose_file)\n', (102, 113), True, 'import numpy as np\n'), ((205, 232), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 7)'}), '(figsize=(10, 7))\n', (215, 232), True, 'import matplotlib.pyplot as plt\n'), ((240, 265), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': '"""3d"""'}), "(projection='3d')\n", (248, 265), True, 'import matplotlib.pyplot as plt\n'), ((324, 342), 'matplotlib.pyplot.title', 'plt.title', (['"""poses"""'], {}), "('poses')\n", (333, 342), True, 'import matplotlib.pyplot as plt\n'), ((343, 353), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (351, 353), True, 'import matplotlib.pyplot as plt\n')]
""" In this file, we analyse the action library generated by Teacher1 and Teacher2. Through 1. filtering out actions that decrease rho less effectively 2. filtering out actions that occur less frequently 3. filtering out "do nothing" action 4. add your filtering rules..., we obtain an action space in the form of numpy array. author: <NAME> mail: <EMAIL> """ import os import numpy as np import pandas as pd def read_data(tabs): data = None for tab in tabs: if data is None: data = pd.read_csv(tab, header=None) else: data = pd.concat((data, pd.read_csv(tab, header=None))) return data def filter_data(data): data['del'] = False for row in range(len(data) - 1): if data.iloc[row, 12] - data.iloc[row + 1, 14] < 0.02: # this action decreases rho less than 2% data.iloc[row, -1] = True if data.iloc[row, 7] == 'None': # this action is "do nothing" data.iloc[row, -1] = True return data def save_action_space(data, save_path, threshold=0): actions = data.iloc[:, -495:-1].astype(np.int16) actions['action_list'] = actions.apply(lambda s: str([i for i in s.values]), axis=1) nums = pd.value_counts(actions['action_list']) # filter out actions that occur less frequently # the actions that occur times less than the threshold would be filtered out action_space = np.array([eval(item) for item in nums[nums >= threshold].index.values]) file = os.path.join(save_path, 'actions%d.npy' % action_space.shape[0]) np.save(file, action_space) print('generate an action space with the size of %d' % action_space.shape[0]) if __name__ == "__main__": # hyper-parameters TABLES = ["./Experiences1.csv", "./Experiences2.csv"] # Use your own data SAVE_PATH = "../ActionSpace" THRESHOLD = 1 data = read_data(TABLES) data = filter_data(data) save_action_space(data, SAVE_PATH, THRESHOLD)
[ "pandas.read_csv", "numpy.save", "os.path.join", "pandas.value_counts" ]
[((1242, 1281), 'pandas.value_counts', 'pd.value_counts', (["actions['action_list']"], {}), "(actions['action_list'])\n", (1257, 1281), True, 'import pandas as pd\n'), ((1517, 1581), 'os.path.join', 'os.path.join', (['save_path', "('actions%d.npy' % action_space.shape[0])"], {}), "(save_path, 'actions%d.npy' % action_space.shape[0])\n", (1529, 1581), False, 'import os\n'), ((1586, 1613), 'numpy.save', 'np.save', (['file', 'action_space'], {}), '(file, action_space)\n', (1593, 1613), True, 'import numpy as np\n'), ((530, 559), 'pandas.read_csv', 'pd.read_csv', (['tab'], {'header': 'None'}), '(tab, header=None)\n', (541, 559), True, 'import pandas as pd\n'), ((610, 639), 'pandas.read_csv', 'pd.read_csv', (['tab'], {'header': 'None'}), '(tab, header=None)\n', (621, 639), True, 'import pandas as pd\n')]
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Extracts non-empty patches of extracted stafflines. Extracts vertical slices of the image where glyphs are expected (see `staffline_extractor.py`), and takes horizontal windows of the slice which will be clustered. Some patches will have a glyph roughly in their center, and the corresponding cluster centroids will be labeled as such. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import apache_beam as beam from apache_beam import metrics from moonlight.staves import staffline_extractor from moonlight.util import more_iter_tools import numpy as np from six.moves import filter import tensorflow as tf def _filter_patch(patch, min_num_dark_pixels=10): unused_patch_name, patch = patch return np.greater_equal(np.sum(np.less(patch, 0.5)), min_num_dark_pixels) class StafflinePatchesDoFn(beam.DoFn): """Runs the staffline patches graph.""" def __init__(self, patch_height, patch_width, num_stafflines, timeout_ms, max_patches_per_page): self.patch_height = patch_height self.patch_width = patch_width self.num_stafflines = num_stafflines self.timeout_ms = timeout_ms self.max_patches_per_page = max_patches_per_page self.total_pages_counter = metrics.Metrics.counter(self.__class__, 'total_pages') self.failed_pages_counter = metrics.Metrics.counter(self.__class__, 'failed_pages') self.successful_pages_counter = metrics.Metrics.counter( self.__class__, 'successful_pages') self.empty_pages_counter = metrics.Metrics.counter(self.__class__, 'empty_pages') self.total_patches_counter = metrics.Metrics.counter( self.__class__, 'total_patches') self.emitted_patches_counter = metrics.Metrics.counter( self.__class__, 'emitted_patches') def start_bundle(self): self.extractor = staffline_extractor.StafflinePatchExtractor( patch_height=self.patch_height, patch_width=self.patch_width, run_options=tf.RunOptions(timeout_in_ms=self.timeout_ms)) self.session = tf.Session(graph=self.extractor.graph) def process(self, png_path): self.total_pages_counter.inc() try: with self.session.as_default(): patches_iter = self.extractor.page_patch_iterator(png_path) # pylint: disable=broad-except except Exception: logging.exception('Skipping failed music score (%s)', png_path) self.failed_pages_counter.inc() return patches_iter = filter(_filter_patch, patches_iter) if 0 < self.max_patches_per_page: # Subsample patches. patches = more_iter_tools.iter_sample(patches_iter, self.max_patches_per_page) else: patches = list(patches_iter) if not patches: self.empty_pages_counter.inc() self.total_patches_counter.inc(len(patches)) # Serialize each patch as an Example. for patch_name, patch in patches: example = tf.train.Example() example.features.feature['name'].bytes_list.value.append( patch_name.encode('utf-8')) example.features.feature['features'].float_list.value.extend( patch.ravel()) example.features.feature['height'].int64_list.value.append(patch.shape[0]) example.features.feature['width'].int64_list.value.append(patch.shape[1]) yield example self.successful_pages_counter.inc() # Patches are sub-sampled by this point. self.emitted_patches_counter.inc(len(patches)) def finish_bundle(self): self.session.close() del self.extractor del self.session
[ "apache_beam.metrics.Metrics.counter", "logging.exception", "tensorflow.train.Example", "moonlight.util.more_iter_tools.iter_sample", "tensorflow.Session", "numpy.less", "tensorflow.RunOptions", "six.moves.filter" ]
[((1860, 1914), 'apache_beam.metrics.Metrics.counter', 'metrics.Metrics.counter', (['self.__class__', '"""total_pages"""'], {}), "(self.__class__, 'total_pages')\n", (1883, 1914), False, 'from apache_beam import metrics\n'), ((2002, 2057), 'apache_beam.metrics.Metrics.counter', 'metrics.Metrics.counter', (['self.__class__', '"""failed_pages"""'], {}), "(self.__class__, 'failed_pages')\n", (2025, 2057), False, 'from apache_beam import metrics\n'), ((2150, 2209), 'apache_beam.metrics.Metrics.counter', 'metrics.Metrics.counter', (['self.__class__', '"""successful_pages"""'], {}), "(self.__class__, 'successful_pages')\n", (2173, 2209), False, 'from apache_beam import metrics\n'), ((2250, 2304), 'apache_beam.metrics.Metrics.counter', 'metrics.Metrics.counter', (['self.__class__', '"""empty_pages"""'], {}), "(self.__class__, 'empty_pages')\n", (2273, 2304), False, 'from apache_beam import metrics\n'), ((2393, 2449), 'apache_beam.metrics.Metrics.counter', 'metrics.Metrics.counter', (['self.__class__', '"""total_patches"""'], {}), "(self.__class__, 'total_patches')\n", (2416, 2449), False, 'from apache_beam import metrics\n'), ((2494, 2552), 'apache_beam.metrics.Metrics.counter', 'metrics.Metrics.counter', (['self.__class__', '"""emitted_patches"""'], {}), "(self.__class__, 'emitted_patches')\n", (2517, 2552), False, 'from apache_beam import metrics\n'), ((2818, 2856), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.extractor.graph'}), '(graph=self.extractor.graph)\n', (2828, 2856), True, 'import tensorflow as tf\n'), ((3236, 3271), 'six.moves.filter', 'filter', (['_filter_patch', 'patches_iter'], {}), '(_filter_patch, patches_iter)\n', (3242, 3271), False, 'from six.moves import filter\n'), ((1389, 1408), 'numpy.less', 'np.less', (['patch', '(0.5)'], {}), '(patch, 0.5)\n', (1396, 1408), True, 'import numpy as np\n'), ((3354, 3422), 'moonlight.util.more_iter_tools.iter_sample', 'more_iter_tools.iter_sample', (['patches_iter', 'self.max_patches_per_page'], {}), '(patches_iter, self.max_patches_per_page)\n', (3381, 3422), False, 'from moonlight.util import more_iter_tools\n'), ((3716, 3734), 'tensorflow.train.Example', 'tf.train.Example', ([], {}), '()\n', (3732, 3734), True, 'import tensorflow as tf\n'), ((2753, 2797), 'tensorflow.RunOptions', 'tf.RunOptions', ([], {'timeout_in_ms': 'self.timeout_ms'}), '(timeout_in_ms=self.timeout_ms)\n', (2766, 2797), True, 'import tensorflow as tf\n'), ((3102, 3165), 'logging.exception', 'logging.exception', (['"""Skipping failed music score (%s)"""', 'png_path'], {}), "('Skipping failed music score (%s)', png_path)\n", (3119, 3165), False, 'import logging\n')]
from casadi import Opti, sin, cos, tan, vertcat import numpy as np import matplotlib.pyplot as plt def bicycle_robot_model(q, u, L=0.3, dt=0.01): """ Implements the discrete time dynamics of your robot. i.e. this function implements F in q_{t+1} = F(q_{t}, u_{t}) dt is the discretization timestep. L is the axel-to-axel length of the car. q = array of casadi MX.sym symbolic variables [x, y, theta, phi]. u = array of casadi MX.sym symbolic variables [u1, u2] (velocity and steering inputs). Use the casadi sin, cos, tan functions. The casadi vertcat or vcat functions may also be useful. Note that to turn a list of casadi expressions into a column vector of those expressions, you should use vertcat or vcat. vertcat takes as input a variable number of arguments, and vcat takes as input a list. Example: x = MX.sym('x') y = MX.sym('y') z = MX.sym('z') q = vertcat(x + y, y, z) # makes a 3x1 matrix with entries x + y, y, and z. # OR q = vcat([x + y, y, z]) # makes a 3x1 matrix with entries x + y, y, and z. """ x, y, theta, sigma = q[0], q[1], q[2], q[3] v, w = u[0], u[1] x_dot = v * cos(theta) y_dot = v * sin(theta) theta_dot = v * tan(sigma) / L sigma_dot = w result = vertcat(x + x_dot * dt, y + y_dot * dt, theta + theta_dot * dt, sigma + sigma_dot * dt) return result def initial_cond(q_start: np.ndarray, q_goal: np.ndarray, n): """ Construct an initial guess for a solution to "warm start" the optimization. An easy way to initialize our optimization is to say that our robot will move in a straight line in configuration space. Of course, this isn't always possible since our dynamics are nonholonomic, but we don't necessarily need our initial condition to be feasible. We just want it to be closer to the final trajectory than any of the other simple initialization strategies (random, all zero, etc). We'll set our initial guess for the inputs to zeros to hopefully bias our solver into picking low control inputs n is the number of timesteps. This function will return two arrays: q0 is an array of shape (4, n+1) representing the initial guess for the state optimization variables. u0 is an array of shape (2, n) representing the initial guess for the state optimization variables. """ q0 = np.zeros((4, n + 1)) u0 = np.zeros((2, n)) # Your code here. q0 = np.linspace(q_start, q_goal, n + 1) return q0, u0 def objective_func(q, u, q_goal, Q, R, P): """ Implements the objective function. q is an array of states and u is an array of inputs. Together, these two arrays contain all the optimization variables in our problem. In particular, q has shape (4, N+1), so that each column of q is an array q[:, i] = [q0, q1, q2, q3] (i.e. [x, y, theta, phi]), the state at time-step i. u has shape (2, N), so that each column of u is an array u[:, i] = [u1, u2], the two control inputs (velocity and steering) of the bicycle model. This function should create an expression of the form sum_{i = 1, ..., N} ((q(i) - q_goal)^T * Q * (q(i) - q_goal) + (u(i)^T * R * u(i))) + (q(N+1) - q_goal)^T * P * (q(N+1) - q_goal) Note: When dealing with casadi symbolic variables, you can use @ for matrix multiplication, and * for standard, numpy-style element-wise (or broadcasted) multiplication. """ n = q.shape[1] - 1 obj = 0 for i in range(n): qi = q[:, i] ui = u[:, i] # Define one term of the summation here: ((q(i) - q_goal)^T * Q * (q(i) - q_goal) + (u(i)^T * R * u(i))) term = (qi - q_goal).T @ Q @ (qi - q_goal) + (ui.T @ R @ ui) obj += term q_last = q[:, n] # Define the last term here: (q(N+1) - q_goal)^T * P * (q(N+1) - q_goal) term_last = (q[:, n] - q_goal).T @ P @ (q[:, n] - q_goal) obj += term_last return obj def constraints(q, u, q_lb, q_ub, u_lb, u_ub, obs_list, q_start, q_goal, L=0.3, dt=0.01): """ Constructs a list where each entry is a casadi.MX symbolic expression representing a constraint of our optimization problem. q has shape (4, N+1), so that each column of q is an array q[:, i] = [q0, q1, q2, q3] (i.e. [x, y, theta, phi]), the state at time-step i. u has shape (2, N), so that each column of u is an array u[:, i] = [u1, u2], the two control inputs (velocity and steering) of the bicycle model. q_lb is a size (4,) array [x_lb, y_lb, theta_lb, phi_lb] containing lower bounds for each state variable. q_ub is a size (4,) array [x_ub, y_ub, theta_ub, phi_ub] containing upper bounds for each state variable. u_lb is a size (2,) array [u1_lb, u2_lb] containing lower bounds for each input. u_ub is a size (2,) array [u1_ub, u2_ub] containing upper bounds for each input. obs_list is a list of obstacles, where each obstacle is represented by 3-tuple (x, y, r) representing the (x, y) center of the obstacle and its radius r. All obstacles are modelled as circles. q_start is a size (4,) array representing the starting state of the plan. q_goal is a size (4,) array representing the goal state of the plan. L is the axel-to-axel length of the car. dt is the discretization timestep. """ constraints = [] # State constraints constraints.extend([q_lb[0] <= q[0, :], q[0, :] <= q_ub[0]]) constraints.extend([q_lb[1] <= q[1, :], q[1, :] <= q_ub[1]]) constraints.extend([q_lb[2] <= q[2, :], q[2, :] <= q_ub[2]]) constraints.extend([q_lb[3] <= q[3, :], q[3, :] <= q_ub[3]]) # Input constraints constraints.extend([u_lb[0] <= u[0, :], u[0, :] <= u_ub[0]]) constraints.extend([u_lb[1] <= u[1, :], u[1, :] <= u_ub[1]]) # Dynamics constraints for t in range(q.shape[1] - 1): q_t = q[:, t] q_tp1 = q[:, t + 1] u_t = u[:, t] constraints.append(q_tp1 - bicycle_robot_model(q=q_t, u=u_t, L=L, dt=dt) == 0) # Obstacle constraints for obj in obs_list: obj_x, obj_y, obj_r = obj for t in range(q.shape[1]): constraints.append( (q[0, t] - obj_x) ** 2 + (q[1, t] - obj_y) ** 2 >= obj_r ** 2) # Define the obstacle constraints. # Initial and final state constraints constraints.append(q[:, 0] == q_start) # Constraint on start state. constraints.append(q[:, -1] == q_goal) # Constraint on final state. return constraints def plan_to_pose(q_start: np.ndarray, q_goal: np.ndarray, q_lb, q_ub, u_lb, u_ub, obs_list, L=0.3, n=1000, dt=0.01): """ Plans a path from q_start to q_goal. q_lb, q_ub are the state lower and upper bounds repspectively. u_lb, u_ub are the input lower and upper bounds repspectively. obs_list is the list of obstacles, each given as a tuple (x, y, r). L is the length of the car. n is the number of timesteps. dt is the discretization timestep. Returns a plan (shape (4, n+1)) of waypoints and a sequence of inputs (shape (2, n)) of inputs at each timestep. """ opti = Opti() q = opti.variable(4, n + 1) u = opti.variable(2, n) Q = np.diag([1, 1, 2, 0.1]) R = 2 * np.diag([1, 0.5]) P = n * Q q0, u0 = initial_cond(q_start, q_goal, n) obj = objective_func(q, u, q_goal, Q, R, P) opti.minimize(obj) opti.subject_to(constraints(q, u, q_lb, q_ub, u_lb, u_ub, obs_list, q_start, q_goal, dt=dt)) opti.set_initial(q, q0.T) opti.set_initial(u, u0) ###### CONSTRUCT SOLVER AND SOLVE ###### opti.solver('ipopt') p_opts = {"expand": False} s_opts = {"max_iter": 1e4} opti.solver('ipopt', p_opts, s_opts) sol = opti.solve() plan = sol.value(q) inputs = sol.value(u) return plan, inputs def plot(plan, inputs, times, q_lb, q_ub, obs_list): # Trajectory plot ax = plt.subplot(1, 1, 1) ax.set_aspect(1) ax.set_xlim(q_lb[0], q_ub[0]) ax.set_ylim(q_lb[1], q_ub[1]) for obs in obs_list: xc, yc, r = obs circle = plt.Circle((xc, yc), r, color='black') ax.add_artist(circle) plan_x = plan[0, :] plan_y = plan[1, :] ax.plot(plan_x, plan_y, color='green') plt.xlabel("X (m)") plt.ylabel("Y (m)") plt.show() # States plot plt.plot(times, plan[0, :], label='x') plt.plot(times, plan[1, :], label='y') plt.plot(times, plan[2, :], label='theta') plt.plot(times, plan[3, :], label='phi') plt.xlabel('Time (s)') plt.legend() plt.show() # Inputs plot plt.plot(times[:-1], inputs[0, :], label='u1') plt.plot(times[:-1], inputs[1, :], label='u2') plt.xlabel('Time (s)') plt.legend() plt.show() def main(): ###### PROBLEM PARAMS ###### n = 1000 dt = 0.01 L = 0.3 xy_low = [-5, -1] xy_high = [10, 10] phi_max = 0.6 u1_max = 2 u2_max = 3 obs_list = [[5, 5, 1], [-3, 4, 1], [4, 2, 2]] q_start = np.array([0, 0, 0, 0]) q_goal = np.array([7, 3, 0, 0]) ###### SETUP PROBLEM ###### q_lb = xy_low + [-1000, -phi_max] q_ub = xy_high + [1000, phi_max] u_lb = [-u1_max, -u2_max] u_ub = [u1_max, u2_max] ###### CONSTRUCT SOLVER AND SOLVE ###### plan, inputs = plan_to_pose(q_start, q_goal, q_lb, q_ub, u_lb, u_ub, obs_list, L=L, n=n, dt=dt) ###### PLOT ###### times = np.arange(0.0, (n + 1) * dt, dt) print("Final Position:", plan[:4, -1]) plot(plan, inputs, times, q_lb, q_ub, obs_list) if __name__ == '__main__': main()
[ "casadi.tan", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "casadi.cos", "numpy.zeros", "matplotlib.pyplot.ylabel", "casadi.sin", "casadi.vertcat", "casadi.Opti", "numpy.array", "numpy.arange", "numpy.linspace", "matplotlib.pyplot.Circle", "numpy.diag", "matplotlib.pyplot.xlabel" ]
[((1314, 1406), 'casadi.vertcat', 'vertcat', (['(x + x_dot * dt)', '(y + y_dot * dt)', '(theta + theta_dot * dt)', '(sigma + sigma_dot * dt)'], {}), '(x + x_dot * dt, y + y_dot * dt, theta + theta_dot * dt, sigma + \n sigma_dot * dt)\n', (1321, 1406), False, 'from casadi import Opti, sin, cos, tan, vertcat\n'), ((2501, 2521), 'numpy.zeros', 'np.zeros', (['(4, n + 1)'], {}), '((4, n + 1))\n', (2509, 2521), True, 'import numpy as np\n'), ((2531, 2547), 'numpy.zeros', 'np.zeros', (['(2, n)'], {}), '((2, n))\n', (2539, 2547), True, 'import numpy as np\n'), ((2580, 2615), 'numpy.linspace', 'np.linspace', (['q_start', 'q_goal', '(n + 1)'], {}), '(q_start, q_goal, n + 1)\n', (2591, 2615), True, 'import numpy as np\n'), ((7244, 7250), 'casadi.Opti', 'Opti', ([], {}), '()\n', (7248, 7250), False, 'from casadi import Opti, sin, cos, tan, vertcat\n'), ((7321, 7344), 'numpy.diag', 'np.diag', (['[1, 1, 2, 0.1]'], {}), '([1, 1, 2, 0.1])\n', (7328, 7344), True, 'import numpy as np\n'), ((8026, 8046), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (8037, 8046), True, 'import matplotlib.pyplot as plt\n'), ((8369, 8388), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X (m)"""'], {}), "('X (m)')\n", (8379, 8388), True, 'import matplotlib.pyplot as plt\n'), ((8393, 8412), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y (m)"""'], {}), "('Y (m)')\n", (8403, 8412), True, 'import matplotlib.pyplot as plt\n'), ((8418, 8428), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8426, 8428), True, 'import matplotlib.pyplot as plt\n'), ((8452, 8490), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'plan[0, :]'], {'label': '"""x"""'}), "(times, plan[0, :], label='x')\n", (8460, 8490), True, 'import matplotlib.pyplot as plt\n'), ((8495, 8533), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'plan[1, :]'], {'label': '"""y"""'}), "(times, plan[1, :], label='y')\n", (8503, 8533), True, 'import matplotlib.pyplot as plt\n'), ((8538, 8580), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'plan[2, :]'], {'label': '"""theta"""'}), "(times, plan[2, :], label='theta')\n", (8546, 8580), True, 'import matplotlib.pyplot as plt\n'), ((8585, 8625), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'plan[3, :]'], {'label': '"""phi"""'}), "(times, plan[3, :], label='phi')\n", (8593, 8625), True, 'import matplotlib.pyplot as plt\n'), ((8631, 8653), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (s)"""'], {}), "('Time (s)')\n", (8641, 8653), True, 'import matplotlib.pyplot as plt\n'), ((8658, 8670), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (8668, 8670), True, 'import matplotlib.pyplot as plt\n'), ((8675, 8685), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8683, 8685), True, 'import matplotlib.pyplot as plt\n'), ((8709, 8755), 'matplotlib.pyplot.plot', 'plt.plot', (['times[:-1]', 'inputs[0, :]'], {'label': '"""u1"""'}), "(times[:-1], inputs[0, :], label='u1')\n", (8717, 8755), True, 'import matplotlib.pyplot as plt\n'), ((8760, 8806), 'matplotlib.pyplot.plot', 'plt.plot', (['times[:-1]', 'inputs[1, :]'], {'label': '"""u2"""'}), "(times[:-1], inputs[1, :], label='u2')\n", (8768, 8806), True, 'import matplotlib.pyplot as plt\n'), ((8812, 8834), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (s)"""'], {}), "('Time (s)')\n", (8822, 8834), True, 'import matplotlib.pyplot as plt\n'), ((8839, 8851), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (8849, 8851), True, 'import matplotlib.pyplot as plt\n'), ((8856, 8866), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8864, 8866), True, 'import matplotlib.pyplot as plt\n'), ((9112, 9134), 'numpy.array', 'np.array', (['[0, 0, 0, 0]'], {}), '([0, 0, 0, 0])\n', (9120, 9134), True, 'import numpy as np\n'), ((9148, 9170), 'numpy.array', 'np.array', (['[7, 3, 0, 0]'], {}), '([7, 3, 0, 0])\n', (9156, 9170), True, 'import numpy as np\n'), ((9523, 9555), 'numpy.arange', 'np.arange', (['(0.0)', '((n + 1) * dt)', 'dt'], {}), '(0.0, (n + 1) * dt, dt)\n', (9532, 9555), True, 'import numpy as np\n'), ((1209, 1219), 'casadi.cos', 'cos', (['theta'], {}), '(theta)\n', (1212, 1219), False, 'from casadi import Opti, sin, cos, tan, vertcat\n'), ((1236, 1246), 'casadi.sin', 'sin', (['theta'], {}), '(theta)\n', (1239, 1246), False, 'from casadi import Opti, sin, cos, tan, vertcat\n'), ((7357, 7374), 'numpy.diag', 'np.diag', (['[1, 0.5]'], {}), '([1, 0.5])\n', (7364, 7374), True, 'import numpy as np\n'), ((8203, 8241), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(xc, yc)', 'r'], {'color': '"""black"""'}), "((xc, yc), r, color='black')\n", (8213, 8241), True, 'import matplotlib.pyplot as plt\n'), ((1267, 1277), 'casadi.tan', 'tan', (['sigma'], {}), '(sigma)\n', (1270, 1277), False, 'from casadi import Opti, sin, cos, tan, vertcat\n')]
# -*- coding: utf-8 -*- """ Created on Wed Nov 18 12:49:59 2020 @author: tonim """ # -*- coding: utf-8 -*- """ Created on Mon Nov 16 09:01:01 2020 Models 1 and 2 @author: Tonima """ #%% Data import and prep import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import keras from keras.models import Model from keras.layers import Input,Conv2D,Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout from keras.optimizers import Adam, Adagrad, SGD, RMSprop from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ReduceLROnPlateau, EarlyStopping from keras.utils import plot_model from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix, plot_confusion_matrix, ConfusionMatrixDisplay import matplotlib.pyplot as plt trdata = ImageDataGenerator(validation_split=0.2, rescale=(1./255),featurewise_center=True) traindata = trdata.flow_from_directory(directory="Torso",target_size=(224,224),batch_size=4, shuffle=True, subset=('training'), class_mode='categorical',color_mode='grayscale') valdata = trdata.flow_from_directory(directory="Torso",target_size=(224,224), batch_size=4,shuffle=True, subset=('validation'), class_mode='categorical', color_mode='grayscale') tsdata = ImageDataGenerator(rescale=(1./255)) # testdata = tsdata.flow_from_directory(directory="test", shuffle= False, target_size=(224,224), class_mode='categorical') testdata = tsdata.flow_from_directory(directory="Torso_test", shuffle=True,batch_size=786, target_size=(224,224), class_mode='categorical',color_mode='grayscale') class_names=[ "DV lower","DV Upper", "LAT Lower","LAT Upper",] #%% trial model 1 from kerastuner import HyperParameters from kerastuner.tuners import Hyperband, RandomSearch print('Model making is under process') def model_builder(hp): act='swish' hp_units=hp.Int('units', min_value = 60, max_value = 120, step = 4)#optimal value from min to max is chosen hp_units2=hp.Int('units', min_value = 42, max_value = 84, step = 2)#optimal value from min to max is chosen hp_lr=hp.Float('learning_rate', min_value=1e-4, max_value=1e-2, step=1e-4) def conv_block(x,filters): c1=Conv2D(filters=filters[0], kernel_size=(1,5), activation=act,padding='same')(x) c2=Conv2D(filters=filters[1], kernel_size=(5,1), activation=act,padding='same')(x) c_o=Concatenate(axis=3)([c1,c2]) return c_o def reduc_block(x): x=Conv2D(8,(1,1), activation=act, padding='same')(x) c1=Conv2D(filters=32, kernel_size=(1,1),activation=act,padding='same')(x) c11=Conv2D(filters=32, kernel_size=(3,3),activation=act,padding='same')(c1) c12=Conv2D(filters=32, kernel_size=(3,3),activation=act,padding='same')(c11) c2=Conv2D(filters=32, kernel_size=(3,3),activation=act,padding='same')(x) c3=MaxPool2D((1))(c2) out=Concatenate(axis=1)([c12,c2,c3]) #out=MaxPool2D(3,3)(out) return out def fire_module(x): # Squeeze layer x1 = Convolution2D(4,(1,1),activation=(act),padding='same')(x) # Expand layer 1x1 filters c1 = Conv2D(16, (1,1), activation=(act),padding='same')(x1) # Expand layer 3x3 filters c2 = Conv2D(16, (3,3),activation=(act), padding='same')(x1) # concatenate outputs y = Concatenate(axis=1)([c1,c2]) return y ins=Input(shape=(224,224,1)) l1=(conv_block(ins,[32,32]))# if filters=[32,32]-->filter[0]=32, filter[1]=32 l1=fire_module(l1) l2=(AvgPool2D(pool_size=(2,2), strides=(2)))(l1) l31=(conv_block(l2,filters=[32,32])) l32=(reduc_block(l31)) l4=(AvgPool2D(pool_size=(2,2), strides=(2)))(l32) l5=(Flatten())(l4) l5=Dropout(0.2)(l5) l6=(Dense(units=hp_units,activation='relu'))(l5) l7=(Dense(units=hp_units2, activation='relu'))(l6) l8=(Dense(4, activation='softmax'))(l7)# 1 can be replaced with 2 or more when it itsnt a binary classification anymore M1=Model(inputs=ins, outputs=l8) print(M1.summary()) M1.compile(optimizer=Adagrad(learning_rate=hp_lr), loss='categorical_crossentropy',metrics=['accuracy']) return M1 tuner = RandomSearch(model_builder,tune_new_entries=True,objective='val_accuracy',executions_per_trial=1, max_trials=2,overwrite=(True)) #tuner.search_space_summary() hist=tuner.search(x = traindata, epochs =2, verbose =1, validation_data=valdata, steps_per_epoch=10) #hist=M1.fit(traindata, epochs = 1, verbose =1, validation_data=valdata, steps_per_epoch=50) print('Model built') best_model = tuner.get_best_models(num_models=1)[0] best_model.save('bestmodel.h5') #%% trial model 2 import numpy from kerastuner import HyperParameters from keras import utils from kerastuner.tuners import Hyperband, RandomSearch print('Model making is under process') def model_builder2(hp): hp_units=hp.Int('units', min_value = 60, max_value = 120, step = 4)#optimal value from min to max is chosen hp_units2=hp.Int('units', min_value = 42, max_value = 84, step = 2)#optimal value from min to max is chosen hp_lr2=hp.Float('learning_rate', min_value=1e-4, max_value=1e-2, step=1e-4) k_1x1="kernal_1x1" k_1x3="kernal_1x3" k_3x1="kernal_3x1" k_3x3="kernal_3x3" mx="maxpool" conc="concatenate" sq="squeeze" ex="expand" def conv3_1_3(x,filters,act): c1=Conv2D(filters=filters[0], kernel_size=(1,3), activation=act,padding='same')(x) c2=Conv2D(filters=filters[0], kernel_size=(3,1), activation=act,padding='same')(c1) return c2 def conv3_1_conc(x,filters,act): c1=Conv2D(filters=filters, kernel_size=(1,3), activation=act,padding='same')(x) c2=Conv2D(filters=filters, kernel_size=(1,3), activation=act,padding='same')(x) conc=Concatenate(axis=3)([c1,c2]) return conc def reduc_block(x): x=Conv2D(8,(1,1), activation=act, padding='same')(x) c1=Conv2D(filters=32, kernel_size=(1,1),activation=act,padding='same')(x) c11=Conv2D(filters=32, kernel_size=(3,3),activation=act,padding='same')(c1) c12=Conv2D(filters=32, kernel_size=(3,3),activation=act,padding='same')(c11) c2=Conv2D(filters=32, kernel_size=(3,3),activation=act,padding='same')(x) c3=MaxPool2D((1))(c2) out=Concatenate(axis=3)([c12,c2,c3]) out=MaxPool2D(4,4)(out) return out def fire_module(x): # Squeeze layer x1 = Convolution2D(4,(1,1),activation=(act),padding='same')(x) # Expand layer 1x1 filters c1 = Conv2D(8, (1,1), activation=(act),padding='same')(x1) # Expand layer 3x3 filters c2 = Conv2D(8, (3,3),activation=(act), padding='same')(x1) # concatenate outputs y = Concatenate(axis=3)([c1,c2]) return y act='swish' ins1=Input(shape=(224,224,1)) ins=fire_module(ins1) l1a=conv3_1_3(ins, [32], act) l1b=conv3_1_3(ins, [32], act) l1=Concatenate(axis=3)([l1a,l1b]) l2=MaxPool2D(pool_size=(4,4) )(l1) l3=Conv2D(filters=32,kernel_size=3,strides=1,padding='same')(l2) l3=reduc_block(l3) l4=conv3_1_conc(l3, 32, act) l5=AvgPool2D(pool_size=(2,2),strides=4)(l4) l5=(Flatten())(l5) l5=Dropout(0.2)(l5) l6=(Dense(units=hp_units,activation='relu'))(l5) l7=(Dense(units=hp_units2, activation='relu'))(l6) l8=(Dense(4, activation='softmax'))(l7) M2=Model(inputs=ins1, outputs=l8) print(M2.summary()) #plot_model(M1) #('Failed to import pydot. You must `pip install pydot` and install graphviz (https://graphviz.gitlab.io/download/), ', 'for `pydotprint` to work.' M2.compile(optimizer=Adagrad(learning_rate=hp_lr2), loss='categorical_crossentropy',metrics=['accuracy']) return M2 tuner2 = RandomSearch(model_builder2,tune_new_entries=True,objective='val_accuracy',executions_per_trial=2, max_trials=2,overwrite=(True)) #tuner.search_space_summary() hist=tuner2.search(x = traindata, epochs = 3, verbose =1, validation_data=valdata, steps_per_epoch=20) #hist=M1.fit(traindata, epochs = 1, verbose =1, validation_data=valdata, steps_per_epoch=50) print('Model built') best_model2 = tuner2.get_best_models(num_models=1)[0] best_model2.save('bestmodel2.h5') #%% training from pytictoc import TicToc t = TicToc() #create instance of class t.tic() #Start timer print(best_model2.summary()) callback=EarlyStopping(monitor="val_loss",min_delta=0,patience=40,verbose=1,mode="auto",baseline=None,restore_best_weights=False) #hist1 = best_model.fit(x = traindata, epochs =100, verbose =1, validation_data=valdata,steps_per_epoch = 25) hist2 = best_model2.fit(x = traindata, epochs =100, verbose =1, validation_data=valdata,steps_per_epoch = 50) t.toc() # plt.plot(hist1.history["accuracy"])# # plt.plot(hist1.history['val_accuracy']) # #plt.plot(hist.history["loss"]) # #plt.plot(hist.history["val_loss"]) # plt.title("model 1") # plt.ylabel("Accuracy") # plt.xlabel("Epoch") # plt.legend(["Accuracy","Validation Accuracy","loss", "val_loss"]) # plt.show() plt.plot(hist2.history["accuracy"])# plt.plot(hist2.history['val_accuracy']) #plt.plot(hist.history["loss"]) #plt.plot(hist.history["val_loss"]) plt.title("model 2") plt.ylabel("Accuracy") plt.xlabel("Epoch") plt.legend(["Accuracy","Validation Accuracy","loss", "val_loss"]) plt.show() max(hist2.history["accuracy"]) max(hist2.history['val_accuracy']) #%% testing from keras.utils.np_utils import to_categorical import os, cv2 from sklearn.utils import shuffle import sklearn from sklearn.model_selection import train_test_split plt.show() inputs=testdata data, tlabel= inputs.next() meh=numpy.array([[1,1,1,1]])#used to generate % of class belonging prediction1=np.zeros((len(data),4)) prediction2=np.zeros((len(data),4)) for i in range(len(data)): image = data[i].reshape(1,224,224,1) #image = image/255 #prediction1[i] = best_model.predict(image) prediction2[i] = best_model2.predict(image) #p1 = np.argmax(prediction1,axis=1) p2 = np.argmax(prediction2,axis=1) test_label=np.argmax(tlabel,axis=1) #cf_matrix1=confusion_matrix(test_label,p1) cf_matrix2=confusion_matrix(test_label,p2) #disp1=ConfusionMatrixDisplay(cf_matrix1,display_labels=(class_names)) disp2=ConfusionMatrixDisplay(cf_matrix2,display_labels=(class_names)) #disp1 = disp1.plot() disp2 = disp2.plot() plt.show() # print("-----------------------------------------------------------------------") # print(cf_matrix1, cf_matrix2) # print("-----------------------------------------------------------------------") # print("Precision, Recall, F1-score:") # print(classification_report(test_label,p1, target_names=class_names)) print("Precision, Recall, F1-score:") print(classification_report(test_label,p2, target_names=class_names)) misclassification2=test_label-p2 def condition(misclassification2):return misclassification2!=0 output=[idx for idx, element in enumerate(misclassification2) if condition (element)] print(output) plt.figure(figsize=(4,4)) for images,labels in testdata: for i in range (output): ax=plt.subplot(3,3,i+1) plt.imshow(images[i].numpy().astype("uint8")) plt.title(int(labels[i])) #plt.axis("off") #%% #%% testing single image from keras.preprocessing import image import numpy as np # select a sample image path img_path8="D:/x ray/#CLASSES/Torso_test/LAT Upper/1.2.826.0.1.3680043.2.876.17357.1.6.0.20200817105801.2.1.jpg" #img_path8="D:/x ray/#CLASSES/Torso_test/DV Lower/1.2.826.0.1.3680043.2.876.8248.1.3.1.20170511212235.2.39.jpg" #img_path8="D:/x ray/#CLASSES/Torso_test/DV Upper/1.2.276.0.7230010.3.0.3.5.1.11072342.4025358845.jpg" #img_path8="D:/x ray/#CLASSES/Torso_test/LAT Lower/1.2.276.0.7230010.3.0.3.5.1.11215350.830898152.jpg" #sample DV upper image imgxray=image.load_img(img_path8, target_size=(224,224,1),color_mode='grayscale') imgxray.show() img = cv2.imread(img_path8,0) edges = cv2.Canny(img,100,200) plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Original Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(edges,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) imgxray=np.asarray(imgxray) imgxray=np.expand_dims(imgxray,axis=0) imgxray=np.rot90(imgxray,1,(1,2)) #resize or not to resize #imgxray=imgxray.reshape(1,224,224,1) y=best_model2.predict(imgxray) print('prediction probability is: ') print(y) class_labels = list(traindata.class_indices.keys()) 0 y_predict = np.argmax(y,axis=1) print("model prediction is: ",class_labels[y_predict[0]]) #%% import tensorflow as tf #meh=numpy.array([[1,1,1,1]]) #or meh1=numpy.array([[1,0,0,0]]) meh2=numpy.array([[0,1,0,0]]) meh3=numpy.array([[0,0,1,0]]) meh4=numpy.array([[0,0,0,1]]) testlocal="D:/x ray/#CLASSES/Torso_test/LAT Upper/1.2.826.0.1.3680043.2.876.17440.2.5.1.20201101122147.2.3.jpg" img = keras.preprocessing.image.load_img( testlocal, target_size=(224,224), color_mode='grayscale') img_array = keras.preprocessing.image.img_to_array(img) img_array = tf.expand_dims(img_array, 0) # Create batch axis PRED = best_model2.predict(img_array) score = PRED[0] a1=np.max(100*np.multiply(meh1,score)) a2=np.max(100*np.multiply(meh2,score)) a3=np.max(100*np.multiply(meh3,score)) a4=np.max(100*np.multiply(meh4,score)) print( "This image is %.2f percent DV Lower, %.2f percent DV Upper,%.2f percent LAT Lower and %.2f percent LAT Upper." % (a1,a2,a3,a4) ) #or # ans=(np.argmax(np.multiply(meh,score))) # print("The image belongs to class %.2f" # % (ans) # )
[ "matplotlib.pyplot.title", "keras.preprocessing.image.ImageDataGenerator", "numpy.argmax", "keras.layers.MaxPool2D", "keras.optimizers.Adagrad", "keras.models.Model", "sklearn.metrics.classification_report", "keras.preprocessing.image.img_to_array", "matplotlib.pyplot.figure", "numpy.rot90", "pytictoc.TicToc", "keras.layers.Input", "keras.layers.AvgPool2D", "numpy.multiply", "matplotlib.pyplot.imshow", "matplotlib.pyplot.yticks", "keras.layers.Flatten", "keras.preprocessing.image.load_img", "matplotlib.pyplot.xticks", "cv2.Canny", "matplotlib.pyplot.show", "keras.layers.Convolution2D", "keras.layers.Dropout", "matplotlib.pyplot.legend", "numpy.asarray", "keras.layers.Concatenate", "keras.layers.Conv2D", "kerastuner.tuners.RandomSearch", "matplotlib.pyplot.ylabel", "tensorflow.expand_dims", "matplotlib.pyplot.subplot", "matplotlib.pyplot.plot", "numpy.expand_dims", "cv2.imread", "keras.callbacks.EarlyStopping", "numpy.array", "keras.layers.Dense", "sklearn.metrics.confusion_matrix", "matplotlib.pyplot.xlabel", "sklearn.metrics.ConfusionMatrixDisplay" ]
[((927, 1015), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'validation_split': '(0.2)', 'rescale': '(1.0 / 255)', 'featurewise_center': '(True)'}), '(validation_split=0.2, rescale=1.0 / 255,\n featurewise_center=True)\n', (945, 1015), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((1377, 1414), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)'}), '(rescale=1.0 / 255)\n', (1395, 1414), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((4330, 4464), 'kerastuner.tuners.RandomSearch', 'RandomSearch', (['model_builder'], {'tune_new_entries': '(True)', 'objective': '"""val_accuracy"""', 'executions_per_trial': '(1)', 'max_trials': '(2)', 'overwrite': '(True)'}), "(model_builder, tune_new_entries=True, objective='val_accuracy',\n executions_per_trial=1, max_trials=2, overwrite=True)\n", (4342, 4464), False, 'from kerastuner.tuners import Hyperband, RandomSearch\n'), ((8022, 8158), 'kerastuner.tuners.RandomSearch', 'RandomSearch', (['model_builder2'], {'tune_new_entries': '(True)', 'objective': '"""val_accuracy"""', 'executions_per_trial': '(2)', 'max_trials': '(2)', 'overwrite': '(True)'}), "(model_builder2, tune_new_entries=True, objective=\n 'val_accuracy', executions_per_trial=2, max_trials=2, overwrite=True)\n", (8034, 8158), False, 'from kerastuner.tuners import Hyperband, RandomSearch\n'), ((8541, 8549), 'pytictoc.TicToc', 'TicToc', ([], {}), '()\n', (8547, 8549), False, 'from pytictoc import TicToc\n'), ((8638, 8769), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'min_delta': '(0)', 'patience': '(40)', 'verbose': '(1)', 'mode': '"""auto"""', 'baseline': 'None', 'restore_best_weights': '(False)'}), "(monitor='val_loss', min_delta=0, patience=40, verbose=1, mode\n ='auto', baseline=None, restore_best_weights=False)\n", (8651, 8769), False, 'from keras.callbacks import ReduceLROnPlateau, EarlyStopping\n'), ((9318, 9353), 'matplotlib.pyplot.plot', 'plt.plot', (["hist2.history['accuracy']"], {}), "(hist2.history['accuracy'])\n", (9326, 9353), True, 'import matplotlib.pyplot as plt\n'), ((9356, 9395), 'matplotlib.pyplot.plot', 'plt.plot', (["hist2.history['val_accuracy']"], {}), "(hist2.history['val_accuracy'])\n", (9364, 9395), True, 'import matplotlib.pyplot as plt\n'), ((9467, 9487), 'matplotlib.pyplot.title', 'plt.title', (['"""model 2"""'], {}), "('model 2')\n", (9476, 9487), True, 'import matplotlib.pyplot as plt\n'), ((9489, 9511), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (9499, 9511), True, 'import matplotlib.pyplot as plt\n'), ((9513, 9532), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (9523, 9532), True, 'import matplotlib.pyplot as plt\n'), ((9534, 9601), 'matplotlib.pyplot.legend', 'plt.legend', (["['Accuracy', 'Validation Accuracy', 'loss', 'val_loss']"], {}), "(['Accuracy', 'Validation Accuracy', 'loss', 'val_loss'])\n", (9544, 9601), True, 'import matplotlib.pyplot as plt\n'), ((9601, 9611), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9609, 9611), True, 'import matplotlib.pyplot as plt\n'), ((9870, 9880), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9878, 9880), True, 'import matplotlib.pyplot as plt\n'), ((9932, 9959), 'numpy.array', 'numpy.array', (['[[1, 1, 1, 1]]'], {}), '([[1, 1, 1, 1]])\n', (9943, 9959), False, 'import numpy\n'), ((10302, 10332), 'numpy.argmax', 'np.argmax', (['prediction2'], {'axis': '(1)'}), '(prediction2, axis=1)\n', (10311, 10332), True, 'import numpy as np\n'), ((10344, 10369), 'numpy.argmax', 'np.argmax', (['tlabel'], {'axis': '(1)'}), '(tlabel, axis=1)\n', (10353, 10369), True, 'import numpy as np\n'), ((10426, 10458), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['test_label', 'p2'], {}), '(test_label, p2)\n', (10442, 10458), False, 'from sklearn.metrics import classification_report, confusion_matrix, plot_confusion_matrix, ConfusionMatrixDisplay\n'), ((10537, 10599), 'sklearn.metrics.ConfusionMatrixDisplay', 'ConfusionMatrixDisplay', (['cf_matrix2'], {'display_labels': 'class_names'}), '(cf_matrix2, display_labels=class_names)\n', (10559, 10599), False, 'from sklearn.metrics import classification_report, confusion_matrix, plot_confusion_matrix, ConfusionMatrixDisplay\n'), ((10647, 10657), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10655, 10657), True, 'import matplotlib.pyplot as plt\n'), ((11292, 11318), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(4, 4)'}), '(figsize=(4, 4))\n', (11302, 11318), True, 'import matplotlib.pyplot as plt\n'), ((12118, 12194), 'keras.preprocessing.image.load_img', 'image.load_img', (['img_path8'], {'target_size': '(224, 224, 1)', 'color_mode': '"""grayscale"""'}), "(img_path8, target_size=(224, 224, 1), color_mode='grayscale')\n", (12132, 12194), False, 'from keras.preprocessing import image\n'), ((12217, 12241), 'cv2.imread', 'cv2.imread', (['img_path8', '(0)'], {}), '(img_path8, 0)\n', (12227, 12241), False, 'import os, cv2\n'), ((12250, 12274), 'cv2.Canny', 'cv2.Canny', (['img', '(100)', '(200)'], {}), '(img, 100, 200)\n', (12259, 12274), False, 'import os, cv2\n'), ((12502, 12521), 'numpy.asarray', 'np.asarray', (['imgxray'], {}), '(imgxray)\n', (12512, 12521), True, 'import numpy as np\n'), ((12531, 12562), 'numpy.expand_dims', 'np.expand_dims', (['imgxray'], {'axis': '(0)'}), '(imgxray, axis=0)\n', (12545, 12562), True, 'import numpy as np\n'), ((12571, 12599), 'numpy.rot90', 'np.rot90', (['imgxray', '(1)', '(1, 2)'], {}), '(imgxray, 1, (1, 2))\n', (12579, 12599), True, 'import numpy as np\n'), ((12813, 12833), 'numpy.argmax', 'np.argmax', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (12822, 12833), True, 'import numpy as np\n'), ((12964, 12991), 'numpy.array', 'numpy.array', (['[[1, 0, 0, 0]]'], {}), '([[1, 0, 0, 0]])\n', (12975, 12991), False, 'import numpy\n'), ((12995, 13022), 'numpy.array', 'numpy.array', (['[[0, 1, 0, 0]]'], {}), '([[0, 1, 0, 0]])\n', (13006, 13022), False, 'import numpy\n'), ((13026, 13053), 'numpy.array', 'numpy.array', (['[[0, 0, 1, 0]]'], {}), '([[0, 0, 1, 0]])\n', (13037, 13053), False, 'import numpy\n'), ((13057, 13084), 'numpy.array', 'numpy.array', (['[[0, 0, 0, 1]]'], {}), '([[0, 0, 0, 1]])\n', (13068, 13084), False, 'import numpy\n'), ((13202, 13299), 'keras.preprocessing.image.load_img', 'keras.preprocessing.image.load_img', (['testlocal'], {'target_size': '(224, 224)', 'color_mode': '"""grayscale"""'}), "(testlocal, target_size=(224, 224),\n color_mode='grayscale')\n", (13236, 13299), False, 'import keras\n'), ((13314, 13357), 'keras.preprocessing.image.img_to_array', 'keras.preprocessing.image.img_to_array', (['img'], {}), '(img)\n', (13352, 13357), False, 'import keras\n'), ((13371, 13399), 'tensorflow.expand_dims', 'tf.expand_dims', (['img_array', '(0)'], {}), '(img_array, 0)\n', (13385, 13399), True, 'import tensorflow as tf\n'), ((3536, 3562), 'keras.layers.Input', 'Input', ([], {'shape': '(224, 224, 1)'}), '(shape=(224, 224, 1))\n', (3541, 3562), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((4141, 4170), 'keras.models.Model', 'Model', ([], {'inputs': 'ins', 'outputs': 'l8'}), '(inputs=ins, outputs=l8)\n', (4146, 4170), False, 'from keras.models import Model\n'), ((7066, 7092), 'keras.layers.Input', 'Input', ([], {'shape': '(224, 224, 1)'}), '(shape=(224, 224, 1))\n', (7071, 7092), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7656, 7686), 'keras.models.Model', 'Model', ([], {'inputs': 'ins1', 'outputs': 'l8'}), '(inputs=ins1, outputs=l8)\n', (7661, 7686), False, 'from keras.models import Model\n'), ((11025, 11088), 'sklearn.metrics.classification_report', 'classification_report', (['test_label', 'p2'], {'target_names': 'class_names'}), '(test_label, p2, target_names=class_names)\n', (11046, 11088), False, 'from sklearn.metrics import classification_report, confusion_matrix, plot_confusion_matrix, ConfusionMatrixDisplay\n'), ((12276, 12292), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (12287, 12292), True, 'import matplotlib.pyplot as plt\n'), ((12293, 12321), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (12303, 12321), True, 'import matplotlib.pyplot as plt\n'), ((12324, 12351), 'matplotlib.pyplot.title', 'plt.title', (['"""Original Image"""'], {}), "('Original Image')\n", (12333, 12351), True, 'import matplotlib.pyplot as plt\n'), ((12353, 12367), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (12363, 12367), True, 'import matplotlib.pyplot as plt\n'), ((12369, 12383), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (12379, 12383), True, 'import matplotlib.pyplot as plt\n'), ((12385, 12401), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (12396, 12401), True, 'import matplotlib.pyplot as plt\n'), ((12402, 12432), 'matplotlib.pyplot.imshow', 'plt.imshow', (['edges'], {'cmap': '"""gray"""'}), "(edges, cmap='gray')\n", (12412, 12432), True, 'import matplotlib.pyplot as plt\n'), ((12435, 12458), 'matplotlib.pyplot.title', 'plt.title', (['"""Edge Image"""'], {}), "('Edge Image')\n", (12444, 12458), True, 'import matplotlib.pyplot as plt\n'), ((12460, 12474), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (12470, 12474), True, 'import matplotlib.pyplot as plt\n'), ((12476, 12490), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (12486, 12490), True, 'import matplotlib.pyplot as plt\n'), ((3679, 3717), 'keras.layers.AvgPool2D', 'AvgPool2D', ([], {'pool_size': '(2, 2)', 'strides': '(2)'}), '(pool_size=(2, 2), strides=2)\n', (3688, 3717), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3803, 3841), 'keras.layers.AvgPool2D', 'AvgPool2D', ([], {'pool_size': '(2, 2)', 'strides': '(2)'}), '(pool_size=(2, 2), strides=2)\n', (3812, 3841), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3858, 3867), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (3865, 3867), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3881, 3893), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (3888, 3893), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3907, 3947), 'keras.layers.Dense', 'Dense', ([], {'units': 'hp_units', 'activation': '"""relu"""'}), "(units=hp_units, activation='relu')\n", (3912, 3947), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3961, 4002), 'keras.layers.Dense', 'Dense', ([], {'units': 'hp_units2', 'activation': '"""relu"""'}), "(units=hp_units2, activation='relu')\n", (3966, 4002), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((4017, 4047), 'keras.layers.Dense', 'Dense', (['(4)'], {'activation': '"""softmax"""'}), "(4, activation='softmax')\n", (4022, 4047), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7196, 7215), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)'}), '(axis=3)\n', (7207, 7215), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7235, 7262), 'keras.layers.MaxPool2D', 'MaxPool2D', ([], {'pool_size': '(4, 4)'}), '(pool_size=(4, 4))\n', (7244, 7262), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7275, 7335), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3)', 'strides': '(1)', 'padding': '"""same"""'}), "(filters=32, kernel_size=3, strides=1, padding='same')\n", (7281, 7335), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7403, 7441), 'keras.layers.AvgPool2D', 'AvgPool2D', ([], {'pool_size': '(2, 2)', 'strides': '(4)'}), '(pool_size=(2, 2), strides=4)\n', (7412, 7441), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7453, 7462), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (7460, 7462), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7476, 7488), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (7483, 7488), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7502, 7542), 'keras.layers.Dense', 'Dense', ([], {'units': 'hp_units', 'activation': '"""relu"""'}), "(units=hp_units, activation='relu')\n", (7507, 7542), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7556, 7597), 'keras.layers.Dense', 'Dense', ([], {'units': 'hp_units2', 'activation': '"""relu"""'}), "(units=hp_units2, activation='relu')\n", (7561, 7597), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7612, 7642), 'keras.layers.Dense', 'Dense', (['(4)'], {'activation': '"""softmax"""'}), "(4, activation='softmax')\n", (7617, 7642), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((11392, 11416), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(3)', '(i + 1)'], {}), '(3, 3, i + 1)\n', (11403, 11416), True, 'import matplotlib.pyplot as plt\n'), ((13494, 13518), 'numpy.multiply', 'np.multiply', (['meh1', 'score'], {}), '(meh1, score)\n', (13505, 13518), True, 'import numpy as np\n'), ((13534, 13558), 'numpy.multiply', 'np.multiply', (['meh2', 'score'], {}), '(meh2, score)\n', (13545, 13558), True, 'import numpy as np\n'), ((13574, 13598), 'numpy.multiply', 'np.multiply', (['meh3', 'score'], {}), '(meh3, score)\n', (13585, 13598), True, 'import numpy as np\n'), ((13614, 13638), 'numpy.multiply', 'np.multiply', (['meh4', 'score'], {}), '(meh4, score)\n', (13625, 13638), True, 'import numpy as np\n'), ((2315, 2393), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'filters[0]', 'kernel_size': '(1, 5)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=filters[0], kernel_size=(1, 5), activation=act, padding='same')\n", (2321, 2393), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((2407, 2485), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'filters[1]', 'kernel_size': '(5, 1)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=filters[1], kernel_size=(5, 1), activation=act, padding='same')\n", (2413, 2485), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((2500, 2519), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)'}), '(axis=3)\n', (2511, 2519), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((2585, 2634), 'keras.layers.Conv2D', 'Conv2D', (['(8)', '(1, 1)'], {'activation': 'act', 'padding': '"""same"""'}), "(8, (1, 1), activation=act, padding='same')\n", (2591, 2634), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((2648, 2718), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(1, 1)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=32, kernel_size=(1, 1), activation=act, padding='same')\n", (2654, 2718), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((2732, 2802), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=32, kernel_size=(3, 3), activation=act, padding='same')\n", (2738, 2802), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((2817, 2887), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=32, kernel_size=(3, 3), activation=act, padding='same')\n", (2823, 2887), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((2902, 2972), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=32, kernel_size=(3, 3), activation=act, padding='same')\n", (2908, 2972), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((2985, 2997), 'keras.layers.MaxPool2D', 'MaxPool2D', (['(1)'], {}), '(1)\n', (2994, 2997), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3017, 3036), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(1)'}), '(axis=1)\n', (3028, 3036), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3168, 3224), 'keras.layers.Convolution2D', 'Convolution2D', (['(4)', '(1, 1)'], {'activation': 'act', 'padding': '"""same"""'}), "(4, (1, 1), activation=act, padding='same')\n", (3181, 3224), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3276, 3326), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(1, 1)'], {'activation': 'act', 'padding': '"""same"""'}), "(16, (1, 1), activation=act, padding='same')\n", (3282, 3326), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3381, 3431), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(3, 3)'], {'activation': 'act', 'padding': '"""same"""'}), "(16, (3, 3), activation=act, padding='same')\n", (3387, 3431), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((3480, 3499), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(1)'}), '(axis=1)\n', (3491, 3499), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((4222, 4250), 'keras.optimizers.Adagrad', 'Adagrad', ([], {'learning_rate': 'hp_lr'}), '(learning_rate=hp_lr)\n', (4229, 4250), False, 'from keras.optimizers import Adam, Adagrad, SGD, RMSprop\n'), ((5560, 5638), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'filters[0]', 'kernel_size': '(1, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=filters[0], kernel_size=(1, 3), activation=act, padding='same')\n", (5566, 5638), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((5652, 5730), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'filters[0]', 'kernel_size': '(3, 1)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=filters[0], kernel_size=(3, 1), activation=act, padding='same')\n", (5658, 5730), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((5814, 5889), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'filters', 'kernel_size': '(1, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=filters, kernel_size=(1, 3), activation=act, padding='same')\n", (5820, 5889), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((5903, 5978), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'filters', 'kernel_size': '(1, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=filters, kernel_size=(1, 3), activation=act, padding='same')\n", (5909, 5978), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((5994, 6013), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)'}), '(axis=3)\n', (6005, 6013), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6090, 6139), 'keras.layers.Conv2D', 'Conv2D', (['(8)', '(1, 1)'], {'activation': 'act', 'padding': '"""same"""'}), "(8, (1, 1), activation=act, padding='same')\n", (6096, 6139), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6153, 6223), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(1, 1)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=32, kernel_size=(1, 1), activation=act, padding='same')\n", (6159, 6223), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6237, 6307), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=32, kernel_size=(3, 3), activation=act, padding='same')\n", (6243, 6307), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6322, 6392), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=32, kernel_size=(3, 3), activation=act, padding='same')\n", (6328, 6392), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6407, 6477), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3, 3)', 'activation': 'act', 'padding': '"""same"""'}), "(filters=32, kernel_size=(3, 3), activation=act, padding='same')\n", (6413, 6477), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6490, 6502), 'keras.layers.MaxPool2D', 'MaxPool2D', (['(1)'], {}), '(1)\n', (6499, 6502), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6522, 6541), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)'}), '(axis=3)\n', (6533, 6541), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6568, 6583), 'keras.layers.MaxPool2D', 'MaxPool2D', (['(4)', '(4)'], {}), '(4, 4)\n', (6577, 6583), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6682, 6738), 'keras.layers.Convolution2D', 'Convolution2D', (['(4)', '(1, 1)'], {'activation': 'act', 'padding': '"""same"""'}), "(4, (1, 1), activation=act, padding='same')\n", (6695, 6738), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6790, 6839), 'keras.layers.Conv2D', 'Conv2D', (['(8)', '(1, 1)'], {'activation': 'act', 'padding': '"""same"""'}), "(8, (1, 1), activation=act, padding='same')\n", (6796, 6839), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6894, 6943), 'keras.layers.Conv2D', 'Conv2D', (['(8)', '(3, 3)'], {'activation': 'act', 'padding': '"""same"""'}), "(8, (3, 3), activation=act, padding='same')\n", (6900, 6943), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((6992, 7011), 'keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)'}), '(axis=3)\n', (7003, 7011), False, 'from keras.layers import Input, Conv2D, Convolution2D, Dense, MaxPool2D, Dropout, Flatten, Concatenate, AvgPool2D, Dropout\n'), ((7912, 7941), 'keras.optimizers.Adagrad', 'Adagrad', ([], {'learning_rate': 'hp_lr2'}), '(learning_rate=hp_lr2)\n', (7919, 7941), False, 'from keras.optimizers import Adam, Adagrad, SGD, RMSprop\n')]
from numpy import array2string from numpy import delete from numpy import s_ from numpy import concatenate from keras.models import model_from_json from sklearn.preprocessing import MinMaxScaler from connectDB import ConnectDB import argparse import time class Predict(object): SYMBOL = 0 ID_COIN = 1 def __init__(self): self.db = ConnectDB() self.scaler = MinMaxScaler(feature_range=(0, 1)) self.n_hours = 1 def get_y(self, values): y = delete(values, s_[1:], 1).reshape(-1) return y def load_model(self): json_file = open('models/model_%s.json'%coin[self.SYMBOL], 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) model.load_weights("weights/weight_%s.h5"%coin[self.SYMBOL]) return model def save_to_db(self, inv_yhat, inv_y, id_coin): time_create = int(time.time()) price_predict = array2string(inv_yhat, separator=',') price_actual = array2string(inv_y, separator=',') price_preidct_last = inv_yhat[-1] price_predict_previous = inv_yhat[-2] price_actual_last = inv_y[-1] price_actual_previous = inv_y[-2] self.db.insert_history_prediction(id_coin, time_create, price_actual, price_predict, price_preidct_last, price_predict_previous, price_actual_last, price_actual_previous) def normalize_data(self, dataset, n_time_predicts=1, n_features=1, dropnan=True): values = dataset.values values = values.astype('float32') values = self.scaler.fit_transform(values) values = values.reshape((n_time_predicts, 1, n_features)) return values def make_predict(self, model, test_X, n_features = 1): yhat = model.predict(test_X) test_X = test_X.reshape((test_X.shape[0], self.n_hours*n_features)) inv_yhat = self.invert_scaling(yhat, test_X, n_features) return inv_yhat def invert_scaling(self, test_y, test_X_reshape, n_features): inv_y = concatenate((test_y, test_X_reshape[:, -(n_features - 1):]), axis=1) inv_y = self.scaler.inverse_transform(inv_y) inv_y = inv_y[:,0] return inv_y def make_predict_price_coin(self, coin): dataset = self.db.get_data_predict_by_id(coin[self.ID_COIN]) inv_y = self.get_y(dataset.values) n_features = len(dataset.columns) n_time_predicts = len(dataset) test_X = self.normalize_data(dataset, n_time_predicts=n_time_predicts, n_features=n_features) model = self.load_model() inv_yhat = self.make_predict(model, test_X, n_features=n_features) self.save_to_db(inv_yhat, inv_y, coin[self.ID_COIN]) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Forecast coin price with deep learning.") parser.add_argument('-id',type=int,help="-id id coin") parser.add_argument('-symbol',type=str,help="-symbol symbol coin") args = parser.parse_args() coin = [args.symbol, args.id] predict = Predict() predict.make_predict_price_coin(coin)
[ "argparse.ArgumentParser", "connectDB.ConnectDB", "numpy.array2string", "sklearn.preprocessing.MinMaxScaler", "time.time", "keras.models.model_from_json", "numpy.delete", "numpy.concatenate" ]
[((2798, 2876), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Forecast coin price with deep learning."""'}), "(description='Forecast coin price with deep learning.')\n", (2821, 2876), False, 'import argparse\n'), ((353, 364), 'connectDB.ConnectDB', 'ConnectDB', ([], {}), '()\n', (362, 364), False, 'from connectDB import ConnectDB\n'), ((387, 421), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 1)'}), '(feature_range=(0, 1))\n', (399, 421), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((734, 768), 'keras.models.model_from_json', 'model_from_json', (['loaded_model_json'], {}), '(loaded_model_json)\n', (749, 768), False, 'from keras.models import model_from_json\n'), ((975, 1012), 'numpy.array2string', 'array2string', (['inv_yhat'], {'separator': '""","""'}), "(inv_yhat, separator=',')\n", (987, 1012), False, 'from numpy import array2string\n'), ((1036, 1070), 'numpy.array2string', 'array2string', (['inv_y'], {'separator': '""","""'}), "(inv_y, separator=',')\n", (1048, 1070), False, 'from numpy import array2string\n'), ((2076, 2144), 'numpy.concatenate', 'concatenate', (['(test_y, test_X_reshape[:, -(n_features - 1):])'], {'axis': '(1)'}), '((test_y, test_X_reshape[:, -(n_features - 1):]), axis=1)\n', (2087, 2144), False, 'from numpy import concatenate\n'), ((938, 949), 'time.time', 'time.time', ([], {}), '()\n', (947, 949), False, 'import time\n'), ((489, 514), 'numpy.delete', 'delete', (['values', 's_[1:]', '(1)'], {}), '(values, s_[1:], 1)\n', (495, 514), False, 'from numpy import delete\n')]