code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
###Classes that pre-process datasets for semi-synthetic experiments import numpy import scipy.sparse import os import os.path class Datasets: def __init__(self): #Must call either loadTxt(...)/loadNpz(...) to set all these members #before using Datasets objects elsewhere self.relevances=None self.features=None self.docsPerQuery=None self.queryMappings=None self.name=None #For filtered datasets, some docsPerQuery may be masked self.mask=None ###As a side-effect, loadTxt(...) stores a npz file for ###faster subsequent loading via loadNpz(...) #file_name: (str) Path to dataset file (.txt format) #name: (str) String to identify this Datasets object henceforth def loadTxt(self, file_name, name): #Internal: Counters to keep track of docID and qID previousQueryID=None docID=None qID=0 relevanceArray=None #QueryMappings: list[int],length=numQueries self.queryMappings=[] self.name=name #DocsPerQuery: list[int],length=numQueries self.docsPerQuery=[] #Relevances: list[Alpha],length=numQueries; Alpha:= numpy.array[int],length=docsForQuery self.relevances=[] #Features: list[Alpha],length=numQueries; #Alpha:= scipy.sparse.coo_matrix[double],shape=(docsForQuery, numFeatures) featureRows=None featureCols=None featureVals=None self.features=[] numFeatures=None #Now read in data with open(file_name, 'r') as f: outputFilename=file_name[:-4] outputFileDir=outputFilename+'_processed' if not os.path.exists(outputFileDir): os.makedirs(outputFileDir) for line in f: tokens=line.split(' ', 2) relevance=int(tokens[0]) queryID=int(tokens[1].split(':', 1)[1]) #Remove any trailing comments before extracting features remainder=tokens[2].split('#', 1) featureTokens=remainder[0].strip().split(' ') if numFeatures is None: numFeatures=len(featureTokens)+1 if (previousQueryID is None) or (queryID!=previousQueryID): #Begin processing a new query's documents docID=0 if relevanceArray is not None: #Previous query's data should be persisted to file/self.members currentRelevances=numpy.array(relevanceArray, dtype=numpy.int, copy=False) self.relevances.append(currentRelevances) numpy.savez_compressed(os.path.join(outputFileDir, str(qID)+'_rel'), relevances=currentRelevances) maxDocs=len(relevanceArray) self.docsPerQuery.append(maxDocs) currentFeatures=scipy.sparse.coo_matrix((featureVals, (featureRows, featureCols)), shape=(maxDocs, numFeatures), dtype=numpy.float64) currentFeatures=currentFeatures.tocsr() self.features.append(currentFeatures) scipy.sparse.save_npz(os.path.join(outputFileDir, str(qID)+'_feat'), currentFeatures) qID+=1 self.queryMappings.append(previousQueryID) if len(self.docsPerQuery)%100==0: print(".", end="", flush=True) relevanceArray=[] featureRows=[] featureCols=[] featureVals=[] previousQueryID=queryID else: docID+=1 relevanceArray.append(relevance) #Add a feature for the the intercept featureRows.append(docID) featureCols.append(0) featureVals.append(0.01) for featureToken in featureTokens: featureTokenSplit=featureToken.split(':', 1) featureIndex=int(featureTokenSplit[0]) featureValue=float(featureTokenSplit[1]) featureRows.append(docID) featureCols.append(featureIndex) featureVals.append(featureValue) #Finish processing the final query's data currentRelevances=numpy.array(relevanceArray, dtype=numpy.int, copy=False) self.relevances.append(currentRelevances) numpy.savez_compressed(os.path.join(outputFileDir, str(qID)+'_rel'), relevances=currentRelevances) maxDocs=len(relevanceArray) self.docsPerQuery.append(maxDocs) currentFeatures=scipy.sparse.coo_matrix((featureVals, (featureRows, featureCols)), shape=(maxDocs, numFeatures), dtype=numpy.float64) currentFeatures=currentFeatures.tocsr() self.features.append(currentFeatures) scipy.sparse.save_npz(os.path.join(outputFileDir, str(qID)+'_feat'), currentFeatures) self.queryMappings.append(previousQueryID) #Persist meta-data for the dataset for faster loading through loadNpz numpy.savez_compressed(outputFilename, docsPerQuery=self.docsPerQuery, name=self.name, queryMappings=self.queryMappings) print("", flush=True) print("Datasets:loadTxt [INFO] Loaded", file_name, "\t NumQueries", len(self.docsPerQuery), "\t [Min/Max]DocsPerQuery", min(self.docsPerQuery), max(self.docsPerQuery), flush=True) #file_name: (str) Path to dataset file/directory def loadNpz(self, file_name): with numpy.load(file_name+'.npz') as npFile: self.docsPerQuery=npFile['docsPerQuery'] self.name=str(npFile['name']) self.queryMappings=npFile['queryMappings'] fileDir = file_name+'_processed' if os.path.exists(fileDir): self.relevances=[] self.features=[] qID=0 while os.path.exists(os.path.join(fileDir, str(qID)+'_rel.npz')): with numpy.load(os.path.join(fileDir, str(qID)+'_rel.npz')) as currRelFile: self.relevances.append(currRelFile['relevances']) self.features.append(scipy.sparse.load_npz(os.path.join(fileDir, str(qID)+'_feat.npz'))) qID+=1 if qID%100==0: print(".", end="", flush=True) print("", flush=True) print("Datasets:loadNpz [INFO] Loaded", file_name, "\t NumQueries", len(self.docsPerQuery), "\t [Min/Max]DocsPerQuery", min(self.docsPerQuery), max(self.docsPerQuery), "\t [Sum] docsPerQuery", sum(self.docsPerQuery), flush=True) if __name__=="__main__": import Settings """ mq2008Data=Datasets() mq2008Data.loadTxt(Settings.DATA_DIR+'MQ2008.txt', 'MQ2008') mq2008Data.loadNpz(Settings.DATA_DIR+'MQ2008') del mq2008Data mq2007Data=Datasets() mq2007Data.loadTxt(Settings.DATA_DIR+'MQ2007.txt', 'MQ2007') mq2007Data.loadNpz(Settings.DATA_DIR+'MQ2007') del mq2007Data """ mslrData=Datasets() mslrData.loadTxt(Settings.DATA_DIR+'MSLR-WEB10K/mslr.txt', 'MSLR10k') del mslrData for foldID in range(1,6): for fraction in ['train','vali','test']: mslrData=Datasets() mslrData.loadTxt(Settings.DATA_DIR+'MSLR-WEB10K\\Fold'+str(foldID)+'\\'+fraction+'.txt', 'MSLR10k-'+str(foldID)+'-'+fraction) del mslrData mslrData=Datasets() mslrData.loadTxt(Settings.DATA_DIR+'MSLR/mslr.txt', 'MSLR') del mslrData for foldID in range(1,6): for fraction in ['train','vali','test']: mslrData=Datasets() mslrData.loadTxt(Settings.DATA_DIR+'MSLR\\Fold'+str(foldID)+'\\'+fraction+'.txt', 'MSLR-'+str(foldID)+'-'+fraction) del mslrData
[ "os.path.exists", "os.makedirs", "numpy.array", "numpy.savez_compressed", "numpy.load" ]
[((6021, 6146), 'numpy.savez_compressed', 'numpy.savez_compressed', (['outputFilename'], {'docsPerQuery': 'self.docsPerQuery', 'name': 'self.name', 'queryMappings': 'self.queryMappings'}), '(outputFilename, docsPerQuery=self.docsPerQuery, name\n =self.name, queryMappings=self.queryMappings)\n', (6043, 6146), False, 'import numpy\n'), ((6829, 6852), 'os.path.exists', 'os.path.exists', (['fileDir'], {}), '(fileDir)\n', (6843, 6852), False, 'import os\n'), ((5057, 5113), 'numpy.array', 'numpy.array', (['relevanceArray'], {'dtype': 'numpy.int', 'copy': '(False)'}), '(relevanceArray, dtype=numpy.int, copy=False)\n', (5068, 5113), False, 'import numpy\n'), ((6578, 6608), 'numpy.load', 'numpy.load', (["(file_name + '.npz')"], {}), "(file_name + '.npz')\n", (6588, 6608), False, 'import numpy\n'), ((1787, 1816), 'os.path.exists', 'os.path.exists', (['outputFileDir'], {}), '(outputFileDir)\n', (1801, 1816), False, 'import os\n'), ((1834, 1860), 'os.makedirs', 'os.makedirs', (['outputFileDir'], {}), '(outputFileDir)\n', (1845, 1860), False, 'import os\n'), ((2741, 2797), 'numpy.array', 'numpy.array', (['relevanceArray'], {'dtype': 'numpy.int', 'copy': '(False)'}), '(relevanceArray, dtype=numpy.int, copy=False)\n', (2752, 2797), False, 'import numpy\n')]
# Copyright 2018 <NAME>. # # Licensed under MIT License # ============================================================ import numpy as np import re from textwrap import wrap from itertools import product def from_labels_and_predictions(labels, predictions, num_classes): '''Compute a confusion matrix from labels and predictions. A drop-in replacement for tf.confusion_matrix that works on CPU data and not tensors. Params ------ labels : array-like 1-D array of real labels for classification predicitions: array-like 1-D array of predicted label classes num_classes: scalar Total number of classes Returns ------- matrix : NxN array Array of shape [num_classes, num_classes] containing the confusion values. ''' assert len(labels) == len(predictions) cm = np.zeros((num_classes, num_classes), dtype=np.int32) for i in range(len(labels)): cm[labels[i], predictions[i]] += 1 return cm def draw(ax, cm, axis_labels=None, normalize=False): '''Plot a confusion matrix. Inspired by https://stackoverflow.com/questions/41617463/tensorflow-confusion-matrix-in-tensorboard Params ------ ax : axis Axis to plot on cm : NxN array Confusion matrix Kwargs ------ axis_labels : array-like Array of size N containing axis labels normalize : bool Whether to plot counts or ratios. ''' cm = np.asarray(cm) num_classes = cm.shape[0] if normalize: with np.errstate(invalid='ignore', divide='ignore'): cm = cm / cm.sum(1, keepdims=True) cm = np.nan_to_num(cm, copy=True) po = np.get_printoptions() np.set_printoptions(precision=2) ax.imshow(cm, cmap='Oranges') ticks = np.arange(num_classes) ax.set_xlabel('Predicted') ax.set_xticks(ticks) ax.xaxis.set_label_position('bottom') ax.xaxis.tick_bottom() ax.set_ylabel('Actual') ax.set_yticks(ticks) ax.yaxis.set_label_position('left') ax.yaxis.tick_left() if axis_labels is not None: ticklabels = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in axis_labels] ticklabels = ['\n'.join(wrap(l, 20)) for l in ticklabels] ax.set_xticklabels(ticklabels, rotation=-90, ha='center') ax.set_yticklabels(ticklabels, va ='center') for i, j in product(range(num_classes), range(num_classes)): if cm[i,j] == 0: txt = '.' elif normalize: txt = '{:.2f}'.format(cm[i,j]) else: txt = '{}'.format(cm[i,j]) ax.text(j, i, txt, horizontalalignment="center", verticalalignment='center', color= "black", fontsize=7) np.set_printoptions(**po)
[ "numpy.nan_to_num", "numpy.get_printoptions", "numpy.asarray", "numpy.errstate", "numpy.zeros", "textwrap.wrap", "re.sub", "numpy.arange", "numpy.set_printoptions" ]
[((860, 912), 'numpy.zeros', 'np.zeros', (['(num_classes, num_classes)'], {'dtype': 'np.int32'}), '((num_classes, num_classes), dtype=np.int32)\n', (868, 912), True, 'import numpy as np\n'), ((1491, 1505), 'numpy.asarray', 'np.asarray', (['cm'], {}), '(cm)\n', (1501, 1505), True, 'import numpy as np\n'), ((1715, 1736), 'numpy.get_printoptions', 'np.get_printoptions', ([], {}), '()\n', (1734, 1736), True, 'import numpy as np\n'), ((1741, 1773), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (1760, 1773), True, 'import numpy as np\n'), ((1826, 1848), 'numpy.arange', 'np.arange', (['num_classes'], {}), '(num_classes)\n', (1835, 1848), True, 'import numpy as np\n'), ((2783, 2808), 'numpy.set_printoptions', 'np.set_printoptions', ([], {}), '(**po)\n', (2802, 2808), True, 'import numpy as np\n'), ((1676, 1704), 'numpy.nan_to_num', 'np.nan_to_num', (['cm'], {'copy': '(True)'}), '(cm, copy=True)\n', (1689, 1704), True, 'import numpy as np\n'), ((1568, 1614), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""ignore"""', 'divide': '"""ignore"""'}), "(invalid='ignore', divide='ignore')\n", (1579, 1614), True, 'import numpy as np\n'), ((2153, 2210), 're.sub', 're.sub', (['"""([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))"""', '"""\\\\1 """', 'x'], {}), "('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\\\1 ', x)\n", (2159, 2210), False, 'import re\n'), ((2266, 2277), 'textwrap.wrap', 'wrap', (['l', '(20)'], {}), '(l, 20)\n', (2270, 2277), False, 'from textwrap import wrap\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np def linealSolverForward(A, b): """Solves a system of equations given a lower triangular matrix. Arguments: A: Lower triangular matrix. Shape: (n, n) b: System's solutions. Shape: (n, 1) Raises: RuntimeError if A is not lower triangular Returns: A numpy array with the system's X vector. Shape: (n, 1) """ # First we check if the matrix is a lower triangle if np.allclose(A, np.tril(A)): n = len(b) x = np.zeros((n, 1)) # we apply the forward formula for every element of x for k in range(0, n): tempSum = [] for number in range(0, k): tempSum.append(-1 * A[k][number] * x[number]) tempSum = sum(tempSum) x[k] = (b[k] + tempSum) / A[k][k] return x else: raise RuntimeError("Matrix A is not lower triangular.") def linealSolverBackwards(A, b): """Solves a system of equations given a upper triangular matrix. Arguments: A: Upper triangular matrix. Shape: (n,n) b: System's solutions. Shape: (n, 1) Raises: RuntimeError if A is not upper triangular Returns: A numpy array with the system's X vector. Shape: (n,1) """ if np.allclose(A, np.triu(A)): n = len(b) x = np.zeros((n, 1)) for k in reversed(range(0, n)): tempSum = [] for number in range(k + 1, n): tempSum.append(-1 * A[k][number] * x[number]) tempSum = sum(tempSum) x[k] = (b[k] + tempSum) / A[k][k] return x else: raise RuntimeError("Matrix A is not upper triangular.") def cholesky(matrix): """Performs the cholesky descomposition into two matrices. Arguments: matrix: Hermitian and definite symmetric matrix to perfom Cholesky's descomposition. Must have shape (n,n) Raises: RuntimeError when an invalid matrix is given (ie. non Hermitian or non definite symmetric). Returns: Two numpy arrays. Both with shape (n,n) """ # check if matrix is Cholesky compatible if matrix.shape[0] != matrix.shape[1]: raise RuntimeError("Matrix is not square.") # Is it symmetric? if not np.allclose(matrix, np.transpose(matrix)): raise RuntimeError("Matrix is not symmetric.") else: size = matrix.shape[0] # Now the algorithm itself lower = np.zeros(matrix.shape) # We iterate over the triangle from left to right and top to bottom for i in range(size): for j in range(i + 1): # The element belongs to the diagonal: if i == j: tosqrt = matrix[i][i] - np.sum(lower[i][:i]**2) if tosqrt <= 0: raise RuntimeError("Matrix is not definite symmetric.") else: lower[i][j] = np.sqrt(tosqrt) # The element *does not* belong to the diagonal else: sumatoria = [] for z in range(j): sumatoria.append(lower[i][z] * lower[j][z]) sumatoria = sum(sumatoria) lower[i][j] = (matrix[i][j] - sumatoria) / lower[j][j] upper = np.matrix.transpose(lower) return lower, upper def test_cholesky(): """Test cholesky. This function will stop the code execution when it finds an error. Returns: None """ # ====== Cholesky ====== # Definite positive matrices # This matrices eigenvalues are > 0 # # Eigenvalues sign has been verified using numpy's linalg.eig positiveMatrices = (np.array([[2, 3], [3, 6]]), np.array([[1, 2], [2, 5]]), np.array([[57, 40, 7], [40, 78, 6], [7, 6, 13]]), np.array([[6, 3, 4, 8], [3, 6, 5, 1], [4, 5, 10, 7], [8, 1, 7, 25]]), np.array([[34, 12, 0, 0], [12, 41, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])) # Not definite positive matrices # This matrices eigenvalues are < 0 # # Eigenvalues sign has been verified using numpy's linalg.eig notPositiveMatrices = (np.array([[4, 2], [2, -1]]), np.array([[-1, 1], [1, 1]]), np.array([[3, 8, 9], [8, -5, 4], [9, 4, 0]]), np.array([[57, 40, 77, 30], [40, 78, 61, 69], [77, 61, 13, 59], [30, 69, 59, 81]])) # Non Hermitian matrices. # As their values are reals, this is the same as 'non symmetric matrices'. notHermitian = (np.array([[1, 3], [9, 7]]), np.array([[1, 5, 7], [2, 4, 9], [0, 3, 0]]), np.array([[5, 7, 5, 2], [9, 2, 6, 2], [40, 54, 78, 84], [10, 43, 21, 19]])) print("="*60, "\nTesting cholesky() function...") # Definite positive matrices for testMatrix in positiveMatrices: print('-'*50) print(f'Testing definite positive matrix: \n{testMatrix}') try: A, B = cholesky(testMatrix) comparison = np.allclose(np.matmul(A, B), testMatrix) assert comparison, \ "The last tested matrix did not pass the test." print("-> Pass <-") except RuntimeError: assert False, "The last tested matrix did not pass the test." # Not definite positive matrices # This matrices should raise and exception (as these aren't valid) for testMatrix in notPositiveMatrices: print('-'*50) print(f'Testing not definite positive matrix: \n{testMatrix}') try: cholesky(testMatrix) assert False, "The last tested matrix did not pass the test." except RuntimeError: assert True print("-> Pass <-") # Not Hermitian matrices # This matrices should raise and exception (as these aren't valid) for testMatrix in notHermitian: print('-'*50) print(f'Testing not Hermitian matrix: \n{testMatrix}') try: cholesky(testMatrix) assert False, "The last tested matrix did not pass the test." except RuntimeError: assert True print("-> Pass <-") def leastsq(A, b): """Solves a least squares problem. Arguments: A: Numpy Matrix b: Numpy array with the points to approximate. Raises: RuntimeError if b is not a nx1 vector or the size of A (which is square) is different than n, also if either A or b are not arrays. Returns: A numpy array with the system's approximation """ if type(A) != np.ndarray or type(b) != np.ndarray: raise RuntimeError("Input error! One of the leastq arguments is not a " + "numpy array") if b.shape[1] != 1 or A.shape[0] != b.shape[0]: print('b', A.shape[1], b.shape[0]) raise RuntimeError("b is not a nx1 vector or the size of A is " + "different than n.") # D is A^t*A and E is A^t*b # D x = E D = np.matmul(np.matrix.transpose(A), A) E = np.matmul(np.matrix.transpose(A), b) # Separates the lower and upper part of the cholesky decomposition of D # lowD uppD x = E lowD, uppD = cholesky(D) # W is equal to uppD x, and thus is the solution for LowD W = E W = linealSolverForward(lowD, E) x = linealSolverBackwards(uppD, W) return x if __name__ == "__main__": #print("Executed as stand-alone script. Running test function.\n") #test_cholesky() print(leastsq(np.array([[1, 2], [3, 4], [5, 6]]), np.array([[5], [11], [17]])))
[ "numpy.matrix.transpose", "numpy.sqrt", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.matmul", "numpy.tril", "numpy.transpose", "numpy.triu" ]
[((2553, 2575), 'numpy.zeros', 'np.zeros', (['matrix.shape'], {}), '(matrix.shape)\n', (2561, 2575), True, 'import numpy as np\n'), ((3390, 3416), 'numpy.matrix.transpose', 'np.matrix.transpose', (['lower'], {}), '(lower)\n', (3409, 3416), True, 'import numpy as np\n'), ((507, 517), 'numpy.tril', 'np.tril', (['A'], {}), '(A)\n', (514, 517), True, 'import numpy as np\n'), ((551, 567), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (559, 567), True, 'import numpy as np\n'), ((1344, 1354), 'numpy.triu', 'np.triu', (['A'], {}), '(A)\n', (1351, 1354), True, 'import numpy as np\n'), ((1388, 1404), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (1396, 1404), True, 'import numpy as np\n'), ((3797, 3823), 'numpy.array', 'np.array', (['[[2, 3], [3, 6]]'], {}), '([[2, 3], [3, 6]])\n', (3805, 3823), True, 'import numpy as np\n'), ((3825, 3851), 'numpy.array', 'np.array', (['[[1, 2], [2, 5]]'], {}), '([[1, 2], [2, 5]])\n', (3833, 3851), True, 'import numpy as np\n'), ((3877, 3925), 'numpy.array', 'np.array', (['[[57, 40, 7], [40, 78, 6], [7, 6, 13]]'], {}), '([[57, 40, 7], [40, 78, 6], [7, 6, 13]])\n', (3885, 3925), True, 'import numpy as np\n'), ((3951, 4019), 'numpy.array', 'np.array', (['[[6, 3, 4, 8], [3, 6, 5, 1], [4, 5, 10, 7], [8, 1, 7, 25]]'], {}), '([[6, 3, 4, 8], [3, 6, 5, 1], [4, 5, 10, 7], [8, 1, 7, 25]])\n', (3959, 4019), True, 'import numpy as np\n'), ((4079, 4149), 'numpy.array', 'np.array', (['[[34, 12, 0, 0], [12, 41, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]'], {}), '([[34, 12, 0, 0], [12, 41, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n', (4087, 4149), True, 'import numpy as np\n'), ((4362, 4389), 'numpy.array', 'np.array', (['[[4, 2], [2, -1]]'], {}), '([[4, 2], [2, -1]])\n', (4370, 4389), True, 'import numpy as np\n'), ((4428, 4455), 'numpy.array', 'np.array', (['[[-1, 1], [1, 1]]'], {}), '([[-1, 1], [1, 1]])\n', (4436, 4455), True, 'import numpy as np\n'), ((4484, 4528), 'numpy.array', 'np.array', (['[[3, 8, 9], [8, -5, 4], [9, 4, 0]]'], {}), '([[3, 8, 9], [8, -5, 4], [9, 4, 0]])\n', (4492, 4528), True, 'import numpy as np\n'), ((4557, 4643), 'numpy.array', 'np.array', (['[[57, 40, 77, 30], [40, 78, 61, 69], [77, 61, 13, 59], [30, 69, 59, 81]]'], {}), '([[57, 40, 77, 30], [40, 78, 61, 69], [77, 61, 13, 59], [30, 69, 59,\n 81]])\n', (4565, 4643), True, 'import numpy as np\n'), ((4808, 4834), 'numpy.array', 'np.array', (['[[1, 3], [9, 7]]'], {}), '([[1, 3], [9, 7]])\n', (4816, 4834), True, 'import numpy as np\n'), ((4856, 4899), 'numpy.array', 'np.array', (['[[1, 5, 7], [2, 4, 9], [0, 3, 0]]'], {}), '([[1, 5, 7], [2, 4, 9], [0, 3, 0]])\n', (4864, 4899), True, 'import numpy as np\n'), ((4921, 4995), 'numpy.array', 'np.array', (['[[5, 7, 5, 2], [9, 2, 6, 2], [40, 54, 78, 84], [10, 43, 21, 19]]'], {}), '([[5, 7, 5, 2], [9, 2, 6, 2], [40, 54, 78, 84], [10, 43, 21, 19]])\n', (4929, 4995), True, 'import numpy as np\n'), ((7329, 7351), 'numpy.matrix.transpose', 'np.matrix.transpose', (['A'], {}), '(A)\n', (7348, 7351), True, 'import numpy as np\n'), ((7374, 7396), 'numpy.matrix.transpose', 'np.matrix.transpose', (['A'], {}), '(A)\n', (7393, 7396), True, 'import numpy as np\n'), ((2389, 2409), 'numpy.transpose', 'np.transpose', (['matrix'], {}), '(matrix)\n', (2401, 2409), True, 'import numpy as np\n'), ((7826, 7860), 'numpy.array', 'np.array', (['[[1, 2], [3, 4], [5, 6]]'], {}), '([[1, 2], [3, 4], [5, 6]])\n', (7834, 7860), True, 'import numpy as np\n'), ((7862, 7889), 'numpy.array', 'np.array', (['[[5], [11], [17]]'], {}), '([[5], [11], [17]])\n', (7870, 7889), True, 'import numpy as np\n'), ((5339, 5354), 'numpy.matmul', 'np.matmul', (['A', 'B'], {}), '(A, B)\n', (5348, 5354), True, 'import numpy as np\n'), ((2838, 2863), 'numpy.sum', 'np.sum', (['(lower[i][:i] ** 2)'], {}), '(lower[i][:i] ** 2)\n', (2844, 2863), True, 'import numpy as np\n'), ((3026, 3041), 'numpy.sqrt', 'np.sqrt', (['tosqrt'], {}), '(tosqrt)\n', (3033, 3041), True, 'import numpy as np\n')]
import json import random import os import numpy as np from pathlib import Path import logging LOGGER = logging.getLogger(__name__) class Config(object): def __init__(self, filename=None): self.config_name = filename self.base_res_dir = "../results" # Directory where result folder is created self.exp_id = "0_Debug" self.seed = 0 # Data specific params self.data_type = "aol" self.fdir = "../data/aol/train" # Directory where training data files are stored self.f_compressed = False # Are training data files compressed or not? self.misc = "" # Suffix to append to result dir self.mode = "train" self.n_jobs = 8 # Model specific params self.query_prefix_delimiter = ( "<@@>" # Delimiter used when concatenating query and prefix in the input ) self.pref_vectorizer = "poswgtd_c-tfidf" # Type of prefix vectorizer self.prefix_vect_data = "train_data" # What data to use to train vectorizer for prefix self.use_label_feat = False # Append label text features instead of PIFA from prefix when creating label embedding for indexing self.label_vectorizer = "use_prefix_vectorizer" # Type of label vectorizer self.label_vect_data = "train_data" # data used to train a label vectorizer self.indexer_type = "hierarchicalkmeans" # Type of label indexing method to use. self.depth = ( -1 ) # This is used for depth of Trie Index, or together with must-link-constraints etc self.imb_depth = 100 # imbalance_depth param used for Hierarchical kmeans self.imb_ratio = 0.0 # imbalance_ratio param used for Hierarchical kmeans self.nr_splits = 2 # Branching factor param for Hierarchical kmeans if filename is not None: self.__dict__.update(json.load(open(filename))) self.np_seed = None self.update_random_seeds(self.seed) def to_json(self): return json.dumps(filter_json(self.__dict__), indent=4, sort_keys=True) def save_config(self, exp_dir, filename="train_config.json"): Path(exp_dir).mkdir(exist_ok=True, parents=True) with open(os.path.join(exp_dir, filename), "w") as fout: fout.write(self.to_json()) fout.write("\n") def __getstate__(self): state = dict(self.__dict__) return state @property def result_dir(self): # Update model name using selected config params model_name = "d={d}_v={v}_i={i}_s={s}{m}".format( d=self.data_type, v=self.pref_vectorizer, i=self.indexer_type.lower(), s=self.seed, m="_{}".format(self.misc) if self.misc != "" else "", ) LOGGER.info("Model name is = {}".format(model_name)) result_dir = "{base}/{exp_id}/{model}".format( base=self.base_res_dir, exp_id=self.exp_id, model=model_name ) LOGGER.info("Updated res dir is = {}".format(result_dir)) return result_dir def update_random_seeds(self, random_seed): self.seed = random_seed random.seed(random_seed) self.np_seed = random.randint(0, 1000) np.random.seed(self.np_seed) def filter_json(the_dict): res = {} for k in the_dict.keys(): if ( type(the_dict[k]) is str or type(the_dict[k]) is float or type(the_dict[k]) is int or type(the_dict[k]) is list or type(the_dict[k]) is bool or the_dict[k] is None ): res[k] = the_dict[k] elif type(the_dict[k]) is dict: res[k] = filter_json(the_dict[k]) return res
[ "logging.getLogger", "pathlib.Path", "os.path.join", "random.seed", "numpy.random.seed", "random.randint" ]
[((105, 132), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (122, 132), False, 'import logging\n'), ((3197, 3221), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (3208, 3221), False, 'import random\n'), ((3246, 3269), 'random.randint', 'random.randint', (['(0)', '(1000)'], {}), '(0, 1000)\n', (3260, 3269), False, 'import random\n'), ((3278, 3306), 'numpy.random.seed', 'np.random.seed', (['self.np_seed'], {}), '(self.np_seed)\n', (3292, 3306), True, 'import numpy as np\n'), ((2180, 2193), 'pathlib.Path', 'Path', (['exp_dir'], {}), '(exp_dir)\n', (2184, 2193), False, 'from pathlib import Path\n'), ((2247, 2278), 'os.path.join', 'os.path.join', (['exp_dir', 'filename'], {}), '(exp_dir, filename)\n', (2259, 2278), False, 'import os\n')]
import csv import json from os import listdir from os.path import isfile, join import numpy as np import torch.backends.cudnn as cudnn from PIL import Image from tqdm.auto import tqdm import pandas as pd from adv_patch_bench.utils import get_box, pad_image DATASET = 'mapillaryvistas' # DATASET = 'bdd100k' if DATASET == 'mapillaryvistas': TRAFFIC_SIGN_LABEL = 95 elif DATASET == 'bdd100k': TRAFFIC_SIGN_LABEL = 'traffic sign' CLASS_LIST = [ 'circle-750.0', 'triangle-900.0', 'octagon-915.0', 'other-0.0-0.0', 'triangle_inverted-1220.0', 'diamond-600.0', 'diamond-915.0', 'square-600.0', 'rect-458.0-610.0', 'rect-762.0-915.0', 'rect-915.0-1220.0', 'pentagon-915.0' ] SHAPE_LIST = [ 'circle', 'triangle', 'triangle_inverted', 'diamond', 'square', 'rect', 'pentagon', 'octagon', 'other' ] # CLASS_LIST = ['octagon-915.0-915.0', # 'diamond-915.0-915.0', # 'pentagon-915.0-915.0', # 'rect-915.0-1220.0', # 'rect-762.0-915.0', # 'triangle-900.0', # 'circle-750.0', # 'triangle_inverted-1220.0-1220.0', # 'rect-458.0-610.0', # 'other-0.0-0.0'] def crop_traffic_signs(filename, panoptic_per_image_id, img_path, label_path, min_area=0, pad=0.1): # Load Mapillary Vistas image img_id = filename.split('.')[0] segment = panoptic_per_image_id[img_id]['segments_info'] panoptic = np.array(Image.open(join(label_path, f'{img_id}.png'))) img_pil = Image.open(join(img_path, filename)) img = np.array(img_pil)[:, :, :3] img_height, img_width, _ = img.shape # Pad image to avoid cutting varying shapes due to boundary img_padded, pad_size = pad_image(img, pad_mode='constant', return_pad_size=True, pad_size=0.25) id_padded = pad_image(panoptic[:, :, 0], pad_mode='constant', pad_size=0.25) outputs = { 'images': [], 'masks': [], 'bbox': [], 'obj_id': [], 'offset_x': [], 'offset_y': [], 'offset_x_ratio': [], 'offset_y_ratio': [] } # Crop the specified object for obj in segment: # Check if bounding box is cut off at the image boundary xmin, ymin, width, height = obj['bbox'] is_oob = (xmin == 0) or (ymin == 0) or \ ((xmin + width) >= img_width - 1) or ((ymin + height) >= img_height - 1) if obj['category_id'] != TRAFFIC_SIGN_LABEL or is_oob: continue # Collect mask extra_pad = int(max(width, height) * 0.2) ymin, xmin = max(0, ymin + pad_size - extra_pad), max(0, xmin + pad_size - extra_pad) temp_mask = (id_padded[ymin:ymin + height + 2 * extra_pad, xmin:xmin + width + 2 * extra_pad] == obj['id']).astype(np.uint8) if temp_mask.sum() < min_area: continue # Get refined crop patch ymin_, ymax_, xmin_, xmax_ = get_box(temp_mask, pad) ymin, ymax, xmin, xmax = ymin + ymin_, ymin + ymax_, xmin + xmin_, xmin + xmax_ bool_mask = (id_padded[ymin:ymax, xmin:xmax] == obj['id']).astype(np.uint8) height, width = bool_mask.shape if height != width: print('height != width') # assert height == width image = img_padded[ymin:ymax, xmin:xmax].astype(np.uint8) outputs['images'].append(image) outputs['masks'].append(bool_mask) outputs['obj_id'].append(obj['id']) outputs['bbox'].append((ymin, ymax, xmin, xmax)) outputs['offset_x'].append(xmin) outputs['offset_y'].append(ymin) assert xmin/img_padded.shape[1] <= 1 assert ymin/img_padded.shape[0] <= 1 outputs['offset_x_ratio'].append(xmin/img_padded.shape[1]) outputs['offset_y_ratio'].append(ymin/img_padded.shape[0]) # FIXME # if DATASET == 'bdd100k': # xmin_, ymin_, width_, height_ = obj['bbox'] # bool_mask[:max(0, ymin_-10), :] = 0 # bool_mask[min(ymin_+height_+10, img_height):, :] = 0 # bool_mask[:, :max(0, xmin_-10)] = 0 # bool_mask[:, min(xmin_+width_+10, img_width):] = 0 return outputs def main(): # Arguments min_area = 1600 if DATASET == 'mapillaryvistas': data_dir = '/data/shared/mapillary_vistas/training/' elif DATASET == 'bdd100k': data_dir = '/data/shared/bdd100k/images/10k/train/' else: raise NotImplementedError(f'{DATASET} dataset is not recognized') # data_dir = '/data/shared/mtsd_v2_fully_annotated/' # model_path = '/home/nab_126/adv-patch-bench/model_weights/resnet18_cropped_signs_good_resolution_and_not_edge_10_labels.pth' cudnn.benchmark = True # Read in panoptic file if DATASET == 'mapillaryvistas': panoptic_json_path = f'{data_dir}/v2.0/panoptic/panoptic_2020.json' elif DATASET == 'bdd100k': panoptic_json_path = '/data/shared/bdd100k/labels/pan_seg/polygons/pan_seg_train.json' with open(panoptic_json_path) as panoptic_file: panoptic = json.load(panoptic_file) if DATASET == 'mapillaryvistas': panoptic_per_image_id = {} for annotation in panoptic['annotations']: print(annotation) print() print() print(annotation.keys()) qq panoptic_per_image_id[annotation['image_id']] = annotation # Convert category infos to category_id indexed dictionary panoptic_category_per_id = {} for category in panoptic['categories']: panoptic_category_per_id[category['id']] = category elif DATASET == 'bdd100k': # creating same mapping for bdd100k panoptic_per_image_id = {} for image_annotation in tqdm(panoptic): filename = image_annotation['name'] image_id = filename.split('.jpg')[0] annotation = {} annotation['filename'] = filename annotation['image_id'] = image_id segments_info = [] for label in image_annotation['labels']: label_dict = {} # TODO: check if occluded and exclude if True if label['category'] == 'traffic sign': # if label['category'] == 'traffic sign' or label['category'] == 'traffic sign frame': # label_dict['id'] = label['id'] label_dict['id'] = 26 label_dict['category_id'] = label['category'] for sign in label['poly2d']: vertices = sign['vertices'] vertices = np.array(vertices) x_cords, y_cords = vertices[:, 0], vertices[:, 1] xmin = min(x_cords) xmax = max(x_cords) ymin = min(y_cords) ymax = max(y_cords) width = xmax - xmin height = ymax - ymin label_dict['area'] = int(width) * int(height) label_dict['bbox'] = [int(xmin), int(ymin), int(width), int(height)] segments_info.append(label_dict) annotation['segments_info'] = segments_info panoptic_per_image_id[image_id] = annotation # mapillary if DATASET == 'mapillaryvistas': img_path = join(data_dir, 'images') label_path = join(data_dir, 'v2.0/panoptic/') filenames = [f for f in listdir(img_path) if isfile(join(img_path, f))] elif DATASET == 'bdd100k': # data_dir = '/data/shared/bdd100k/images/10k/train/' label_path = '/data/shared/bdd100k/labels/pan_seg/bitmasks/train/' filenames = [f for f in listdir(data_dir) if isfile(join(data_dir, f))] img_path = data_dir filenames.sort() print('[INFO] running detection algorithm') save_paths = [join(data_dir, 'traffic_signs'), join(data_dir, 'masks')] offset_df = pd.DataFrame(columns=['filename', 'obj_id', 'xmin', 'ymin', 'xmin_ratio', 'ymin_ratio']) for filename in tqdm(filenames): output = crop_traffic_signs( filename, panoptic_per_image_id, img_path, label_path, min_area=min_area, pad=0.) q # save_images(output, filename.split('.')[0], save_paths) offset_df = save_offset(output, filename.split('.')[0], save_paths, offset_df) offset_df.to_csv('offset.csv', index=False) def save_images(output, filename, paths): for img, mask, obj_id in zip(output['images'], output['masks'], output['obj_id']): Image.fromarray(img, 'RGB').save(join(paths[0], f'{filename}_{obj_id}.png')) Image.fromarray(mask * 255).save(join(paths[1], f'{filename}_{obj_id}.png')) def save_offset(output, filename, paths, offset_df): # for obj_id in output['obj_id']: for obj_id, xmin, ymin, xmin_ratio, ymin_ratio in zip( output['obj_id'], output['offset_x'], output['offset_y'], output['offset_x_ratio'], output['offset_y_ratio']): offset_df = offset_df.append( {'filename': f'{filename}.jpg', 'obj_id': obj_id, 'xmin': xmin, 'ymin': ymin, 'xmin_ratio': xmin_ratio, 'ymin_ratio': ymin_ratio}, ignore_index=True) return offset_df if __name__ == '__main__': main()
[ "PIL.Image.fromarray", "os.listdir", "os.path.join", "adv_patch_bench.utils.pad_image", "adv_patch_bench.utils.get_box", "numpy.array", "json.load", "tqdm.auto.tqdm", "pandas.DataFrame" ]
[((1815, 1887), 'adv_patch_bench.utils.pad_image', 'pad_image', (['img'], {'pad_mode': '"""constant"""', 'return_pad_size': '(True)', 'pad_size': '(0.25)'}), "(img, pad_mode='constant', return_pad_size=True, pad_size=0.25)\n", (1824, 1887), False, 'from adv_patch_bench.utils import get_box, pad_image\n'), ((1904, 1968), 'adv_patch_bench.utils.pad_image', 'pad_image', (['panoptic[:, :, 0]'], {'pad_mode': '"""constant"""', 'pad_size': '(0.25)'}), "(panoptic[:, :, 0], pad_mode='constant', pad_size=0.25)\n", (1913, 1968), False, 'from adv_patch_bench.utils import get_box, pad_image\n'), ((8112, 8204), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['filename', 'obj_id', 'xmin', 'ymin', 'xmin_ratio', 'ymin_ratio']"}), "(columns=['filename', 'obj_id', 'xmin', 'ymin', 'xmin_ratio',\n 'ymin_ratio'])\n", (8124, 8204), True, 'import pandas as pd\n'), ((8221, 8236), 'tqdm.auto.tqdm', 'tqdm', (['filenames'], {}), '(filenames)\n', (8225, 8236), False, 'from tqdm.auto import tqdm\n'), ((1618, 1642), 'os.path.join', 'join', (['img_path', 'filename'], {}), '(img_path, filename)\n', (1622, 1642), False, 'from os.path import isfile, join\n'), ((1654, 1671), 'numpy.array', 'np.array', (['img_pil'], {}), '(img_pil)\n', (1662, 1671), True, 'import numpy as np\n'), ((3033, 3056), 'adv_patch_bench.utils.get_box', 'get_box', (['temp_mask', 'pad'], {}), '(temp_mask, pad)\n', (3040, 3056), False, 'from adv_patch_bench.utils import get_box, pad_image\n'), ((5172, 5196), 'json.load', 'json.load', (['panoptic_file'], {}), '(panoptic_file)\n', (5181, 5196), False, 'import json\n'), ((7513, 7537), 'os.path.join', 'join', (['data_dir', '"""images"""'], {}), "(data_dir, 'images')\n", (7517, 7537), False, 'from os.path import isfile, join\n'), ((7559, 7591), 'os.path.join', 'join', (['data_dir', '"""v2.0/panoptic/"""'], {}), "(data_dir, 'v2.0/panoptic/')\n", (7563, 7591), False, 'from os.path import isfile, join\n'), ((8037, 8068), 'os.path.join', 'join', (['data_dir', '"""traffic_signs"""'], {}), "(data_dir, 'traffic_signs')\n", (8041, 8068), False, 'from os.path import isfile, join\n'), ((8070, 8093), 'os.path.join', 'join', (['data_dir', '"""masks"""'], {}), "(data_dir, 'masks')\n", (8074, 8093), False, 'from os.path import isfile, join\n'), ((1556, 1589), 'os.path.join', 'join', (['label_path', 'f"""{img_id}.png"""'], {}), "(label_path, f'{img_id}.png')\n", (1560, 1589), False, 'from os.path import isfile, join\n'), ((5875, 5889), 'tqdm.auto.tqdm', 'tqdm', (['panoptic'], {}), '(panoptic)\n', (5879, 5889), False, 'from tqdm.auto import tqdm\n'), ((8764, 8806), 'os.path.join', 'join', (['paths[0]', 'f"""{filename}_{obj_id}.png"""'], {}), "(paths[0], f'{filename}_{obj_id}.png')\n", (8768, 8806), False, 'from os.path import isfile, join\n'), ((8849, 8891), 'os.path.join', 'join', (['paths[1]', 'f"""{filename}_{obj_id}.png"""'], {}), "(paths[1], f'{filename}_{obj_id}.png')\n", (8853, 8891), False, 'from os.path import isfile, join\n'), ((7624, 7641), 'os.listdir', 'listdir', (['img_path'], {}), '(img_path)\n', (7631, 7641), False, 'from os import listdir\n'), ((8731, 8758), 'PIL.Image.fromarray', 'Image.fromarray', (['img', '"""RGB"""'], {}), "(img, 'RGB')\n", (8746, 8758), False, 'from PIL import Image\n'), ((8816, 8843), 'PIL.Image.fromarray', 'Image.fromarray', (['(mask * 255)'], {}), '(mask * 255)\n', (8831, 8843), False, 'from PIL import Image\n'), ((7652, 7669), 'os.path.join', 'join', (['img_path', 'f'], {}), '(img_path, f)\n', (7656, 7669), False, 'from os.path import isfile, join\n'), ((7872, 7889), 'os.listdir', 'listdir', (['data_dir'], {}), '(data_dir)\n', (7879, 7889), False, 'from os import listdir\n'), ((7900, 7917), 'os.path.join', 'join', (['data_dir', 'f'], {}), '(data_dir, f)\n', (7904, 7917), False, 'from os.path import isfile, join\n'), ((6747, 6765), 'numpy.array', 'np.array', (['vertices'], {}), '(vertices)\n', (6755, 6765), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np import os # Detect problems with a dataset def detect_problems(data): # Test for suspicious maxima if np.max(data, axis=0)[0] == 0 and np.max(data, axis=0)[20] == 20: print("Suspicious-looking maxima!") elif np.sum(data.min(axis=0)) == 0: print("Minima sum to zero!") else: print("Seems OK!") # Plot dataset def plot_data(data, fname): # Create figure fig = plt.figure(figsize=(10.0, 3.0)) axes1 = fig.add_subplot(1, 3, 1) axes2 = fig.add_subplot(1, 3, 2) axes3 = fig.add_subplot(1, 3, 3) # Decorate axes axes1.set_ylabel('average') axes2.set_ylabel('maximum') axes3.set_ylabel('minimum') # Plot data axes1.plot(data.mean(axis=0)) axes2.plot(data.max(axis=0)) axes3.plot(data.min(axis=0)) # Tidy plot and write file fig.tight_layout() print("Writing image to:", imgname) plt.savefig(imgname) # Get a list of data files files = [] for fname in os.listdir('data'): if ('inflammation' in fname) and ('.csv' in fname): files.append(os.path.join('data', fname)) print("inflammation data files:", files) # Loop over files and analyse each file for fname in files: print("Analysing:", fname) # load data data = np.loadtxt(fname, delimiter=",") # Detect problems detect_problems(data) # Plot data imgname = fname[:-4] + '.png' plot_data(data, imgname)
[ "os.listdir", "matplotlib.pyplot.savefig", "os.path.join", "numpy.max", "matplotlib.pyplot.figure", "numpy.loadtxt" ]
[((1010, 1028), 'os.listdir', 'os.listdir', (['"""data"""'], {}), "('data')\n", (1020, 1028), False, 'import os\n'), ((460, 491), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10.0, 3.0)'}), '(figsize=(10.0, 3.0))\n', (470, 491), True, 'import matplotlib.pyplot as plt\n'), ((936, 956), 'matplotlib.pyplot.savefig', 'plt.savefig', (['imgname'], {}), '(imgname)\n', (947, 956), True, 'import matplotlib.pyplot as plt\n'), ((1297, 1329), 'numpy.loadtxt', 'np.loadtxt', (['fname'], {'delimiter': '""","""'}), "(fname, delimiter=',')\n", (1307, 1329), True, 'import numpy as np\n'), ((1107, 1134), 'os.path.join', 'os.path.join', (['"""data"""', 'fname'], {}), "('data', fname)\n", (1119, 1134), False, 'import os\n'), ((162, 182), 'numpy.max', 'np.max', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (168, 182), True, 'import numpy as np\n'), ((195, 215), 'numpy.max', 'np.max', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (201, 215), True, 'import numpy as np\n')]
import numpy as np import scipy import skimage from skimage.draw import disk from scipy import signal # function that returns a circular kernel field def construct_circular_kernel_field(r): r_int_max=np.int(np.floor(r)) shape = (r_int_max*2+1, r_int_max*2+1) fcirc = np.zeros(shape) rr, cc = skimage.draw.disk((r_int_max, r_int_max), r+0.0001, shape=shape) fcirc[rr, cc] = 1 return (fcirc/np.sum(fcirc)) def calculate_PSS(fa, fb, r, Q): fkernel=construct_circular_kernel_field(r=r) # smoothing - this function also automatically enlarges the domain area fa_smooth=scipy.signal.fftconvolve(fa, fkernel, mode='full') fb_smooth=scipy.signal.fftconvolve(fb, fkernel, mode='full') PSS=1.0-1.0/(2.0*float(fa.size)*Q)*(np.abs(fa_smooth - fb_smooth)).sum() return(PSS) def calculate_PSD(fa, fb): # make a copy of the fields so the values in the input fields are not changed fa1=fa.copy() fb1=fb.copy() # compare dimensions of fields if fa1.shape != fb1.shape: print("ERROR: fa and fb arrays do not have the same shape. Returning -1 as result!") return(-1) # compare number of dimensions of fields if fa1.ndim != 2 or fb1.ndim != 2: print("ERROR: fa and fb arrays are not two-dimensional. Returning -1 as result!") return(-1) # compare the array has some elements if fa1.size == 0 or fb1.size == 0: print("ERROR: the dimensions of fa and fb arrays are zero. Returning -1 as result!") return(-1) # detect non-numeric values result=np.where(np.isfinite(fa1) == False) if len(result[0]) > 0: print("ERROR: fa or fb arrays contain some non-numeric values. Returning -1 as result!") return(-1) result=np.where(np.isfinite(fb1) == False) if len(result[0]) > 0: print("ERROR: fa or fb arrays contain some non-numeric values. Returning -1 as result!") return(-1) # detect masked array if isinstance(fa1, np.ma.MaskedArray) or isinstance(fb1, np.ma.MaskedArray) : print("ERROR: fa or fb arrays are masked arrays which is not allowed. Returning -1 as result!") return(-1) # detect negative values if fa1[fa1<0].size > 0 or fb1[fb1<0].size > 0 : print("ERROR: fa or fb arrays contain some negative values which is not allowed . Returning -1 as result!") return(-1) # cast to float - just in case the input fields are integers fa1=fa1.astype(float) fb1=fb1.astype(float) # Normalization fa1_avg=np.average(fa1) fb1_avg=np.average(fb1) if (fa1_avg == 0 or fb1_avg == 0): print("WARNING: At least one of the fields is empty (contains only zero values). Returning -1 as result!") return(-1) fa2=fa1.copy() fb2=fb1.copy() fa2=fa1/fa1_avg fb2=fb1/fb1_avg #special case if the two fields are indetical - return 0 in this case if (fa2==fb2).all(): return(0) # Removal of overlapping values fa3=fa2.copy() fb3=fb2.copy() fa3=fa2 - np.minimum(fa2,fb2) fb3=fb2 - np.minimum(fa2,fb2) Q = fa3.sum()/fa2.sum() r1=1 PSS1=calculate_PSS(fa=fa3, fb=fb3, r=r1, Q=Q) # special case when PSS > 0.5 at n=1 if PSS1 > 0.5: return(1); # increase r in steps of 5 % diagonal = np.sqrt(fa1.shape[0]*fa1.shape[0] + fa1.shape[1]*fa1.shape[1]) dr = np.ceil(diagonal*0.05) r2=r1+dr PSS2=calculate_PSS(fa=fa3, fb=fb3, r=r2, Q=Q) while PSS2 < 0.5: r1=r2 PSS1=PSS2 r2=r1+dr PSS2=calculate_PSS(fa=fa3, fb=fb3, r=r2, Q=Q) # Bisection to get to the final r1 and r2 that bound the PSS=0.5 value while r2 - r1 > 1: # select middle point rnew=int((r1 + r2)/2); PSSnew=calculate_PSS(fa=fa3, fb=fb3, r=rnew, Q=Q) if PSSnew > 0.5: r2=rnew; PSS2=PSSnew; else: r1=rnew; PSS1=PSSnew; PSD = 0.808*Q*float(r2) return(PSD)
[ "numpy.abs", "numpy.ceil", "numpy.sqrt", "numpy.minimum", "numpy.average", "scipy.signal.fftconvolve", "numpy.floor", "numpy.sum", "numpy.zeros", "numpy.isfinite", "skimage.draw.disk" ]
[((271, 286), 'numpy.zeros', 'np.zeros', (['shape'], {}), '(shape)\n', (279, 286), True, 'import numpy as np\n'), ((297, 363), 'skimage.draw.disk', 'skimage.draw.disk', (['(r_int_max, r_int_max)', '(r + 0.0001)'], {'shape': 'shape'}), '((r_int_max, r_int_max), r + 0.0001, shape=shape)\n', (314, 363), False, 'import skimage\n'), ((579, 629), 'scipy.signal.fftconvolve', 'scipy.signal.fftconvolve', (['fa', 'fkernel'], {'mode': '"""full"""'}), "(fa, fkernel, mode='full')\n", (603, 629), False, 'import scipy\n'), ((641, 691), 'scipy.signal.fftconvolve', 'scipy.signal.fftconvolve', (['fb', 'fkernel'], {'mode': '"""full"""'}), "(fb, fkernel, mode='full')\n", (665, 691), False, 'import scipy\n'), ((2367, 2382), 'numpy.average', 'np.average', (['fa1'], {}), '(fa1)\n', (2377, 2382), True, 'import numpy as np\n'), ((2392, 2407), 'numpy.average', 'np.average', (['fb1'], {}), '(fb1)\n', (2402, 2407), True, 'import numpy as np\n'), ((3068, 3134), 'numpy.sqrt', 'np.sqrt', (['(fa1.shape[0] * fa1.shape[0] + fa1.shape[1] * fa1.shape[1])'], {}), '(fa1.shape[0] * fa1.shape[0] + fa1.shape[1] * fa1.shape[1])\n', (3075, 3134), True, 'import numpy as np\n'), ((3137, 3161), 'numpy.ceil', 'np.ceil', (['(diagonal * 0.05)'], {}), '(diagonal * 0.05)\n', (3144, 3161), True, 'import numpy as np\n'), ((209, 220), 'numpy.floor', 'np.floor', (['r'], {}), '(r)\n', (217, 220), True, 'import numpy as np\n'), ((396, 409), 'numpy.sum', 'np.sum', (['fcirc'], {}), '(fcirc)\n', (402, 409), True, 'import numpy as np\n'), ((2821, 2841), 'numpy.minimum', 'np.minimum', (['fa2', 'fb2'], {}), '(fa2, fb2)\n', (2831, 2841), True, 'import numpy as np\n'), ((2852, 2872), 'numpy.minimum', 'np.minimum', (['fa2', 'fb2'], {}), '(fa2, fb2)\n', (2862, 2872), True, 'import numpy as np\n'), ((1488, 1504), 'numpy.isfinite', 'np.isfinite', (['fa1'], {}), '(fa1)\n', (1499, 1504), True, 'import numpy as np\n'), ((1660, 1676), 'numpy.isfinite', 'np.isfinite', (['fb1'], {}), '(fb1)\n', (1671, 1676), True, 'import numpy as np\n'), ((731, 760), 'numpy.abs', 'np.abs', (['(fa_smooth - fb_smooth)'], {}), '(fa_smooth - fb_smooth)\n', (737, 760), True, 'import numpy as np\n')]
import os import numpy as np import tensorflow as tf import cv2 from utils.load_config import load_config from utils.load_data import load_data from utils.extraction_model import load_extraction_model np.random.seed(0) np.set_printoptions(precision=3, suppress=True, linewidth=150) """ test script to try the computations of feature positions within a feature map run: python -m tests.CNN.t04_optical_flow_on_ft """ # define configuration config_path = 'CNN_t04_optical_flow_m0001.json' # load config config = load_config(config_path, path='configs/CNN') # create save folder in case path = os.path.join("models/saved", config["config_name"]) if not os.path.exists(path): os.mkdir(path) # choose feature map index eyebrow_ft_idx = 148 # the index comes from t02_find_semantic_units, it is the highest IoU score for eyebrow # load and define model model = load_extraction_model(config, input_shape=tuple(config["input_shape"])) model = tf.keras.Model(inputs=model.input, outputs=model.get_layer(config['v4_layer']).output) size_ft = tuple(np.shape(model.output)[1:3]) size_ft = (280, 280) print("size_ft", size_ft) # load morphing sequence data = load_data(config) # raw_seq = load_data(config, get_raw=True)[0] print("[DATA] loaded sequence") # predict preds = model.predict(data)[..., eyebrow_ft_idx] preds = np.expand_dims(preds, axis=3) preds = preds / np.amax(preds) # normalize so we can compare with the positions print("[PRED] Shape predictions", np.shape(preds)) print("[PRED] Finish to predict") print() # ---------------------------------------------------------------------------------------------------------------------- # test 1 - compute optical flow on eye brow feature map # code taken frm: https://nanonets.com/blog/optical-flow/ # transform to gray images predictions = preds[..., 0] # plot first feature map pred0 = np.array(predictions[0]) * 255 print("shape pred0", np.shape(pred0)) pred0_fm148 = cv2.cvtColor(pred0.astype(np.uint8), cv2.COLOR_GRAY2BGR) cv2.imwrite(os.path.join(path, 'pred0_fm148.png'), pred0_fm148) # Creates an image filled with zero intensities with the same dimensions as the frame mask = np.zeros(size_ft + (3, )) # add tuple to set up size of rgb image print("[TEST 1] shape mask", np.shape(mask)) # Sets image saturation to maximum mask[..., 1] = 255 # initialize video writer fourcc = cv2.VideoWriter_fourcc(*'mp4v') fps = 30 of_video_filename = os.path.join(path, 'optical_flow_fm148.mp4') of_out = cv2.VideoWriter(of_video_filename, fourcc, fps, size_ft) # create raw output fm_video_filename = os.path.join(path, 'raw_output_fm148.mp4') fm_out = cv2.VideoWriter(fm_video_filename, fourcc, fps, size_ft) # for i in range(1, np.shape(predictions)[0]): for i in range(1, 5): # get current and previous frame prev_frame = np.array(np.array(predictions[i - 1]) * 255).astype(np.uint8) curr_frame = np.array(np.array(predictions[i]) * 255).astype(np.uint8) # tests # curr_frame = np.zeros(size_ft).astype(np.uint8) prev_frame = np.zeros(size_ft).astype(np.uint8) curr_frame = np.zeros(size_ft).astype(np.uint8) # single dot # prev_frame[100:101, (30+i):(31+i)] = 255 # for size_ft (280, 280) # curr_frame[100:101, (31+i):(32+i)] = 255 # cube prev_frame[100:110, (30+i):(40+i)] = 255 # for size_ft (280, 280) curr_frame[100:110, (31+i):(41+i)] = 255 # single dot # prev_frame[10:11, (3+i):(4+i)] = 255 # for size_ft (28, 28) # curr_frame[10:11, (4+i):(5+i)] = 255 # cube # prev_frame[10:14, (3+i):(7+i)] = 255 # for size_ft (28, 28) # curr_frame[10:14, (4+i):(8+i)] = 255 print("shape curr_frame", np.shape(curr_frame)) print("min max curr_frame", np.amin(curr_frame), np.amax(curr_frame)) # transform current frame to BGR for visualization fm = cv2.cvtColor(curr_frame, cv2.COLOR_GRAY2BGR) print("min max fm", np.amin(fm), np.amax(fm)) # compute optical flow # parameters explanation: https://www.geeksforgeeks.org/opencv-the-gunnar-farneback-optical-flow/ # - winsize: It is the average window size, larger the size, the more robust the algorithm is to noise, and # provide fast motion detection, though gives blurred motion fields. # - poly_n : It is typically 5 or 7, it is the size of the pixel neighbourhood which is used to find polynomial # expansion between the pixels. flow = cv2.calcOpticalFlowFarneback(prev_frame, curr_frame, flow=None, pyr_scale=0.5, levels=1, winsize=3, # 15 iterations=5, # 3 poly_n=5, # 5 poly_sigma=1.2, flags=0) # build image # Computes the magnitude and angle of the 2D vectors magnitude, angle = cv2.cartToPolar(flow[..., 0], flow[..., 1]) print("shape magnitude", np.shape(magnitude)) print("min max magnitude", np.amin(magnitude), np.amax(magnitude)) print("shape angle", np.shape(angle)) print("min max angle", np.amin(angle), np.amax(angle)) # Sets image hue according to the optical flow direction mask[..., 0] = angle * 180 / np.pi / 2 # Sets image value according to the optical flow magnitude (normalized) mask[..., 2] = cv2.normalize(magnitude, None, 0, 255, cv2.NORM_MINMAX) # Converts HSV to RGB (BGR) color representation print("min max mask[..., 0]", np.amin(mask[..., 0]), np.amax(mask[..., 0])) print("min max mask[..., 1]", np.amin(mask[..., 1]), np.amax(mask[..., 1])) print("min max mask[..., 2]", np.amin( mask[..., 2]), np.amax( mask[..., 2])) bgr = cv2.cvtColor(mask.astype('float32'), cv2.COLOR_HSV2BGR) # bgr = np.array(bgr).astype(np.uint8) # bgr[bgr < 0] = 0 # bgr[:5, :5, 0] = 255 print("min max bgr", np.amin(bgr), np.amax(bgr)) print("min max b channel", np.amin(bgr[..., 0]), np.amax(bgr[..., 0])) print("min max g channel", np.amin(bgr[..., 1]), np.amax(bgr[..., 1])) print("min max r channel", np.amin(bgr[..., 2]), np.amax(bgr[..., 2])) cv2.imwrite(os.path.join(path, "bgr_{}.png".format(i)), bgr.astype(np.uint8)) # write image of_out.write(bgr.astype(np.uint8)) # seems to create weird horizontal lines fm_out.write(fm) print() of_out.release() fm_out.release() print("[TEST 1] Finish optical flow on first feature map")
[ "cv2.normalize", "numpy.array", "os.path.exists", "utils.load_config.load_config", "cv2.VideoWriter", "numpy.random.seed", "cv2.VideoWriter_fourcc", "os.mkdir", "cv2.calcOpticalFlowFarneback", "numpy.amin", "cv2.cvtColor", "numpy.shape", "numpy.set_printoptions", "cv2.cartToPolar", "os.p...
[((203, 220), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (217, 220), True, 'import numpy as np\n'), ((221, 283), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)', 'suppress': '(True)', 'linewidth': '(150)'}), '(precision=3, suppress=True, linewidth=150)\n', (240, 283), True, 'import numpy as np\n'), ((516, 560), 'utils.load_config.load_config', 'load_config', (['config_path'], {'path': '"""configs/CNN"""'}), "(config_path, path='configs/CNN')\n", (527, 560), False, 'from utils.load_config import load_config\n'), ((598, 649), 'os.path.join', 'os.path.join', (['"""models/saved"""', "config['config_name']"], {}), "('models/saved', config['config_name'])\n", (610, 649), False, 'import os\n'), ((1162, 1179), 'utils.load_data.load_data', 'load_data', (['config'], {}), '(config)\n', (1171, 1179), False, 'from utils.load_data import load_data\n'), ((1327, 1356), 'numpy.expand_dims', 'np.expand_dims', (['preds'], {'axis': '(3)'}), '(preds, axis=3)\n', (1341, 1356), True, 'import numpy as np\n'), ((2154, 2178), 'numpy.zeros', 'np.zeros', (['(size_ft + (3,))'], {}), '(size_ft + (3,))\n', (2162, 2178), True, 'import numpy as np\n'), ((2356, 2387), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mp4v'"], {}), "(*'mp4v')\n", (2378, 2387), False, 'import cv2\n'), ((2417, 2461), 'os.path.join', 'os.path.join', (['path', '"""optical_flow_fm148.mp4"""'], {}), "(path, 'optical_flow_fm148.mp4')\n", (2429, 2461), False, 'import os\n'), ((2471, 2527), 'cv2.VideoWriter', 'cv2.VideoWriter', (['of_video_filename', 'fourcc', 'fps', 'size_ft'], {}), '(of_video_filename, fourcc, fps, size_ft)\n', (2486, 2527), False, 'import cv2\n'), ((2568, 2610), 'os.path.join', 'os.path.join', (['path', '"""raw_output_fm148.mp4"""'], {}), "(path, 'raw_output_fm148.mp4')\n", (2580, 2610), False, 'import os\n'), ((2620, 2676), 'cv2.VideoWriter', 'cv2.VideoWriter', (['fm_video_filename', 'fourcc', 'fps', 'size_ft'], {}), '(fm_video_filename, fourcc, fps, size_ft)\n', (2635, 2676), False, 'import cv2\n'), ((657, 677), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (671, 677), False, 'import os\n'), ((683, 697), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (691, 697), False, 'import os\n'), ((1373, 1387), 'numpy.amax', 'np.amax', (['preds'], {}), '(preds)\n', (1380, 1387), True, 'import numpy as np\n'), ((1472, 1487), 'numpy.shape', 'np.shape', (['preds'], {}), '(preds)\n', (1480, 1487), True, 'import numpy as np\n'), ((1856, 1880), 'numpy.array', 'np.array', (['predictions[0]'], {}), '(predictions[0])\n', (1864, 1880), True, 'import numpy as np\n'), ((1908, 1923), 'numpy.shape', 'np.shape', (['pred0'], {}), '(pred0)\n', (1916, 1923), True, 'import numpy as np\n'), ((2008, 2045), 'os.path.join', 'os.path.join', (['path', '"""pred0_fm148.png"""'], {}), "(path, 'pred0_fm148.png')\n", (2020, 2045), False, 'import os\n'), ((2250, 2264), 'numpy.shape', 'np.shape', (['mask'], {}), '(mask)\n', (2258, 2264), True, 'import numpy as np\n'), ((3812, 3856), 'cv2.cvtColor', 'cv2.cvtColor', (['curr_frame', 'cv2.COLOR_GRAY2BGR'], {}), '(curr_frame, cv2.COLOR_GRAY2BGR)\n', (3824, 3856), False, 'import cv2\n'), ((4393, 4546), 'cv2.calcOpticalFlowFarneback', 'cv2.calcOpticalFlowFarneback', (['prev_frame', 'curr_frame'], {'flow': 'None', 'pyr_scale': '(0.5)', 'levels': '(1)', 'winsize': '(3)', 'iterations': '(5)', 'poly_n': '(5)', 'poly_sigma': '(1.2)', 'flags': '(0)'}), '(prev_frame, curr_frame, flow=None, pyr_scale=\n 0.5, levels=1, winsize=3, iterations=5, poly_n=5, poly_sigma=1.2, flags=0)\n', (4421, 4546), False, 'import cv2\n'), ((4977, 5020), 'cv2.cartToPolar', 'cv2.cartToPolar', (['flow[..., 0]', 'flow[..., 1]'], {}), '(flow[..., 0], flow[..., 1])\n', (4992, 5020), False, 'import cv2\n'), ((5442, 5497), 'cv2.normalize', 'cv2.normalize', (['magnitude', 'None', '(0)', '(255)', 'cv2.NORM_MINMAX'], {}), '(magnitude, None, 0, 255, cv2.NORM_MINMAX)\n', (5455, 5497), False, 'import cv2\n'), ((1053, 1075), 'numpy.shape', 'np.shape', (['model.output'], {}), '(model.output)\n', (1061, 1075), True, 'import numpy as np\n'), ((3651, 3671), 'numpy.shape', 'np.shape', (['curr_frame'], {}), '(curr_frame)\n', (3659, 3671), True, 'import numpy as np\n'), ((3705, 3724), 'numpy.amin', 'np.amin', (['curr_frame'], {}), '(curr_frame)\n', (3712, 3724), True, 'import numpy as np\n'), ((3726, 3745), 'numpy.amax', 'np.amax', (['curr_frame'], {}), '(curr_frame)\n', (3733, 3745), True, 'import numpy as np\n'), ((3881, 3892), 'numpy.amin', 'np.amin', (['fm'], {}), '(fm)\n', (3888, 3892), True, 'import numpy as np\n'), ((3894, 3905), 'numpy.amax', 'np.amax', (['fm'], {}), '(fm)\n', (3901, 3905), True, 'import numpy as np\n'), ((5050, 5069), 'numpy.shape', 'np.shape', (['magnitude'], {}), '(magnitude)\n', (5058, 5069), True, 'import numpy as np\n'), ((5102, 5120), 'numpy.amin', 'np.amin', (['magnitude'], {}), '(magnitude)\n', (5109, 5120), True, 'import numpy as np\n'), ((5122, 5140), 'numpy.amax', 'np.amax', (['magnitude'], {}), '(magnitude)\n', (5129, 5140), True, 'import numpy as np\n'), ((5167, 5182), 'numpy.shape', 'np.shape', (['angle'], {}), '(angle)\n', (5175, 5182), True, 'import numpy as np\n'), ((5211, 5225), 'numpy.amin', 'np.amin', (['angle'], {}), '(angle)\n', (5218, 5225), True, 'import numpy as np\n'), ((5227, 5241), 'numpy.amax', 'np.amax', (['angle'], {}), '(angle)\n', (5234, 5241), True, 'import numpy as np\n'), ((5585, 5606), 'numpy.amin', 'np.amin', (['mask[..., 0]'], {}), '(mask[..., 0])\n', (5592, 5606), True, 'import numpy as np\n'), ((5608, 5629), 'numpy.amax', 'np.amax', (['mask[..., 0]'], {}), '(mask[..., 0])\n', (5615, 5629), True, 'import numpy as np\n'), ((5665, 5686), 'numpy.amin', 'np.amin', (['mask[..., 1]'], {}), '(mask[..., 1])\n', (5672, 5686), True, 'import numpy as np\n'), ((5688, 5709), 'numpy.amax', 'np.amax', (['mask[..., 1]'], {}), '(mask[..., 1])\n', (5695, 5709), True, 'import numpy as np\n'), ((5745, 5766), 'numpy.amin', 'np.amin', (['mask[..., 2]'], {}), '(mask[..., 2])\n', (5752, 5766), True, 'import numpy as np\n'), ((5769, 5790), 'numpy.amax', 'np.amax', (['mask[..., 2]'], {}), '(mask[..., 2])\n', (5776, 5790), True, 'import numpy as np\n'), ((5977, 5989), 'numpy.amin', 'np.amin', (['bgr'], {}), '(bgr)\n', (5984, 5989), True, 'import numpy as np\n'), ((5991, 6003), 'numpy.amax', 'np.amax', (['bgr'], {}), '(bgr)\n', (5998, 6003), True, 'import numpy as np\n'), ((6036, 6056), 'numpy.amin', 'np.amin', (['bgr[..., 0]'], {}), '(bgr[..., 0])\n', (6043, 6056), True, 'import numpy as np\n'), ((6058, 6078), 'numpy.amax', 'np.amax', (['bgr[..., 0]'], {}), '(bgr[..., 0])\n', (6065, 6078), True, 'import numpy as np\n'), ((6111, 6131), 'numpy.amin', 'np.amin', (['bgr[..., 1]'], {}), '(bgr[..., 1])\n', (6118, 6131), True, 'import numpy as np\n'), ((6133, 6153), 'numpy.amax', 'np.amax', (['bgr[..., 1]'], {}), '(bgr[..., 1])\n', (6140, 6153), True, 'import numpy as np\n'), ((6186, 6206), 'numpy.amin', 'np.amin', (['bgr[..., 2]'], {}), '(bgr[..., 2])\n', (6193, 6206), True, 'import numpy as np\n'), ((6208, 6228), 'numpy.amax', 'np.amax', (['bgr[..., 2]'], {}), '(bgr[..., 2])\n', (6215, 6228), True, 'import numpy as np\n'), ((3022, 3039), 'numpy.zeros', 'np.zeros', (['size_ft'], {}), '(size_ft)\n', (3030, 3039), True, 'import numpy as np\n'), ((3074, 3091), 'numpy.zeros', 'np.zeros', (['size_ft'], {}), '(size_ft)\n', (3082, 3091), True, 'import numpy as np\n'), ((2810, 2838), 'numpy.array', 'np.array', (['predictions[i - 1]'], {}), '(predictions[i - 1])\n', (2818, 2838), True, 'import numpy as np\n'), ((2889, 2913), 'numpy.array', 'np.array', (['predictions[i]'], {}), '(predictions[i])\n', (2897, 2913), True, 'import numpy as np\n')]
from pybit import HTTP from pybit.exceptions import InvalidRequestError from datetime import datetime as dt import numpy as np import time import config def _print(message, level='info'): """ Just a custom print function. Better than logging. """ if level == 'position': print(f'{dt.utcnow()} - {message}.', end='\r') else: print(f'{dt.utcnow()} - {level.upper()} - {message}.') def scale_qtys(x, n): """ Will create a list of qtys on both long and short side that scale additively i.e. [5, 4, 3, 2, 1, -1, -2, -3, -4, -5]. x: How much of your balance to use. n: Number of orders. """ n_ = x / ((n + n ** 2) / 2) if n_ < 1: _print("You need more equity to make this work, setting it to the minimum") n_ = 1 long_qtys = [int(n_ * i) for i in reversed(range(1, n + 1))] short_qtys = [-i for i in long_qtys] return long_qtys + short_qtys[::-1] def prepare_orders(qtys) -> object: orders = [ { 'symbol': config.SYMBOL, 'side': 'Buy' if qtys[k] > 0 else 'Sell', 'order_type': 'Limit', 'qty': abs(qtys[k]), 'price': int(prices[k]), 'time_in_force': 'GoodTillCancel', } for k in range(len(qtys)) ] return orders _print('Submitting orders') if __name__ == '__main__': # print('\n--- SAMPLE MARKET MAKER V2 ---') # print('For pybit, created by verata_veritatis.') # print('For pybit, modified by xbrandonx.') if not config.API_KEY or not config.PRIVATE_KEY or not config.ENDPOINT: raise PermissionError('An API key and endpoint is required to run this program.') print('\nUSE AT YOUR OWN RISK!!!\n') _print('Opening session') s = HTTP( api_key=config.API_KEY, api_secret=config.PRIVATE_KEY, endpoint=config.ENDPOINT, logging_level=50, retry_codes={10002, 10006}, ignore_codes={20001, 30034}, force_retry=True, max_retries=10, retry_delay=15 ) # Adjust as required above # Auth sanity test. try: s.get_wallet_balance() except InvalidRequestError as e: raise PermissionError('API key is invalid.') else: _print('Authenticated sanity check passed') # Set leverage to cross. try: s.set_leverage( symbol=config.SYMBOL, leverage=0 ) except InvalidRequestError as e: if e.status_code == 34015: _print('Margin is already set to cross') else: _print('Forced cross margin') print('\n------------------------------\n') # Main loop. while True: # Cancel orders. s.cancel_all_active_orders( symbol=config.SYMBOL ) # REMOVED. We are going to perpetually check for a position AND orders using a timer. # Close position if open. # s.close_position( # symbol=config.SYMBOL # ) # Grab the last price. _print('Checking last price') last = float(s.latest_information_for_symbol( symbol=config.SYMBOL )['result'][0]['last_price']) _print(last) # Grab the position size _print('Checking position price') position = float(s.my_position( symbol=config.SYMBOL )['result']['entry_price']) _print('Checked position price') price_range = config.RANGE * last # Create order price span. _print('Generating order prices') prices = np.linspace( last - price_range / 2, last + price_range / 2, config.NUM_ORDERS * 2 ) if position: _print('YES THERE IS A POSITION') price_range = config.RANGE * last # Create order price span. _print('Generating TP price around last price') if s.my_position( symbol=config.SYMBOL )['result']['side'] == 'Sell': _print('Set Take Profit on Sell Position') tp_dp = config.TP_DIST * position elif s.my_position( symbol=config.SYMBOL )['result']['side'] == 'Buy': _print('Set Take Profit on Buy Position') tp_dp = config.TP_DIST * position else: _print('NO POSITION') tp_dp = config.TP_DIST * last # price_range = config.RANGE * last # moved up ############################################################################# # Scale quantity additively (1x, 2x, 3x, 4x). _print('Generating order quantities') balance_in_usd = float(s.get_wallet_balance( coin=config.COIN )['result'][config.COIN]['available_balance']) * last available_equity = balance_in_usd * config.EQUITY qtys = scale_qtys(available_equity, config.NUM_ORDERS) # NEED TO CHECK FOR ZERO QTY ORDERS !!!!!!!!!!!!!!!!!!! ############################################################################# # Prepare orders. orders = prepare_orders(qtys) responses = s.place_active_order_bulk(orders=orders) _print('Prepared order quantities') ############################################################################# # Let's create an ID list of buys and sells as a dict. _print('Orders submitted successfully') order_ids = { 'Buy': [i['result']['order_id'] for i in responses if i['result']['side'] == 'Buy'], 'Sell': [i['result']['order_id'] for i in responses if i['result']['side'] == 'Sell'], } ############################################################################# # In-position loop. while True: start = time.time() print("Clock is:") print(start) # Await position. _print('Awaiting Fireworks') while not abs(s.my_position( symbol=config.SYMBOL )['result']['size']): time.sleep(1 / config.POLLING_RATE) ############################################################################# # When we have a position, get the size and cancel all the # opposing orders. if s.my_position( symbol=config.SYMBOL )['result']['side'] == 'Buy': to_cancel = [{ 'symbol': config.SYMBOL, 'order_id': i } for i in order_ids['Sell']] elif s.my_position( symbol=config.SYMBOL )['result']['side'] == 'Sell': to_cancel = [{ 'symbol': config.SYMBOL, 'order_id': i } for i in order_ids['Buy']] else: ############################################################################# # Position was closed immediately for some reason. Restart. _print('Position closed unexpectedly—resetting') break # time.sleep(1) s.cancel_active_order_bulk( orders=to_cancel ) # modify to cancel all orders, not just a list # s.cancel_all_active_orders # time.sleep(1) ############################################################################# # Set a TP. p = s.my_position(symbol=config.SYMBOL)['result'] e = float(p['entry_price']) tp_response = s.place_active_order( symbol=config.SYMBOL, side='Sell' if p['side'] == 'Buy' else 'Buy', order_type='Limit', qty=p['size'], price=int(e + tp_dp if p['side'] == 'Buy' else e - tp_dp), time_in_force='GoodTillCancel', reduce_only=True ) curr_size = p['size'] _print('TP has been set to:') ############################################################################# # Set a position stop. # time.sleep(1) if config.STOP_DIST: e = float(p['entry_price']) if p['side'] == 'Buy': stop_price = e - (e * config.STOP_DIST) _print('Setting Buy Side Stop') _print(stop_price) else: stop_price = e + (e * config.STOP_DIST) _print('Setting Sell Side Stop') _print(stop_price) s.set_trading_stop( symbol=config.SYMBOL, stop_loss=int(stop_price) ) ############################################################################# # Monitor position. print('\n------------------------------\n') while p['size']: ############################################################################# # Get the size with sign based on side. sign = p['size'] if p['side'] == 'Buy' else -p['size'] pnl_sign = '+' if float(p['unrealised_pnl']) > 0 else '-' ############################################################################# # Show status. _print( f'Size: {sign} ({float(p["effective_leverage"]):.2f}x), ' f'Entry: {float(p["entry_price"]):.2f}, ' f'Balance: {float(p["wallet_balance"]):.8f}, ' f'PNL: {pnl_sign}{abs(float(p["unrealised_pnl"])):.8f}', level='position' ) ############################################################################# # Sleep and re-fetch. time.sleep(1 / config.POLLING_RATE) p = s.my_position(symbol=config.SYMBOL)['result'] ############################################################################# # If size has changed, update TP based on entry and size. if p['size'] > curr_size: e = float(p['entry_price']) tp_price = e + tp_dp if p['side'] == 'Buy' else e - tp_dp s.replace_active_order( symbol=config.SYMBOL, order_id=tp_response['result']['order_id'], p_r_price=int(tp_price), p_r_qty=p['size'] ) curr_size = p['size'] ############################################################################# # If all orders have been filled create a new batch and place on the correct side # code to follow ############################################################################# # If an elapsed time has expired reset and place a new batch of orders # Configure time in config current = time.time() elapsed = current - start print(elapsed) if elapsed > config.TIMETOWAIT: break ############################################################################# # Position has closed—get PNL information. print(' ' * 120, end='\r') pnl_r = s.closed_profit_and_loss( symbol=config.SYMBOL )['result']['data'][0] ############################################################################# # Store PNL data as string. side = 'Buy' if pnl_r['side'].lower() == 'sell' else 'Sell' pos = f'{side} {pnl_r["qty"]}' prc = f'{pnl_r["avg_entry_price"]} -> {pnl_r["avg_exit_price"]}' ############################################################################# # Display PNL info. _print(f'Position closed successfully: {pos} ({prc})') print('\n------------------------------\n') break
[ "pybit.HTTP", "datetime.datetime.utcnow", "time.sleep", "numpy.linspace", "time.time" ]
[((1774, 1994), 'pybit.HTTP', 'HTTP', ([], {'api_key': 'config.API_KEY', 'api_secret': 'config.PRIVATE_KEY', 'endpoint': 'config.ENDPOINT', 'logging_level': '(50)', 'retry_codes': '{10002, 10006}', 'ignore_codes': '{20001, 30034}', 'force_retry': '(True)', 'max_retries': '(10)', 'retry_delay': '(15)'}), '(api_key=config.API_KEY, api_secret=config.PRIVATE_KEY, endpoint=config\n .ENDPOINT, logging_level=50, retry_codes={10002, 10006}, ignore_codes={\n 20001, 30034}, force_retry=True, max_retries=10, retry_delay=15)\n', (1778, 1994), False, 'from pybit import HTTP\n'), ((3588, 3675), 'numpy.linspace', 'np.linspace', (['(last - price_range / 2)', '(last + price_range / 2)', '(config.NUM_ORDERS * 2)'], {}), '(last - price_range / 2, last + price_range / 2, config.\n NUM_ORDERS * 2)\n', (3599, 3675), True, 'import numpy as np\n'), ((5903, 5914), 'time.time', 'time.time', ([], {}), '()\n', (5912, 5914), False, 'import time\n'), ((6175, 6210), 'time.sleep', 'time.sleep', (['(1 / config.POLLING_RATE)'], {}), '(1 / config.POLLING_RATE)\n', (6185, 6210), False, 'import time\n'), ((10020, 10055), 'time.sleep', 'time.sleep', (['(1 / config.POLLING_RATE)'], {}), '(1 / config.POLLING_RATE)\n', (10030, 10055), False, 'import time\n'), ((11249, 11260), 'time.time', 'time.time', ([], {}), '()\n', (11258, 11260), False, 'import time\n'), ((308, 319), 'datetime.datetime.utcnow', 'dt.utcnow', ([], {}), '()\n', (317, 319), True, 'from datetime import datetime as dt\n'), ((373, 384), 'datetime.datetime.utcnow', 'dt.utcnow', ([], {}), '()\n', (382, 384), True, 'from datetime import datetime as dt\n')]
# -*- coding: utf-8 -*- # ====================================== # # @Author : <NAME> # @Email : <EMAIL> # @File : stru.py # ALL RIGHTS ARE RESERVED UNLESS STATED. # ====================================== # import pathlib from collections import OrderedDict import numpy as np from ase.units import Angstrom, Bohr AbacusStruKeyDict = OrderedDict() AbacusStruKeyDict.update({ "ATOMIC_SPECIES": [ "label_list", "mass_list", "pseudo_file_list", ], "NUMERICAL_ORBITAL": [ "numerical_orbital_file", ], "LATTICE_CONSTANT": # unit:Bohr, but input(in this package) is Ang [ "lattice_constant", ], "LATTICE_VECTORS": [ "lattice_matrix", # 3by3 matrix ], "ATOMIC_POSITIONS": [ "coordinate_type", # Cartesian or Direct "atom_type_list", "magnetism_list", "number_of_atoms_list", "pos_list", # posx posy posz flagx flagy flagz ] }) AbacusStruBlock = {'atom_type_list': 'ATOMIC_POSITIONS', 'coordinate_type': 'ATOMIC_POSITIONS', 'label_list': 'ATOMIC_SPECIES', 'lattice_constant': 'LATTICE_CONSTANT', # unit: same as ase, Ang, convert to Bohr by program. 'lattice_matrix': 'LATTICE_VECTORS', 'magnetism_list': 'ATOMIC_POSITIONS', 'mass_list': 'ATOMIC_SPECIES', 'number_of_atoms_list': 'ATOMIC_POSITIONS', 'numerical_orbital_file': 'NUMERICAL_ORBITAL', 'pos_list': 'ATOMIC_POSITIONS', 'pseudo_file_list': 'ATOMIC_SPECIES'} def write_abacus_stru( task_root: str, stru_para_dict: dict ): all_stru_keys = stru_para_dict.keys() stru_blocks = set() for key in all_stru_keys: try: stru_blocks.add(AbacusStruBlock[key]) except KeyError: raise KeyError(f"Invalid STRU Key for ABACUS: {key}") with open(pathlib.Path(task_root) / "STRU", "w") as f: # MUST IN ORDER if "ATOMIC_SPECIES" in stru_blocks: print(generate_atom_species_lines(stru_para_dict), file=f) if "NUMERICAL_ORBITAL" in stru_blocks: print(generate_numerical_orbital_lines(stru_para_dict), file=f) if "LATTICE_CONSTANT" in stru_blocks: print(generate_lattice_constant_lines(stru_para_dict), file=f) if "LATTICE_VECTORS" in stru_blocks: print(generate_lattice_vectors_lines(stru_para_dict), file=f) if "ATOMIC_POSITIONS" in stru_blocks: print(generate_atomic_positions_lines(stru_para_dict), file=f) def generate_atom_species_lines(stru_para_dict): # ATOMIC_SPECIES lines label_list = stru_para_dict["label_list"] mass_list = stru_para_dict["mass_list"] pseudo_file_list = stru_para_dict["pseudo_file_list"] assert len(label_list) == len(mass_list) == len(pseudo_file_list) lines = "ATOMIC_SPECIES\n" for idx, ele in enumerate(label_list): lines += f"{ele} {mass_list[idx]} {pseudo_file_list[idx]}\n" return lines def generate_numerical_orbital_lines(stru_para_dict): # NUMERICAL_ORBITAL lines raise NotImplementedError def generate_lattice_constant_lines(stru_para_dict): # LATTICE_CONSTANT lines return f"LATTICE_CONSTANT\n{stru_para_dict['lattice_constant'] * Angstrom / Bohr}\n" def generate_lattice_vectors_lines(stru_para_dict): # LATTICE_VECTORS lines lat_vec = stru_para_dict["lattice_matrix"] if isinstance(lat_vec, list): if len(lat_vec) == 3: return f"{lat_vec[0][0]} {lat_vec[0][1]} {lat_vec[0][2]}\n" + \ f"{lat_vec[1][0]} {lat_vec[1][1]} {lat_vec[1][2]}\n" + \ f"{lat_vec[2][0]} {lat_vec[2][1]} {lat_vec[2][2]}\n" else: raise ValueError(f"stru_para_dict[\"lattice_matrix\"] is list and has wrong shape: {len(lat_vec)}*({len(lat_vec[0])},{len(lat_vec[1])},{len(lat_vec[2])}).") elif isinstance(lat_vec, np.ndarray): assert lat_vec.shape == (3, 3) return "LATTICE_VECTORS\n" \ f"{lat_vec[0][0]} {lat_vec[0][1]} {lat_vec[0][2]}\n" + \ f"{lat_vec[1][0]} {lat_vec[1][1]} {lat_vec[1][2]}\n" + \ f"{lat_vec[2][0]} {lat_vec[2][1]} {lat_vec[2][2]}\n" def generate_atomic_positions_lines(stru_para_dict): # ATOMIC_POSITIONS lines lines = "ATOMIC_POSITIONS\n" coordinate_type = stru_para_dict["coordinate_type"] if coordinate_type == "Cartesian" or "Direct": lines += f"{coordinate_type}\n\n" else: raise KeyError(f"Unknown `coordinate_type`: {coordinate_type}.") atom_type_list = stru_para_dict["atom_type_list"] magnetism_list = stru_para_dict["magnetism_list"] number_of_atoms_list = stru_para_dict["number_of_atoms_list"] pos_list = stru_para_dict["pos_list"] # each element for idx, ele in enumerate(atom_type_list): lines += f"{ele}\n" lines += f"{magnetism_list[idx]}\n" lines += f"{number_of_atoms_list[idx]}\n" ele_num = int(number_of_atoms_list[idx]) ele_pos_list = pos_list[idx] if isinstance(ele_pos_list, list): if len(ele_pos_list) == ele_num: for atom in ele_pos_list: assert len(lines) == 6, "Atom position in ABACUS STRU file need 6 numbers." lines += f"{atom[0]} {atom[1]} {atom[2]} {atom[3]} {atom[4]} {atom[5]}\n" else: raise ValueError(f"stru_para_dict[\"pos_list\"] is list and has wrong number: {len(lat_vec)} != ele_num of {atom}:{ele_num}.") elif isinstance(ele_pos_list, np.ndarray): assert ele_pos_list.shape == (ele_num, 6), f"Atom position in ABACUS STRU file need 6 numbers. Got {ele_pos_list.shape}." for atom in ele_pos_list: lines += f"{atom[0]} {atom[1]} {atom[2]} {int(atom[3])} {int(atom[4])} {int(atom[5])}\n" return lines if __name__ == '__main__': write_abacus_stru(".", { "label_list": ["Si", "O"], "mass_list": ["1.000", "1.000"], "pseudo_file_list": ["Si.pz-vbc.UPF", "O.pz-vbc.UPF"], "lattice_constant": 10.2, # Unit in Bohr, cif file unit is Angstrom!!! "lattice_matrix": np.array([ [0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.5, 0.5] ]), "coordinate_type": "Cartesian", "atom_type_list": ["Si", "O"], "magnetism_list": [0.0, 0], "number_of_atoms_list": [2, 2], "pos_list": [np.array([ [0, 0, 0, 0, 0, 0], [0.25, 0.25, 0.25, 1, 1, 1] ]), np.array([ [0, 0, 0, 0, 0, 0], [0.25, 0.25, 0.25, 1, 1, 1] ]) ] })
[ "numpy.array", "collections.OrderedDict", "pathlib.Path" ]
[((342, 355), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (353, 355), False, 'from collections import OrderedDict\n'), ((6402, 6463), 'numpy.array', 'np.array', (['[[0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.5, 0.5]]'], {}), '([[0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.5, 0.5]])\n', (6410, 6463), True, 'import numpy as np\n'), ((2090, 2113), 'pathlib.Path', 'pathlib.Path', (['task_root'], {}), '(task_root)\n', (2102, 2113), False, 'import pathlib\n'), ((6687, 6746), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 0], [0.25, 0.25, 0.25, 1, 1, 1]]'], {}), '([[0, 0, 0, 0, 0, 0], [0.25, 0.25, 0.25, 1, 1, 1]])\n', (6695, 6746), True, 'import numpy as np\n'), ((6794, 6853), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 0], [0.25, 0.25, 0.25, 1, 1, 1]]'], {}), '([[0, 0, 0, 0, 0, 0], [0.25, 0.25, 0.25, 1, 1, 1]])\n', (6802, 6853), True, 'import numpy as np\n')]
import numpy as np from utils.misc import hamming_distance # TODO(andre:2018-05-29): Fazer com que as funcoes de movimento realizem o # numero correto de passos. Atualmente os materiais que sao iguais aos materiais # da direcao para a qual se esta se movendo contam como um passo mesmo que # nenhuma mudanca seja realizada def move_population_roulette(population, num_steps, roulette, roulette_population): new_population = np.copy(population) step_order = np.random.rand(population.shape[0], population.shape[1]).argsort() # print('New population:\n{}\n'.format(new_population)) # print('Step order:\n{}\n'.format(step_order)) # print('Num steps:\n{}\n'.format(num_steps)) # print('Mask:\n{}\n'.format(mask)) try: biggest_num_steps = int(np.max(num_steps)) except ValueError: # Caso follow_num_steps esteja vazio biggest_num_steps = 0 for i in range(biggest_num_steps): still_moving_mask = (num_steps > i) still_moving_indices = np.where(still_moving_mask)[0] # TODO(andre:2018-05-28): Garantir que max_steps nunca é maior do que o numero de materiais materials_indices = step_order[still_moving_mask, i] still_moving_roulette = roulette[still_moving_mask] follow_individual = [still_moving_roulette[index].spin() for index in np.ndindex(still_moving_roulette.shape)] # print('-----------------------------' + str(i)) # print('Still moving population:\n{}\n'.format(new_population[still_moving_mask])) # print('Materials to change:\n{}\n'.format(new_population[still_moving_indices, materials_indices])) # print('Materials to assign:\n{}\n'.format(roulette_population[follow_individual, materials_indices])) # print('Follow individual:\n{}\n'.format(follow_individual)) # print('Unchanged population:\n{}\n'.format(new_population)) new_population[still_moving_indices, materials_indices] = roulette_population[follow_individual, materials_indices] return new_population def move_population_direction(population, num_steps, direction): new_population = np.copy(population) step_order = np.random.rand(population.shape[0], population.shape[1]).argsort() try: biggest_num_steps = int(np.max(num_steps)) except ValueError: # Caso follow_num_steps esteja vazio biggest_num_steps = 0 for i in range(biggest_num_steps): still_moving_mask = (num_steps > i) still_moving_indices = np.where(still_moving_mask)[0] # TODO(andre:2018-05-28): Garantir que max_steps nunca é maior do que o numero de materiais materials_indices = step_order[still_moving_mask, i] new_population[still_moving_indices, materials_indices] = direction[still_moving_indices, materials_indices] return new_population # def move_population_direction(population, num_steps, direction, mask): # new_population = np.copy(population) # # step_order = np.random.rand(population.shape[0], population.shape[1]).argsort() # # try: # biggest_num_steps = int(np.max(num_steps[mask])) # except ValueError: # Caso follow_num_steps esteja vazio # biggest_num_steps = 0 # # for i in range(biggest_num_steps): # still_moving_mask = ((num_steps > i) & mask) # # still_moving_indices = np.where(still_moving_mask)[0] # # TODO(andre:2018-05-28): Garantir que max_steps nunca é maior do que o numero de materiais # materials_indices = step_order[still_moving_mask, i] # # new_population[still_moving_indices, materials_indices] = direction[still_moving_indices, materials_indices] # # return new_population def move_population_random(population, num_steps): directions = np.random.randint(2, size=population.shape, dtype=bool) # print('Random direction:\n{}\n'.format(direction)) new_population = move_population_direction(population, num_steps, directions) return new_population # def move_population_random(population, num_steps, mask): # directions = np.random.randint(2, size=population.shape, dtype=bool) # # print('Random direction:\n{}\n'.format(direction)) # new_population = move_population_direction(population, num_steps, directions, mask) # # return new_population def move_population_random_complement(population, num_steps, away_direction): directions = np.random.randint(2, size=population.shape, dtype=bool) complement_directions = ~directions distances = hamming_distance(directions, away_direction, axis=1) complement_distances = hamming_distance(complement_directions, away_direction, axis=1) farther_directions = np.where(np.repeat((distances > complement_distances)[:, np.newaxis], population.shape[1], axis=1), directions, complement_directions) # print('Away direction:\n{}\n'.format(away_direction)) # print('Random direction:\n{}\n'.format(directions)) # print('Complement direction:\n{}\n'.format(complement_directions)) # print('Random distance:\n{}\n'.format(distances)) # print('Complement distance:\n{}\n'.format(complement_distances)) # print('Farther direction:\n{}\n'.format(farther_direction)) new_population = move_population_direction(population, num_steps, farther_directions) return new_population # def move_population_random_complement(population, num_steps, away_direction, mask): # directions = np.random.randint(2, size=population.shape, dtype=bool) # complement_directions = ~directions # # distances = hamming_distance(directions, away_direction, axis=1) # complement_distances = hamming_distance(complement_directions, away_direction, axis=1) # # farther_directions = np.where(np.repeat((distances > complement_distances)[:, np.newaxis], population.shape[1], axis=1), directions, complement_directions) # # print('Away direction:\n{}\n'.format(away_direction)) # # print('Random direction:\n{}\n'.format(directions)) # # print('Complement direction:\n{}\n'.format(complement_directions)) # # print('Random distance:\n{}\n'.format(distances)) # # print('Complement distance:\n{}\n'.format(complement_distances)) # # print('Farther direction:\n{}\n'.format(farther_direction)) # new_population = move_population_direction(population, num_steps, farther_directions, mask) # # return new_population def move_population_local_search(population, fitness_function, max_steps, num_tries, instance, timer): # mask = np.ones(population.shape[0], dtype=bool) best_survival_values = fitness_function(population, instance, timer) for i in range(num_tries): # print('-----------------------------' + str(i)) num_steps = np.round(max_steps * np.random.rand(population.shape[0])) # temp_population = move_population_random(population, num_steps, mask) temp_population = move_population_random(population, num_steps) temp_survival_values = fitness_function(temp_population, instance, timer) # print('Temp population:\n{}\n'.format(temp_population)) # print('Temp survival values:\n{}\n'.format(temp_survival_values)) better_survival_values = (temp_survival_values < best_survival_values) population = np.where(np.repeat(better_survival_values[:, np.newaxis], population.shape[1], axis=1), temp_population, population) best_survival_values = np.where(better_survival_values, temp_survival_values, best_survival_values) # print('Partial best population:\n{}\n'.format(best_population)) # print('Partial best survival values:\n{}\n'.format(best_survival_values)) # return best_population return population
[ "numpy.copy", "numpy.repeat", "numpy.random.rand", "numpy.where", "numpy.ndindex", "numpy.max", "numpy.random.randint", "utils.misc.hamming_distance" ]
[((432, 451), 'numpy.copy', 'np.copy', (['population'], {}), '(population)\n', (439, 451), True, 'import numpy as np\n'), ((2131, 2150), 'numpy.copy', 'np.copy', (['population'], {}), '(population)\n', (2138, 2150), True, 'import numpy as np\n'), ((3761, 3816), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'population.shape', 'dtype': 'bool'}), '(2, size=population.shape, dtype=bool)\n', (3778, 3816), True, 'import numpy as np\n'), ((4394, 4449), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'population.shape', 'dtype': 'bool'}), '(2, size=population.shape, dtype=bool)\n', (4411, 4449), True, 'import numpy as np\n'), ((4507, 4559), 'utils.misc.hamming_distance', 'hamming_distance', (['directions', 'away_direction'], {'axis': '(1)'}), '(directions, away_direction, axis=1)\n', (4523, 4559), False, 'from utils.misc import hamming_distance\n'), ((4587, 4650), 'utils.misc.hamming_distance', 'hamming_distance', (['complement_directions', 'away_direction'], {'axis': '(1)'}), '(complement_directions, away_direction, axis=1)\n', (4603, 4650), False, 'from utils.misc import hamming_distance\n'), ((4686, 4780), 'numpy.repeat', 'np.repeat', (['(distances > complement_distances)[:, np.newaxis]', 'population.shape[1]'], {'axis': '(1)'}), '((distances > complement_distances)[:, np.newaxis], population.\n shape[1], axis=1)\n', (4695, 4780), True, 'import numpy as np\n'), ((7396, 7472), 'numpy.where', 'np.where', (['better_survival_values', 'temp_survival_values', 'best_survival_values'], {}), '(better_survival_values, temp_survival_values, best_survival_values)\n', (7404, 7472), True, 'import numpy as np\n'), ((470, 526), 'numpy.random.rand', 'np.random.rand', (['population.shape[0]', 'population.shape[1]'], {}), '(population.shape[0], population.shape[1])\n', (484, 526), True, 'import numpy as np\n'), ((781, 798), 'numpy.max', 'np.max', (['num_steps'], {}), '(num_steps)\n', (787, 798), True, 'import numpy as np\n'), ((1006, 1033), 'numpy.where', 'np.where', (['still_moving_mask'], {}), '(still_moving_mask)\n', (1014, 1033), True, 'import numpy as np\n'), ((2169, 2225), 'numpy.random.rand', 'np.random.rand', (['population.shape[0]', 'population.shape[1]'], {}), '(population.shape[0], population.shape[1])\n', (2183, 2225), True, 'import numpy as np\n'), ((2278, 2295), 'numpy.max', 'np.max', (['num_steps'], {}), '(num_steps)\n', (2284, 2295), True, 'import numpy as np\n'), ((2503, 2530), 'numpy.where', 'np.where', (['still_moving_mask'], {}), '(still_moving_mask)\n', (2511, 2530), True, 'import numpy as np\n'), ((7257, 7334), 'numpy.repeat', 'np.repeat', (['better_survival_values[:, np.newaxis]', 'population.shape[1]'], {'axis': '(1)'}), '(better_survival_values[:, np.newaxis], population.shape[1], axis=1)\n', (7266, 7334), True, 'import numpy as np\n'), ((1337, 1376), 'numpy.ndindex', 'np.ndindex', (['still_moving_roulette.shape'], {}), '(still_moving_roulette.shape)\n', (1347, 1376), True, 'import numpy as np\n'), ((6733, 6768), 'numpy.random.rand', 'np.random.rand', (['population.shape[0]'], {}), '(population.shape[0])\n', (6747, 6768), True, 'import numpy as np\n')]
from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() import unittest import mock import json import pytumblr from urllib.parse import parse_qs import sys import csv from multiprocessing import Process, Queue import re import urllib import random import pandas as pd import numpy as np import pickle from keras.preprocessing.text import Tokenizer from keras.models import Sequential from keras.layers import Activation, Dense, Dropout from sklearn.preprocessing import LabelBinarizer import sklearn.datasets as skds from pathlib import Path from keras.models import load_model from pathlib import Path import sys def downloader(folder, image_url): file_name = image_url.split("/")[-1] full_file_name = "./" + str("images") + "/" + str(file_name) my_file = Path(full_file_name) if my_file.is_file(): print("file exists") else: try: resp = urllib.request.urlopen(image_url) respHtml = resp.read() binfile = open(full_file_name, "wb") binfile.write(respHtml) binfile.close() except: print("exception occurred") return file_name #urllib.request.urlretrieve(image_url,full_file_name) def get_dict_on_blog(): reader = csv.reader(open("./on_blog.csv")) x = True count = 0 dict_of_posts = dict(); for row in reader: if x: dict_of_posts[row[0]] = row[1] x = False else: x = True count = count + 1 return dict_of_posts def get_dict_not_on_blog(): reader = csv.reader(open("./not_on_blog.csv")) x = True count = 0 dict_of_posts = dict(); for row in reader: if x: dict_of_posts[row[0]] = row[1] x = False else: x = True count = count + 1 return dict_of_posts def remove_dups(on_blog, not_on_blog): print(len(not_on_blog.keys())) for x in on_blog: if x in not_on_blog: del not_on_blog[x] print(len(not_on_blog.keys())) print(len(on_blog.keys())) with open('not_on_blog_fix.csv','w', newline='') as f: w = csv.writer(f) w.writerows(not_on_blog.items()) with open('on_blog_fix.csv','w', newline='') as f: w = csv.writer(f) w.writerows(on_blog.items()) def right_all(client, on_blog, name): not_on_blog = dict() count = 1 start_from = False offset = 0 blog = get_followers(client, name) while len(not_on_blog) < len(on_blog): get_posts(offset, on_blog, not_on_blog, blog) offset = offset + 20 print(str(count) + " : " + str(len(not_on_blog))) count = count + 1 with open('combined_new.csv','w', newline='') as f: w = csv.writer(f) w.writerows(not_on_blog.values()) w.writerows(on_blog.values()) def reblog_all(client, on_blog, name): #id = enter id number of post you want to start reblogging from length = 20 dict_of_posts = dict() count = 1 start_from = False while length == 20: x = client.dashboard(reblog_info=True, since_id=id)[u'posts'] length = len(x); for i in range(0, length): if x[i][u'summary'] not in dict_of_posts and x[i][u'summary'] not in on_blog: hash = x[i][u'summary'] dict_of_posts[hash] = x[i] id = x[1][u'id'] print(str(count) + " : " + str(len(dict_of_posts))) count = count + 1 #add body to be posted in html body="" #add tags to add array tags=[] keys = list(dict_of_posts.keys()) for i in range(0, len(keys)): post = dict_of_posts[keys[i]] id = post['id'] reblog_key = post['reblog_key'] client.reblog(name, comment=body, tags=tags, id=id, reblog_key=reblog_key); print(str(((i+1)/len(keys))*100) + "%") def get_all_posts(client, name): length = 20 offset = 0 count = 1 dict_of_posts = dict() while length == 20: x = client.posts(name, offset=offset, reblog_info=True) if len(x) > 0: x = x[u'posts'] length = len(x); print(length) for i in range(0, length): sum = clean_string(x[i][u'summary']) if sum not in dict_of_posts and len(sum) > 0: hash = sum if 'reblogged_from_name' in x[i] and len(x[i]['reblogged_from_name']) > 0: reblog = x[i]['reblogged_from_name'] dict_of_posts[hash] = [hash, reblog ,"reblog"] if 'photos' in x[i]: file_name = downloader('reblog',x[i]['photos'][0]['original_size']['url']) dict_of_posts[hash] = [hash, reblog, file_name,"reblog"] else: dict_of_posts[hash] = [hash, reblog, "", "reblog"] else: if 'photos' in x[i]: file_name = downloader('reblog',x[i]['photos'][0]['original_size']['url']) dict_of_posts[hash] = [hash, reblog, file_name,"reblog"] else: dict_of_posts[hash] = [hash, name, "", "reblog"] print(str(count) + " : " + str(len(dict_of_posts))) count = count + 1 offset = offset + 20 return dict_of_posts def clean_string(word): word = word.replace('“','"').replace('”','"') word = word.replace('‘',"'").replace('’',"'") word = re.sub(r"[^\w\d'\s]+",'',word) word = word.lower() word = ''.join([x for x in word if ord(x) < 128]) return word def get_followers(client, blog_names): blog = [] length = 20 offset = 0 while length == 20: x = client.blog_following(blog_names, offset=offset)['blogs'] if len(x) > 0: length = len(x) for y in x: blog.append(y['name']) offset = offset + 20 return blog def get_posts(offset, on_blog, not_on_blog, blogs): for blog in blogs: x = client.posts(blog, offset=offset) if len(x) != 0: x = x[u'posts'] for y in x: sum = clean_string(y[u'summary']) if sum not in on_blog and sum not in not_on_blog: hash = sum if 'photos' in y: file_name = downloader('reblog',y['photos'][0]['original_size']['url']) dict_of_posts[hash] = [hash, blog, file_name, "not on blog"] else: dict_of_posts[hash] = [hash, blog, "", "not on blog"] def most_notes(client, name): length = 20 offset = 0 count = 1 dict_of_posts = dict() f = open("most_notes.txt", "w") while length == 20: x = client.posts(name, offset=offset)[u'posts'] length = len(x); for i in range(0, length): if x[i][u'summary'] not in dict_of_posts: hash = x[i][u'summary'] dict_of_posts[hash] = x[i] date = x[i][u'date'].split()[1] notes = x[i][u'note_count'] f.write(date + '\t' + str(notes) + "\n") print(str(count) + " : " + str(len(dict_of_posts))) count = count + 1 offset = offset + 20 return dict_of_posts def reblog_prediction(client, id_num): id = int(id_num) #enter id number to start from on dashboard x = client.dashboard(reblog_info=True, since_id=id)[u'posts'] #load our saved model model = load_model('my_model.h5') # load tokenizer tokenizer = Tokenizer() with open('tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) encoder = LabelBinarizer() encoder.classes_ = ["reblog", "not on blog"] labels = np.array(["reblog", "not on blog"]) x_data = [] length = len(x) for i in range(0, length): str = clean_string(x[i]['blog_name'] + " " + x[i][u"summary"]) x_data.append(str) x_data_series = pd.Series(x_data) x_tokenized = tokenizer.texts_to_matrix(x_data_series, mode='tfidf') i=0 for x_t in x_tokenized: prediction = model.predict(np.array([x_t])) predicted_label = labels[np.argmax(prediction[0])] print("Summary: " + x_data[i] + "\nPredicted label: " + predicted_label) i += 1 if __name__ == "__main__": #paste the API tokens from tumblr OAuth client = pytumblr.TumblrRestClient( #Add tumblr API token codes ) if (len(sys.argv) == 3): if (sys.argv[1] == "get_data"): name = sys.argv[2] on_blog = get_all_posts(client, name) right_all(client, on_blog, name) if (sys.argv[1] == "prediction"): id = sys.argv[2] reblog_prediction(client, id) else: print("Please enter either get_blogs or prediction as the 1st argument") print("Please enter a blog name or id respectively") #on_blog = get_dict() #most_notes(client, name) #reblog_all(client, on_blog, name) #on_blog = get_dict_on_blog() #not_on_blog = get_dict_not_on_blog() #remove_dups(on_blog, not_on_blog)
[ "pandas.Series", "sklearn.preprocessing.LabelBinarizer", "keras.models.load_model", "keras.preprocessing.text.Tokenizer", "pathlib.Path", "csv.writer", "pickle.load", "numpy.argmax", "future.standard_library.install_aliases", "numpy.array", "re.sub", "pytumblr.TumblrRestClient", "urllib.requ...
[((78, 112), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (110, 112), False, 'from future import standard_library\n'), ((862, 882), 'pathlib.Path', 'Path', (['full_file_name'], {}), '(full_file_name)\n', (866, 882), False, 'from pathlib import Path\n'), ((5837, 5871), 're.sub', 're.sub', (['"""[^\\\\w\\\\d\'\\\\s]+"""', '""""""', 'word'], {}), '("[^\\\\w\\\\d\'\\\\s]+", \'\', word)\n', (5843, 5871), False, 'import re\n'), ((7973, 7998), 'keras.models.load_model', 'load_model', (['"""my_model.h5"""'], {}), "('my_model.h5')\n", (7983, 7998), False, 'from keras.models import load_model\n'), ((8040, 8051), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {}), '()\n', (8049, 8051), False, 'from keras.preprocessing.text import Tokenizer\n'), ((8162, 8178), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (8176, 8178), False, 'from sklearn.preprocessing import LabelBinarizer\n'), ((8245, 8280), 'numpy.array', 'np.array', (["['reblog', 'not on blog']"], {}), "(['reblog', 'not on blog'])\n", (8253, 8280), True, 'import numpy as np\n'), ((8480, 8497), 'pandas.Series', 'pd.Series', (['x_data'], {}), '(x_data)\n', (8489, 8497), True, 'import pandas as pd\n'), ((8913, 8940), 'pytumblr.TumblrRestClient', 'pytumblr.TumblrRestClient', ([], {}), '()\n', (8938, 8940), False, 'import pytumblr\n'), ((2290, 2303), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2300, 2303), False, 'import csv\n'), ((2417, 2430), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2427, 2430), False, 'import csv\n'), ((2924, 2937), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2934, 2937), False, 'import csv\n'), ((8125, 8144), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (8136, 8144), False, 'import pickle\n'), ((987, 1020), 'urllib.request.urlopen', 'urllib.request.urlopen', (['image_url'], {}), '(image_url)\n', (1009, 1020), False, 'import urllib\n'), ((8648, 8663), 'numpy.array', 'np.array', (['[x_t]'], {}), '([x_t])\n', (8656, 8663), True, 'import numpy as np\n'), ((8699, 8723), 'numpy.argmax', 'np.argmax', (['prediction[0]'], {}), '(prediction[0])\n', (8708, 8723), True, 'import numpy as np\n')]
import hashlib from typing import Optional import numpy as np from allennlp_dataframe_mapper.transforms import RegistrableTransform from overrides import overrides @RegistrableTransform.register("hashname") class HashName(RegistrableTransform): def __init__(self, ext: Optional[str] = None) -> None: super().__init__() self._ext = ext def to_hash_name(self, url: str) -> str: hash_name = hashlib.md5(url.encode("utf8")).hexdigest() if self._ext is not None: return hash_name + self._ext return hash_name @overrides def fit(self, *args, **kwargs): return self @overrides def transform(self, X): return np.vectorize(self.to_hash_name)(X)
[ "numpy.vectorize", "allennlp_dataframe_mapper.transforms.RegistrableTransform.register" ]
[((168, 209), 'allennlp_dataframe_mapper.transforms.RegistrableTransform.register', 'RegistrableTransform.register', (['"""hashname"""'], {}), "('hashname')\n", (197, 209), False, 'from allennlp_dataframe_mapper.transforms import RegistrableTransform\n'), ((699, 730), 'numpy.vectorize', 'np.vectorize', (['self.to_hash_name'], {}), '(self.to_hash_name)\n', (711, 730), True, 'import numpy as np\n')]
# Copyright (C) 2020 Secure Systems Group, University of Waterloo and Aalto University # License: see LICENSE.txt # Author: <NAME> and <NAME> import os import pandas as pd import numpy as np from collections import deque import tqdm import joblib # contains subroutines for training, saving/loading pipeline import logistic_regression from sklearn.metrics import classification_report, precision_recall_fscore_support import data_helpers from augmentation_helpers import augmentation_helper # include standard modules import argparse # Phase 1: determine experiment parameters class ExperimentParameters: dataset_name = 'threat' percentage = 5 classifier_name = 'char-lr' aug_name = 'baseline' #aug_name = 'copy' augment_classes = [0,1] random_seed = 20200303 # lazy imports def import_optional_libraries(): if ExperimentParameters.aug_name == 'eda': global eda from eda_scripts.eda import eda elif ExperimentParameters.aug_name == 'add': global add_sentences, augmentation_helper_add from augmentation_helpers import add_sentences, augmentation_helper_add if ExperimentParameters.aug_name == 'ppdb': global augment_ppdb from ppdb_scripts.augmentation_ppdb import augment_ppdb elif ExperimentParameters.aug_name == 'wn': global augment_wn from wn_scripts.augmentation_wn import augment_wn elif ExperimentParameters.aug_name == 'gensim': global gensim_aug from embedding_scripts.augmentation_gensim import gensim_aug elif ExperimentParameters.aug_name == 'bpemb': global bpemb_aug from embedding_scripts.augmentation_bpemb import bpemb_aug elif ExperimentParameters.aug_name == 'gpt2': global lm_aug, LanguageModelWrapper, load_lm_corpus from gpt2_scripts.augmentation_lm import lm_aug, LanguageModelWrapper, load_lm_corpus # import classifier-specific libraries if ExperimentParameters.classifier_name == 'bert': global BertWrapper from fast_bert_scripts.bert_helpers import BertWrapper elif ExperimentParameters.classifier_name == 'cnn': global CNN_wrapper from cnn_scripts.cnn_helpers import CNN_wrapper def run_experiment(): import_optional_libraries() # Phase 1: determine experiment parameters assert ExperimentParameters.dataset_name in ['threat', 'identity_hate'] ExperimentParameters.aug_dir = '../data/augmentations/%s-%03d/%s-%s'%(ExperimentParameters.dataset_name, ExperimentParameters.percentage, ExperimentParameters.aug_name, ''.join(list(map(str, ExperimentParameters.augment_classes)))) ExperimentParameters.save_dir = '../results/%s-%03d/%s/%s-%s'%(ExperimentParameters.dataset_name, ExperimentParameters.percentage, ExperimentParameters.classifier_name, ExperimentParameters.aug_name, ''.join(list(map(str, ExperimentParameters.augment_classes)))) ExperimentParameters.results_file = os.path.join(ExperimentParameters.save_dir,'%s.txt'%ExperimentParameters.random_seed) if ExperimentParameters.classifier_name == 'bert': bert_wrapper = BertWrapper(model_dir = ExperimentParameters.save_dir, data_dir = ExperimentParameters.aug_dir, results_filename = '%s'%ExperimentParameters.random_seed, random_state = ExperimentParameters.random_seed) else: bert_wrapper = None if ExperimentParameters.classifier_name == 'cnn': cnn_wrapper = CNN_wrapper(model_dir = ExperimentParameters.save_dir, data_dir = ExperimentParameters.aug_dir, results_filename = '%s'%ExperimentParameters.random_seed, random_state = ExperimentParameters.random_seed) else: cnn_wrapper = None # Phase 2: load datasets DATA_DIR = '../data/' if not os.path.exists(DATA_DIR): os.makedirs(DATA_DIR) if not os.path.exists(os.path.join(DATA_DIR,'jigsaw-toxic-comment-classification-challenge')): print('Jigsaw dataset not found. ') print('Please download from https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge') print('.. and extract to the directory data-augmentation/data/jigsaw-toxic-comment-classification-challenge') return else: print('Found Jigsaw dataset.') # load train data data_dir = '../data/jigsaw-toxic-comment-classification-challenge' file = 'train.csv' train_csv = os.path.join(data_dir,file) assert os.path.exists(train_csv) df_train = pd.read_csv(train_csv) # load test data file = 'test.csv' test_csv_comments = os.path.join(data_dir,file) df_test_comments = pd.read_csv(test_csv_comments) file = 'test_labels.csv' test_csv_labels = os.path.join(data_dir,file) df_test_labels = pd.read_csv(test_csv_labels) # verify 'id' is unique for each row assert len(np.unique(df_test_labels['id'].values)) == len(df_test_labels) # reindex with 'id' df_test_labels.index = df_test_labels.id del df_test_labels['id'] # verify 'id' is unique for each row assert len(np.unique(df_test_comments['id'].values)) == len(df_test_comments) # reindex with 'id' df_test_comments.index = df_test_comments.id del df_test_comments['id'] for ind in df_test_comments.index: assert ind in df_test_labels.index for ind in df_test_labels.index: assert ind in df_test_comments.index # merge dataframes (add columns) df_test = pd.concat([df_test_comments, df_test_labels], axis=1) df_test.head() # drop the comments that do not have annotation def parse_dataset(df): q = '%s != -1'%ExperimentParameters.dataset_name df = df.query(q) X = df['comment_text'].\ str.replace('\n',' ').\ str.replace('\t',' ').\ str.strip().\ str.split().\ str.join(' ') y = df[ExperimentParameters.dataset_name] return X, y X_train, y_train = parse_dataset(df_train) X_test, y_test = parse_dataset(df_test) # obtain bootstrapped variation of training data dataset_name = "%s_%s_%d" % (ExperimentParameters.dataset_name, 'Percentage-%03d'%ExperimentParameters.percentage, ExperimentParameters.random_seed) X_train_tiny, y_train_tiny = data_helpers.get_stratified_subset(X_train, y_train, percentage=ExperimentParameters.percentage, random_state = ExperimentParameters.random_seed) data_helpers.save_categorical_dataset(X_train_tiny, y_train_tiny, DATA_DIR, dataset_name) if ExperimentParameters.aug_name == 'gpt2': # keep all epochs in the same folder load_corpus_fun = lambda : load_lm_corpus('../data/'+dataset_name+'.txt') print('Creating LMWrapper for dataset') model_save_dir = '../models/%s/%s/'%('gpt2', dataset_name) lm = LanguageModelWrapper(load_corpus_fun, model_save_dir = model_save_dir, random_state = ExperimentParameters.random_seed) if not os.path.exists(model_save_dir): print('Fine-tuned GPT2 path not found. Training...') lm.train(num_epochs = 2) else: print('Found fine-tuned GPT2 directory') # maps augmentation names to functions class Mapper: dict = { 'baseline' : lambda document,num_aug: [document], 'copy' : lambda document,num_aug: [document]*num_aug, # set recommended settings for small-dataset EDA 'eda' : lambda document,num_aug: eda(document, random_state = ExperimentParameters.random_seed, alpha_sr=0.05, alpha_ri=0.05, alpha_rs=0.05, p_rd=0.05, num_aug=num_aug), 'add': None, 'ppdb' : lambda document,num_aug: augment_ppdb(document,num_aug, random_state = ExperimentParameters.random_seed), 'wn' : lambda document,num_aug: augment_wn(document,num_aug, random_state = ExperimentParameters.random_seed), 'bpemb' : lambda document,num_aug: bpemb_aug(document,num_aug, random_state = ExperimentParameters.random_seed, max_candidates = 10, incl_orig = True, min_similarity = 0., change_rate = .25), 'gensim' : lambda document,num_aug: gensim_aug(document,num_aug, random_state = ExperimentParameters.random_seed, max_candidates = 10, incl_orig = True, min_similarity = 0., change_rate = .25), 'gpt2' : lambda document,num_aug: lm_aug(document, num_aug, random_state = ExperimentParameters.random_seed, incl_orig=True, epoch = 2, lm_wrapper = lm), 'add_bpemb' : None, # run combine_augmentations.py 'add_bpemb_gpt2' : None, # run combine_augmentations.py # functions for training networks # (numpy array, numpy array) -> object 'char-lr' : lambda x,y: logistic_regression.train_model(x, y, ngram_type='char', random_state = ExperimentParameters.random_seed), 'word-lr' : lambda x,y: logistic_regression.train_model(x, y, ngram_type='word', random_state = ExperimentParameters.random_seed), 'bert' : lambda x,y: bert_wrapper.train_model(x, y, num_epochs = 6), 'cnn': lambda x, y: cnn_wrapper.train_model(x, y, num_epochs = 4) } assert ExperimentParameters.aug_name in Mapper.dict ExperimentParameters.aug_fun = Mapper.dict[ExperimentParameters.aug_name] os.makedirs(ExperimentParameters.save_dir, exist_ok=True) if os.path.exists(ExperimentParameters.results_file): print('Experiment results found.') with open(ExperimentParameters.results_file,'r',encoding='utf-8') as f: print(f.read()) print('Exiting...') return else: print('Experiment results will be saved in\n\t',ExperimentParameters.results_file) os.makedirs(ExperimentParameters.aug_dir, exist_ok=True) ExperimentParameters.aug_file = os.path.join(ExperimentParameters.aug_dir,'%s.txt'%ExperimentParameters.random_seed) print('Augmentations will be saved in\n\t',ExperimentParameters.aug_file) assert ExperimentParameters.classifier_name in Mapper.dict ExperimentParameters.classifier_train_fun = Mapper.dict[ExperimentParameters.classifier_name] ExperimentParameters.classifier_file = os.path.join(ExperimentParameters.save_dir,'clf_%s.pkl'%ExperimentParameters.random_seed) print('Classifier will be saved in\n\t',ExperimentParameters.classifier_file) # run data augmentation if not os.path.exists(ExperimentParameters.aug_file): if ExperimentParameters.aug_name == 'add': augmentation_helper_add(input='../data/%s.txt'%dataset_name, output=ExperimentParameters.aug_file, num_aug = 20, target_classes = ExperimentParameters.augment_classes, random_state = ExperimentParameters.random_seed) else: augmentation_helper(input='../data/%s.txt'%dataset_name, output=ExperimentParameters.aug_file, aug_function = ExperimentParameters.aug_fun, num_aug = 20, target_classes = ExperimentParameters.augment_classes) # load augmented dataset X_train_aug, y_train_aug = data_helpers.load_categorical_dataset(ExperimentParameters.aug_file) X_train_aug = pd.Series([x.lower() for x in X_train_aug]) print('\tDataset shapes',X_train_aug.shape, y_train_aug.shape) # create classifier if not os.path.exists(ExperimentParameters.classifier_file): print("Training model...") clf = ExperimentParameters.classifier_train_fun(X_train_aug, y_train_aug) print("\tSaving model to... %s"%ExperimentParameters.classifier_file) joblib.dump(clf, ExperimentParameters.classifier_file) print("Reloading Model...") clf = joblib.load(ExperimentParameters.classifier_file) print(clf.predict_proba(['if you do not stop, the wikapidea nijas will come to your house and kill you'])) print("Predicting test data...") if ExperimentParameters.classifier_name == 'bert': y_pred = clf.predict(X_test) else: prediction_dir = '%s/%s'%(ExperimentParameters.save_dir, 'predictions') os.makedirs(prediction_dir, exist_ok=True) prediction_file = '%s/%d-output.csv'%(prediction_dir,ExperimentParameters.random_seed) print('... saving prediction results to %s.'%prediction_dir) y_pred_prob = clf.predict_proba(X_test) # output from CNN is a list of lists y_pred_prob = np.array(y_pred_prob) y_pred = np.array(y_pred_prob[:,1] > 0.5, dtype = int) with open(prediction_file, 'w',encoding='utf-8') as f: for line in y_pred_prob: line = ', '.join(map(str,line)) f.write('%s\n'%line) print(classification_report(y_test, y_pred)) res_0 = precision_recall_fscore_support(y_test, y_pred, pos_label=0, average='binary') res_1 = precision_recall_fscore_support(y_test, y_pred, pos_label=1, average='binary') res_m = precision_recall_fscore_support(y_test, y_pred, average='macro') with open(ExperimentParameters.results_file,'w',encoding='utf-8') as f: f.write('\tPrecision\tRecall\tF-score\n') f.write('0:\t') f.write('\t'.join(map(str,res_0[:-1]))) f.write('\n') f.write('1:\t') f.write('\t'.join(map(str,res_1[:-1]))) f.write('\n') f.write('macro:\t') f.write('\t'.join(map(str,res_m[:-1]))) f.write('\n') if args.remove_cache: # BERT classifier weigths take 421 MB if ExperimentParameters.classifier_name == 'bert': bert_wrapper.delete_cache() print('Done.') # word-lr takes 30 MB per file else: print('Deleting classifier file...', end='') os.remove(ExperimentParameters.classifier_file) print('Done.') if __name__ == '__main__': # initiate the parser parser = argparse.ArgumentParser() # add long and short argument parser.add_argument("--dataset_name", "-d", help="obscene/threat", required=True) parser.add_argument("--percentage", "-p", help="5", type=int, default=5) parser.add_argument("--classifier_name", "-c", help="char-lr/char-word", required=True) parser.add_argument("--augmentation_name", "-a", help="baseline/copy/bpemb", required=True) parser.add_argument("--random_seed", "-r", help="20200303", type=int, required=True) parser.add_argument("--augmentation_classes", "-n", nargs='+', help="0 1 / 1", type=int, default = [1]) parser.add_argument("--remove_cache", action='store_true') # read arguments from the command line args = parser.parse_args() print() print(args) # Phase 1: determine experiment parameters ExperimentParameters.dataset_name = args.dataset_name ExperimentParameters.percentage = args.percentage ExperimentParameters.classifier_name = args.classifier_name ExperimentParameters.aug_name = args.augmentation_name ExperimentParameters.augment_classes = args.augmentation_classes ExperimentParameters.random_seed = args.random_seed run_experiment() print()
[ "cnn_scripts.cnn_helpers.CNN_wrapper", "pandas.read_csv", "sklearn.metrics.classification_report", "gpt2_scripts.augmentation_lm.LanguageModelWrapper", "augmentation_helpers.augmentation_helper", "numpy.array", "data_helpers.get_stratified_subset", "wn_scripts.augmentation_wn.augment_wn", "os.remove...
[((3425, 3518), 'os.path.join', 'os.path.join', (['ExperimentParameters.save_dir', "('%s.txt' % ExperimentParameters.random_seed)"], {}), "(ExperimentParameters.save_dir, '%s.txt' % ExperimentParameters\n .random_seed)\n", (3437, 3518), False, 'import os\n'), ((5046, 5074), 'os.path.join', 'os.path.join', (['data_dir', 'file'], {}), '(data_dir, file)\n', (5058, 5074), False, 'import os\n'), ((5086, 5111), 'os.path.exists', 'os.path.exists', (['train_csv'], {}), '(train_csv)\n', (5100, 5111), False, 'import os\n'), ((5128, 5150), 'pandas.read_csv', 'pd.read_csv', (['train_csv'], {}), '(train_csv)\n', (5139, 5150), True, 'import pandas as pd\n'), ((5220, 5248), 'os.path.join', 'os.path.join', (['data_dir', 'file'], {}), '(data_dir, file)\n', (5232, 5248), False, 'import os\n'), ((5271, 5301), 'pandas.read_csv', 'pd.read_csv', (['test_csv_comments'], {}), '(test_csv_comments)\n', (5282, 5301), True, 'import pandas as pd\n'), ((5354, 5382), 'os.path.join', 'os.path.join', (['data_dir', 'file'], {}), '(data_dir, file)\n', (5366, 5382), False, 'import os\n'), ((5403, 5431), 'pandas.read_csv', 'pd.read_csv', (['test_csv_labels'], {}), '(test_csv_labels)\n', (5414, 5431), True, 'import pandas as pd\n'), ((6098, 6151), 'pandas.concat', 'pd.concat', (['[df_test_comments, df_test_labels]'], {'axis': '(1)'}), '([df_test_comments, df_test_labels], axis=1)\n', (6107, 6151), True, 'import pandas as pd\n'), ((6990, 7143), 'data_helpers.get_stratified_subset', 'data_helpers.get_stratified_subset', (['X_train', 'y_train'], {'percentage': 'ExperimentParameters.percentage', 'random_state': 'ExperimentParameters.random_seed'}), '(X_train, y_train, percentage=\n ExperimentParameters.percentage, random_state=ExperimentParameters.\n random_seed)\n', (7024, 7143), False, 'import data_helpers\n'), ((7140, 7233), 'data_helpers.save_categorical_dataset', 'data_helpers.save_categorical_dataset', (['X_train_tiny', 'y_train_tiny', 'DATA_DIR', 'dataset_name'], {}), '(X_train_tiny, y_train_tiny, DATA_DIR,\n dataset_name)\n', (7177, 7233), False, 'import data_helpers\n'), ((10000, 10057), 'os.makedirs', 'os.makedirs', (['ExperimentParameters.save_dir'], {'exist_ok': '(True)'}), '(ExperimentParameters.save_dir, exist_ok=True)\n', (10011, 10057), False, 'import os\n'), ((10066, 10115), 'os.path.exists', 'os.path.exists', (['ExperimentParameters.results_file'], {}), '(ExperimentParameters.results_file)\n', (10080, 10115), False, 'import os\n'), ((10418, 10474), 'os.makedirs', 'os.makedirs', (['ExperimentParameters.aug_dir'], {'exist_ok': '(True)'}), '(ExperimentParameters.aug_dir, exist_ok=True)\n', (10429, 10474), False, 'import os\n'), ((10511, 10603), 'os.path.join', 'os.path.join', (['ExperimentParameters.aug_dir', "('%s.txt' % ExperimentParameters.random_seed)"], {}), "(ExperimentParameters.aug_dir, '%s.txt' % ExperimentParameters.\n random_seed)\n", (10523, 10603), False, 'import os\n'), ((10881, 10977), 'os.path.join', 'os.path.join', (['ExperimentParameters.save_dir', "('clf_%s.pkl' % ExperimentParameters.random_seed)"], {}), "(ExperimentParameters.save_dir, 'clf_%s.pkl' %\n ExperimentParameters.random_seed)\n", (10893, 10977), False, 'import os\n'), ((11720, 11788), 'data_helpers.load_categorical_dataset', 'data_helpers.load_categorical_dataset', (['ExperimentParameters.aug_file'], {}), '(ExperimentParameters.aug_file)\n', (11757, 11788), False, 'import data_helpers\n'), ((12312, 12361), 'joblib.load', 'joblib.load', (['ExperimentParameters.classifier_file'], {}), '(ExperimentParameters.classifier_file)\n', (12323, 12361), False, 'import joblib\n'), ((13361, 13439), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['y_test', 'y_pred'], {'pos_label': '(0)', 'average': '"""binary"""'}), "(y_test, y_pred, pos_label=0, average='binary')\n", (13392, 13439), False, 'from sklearn.metrics import classification_report, precision_recall_fscore_support\n'), ((13452, 13530), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['y_test', 'y_pred'], {'pos_label': '(1)', 'average': '"""binary"""'}), "(y_test, y_pred, pos_label=1, average='binary')\n", (13483, 13530), False, 'from sklearn.metrics import classification_report, precision_recall_fscore_support\n'), ((13543, 13607), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['y_test', 'y_pred'], {'average': '"""macro"""'}), "(y_test, y_pred, average='macro')\n", (13574, 13607), False, 'from sklearn.metrics import classification_report, precision_recall_fscore_support\n'), ((14490, 14515), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (14513, 14515), False, 'import argparse\n'), ((3590, 3800), 'fast_bert_scripts.bert_helpers.BertWrapper', 'BertWrapper', ([], {'model_dir': 'ExperimentParameters.save_dir', 'data_dir': 'ExperimentParameters.aug_dir', 'results_filename': "('%s' % ExperimentParameters.random_seed)", 'random_state': 'ExperimentParameters.random_seed'}), "(model_dir=ExperimentParameters.save_dir, data_dir=\n ExperimentParameters.aug_dir, results_filename='%s' %\n ExperimentParameters.random_seed, random_state=ExperimentParameters.\n random_seed)\n", (3601, 3800), False, 'from fast_bert_scripts.bert_helpers import BertWrapper\n'), ((4010, 4220), 'cnn_scripts.cnn_helpers.CNN_wrapper', 'CNN_wrapper', ([], {'model_dir': 'ExperimentParameters.save_dir', 'data_dir': 'ExperimentParameters.aug_dir', 'results_filename': "('%s' % ExperimentParameters.random_seed)", 'random_state': 'ExperimentParameters.random_seed'}), "(model_dir=ExperimentParameters.save_dir, data_dir=\n ExperimentParameters.aug_dir, results_filename='%s' %\n ExperimentParameters.random_seed, random_state=ExperimentParameters.\n random_seed)\n", (4021, 4220), False, 'from cnn_scripts.cnn_helpers import CNN_wrapper\n'), ((4420, 4444), 'os.path.exists', 'os.path.exists', (['DATA_DIR'], {}), '(DATA_DIR)\n', (4434, 4444), False, 'import os\n'), ((4454, 4475), 'os.makedirs', 'os.makedirs', (['DATA_DIR'], {}), '(DATA_DIR)\n', (4465, 4475), False, 'import os\n'), ((7535, 7654), 'gpt2_scripts.augmentation_lm.LanguageModelWrapper', 'LanguageModelWrapper', (['load_corpus_fun'], {'model_save_dir': 'model_save_dir', 'random_state': 'ExperimentParameters.random_seed'}), '(load_corpus_fun, model_save_dir=model_save_dir,\n random_state=ExperimentParameters.random_seed)\n', (7555, 7654), False, 'from gpt2_scripts.augmentation_lm import lm_aug, LanguageModelWrapper, load_lm_corpus\n'), ((11095, 11140), 'os.path.exists', 'os.path.exists', (['ExperimentParameters.aug_file'], {}), '(ExperimentParameters.aug_file)\n', (11109, 11140), False, 'import os\n'), ((11954, 12006), 'os.path.exists', 'os.path.exists', (['ExperimentParameters.classifier_file'], {}), '(ExperimentParameters.classifier_file)\n', (11968, 12006), False, 'import os\n'), ((12213, 12267), 'joblib.dump', 'joblib.dump', (['clf', 'ExperimentParameters.classifier_file'], {}), '(clf, ExperimentParameters.classifier_file)\n', (12224, 12267), False, 'import joblib\n'), ((12703, 12745), 'os.makedirs', 'os.makedirs', (['prediction_dir'], {'exist_ok': '(True)'}), '(prediction_dir, exist_ok=True)\n', (12714, 12745), False, 'import os\n'), ((13026, 13047), 'numpy.array', 'np.array', (['y_pred_prob'], {}), '(y_pred_prob)\n', (13034, 13047), True, 'import numpy as np\n'), ((13065, 13109), 'numpy.array', 'np.array', (['(y_pred_prob[:, 1] > 0.5)'], {'dtype': 'int'}), '(y_pred_prob[:, 1] > 0.5, dtype=int)\n', (13073, 13109), True, 'import numpy as np\n'), ((13309, 13346), 'sklearn.metrics.classification_report', 'classification_report', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (13330, 13346), False, 'from sklearn.metrics import classification_report, precision_recall_fscore_support\n'), ((4503, 4574), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""jigsaw-toxic-comment-classification-challenge"""'], {}), "(DATA_DIR, 'jigsaw-toxic-comment-classification-challenge')\n", (4515, 4574), False, 'import os\n'), ((5489, 5527), 'numpy.unique', 'np.unique', (["df_test_labels['id'].values"], {}), "(df_test_labels['id'].values)\n", (5498, 5527), True, 'import numpy as np\n'), ((5708, 5748), 'numpy.unique', 'np.unique', (["df_test_comments['id'].values"], {}), "(df_test_comments['id'].values)\n", (5717, 5748), True, 'import numpy as np\n'), ((7360, 7410), 'gpt2_scripts.augmentation_lm.load_lm_corpus', 'load_lm_corpus', (["('../data/' + dataset_name + '.txt')"], {}), "('../data/' + dataset_name + '.txt')\n", (7374, 7410), False, 'from gpt2_scripts.augmentation_lm import lm_aug, LanguageModelWrapper, load_lm_corpus\n'), ((7670, 7700), 'os.path.exists', 'os.path.exists', (['model_save_dir'], {}), '(model_save_dir)\n', (7684, 7700), False, 'import os\n'), ((11206, 11433), 'augmentation_helpers.augmentation_helper_add', 'augmentation_helper_add', ([], {'input': "('../data/%s.txt' % dataset_name)", 'output': 'ExperimentParameters.aug_file', 'num_aug': '(20)', 'target_classes': 'ExperimentParameters.augment_classes', 'random_state': 'ExperimentParameters.random_seed'}), "(input='../data/%s.txt' % dataset_name, output=\n ExperimentParameters.aug_file, num_aug=20, target_classes=\n ExperimentParameters.augment_classes, random_state=ExperimentParameters\n .random_seed)\n", (11229, 11433), False, 'from augmentation_helpers import add_sentences, augmentation_helper_add\n'), ((11449, 11663), 'augmentation_helpers.augmentation_helper', 'augmentation_helper', ([], {'input': "('../data/%s.txt' % dataset_name)", 'output': 'ExperimentParameters.aug_file', 'aug_function': 'ExperimentParameters.aug_fun', 'num_aug': '(20)', 'target_classes': 'ExperimentParameters.augment_classes'}), "(input='../data/%s.txt' % dataset_name, output=\n ExperimentParameters.aug_file, aug_function=ExperimentParameters.\n aug_fun, num_aug=20, target_classes=ExperimentParameters.augment_classes)\n", (11468, 11663), False, 'from augmentation_helpers import augmentation_helper\n'), ((14347, 14394), 'os.remove', 'os.remove', (['ExperimentParameters.classifier_file'], {}), '(ExperimentParameters.classifier_file)\n', (14356, 14394), False, 'import os\n'), ((8185, 8322), 'eda_scripts.eda.eda', 'eda', (['document'], {'random_state': 'ExperimentParameters.random_seed', 'alpha_sr': '(0.05)', 'alpha_ri': '(0.05)', 'alpha_rs': '(0.05)', 'p_rd': '(0.05)', 'num_aug': 'num_aug'}), '(document, random_state=ExperimentParameters.random_seed, alpha_sr=0.05,\n alpha_ri=0.05, alpha_rs=0.05, p_rd=0.05, num_aug=num_aug)\n', (8188, 8322), False, 'from eda_scripts.eda import eda\n'), ((8394, 8472), 'ppdb_scripts.augmentation_ppdb.augment_ppdb', 'augment_ppdb', (['document', 'num_aug'], {'random_state': 'ExperimentParameters.random_seed'}), '(document, num_aug, random_state=ExperimentParameters.random_seed)\n', (8406, 8472), False, 'from ppdb_scripts.augmentation_ppdb import augment_ppdb\n'), ((8519, 8595), 'wn_scripts.augmentation_wn.augment_wn', 'augment_wn', (['document', 'num_aug'], {'random_state': 'ExperimentParameters.random_seed'}), '(document, num_aug, random_state=ExperimentParameters.random_seed)\n', (8529, 8595), False, 'from wn_scripts.augmentation_wn import augment_wn\n'), ((8645, 8797), 'embedding_scripts.augmentation_bpemb.bpemb_aug', 'bpemb_aug', (['document', 'num_aug'], {'random_state': 'ExperimentParameters.random_seed', 'max_candidates': '(10)', 'incl_orig': '(True)', 'min_similarity': '(0.0)', 'change_rate': '(0.25)'}), '(document, num_aug, random_state=ExperimentParameters.random_seed,\n max_candidates=10, incl_orig=True, min_similarity=0.0, change_rate=0.25)\n', (8654, 8797), False, 'from embedding_scripts.augmentation_bpemb import bpemb_aug\n'), ((8850, 9003), 'embedding_scripts.augmentation_gensim.gensim_aug', 'gensim_aug', (['document', 'num_aug'], {'random_state': 'ExperimentParameters.random_seed', 'max_candidates': '(10)', 'incl_orig': '(True)', 'min_similarity': '(0.0)', 'change_rate': '(0.25)'}), '(document, num_aug, random_state=ExperimentParameters.random_seed,\n max_candidates=10, incl_orig=True, min_similarity=0.0, change_rate=0.25)\n', (8860, 9003), False, 'from embedding_scripts.augmentation_gensim import gensim_aug\n'), ((9055, 9171), 'gpt2_scripts.augmentation_lm.lm_aug', 'lm_aug', (['document', 'num_aug'], {'random_state': 'ExperimentParameters.random_seed', 'incl_orig': '(True)', 'epoch': '(2)', 'lm_wrapper': 'lm'}), '(document, num_aug, random_state=ExperimentParameters.random_seed,\n incl_orig=True, epoch=2, lm_wrapper=lm)\n', (9061, 9171), False, 'from gpt2_scripts.augmentation_lm import lm_aug, LanguageModelWrapper, load_lm_corpus\n'), ((9441, 9549), 'logistic_regression.train_model', 'logistic_regression.train_model', (['x', 'y'], {'ngram_type': '"""char"""', 'random_state': 'ExperimentParameters.random_seed'}), "(x, y, ngram_type='char', random_state=\n ExperimentParameters.random_seed)\n", (9472, 9549), False, 'import logistic_regression\n'), ((9584, 9692), 'logistic_regression.train_model', 'logistic_regression.train_model', (['x', 'y'], {'ngram_type': '"""word"""', 'random_state': 'ExperimentParameters.random_seed'}), "(x, y, ngram_type='word', random_state=\n ExperimentParameters.random_seed)\n", (9615, 9692), False, 'import logistic_regression\n')]
import numpy as np from random import shuffle from past.builtins import xrange def svm_loss_naive(W, X, y, reg): """ Structured SVM loss function, naive implementation (with loops). Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ dW = np.zeros(W.shape) # initialize the gradient as zero # compute the loss and the gradient num_classes = W.shape[1] num_train = X.shape[0] loss = 0.0 for i in xrange(num_train): scores = X[i].dot(W) correct_class_score = scores[y[i]] wrong_predicted = 0 for j in xrange(num_classes): if j == y[i]: continue margin = scores[j] - correct_class_score + 1 # note delta = 1 if margin > 0: loss += margin wrong_predicted += 1 dW[:, j] += X[i, :] dW[:, y[i]] -= wrong_predicted * X[i, :] # Right now the loss is a sum over all training examples, but we want it # to be an average instead so we divide by num_train. loss /= num_train # Add regularization to the loss. loss += reg * np.sum(W * W) dW = dW / num_train + 2 * reg * W return loss, dW def svm_loss_vectorized(W, X, y, reg): """ Structured SVM loss function, vectorized implementation. Inputs and outputs are the same as svm_loss_naive. """ loss = 0.0 dW = np.zeros(W.shape) # initialize the gradient as zero num_train = X.shape[0] delta = 1.0 #score_kj = sum_n [x_kn * w_nj] scores = X.dot(W) scores_correct_class = scores[np.arange(num_train), y] #margins_kj = max(0, s_kj - s_k_(y_k) + delta) margins = np.maximum(0, scores - scores_correct_class[:, np.newaxis] + delta) loss = (margins.sum() - delta * num_train) / num_train + reg * np.sum(W*W) margins_binary = np.vectorize(lambda x: 1. if x>0 else 0)(margins) margins_binary[np.arange(num_train), y] = 0 margins_binary[np.arange(num_train), y] = -margins_binary.sum(axis=1) dW = X.T.dot(margins_binary) / num_train + 2 * reg * W return loss, dW
[ "past.builtins.xrange", "numpy.sum", "numpy.zeros", "numpy.maximum", "numpy.vectorize", "numpy.arange" ]
[((713, 730), 'numpy.zeros', 'np.zeros', (['W.shape'], {}), '(W.shape)\n', (721, 730), True, 'import numpy as np\n'), ((880, 897), 'past.builtins.xrange', 'xrange', (['num_train'], {}), '(num_train)\n', (886, 897), False, 'from past.builtins import xrange\n'), ((1733, 1750), 'numpy.zeros', 'np.zeros', (['W.shape'], {}), '(W.shape)\n', (1741, 1750), True, 'import numpy as np\n'), ((1997, 2064), 'numpy.maximum', 'np.maximum', (['(0)', '(scores - scores_correct_class[:, np.newaxis] + delta)'], {}), '(0, scores - scores_correct_class[:, np.newaxis] + delta)\n', (2007, 2064), True, 'import numpy as np\n'), ((1000, 1019), 'past.builtins.xrange', 'xrange', (['num_classes'], {}), '(num_classes)\n', (1006, 1019), False, 'from past.builtins import xrange\n'), ((1477, 1490), 'numpy.sum', 'np.sum', (['(W * W)'], {}), '(W * W)\n', (1483, 1490), True, 'import numpy as np\n'), ((2162, 2205), 'numpy.vectorize', 'np.vectorize', (['(lambda x: 1.0 if x > 0 else 0)'], {}), '(lambda x: 1.0 if x > 0 else 0)\n', (2174, 2205), True, 'import numpy as np\n'), ((1911, 1931), 'numpy.arange', 'np.arange', (['num_train'], {}), '(num_train)\n', (1920, 1931), True, 'import numpy as np\n'), ((2130, 2143), 'numpy.sum', 'np.sum', (['(W * W)'], {}), '(W * W)\n', (2136, 2143), True, 'import numpy as np\n'), ((2229, 2249), 'numpy.arange', 'np.arange', (['num_train'], {}), '(num_train)\n', (2238, 2249), True, 'import numpy as np\n'), ((2275, 2295), 'numpy.arange', 'np.arange', (['num_train'], {}), '(num_train)\n', (2284, 2295), True, 'import numpy as np\n')]
import numpy as np # Answer for Part 2b) def viterbi(emission_dict, transition_dict, test_dir, output_dir = "data/ES/dev.p2.out"): ''' Perform Viterbi :param emission_dict: emission_dict dictionary :type emission_dict: dict :param transition_dict: transition dictionary :type transition_dict: dict :param test_dir: our test file in either ES or RU :type test_dir: str :param output_dir: our output file for either ES or RU :type test_dir: str :Output: "dev.p2.out" by default to the directory given :rtype: .out file ''' test_array = [] viterbi_array = [{"word": "", 'O': float("-inf"), "START": (1, ''), 'STOP': float("-inf"), 'B-positive': float("-inf"), 'B-negative': float("-inf"), 'B-neutral': float("-inf"), 'I-positive': float("-inf"), 'I-negative': float("-inf"), 'I-neutral': float("-inf")}] labels = ['O', 'START', 'STOP', 'B-positive', 'B-negative', 'B-neutral', 'I-positive', 'I-negative', 'I-neutral'] emission_word_set = set(i[0] for i in list(emission_dict.keys())) with open(test_dir, 'r',encoding="utf-8") as file: for line in file: test_array += [line.replace("\n","")] count = 1 #Parse each line, calculate the probabilities for each label and create a dictionary for each line with the label probabilities. for word in test_array: temp_dict = {'word': word} if word == '': temp_list = [] for prev_y in labels: if viterbi_array[count - 1].get(prev_y) != float("-inf"): if transition_dict.get((prev_y, "STOP")): temp_list.append(np.longdouble(viterbi_array[count - 1].get(prev_y)[0] + transition_dict.get((prev_y, "STOP")))) else: temp_list.append(float("-inf")) else: temp_list.append(float("-inf")) max_index = np.argmax(temp_list) for y in labels: if y == "STOP": temp_dict[y] = (temp_list[max_index], labels[max_index]) elif y == "START": temp_dict[y] = (1, '') else: temp_dict[y] = float("-inf") viterbi_array.append(temp_dict) else: if word not in emission_word_set: word = "#UNK#" for t in labels: if emission_dict.get((word, t)): temp_list = [] for prev_y in labels: if viterbi_array[count - 1].get(prev_y) != float("-inf"): if transition_dict.get((prev_y, t)): temp_list.append(viterbi_array[count - 1].get(prev_y)[0] + transition_dict.get((prev_y, t)) + emission_dict.get((word, t))) else: temp_list.append(float("-inf")) else: temp_list.append(float("-inf")) max_index = np.argmax(temp_list) temp_dict[t] = (temp_list[max_index], labels[max_index]) else: temp_dict[t] = float("-inf") viterbi_array.append(temp_dict) count += 1 #Backtrack the viterbi array to find the highest probability paths result_array = [""]*len(viterbi_array) for i in range(len(viterbi_array) - 1, 0, -1): if i == len(viterbi_array) - 1: result_array[i] = viterbi_array[i].get("word") tmp_list = [] if viterbi_array[i].get('word') == '': result_array[i] = '' prev_label = viterbi_array[i].get('STOP')[1] else: result_array[i] = viterbi_array[i].get("word") + " " + prev_label try: prev_label = viterbi_array[i].get(prev_label)[1] except: prev_label = 'O' #Write the results into a text file with open(output_dir,'w', encoding="utf-8") as f: for i in result_array[1:]: f.write(i + '\n')
[ "numpy.argmax" ]
[((1945, 1965), 'numpy.argmax', 'np.argmax', (['temp_list'], {}), '(temp_list)\n', (1954, 1965), True, 'import numpy as np\n'), ((3066, 3086), 'numpy.argmax', 'np.argmax', (['temp_list'], {}), '(temp_list)\n', (3075, 3086), True, 'import numpy as np\n')]
"""PyTorch-compatible datasets. Guaranteed to implement `__len__`, and `__getitem__`. See: https://pytorch.org/docs/stable/data.html """ import os import sys import torch from PIL import Image import torch.utils.data import cv2 import numpy as np import rasterio as rio from mercantile import Tile from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3 """ datasets.py utilities for loading imagery datasets """ import torch.utils.data from mercantile import Tile from copy import deepcopy import rasterio as rio from rasterio.session import AWSSession from itertools import chain import os import numpy as np import s3fs import boto3 import pandas as pd class PairedTiles(torch.utils.data.Dataset): """ Pairs images with mask from <image> and <tiles> directories based on tile information encoded in filenames, e.g.: images/12_123_66_0.tif --> masks/12_123_66_0.tif etc """ def __init__(self, imagedir, maskdir, joint_transform = None, indices = None): """ imagedir: flat directory of N-band TIFF images as above maskdir: flat directory of 1-band TIFF masks as above joint_transform = a transforms.JointTransform object to apply to data indices = optional list of 0-indexed image indices for subsetting. """ super().__init__() self.joint_transform = joint_transform self.imagedir = imagedir self.maskdir = maskdir self.images = os.listdir(imagedir) self.masks = os.listdir(maskdir) print(self.imagedir) if indices is not None: self.images = [self.images[i] for i in indices] self.imagetiles = [Tile(*f.split("_")[:3]) for f in self.images] self.masktiles = [Tile(*f.split("_")[:3]) for f in self.masks] assert (set(self.imagetiles).issubset(set(self.masktiles))), "Image and Mask tilesets must be equal!" def __len__(self): return len(self.images) def __getitem__(self, i): ## 1. grab, open image i ## 2. grab, open corresponding mask imageFile = self.images[i] maskFile = "{}_{}_{}_0.tif".format(*imageFile.split('_')[:3]) image = rio.open(os.path.join(self.imagedir, imageFile)).read() mask = rio.open(os.path.join(self.maskdir, maskFile)).read() mask = np.squeeze(mask) if self.joint_transform: augmented = self.joint_transform(image=image, mask=mask) image = augmented['image'] mask = augmented['mask'] return(image, torch.from_numpy(mask).long()) # Single Slippy Map directory structure class S3SlippyMapTiles(torch.utils.data.Dataset): """Dataset for images stored in slippy map format on AWS S3 """ def __init__(self, root, mode, transform=None, aws_profile = 'default'): super().__init__() self.tiles = [] self.transform = transform self.aws_profile = aws_profile self.tiles = [(id, tile, path) for id, tile, path in tiles_from_slippy_map_s3(root, aws_profile)] self.tiles.sort(key=lambda tile: tile[0]) self.mode = mode def __len__(self): return len(self.tiles) def __getitem__(self, i): id, tile, path = self.tiles[i] image = None with rio.Env(profile_name=self.aws_profile): if self.mode == "image": image = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB) elif self.mode == "multibands": image = rio.open(path).read() elif self.mode == "mask": image = np.array(Image.open(path).convert("P")) if self.transform is not None: image = self.transform(image = image)['image'] return tile, torch.FloatTensor(image) # Single Slippy Map directory structure class SlippyMapTiles(torch.utils.data.Dataset): """Dataset for images stored in slippy map format. """ def __init__(self, root, mode, transform=None, tile_index = False): super().__init__() self.tiles = [] self.transform = transform self.tile_index = tile_index self.tiles = [(tile, path) for tile, path in tiles_from_slippy_map(root)] if tile_index: self.tiles = dict(self.tiles) #self.tiles.sort(key=lambda tile: tile[0]) self.mode = mode def __len__(self): return len(self.tiles) def __getitem__(self, i): tile, path = self.tiles[i] if self.mode == "image": image = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB) elif self.mode == "multibands": image = rio.open(path).read() elif self.mode == "mask": image = np.array(Image.open(path).convert("P")) if self.transform is not None: image = self.transform(image = image)['image'] return tile, image class MultiSlippyMapTilesConcatenation(torch.utils.data.Dataset): """ supports multiple image and mask slippy mask directories. ensures that each image tile is matched with a mask tile. unique source directory identifiers are used to support tile overlap (e.g. if SourceDir1 has tile 200/15/6 and SourceDir2 has tile 200/15/6, both are preserved, one of the MaskSourceDirs contains 200/15/6 ) """ def __init__(self, imageSources, maskSources, joint_transform = None, aws_profile = None, image_ids = None): super().__init__() self.aws_profile = aws_profile self.joint_transform = joint_transform self.image_ids = image_ids # see if we need to remove s3:// self.trim_protocol = False if all([i.startswith('s3://') and m.startswith('s3://') for i, m in zip(imageSources, maskSources)]): self.trim_protocol = True datacols = ['id', 'tile', 'path'] self.imagery = list(chain.from_iterable([tiles_from_slippy_map_s3(src, aws_profile = aws_profile, trim_protocol = self.trim_protocol) for src in imageSources])) self.masks = list(chain.from_iterable([tiles_from_slippy_map_s3(src, aws_profile = aws_profile, trim_protocol = self.trim_protocol) for src in maskSources])) self.imagery = pd.DataFrame(self.imagery, columns = datacols) self.masks = pd.DataFrame(self.masks, columns = datacols) ## match masks with imagery self.overlap = self.imagery.set_index('tile').join(self.masks.set_index('tile'), how = 'inner', rsuffix = '_mask') self.overlap = self.overlap.set_index('id') if (self.image_ids is not None): self.overlap = self.overlap.loc[self.image_ids] self.image_ids = self.overlap.index.values def __len__(self): return(len(self.overlap)) def getIds(self): return self.image_ids def __getitem__(self, i): match = self.overlap.iloc[i] s = boto3.Session(profile_name = self.aws_profile) with rio.Env(AWSSession(s)): mask = np.squeeze(rio.open(match.path_mask).read()) data = rio.open(match.path).read() if self.joint_transform: augmented = self.joint_transform(image=data, mask=mask) data = augmented['image'] mask = augmented['mask'] return(torch.FloatTensor(data), torch.from_numpy(mask).double(), match.name) # Paired Image and Mask slippy map directories. class SlippyMapTilesConcatenation(torch.utils.data.Dataset): """Dataset to concate multiple input images stored in slippy map format. """ def __init__(self, path, target, tiles = None, joint_transform=None, aws_profile = None): super().__init__() self._data_on_s3 = False if (path.startswith("s3://") and target.startswith("s3://")): self._data_on_s3 = True self.inputs = tiles_from_slippy_map_s3(path, aws_profile = aws_profile) self.target = tiles_from_slippy_map_s3(target, aws_profile = aws_profile) else: self.inputs = SlippyMapTiles(path, mode='multibands') self.target = SlippyMapTiles(target, mode="multibands") self.inputs = dict(self.inputs) self.target = dict(self.target) data_tiles = self.inputs.keys() mask_tiles = self.target.keys() self.tiles = list(set(data_tiles).intersection(set(mask_tiles))) if (tiles is not None): # only use those tiles specified in `tiles` argument self.tiles = [t for t in self.tiles if t in tiles] print(len(self.tiles)) self.inputs = {tile : path for tile, path in self.inputs.items() if tile in self.tiles} self.target = {tile : path for tile, path in self.target.items() if tile in self.tiles} # No transformations in the `SlippyMapTiles` instead joint transformations in getitem self.joint_transform = joint_transform def __len__(self): return len(self.tiles) def __getitem__(self, i): tile = self.tiles[i] if(self._data_on_s3): # open and read files at __getitem__ mask = rio.open(self.target[tile]).read() data = rio.open(self.inputs[tile]).read() else: # open and read files already happened. mask = self.target[tile] data = self.inputs[tile] # for channel in self.channels: # try: # data, band_tile = self.inputs[channel["sub"]][i] # assert band_tile == tile # # for band in channel["bands"]: # data_band = data[:, :, int(band) - 1] if len(data.shape) == 3 else [] # data_band = data_band.reshape(mask.shape[0], mask.shape[1], 1) # tensor = np.concatenate((tensor, data_band), axis=2) if "tensor" in locals() else data_band # noqa F821 # except: # sys.exit("Unable to concatenate input Tensor") if self.joint_transform is not None: transformed = self.joint_transform(image = data, mask = mask) data = transformed['image'] mask = transformed['mask'] return torch.FloatTensor(data), mask.squeeze(), tile # Todo: once we have the SlippyMapDataset this dataset should wrap # it adding buffer and unbuffer glue on top of the raw tile dataset. class BufferedSlippyMapDirectory(torch.utils.data.Dataset): """Dataset for buffered slippy map tiles with overlap. """ def __init__(self, root, transform=None, size=512, overlap=32): """ Args: root: the slippy map directory root with a `z/x/y.png` sub-structure. transform: the transformation to run on the buffered tile. size: the Slippy Map tile size in pixels overlap: the tile border to add on every side; in pixel. Note: The overlap must not span multiple tiles. Use `unbuffer` to get back the original tile. """ super().__init__() assert overlap >= 0 assert size >= 256 self.transform = transform self.size = size self.overlap = overlap self.tiles = list(tiles_from_slippy_map(root)) def __len__(self): return len(self.tiles) def __getitem__(self, i): tile, path = self.tiles[i] image = np.array(buffer_tile_image(tile, self.tiles, overlap=self.overlap, tile_size=self.size)) if self.transform is not None: image = self.transform(image) return image, torch.IntTensor([tile.x, tile.y, tile.z]) def unbuffer(self, probs): """Removes borders from segmentation probabilities added to the original tile image. Args: probs: the segmentation probability mask to remove buffered borders. Returns: The probability mask with the original tile's dimensions without added overlap borders. """ o = self.overlap _, x, y = probs.shape return probs[:, o : x - o, o : y - o]
[ "os.listdir", "robosat_pink.tiles.buffer_tile_image", "rasterio.session.AWSSession", "PIL.Image.open", "rasterio.open", "boto3.Session", "rasterio.Env", "robosat_pink.tiles.tiles_from_slippy_map_s3", "robosat_pink.tiles.tiles_from_slippy_map", "numpy.squeeze", "os.path.join", "torch.from_numpy...
[((1515, 1535), 'os.listdir', 'os.listdir', (['imagedir'], {}), '(imagedir)\n', (1525, 1535), False, 'import os\n'), ((1557, 1576), 'os.listdir', 'os.listdir', (['maskdir'], {}), '(maskdir)\n', (1567, 1576), False, 'import os\n'), ((2386, 2402), 'numpy.squeeze', 'np.squeeze', (['mask'], {}), '(mask)\n', (2396, 2402), True, 'import numpy as np\n'), ((6283, 6327), 'pandas.DataFrame', 'pd.DataFrame', (['self.imagery'], {'columns': 'datacols'}), '(self.imagery, columns=datacols)\n', (6295, 6327), True, 'import pandas as pd\n'), ((6351, 6393), 'pandas.DataFrame', 'pd.DataFrame', (['self.masks'], {'columns': 'datacols'}), '(self.masks, columns=datacols)\n', (6363, 6393), True, 'import pandas as pd\n'), ((6966, 7010), 'boto3.Session', 'boto3.Session', ([], {'profile_name': 'self.aws_profile'}), '(profile_name=self.aws_profile)\n', (6979, 7010), False, 'import boto3\n'), ((3347, 3385), 'rasterio.Env', 'rio.Env', ([], {'profile_name': 'self.aws_profile'}), '(profile_name=self.aws_profile)\n', (3354, 3385), True, 'import rasterio as rio\n'), ((3823, 3847), 'torch.FloatTensor', 'torch.FloatTensor', (['image'], {}), '(image)\n', (3840, 3847), False, 'import torch\n'), ((7356, 7379), 'torch.FloatTensor', 'torch.FloatTensor', (['data'], {}), '(data)\n', (7373, 7379), False, 'import torch\n'), ((7914, 7969), 'robosat_pink.tiles.tiles_from_slippy_map_s3', 'tiles_from_slippy_map_s3', (['path'], {'aws_profile': 'aws_profile'}), '(path, aws_profile=aws_profile)\n', (7938, 7969), False, 'from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3\n'), ((8050, 8107), 'robosat_pink.tiles.tiles_from_slippy_map_s3', 'tiles_from_slippy_map_s3', (['target'], {'aws_profile': 'aws_profile'}), '(target, aws_profile=aws_profile)\n', (8074, 8107), False, 'from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3\n'), ((10365, 10388), 'torch.FloatTensor', 'torch.FloatTensor', (['data'], {}), '(data)\n', (10382, 10388), False, 'import torch\n'), ((11376, 11403), 'robosat_pink.tiles.tiles_from_slippy_map', 'tiles_from_slippy_map', (['root'], {}), '(root)\n', (11397, 11403), False, 'from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3\n'), ((11551, 11629), 'robosat_pink.tiles.buffer_tile_image', 'buffer_tile_image', (['tile', 'self.tiles'], {'overlap': 'self.overlap', 'tile_size': 'self.size'}), '(tile, self.tiles, overlap=self.overlap, tile_size=self.size)\n', (11568, 11629), False, 'from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3\n'), ((11736, 11777), 'torch.IntTensor', 'torch.IntTensor', (['[tile.x, tile.y, tile.z]'], {}), '([tile.x, tile.y, tile.z])\n', (11751, 11777), False, 'import torch\n'), ((3066, 3109), 'robosat_pink.tiles.tiles_from_slippy_map_s3', 'tiles_from_slippy_map_s3', (['root', 'aws_profile'], {}), '(root, aws_profile)\n', (3090, 3109), False, 'from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3\n'), ((4254, 4281), 'robosat_pink.tiles.tiles_from_slippy_map', 'tiles_from_slippy_map', (['root'], {}), '(root)\n', (4275, 4281), False, 'from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3\n'), ((4614, 4630), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (4624, 4630), False, 'import cv2\n'), ((7035, 7048), 'rasterio.session.AWSSession', 'AWSSession', (['s'], {}), '(s)\n', (7045, 7048), False, 'from rasterio.session import AWSSession\n'), ((2255, 2293), 'os.path.join', 'os.path.join', (['self.imagedir', 'imageFile'], {}), '(self.imagedir, imageFile)\n', (2267, 2293), False, 'import os\n'), ((2326, 2362), 'os.path.join', 'os.path.join', (['self.maskdir', 'maskFile'], {}), '(self.maskdir, maskFile)\n', (2338, 2362), False, 'import os\n'), ((2605, 2627), 'torch.from_numpy', 'torch.from_numpy', (['mask'], {}), '(mask)\n', (2621, 2627), False, 'import torch\n'), ((3462, 3478), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (3472, 3478), False, 'import cv2\n'), ((5971, 6064), 'robosat_pink.tiles.tiles_from_slippy_map_s3', 'tiles_from_slippy_map_s3', (['src'], {'aws_profile': 'aws_profile', 'trim_protocol': 'self.trim_protocol'}), '(src, aws_profile=aws_profile, trim_protocol=self.\n trim_protocol)\n', (5995, 6064), False, 'from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3\n'), ((6139, 6232), 'robosat_pink.tiles.tiles_from_slippy_map_s3', 'tiles_from_slippy_map_s3', (['src'], {'aws_profile': 'aws_profile', 'trim_protocol': 'self.trim_protocol'}), '(src, aws_profile=aws_profile, trim_protocol=self.\n trim_protocol)\n', (6163, 6232), False, 'from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_image, tiles_from_slippy_map_s3\n'), ((7134, 7154), 'rasterio.open', 'rio.open', (['match.path'], {}), '(match.path)\n', (7142, 7154), True, 'import rasterio as rio\n'), ((7381, 7403), 'torch.from_numpy', 'torch.from_numpy', (['mask'], {}), '(mask)\n', (7397, 7403), False, 'import torch\n'), ((9299, 9326), 'rasterio.open', 'rio.open', (['self.target[tile]'], {}), '(self.target[tile])\n', (9307, 9326), True, 'import rasterio as rio\n'), ((9353, 9380), 'rasterio.open', 'rio.open', (['self.inputs[tile]'], {}), '(self.inputs[tile])\n', (9361, 9380), True, 'import rasterio as rio\n'), ((4712, 4726), 'rasterio.open', 'rio.open', (['path'], {}), '(path)\n', (4720, 4726), True, 'import rasterio as rio\n'), ((7081, 7106), 'rasterio.open', 'rio.open', (['match.path_mask'], {}), '(match.path_mask)\n', (7089, 7106), True, 'import rasterio as rio\n'), ((3568, 3582), 'rasterio.open', 'rio.open', (['path'], {}), '(path)\n', (3576, 3582), True, 'import rasterio as rio\n'), ((4798, 4814), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (4808, 4814), False, 'from PIL import Image\n'), ((3662, 3678), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (3672, 3678), False, 'from PIL import Image\n')]
""" @file: innerProduct.py @description: answers to problems in exercises 6.8 (Linear Algebra and its applications, David C. Lay 3ed) @author: <NAME> @date: June 9, 2021 """ from linearModel import delimeter, getLeastSquare import numpy as np def problem15(): time = [x for x in range(13)] data = [0, 8.8, 29.9, 62.0, 104.7, 159.1, 222.0, 294.5, 380.4, 471.1, 571.7, 686.8, 809.2] X = np.array([[1 for x in range(len(time))], [x for x in time], [x*x for x in time], [x*x*x for x in time]]).T y = np.array(data) W = np.diag([1,1,1,.9,.9,.8,.7,.6,.5,.4,.3,.2,.1]) res = getLeastSquare(np.matmul(W, X), np.matmul(W, y)) b = res[0] func = lambda t: b[1] + 2 * b[2] * t + 3 * b[3] * t * t print("velocity of the plane at time 4.5 is ", func(4.5)) def problem16(): # me using desmos.com pass if __name__ == "__main__": problem15()
[ "numpy.array", "numpy.matmul", "numpy.diag" ]
[((630, 644), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (638, 644), True, 'import numpy as np\n'), ((658, 726), 'numpy.diag', 'np.diag', (['[1, 1, 1, 0.9, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]'], {}), '([1, 1, 1, 0.9, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1])\n', (665, 726), True, 'import numpy as np\n'), ((735, 750), 'numpy.matmul', 'np.matmul', (['W', 'X'], {}), '(W, X)\n', (744, 750), True, 'import numpy as np\n'), ((752, 767), 'numpy.matmul', 'np.matmul', (['W', 'y'], {}), '(W, y)\n', (761, 767), True, 'import numpy as np\n')]
import numpy as np from scipy import interpolate from scipy.signal import iirfilter, lfilter, filtfilt def filter_base(signal, axis=-1, fs=250.): """ Perform 60 Hz notch filtering using scipy library. Parameters ---------- signal : 1D numpy.array Array to filter. axis: int Choose axis where to perform filtering. forward_backward : boolean Set True if you want a null phase shift filtered signal Returns ------- 1D numpy.array The signal filtered """ b1, a1 = iirfilter(2, [0.4 / (fs / 2.), 18 / (fs / 2.)], btype='bandpass', ftype='butter') b2, a2 = iirfilter(3, [58 / (fs / 2.), 62 / (fs / 2.)], btype='bandstop', ftype='butter') b3, a3 = iirfilter(3, [48 / (fs / 2.), 52 / (fs / 2.)], btype='bandstop', ftype='butter') b4, a4 = iirfilter(1, [62 / (fs / 2.), 63 / (fs / 2.)], btype='bandstop', ftype='bessel') a = np.polymul(np.polymul(np.polymul(a1, a2), a3), a4) b = np.polymul(np.polymul(np.polymul(b1, b2), b3), b4) result = lfilter(b, a, signal, axis) return result def filter(signal, signal_properties): signal = filter_base(signal, axis=0, fs=signal_properties['fs']) return signal, signal_properties def iir_bandpass_filter(signal, fs=250., order=4, frequency_band=[0.4, 18], filter_type='butter', axis=-1, forward_backward=False): """ Perform bandpass filtering using scipy library. Parameters ---------- signal : 1D numpy.array Array to filter. fs : float Sampling frequency order : int Order of the filter frequency_band : list Specify bandpass eg: [0.5, 20] will keep frequencies between 0.5 and 20 Hz filter_type : str Choose type of IIR filter: butter, cheby1, cheby2, ellip, bessel axis: int Choose axis where to perform filtering. forward_backward : boolean Set True if you want a null phase shift filtered signal Returns ------- 1D numpy.array The signal filtered """ b, a = iirfilter(order, [ff * 2. / fs for ff in frequency_band], btype='bandpass', ftype=filter_type) if forward_backward: result = filtfilt(b, a, signal, axis) else: result = lfilter(b, a, signal, axis) return result def filter_cardio(signal, signal_properties): signal = iir_bandpass_filter(signal, fs=signal_properties['fs'], order=2, frequency_band=[0.6, 3], filter_type='bessel', axis=0, forward_backward=False) return signal, signal_properties def filter_respiration(signal, signal_properties): signal = iir_bandpass_filter(signal, fs=signal_properties['fs'], order=2, frequency_band=[0.1, 0.5], filter_type='bessel', axis=0, forward_backward=False) return signal, signal_properties def resample(signal, signal_properties, target_frequency, interpolation_args={}): signal_frequency = signal_properties['fs'] resampling_ratio = signal_frequency / target_frequency x_base = np.arange(0, len(signal)) interpolator = interpolate.interp1d(x_base, signal, axis=0, bounds_error=False, fill_value='extrapolate', **interpolation_args) x_interp = np.arange(0, len(signal), resampling_ratio) signal_duration = signal.shape[0] / signal_frequency resampled_length = round(signal_duration * target_frequency) resampled_signal = interpolator(x_interp) if len(resampled_signal) < resampled_length: padding = np.zeros((resampled_length - len(resampled_signal), signal.shape[-1])) resampled_signal = np.concatenate([resampled_signal, padding]) signal_properties = {'fs': target_frequency, 'padding': signal_properties['padding']} return resampled_signal, signal_properties def weighted_sum(signal, signal_properties, weights=None): if weights is None: return np.sum(signal, -1, keepdims=True), signal_properties else: return np.sum(signal * np.array(weights), -1, keepdims=True), signal_properties def pad_signal(signal, signal_properties, padding_duration, value=0): if padding_duration == 0: return signal, signal_properties else: fs = signal_properties['fs'] padding_array = np.zeros((padding_duration * fs,) + signal.shape[1:]) + value signal = [padding_array] + [signal] + [padding_array] signal_properties = {'fs': fs, 'padding': signal_properties['padding'] + padding_duration} return np.concatenate(signal), signal_properties signal_processings = { 'filter': filter, 'filter_cardio': filter_cardio, 'filter_respiration': filter_respiration, 'resample': resample, 'padding': pad_signal, 'weighted_sum': weighted_sum }
[ "numpy.polymul", "scipy.signal.iirfilter", "scipy.signal.filtfilt", "scipy.interpolate.interp1d", "numpy.sum", "scipy.signal.lfilter", "numpy.zeros", "numpy.array", "numpy.concatenate" ]
[((549, 637), 'scipy.signal.iirfilter', 'iirfilter', (['(2)', '[0.4 / (fs / 2.0), 18 / (fs / 2.0)]'], {'btype': '"""bandpass"""', 'ftype': '"""butter"""'}), "(2, [0.4 / (fs / 2.0), 18 / (fs / 2.0)], btype='bandpass', ftype=\n 'butter')\n", (558, 637), False, 'from scipy.signal import iirfilter, lfilter, filtfilt\n'), ((714, 801), 'scipy.signal.iirfilter', 'iirfilter', (['(3)', '[58 / (fs / 2.0), 62 / (fs / 2.0)]'], {'btype': '"""bandstop"""', 'ftype': '"""butter"""'}), "(3, [58 / (fs / 2.0), 62 / (fs / 2.0)], btype='bandstop', ftype=\n 'butter')\n", (723, 801), False, 'from scipy.signal import iirfilter, lfilter, filtfilt\n'), ((877, 964), 'scipy.signal.iirfilter', 'iirfilter', (['(3)', '[48 / (fs / 2.0), 52 / (fs / 2.0)]'], {'btype': '"""bandstop"""', 'ftype': '"""butter"""'}), "(3, [48 / (fs / 2.0), 52 / (fs / 2.0)], btype='bandstop', ftype=\n 'butter')\n", (886, 964), False, 'from scipy.signal import iirfilter, lfilter, filtfilt\n'), ((1040, 1127), 'scipy.signal.iirfilter', 'iirfilter', (['(1)', '[62 / (fs / 2.0), 63 / (fs / 2.0)]'], {'btype': '"""bandstop"""', 'ftype': '"""bessel"""'}), "(1, [62 / (fs / 2.0), 63 / (fs / 2.0)], btype='bandstop', ftype=\n 'bessel')\n", (1049, 1127), False, 'from scipy.signal import iirfilter, lfilter, filtfilt\n'), ((1322, 1349), 'scipy.signal.lfilter', 'lfilter', (['b', 'a', 'signal', 'axis'], {}), '(b, a, signal, axis)\n', (1329, 1349), False, 'from scipy.signal import iirfilter, lfilter, filtfilt\n'), ((2489, 2591), 'scipy.signal.iirfilter', 'iirfilter', (['order', '[(ff * 2.0 / fs) for ff in frequency_band]'], {'btype': '"""bandpass"""', 'ftype': 'filter_type'}), "(order, [(ff * 2.0 / fs) for ff in frequency_band], btype=\n 'bandpass', ftype=filter_type)\n", (2498, 2591), False, 'from scipy.signal import iirfilter, lfilter, filtfilt\n'), ((3927, 4044), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['x_base', 'signal'], {'axis': '(0)', 'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(x_base, signal, axis=0, bounds_error=False, fill_value\n ='extrapolate', **interpolation_args)\n", (3947, 4044), False, 'from scipy import interpolate\n'), ((2689, 2717), 'scipy.signal.filtfilt', 'filtfilt', (['b', 'a', 'signal', 'axis'], {}), '(b, a, signal, axis)\n', (2697, 2717), False, 'from scipy.signal import iirfilter, lfilter, filtfilt\n'), ((2745, 2772), 'scipy.signal.lfilter', 'lfilter', (['b', 'a', 'signal', 'axis'], {}), '(b, a, signal, axis)\n', (2752, 2772), False, 'from scipy.signal import iirfilter, lfilter, filtfilt\n'), ((4514, 4557), 'numpy.concatenate', 'np.concatenate', (['[resampled_signal, padding]'], {}), '([resampled_signal, padding])\n', (4528, 4557), True, 'import numpy as np\n'), ((1221, 1239), 'numpy.polymul', 'np.polymul', (['a1', 'a2'], {}), '(a1, a2)\n', (1231, 1239), True, 'import numpy as np\n'), ((1280, 1298), 'numpy.polymul', 'np.polymul', (['b1', 'b2'], {}), '(b1, b2)\n', (1290, 1298), True, 'import numpy as np\n'), ((4796, 4829), 'numpy.sum', 'np.sum', (['signal', '(-1)'], {'keepdims': '(True)'}), '(signal, -1, keepdims=True)\n', (4802, 4829), True, 'import numpy as np\n'), ((5161, 5214), 'numpy.zeros', 'np.zeros', (['((padding_duration * fs,) + signal.shape[1:])'], {}), '((padding_duration * fs,) + signal.shape[1:])\n', (5169, 5214), True, 'import numpy as np\n'), ((5399, 5421), 'numpy.concatenate', 'np.concatenate', (['signal'], {}), '(signal)\n', (5413, 5421), True, 'import numpy as np\n'), ((4890, 4907), 'numpy.array', 'np.array', (['weights'], {}), '(weights)\n', (4898, 4907), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """"tests for structure.py""" import unittest import numpy as np from scipy import sparse from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic from sknetwork.utils.format import bipartite2undirected, directed2undirected class TestStructure(unittest.TestCase): def test_largest_cc(self): adjacency = cyclic_digraph(3) adjacency += adjacency.T largest_cc, indices = get_largest_connected_component(adjacency, return_labels=True) self.assertAlmostEqual(np.linalg.norm(largest_cc.toarray() - np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]])), 0) self.assertEqual(np.linalg.norm(indices - np.array([0, 1, 2])), 0) biadjacency = star_wars(metadata=False) largest_cc, indices = get_largest_connected_component(biadjacency, return_labels=True) self.assertAlmostEqual(np.linalg.norm(largest_cc.toarray() - np.array([[1, 0, 1], [1, 0, 0], [1, 1, 1], [0, 1, 1]])), 0) self.assertEqual(np.linalg.norm(indices[0] - np.array([0, 1, 2, 3])), 0) self.assertEqual(np.linalg.norm(indices[1] - np.array([0, 1, 2])), 0) self.assertTrue(isinstance(get_largest_connected_component(adjacency, return_labels=False), sparse.csr_matrix)) def test_is_bipartite(self): biadjacency = star_wars(metadata=False) adjacency = bipartite2undirected(biadjacency) self.assertTrue(is_bipartite(adjacency)) bipartite, biadjacency_pred, _, _ = is_bipartite(adjacency, return_biadjacency=True) self.assertEqual(bipartite, True) self.assertEqual(np.all(biadjacency.data == biadjacency_pred.data), True) adjacency = sparse.identity(2, format='csr') bipartite, biadjacency, _, _ = is_bipartite(adjacency, return_biadjacency=True) self.assertEqual(bipartite, False) self.assertIsNone(biadjacency) adjacency = directed2undirected(cyclic_digraph(3)) bipartite, biadjacency, _, _ = is_bipartite(adjacency, return_biadjacency=True) self.assertEqual(bipartite, False) self.assertIsNone(biadjacency) with self.assertRaises(ValueError): is_bipartite(cyclic_digraph(3)) self.assertFalse(is_bipartite(sparse.eye(3))) adjacency = directed2undirected(cyclic_digraph(3)) bipartite = is_bipartite(adjacency, return_biadjacency=False) self.assertEqual(bipartite, False) def test_is_acyclic(self): adjacency_with_self_loops = sparse.identity(2, format='csr') self.assertFalse(is_acyclic(adjacency_with_self_loops)) directed_cycle = cyclic_digraph(3) self.assertFalse(is_acyclic(directed_cycle)) undirected_line = linear_graph(2) self.assertFalse(is_acyclic(undirected_line)) acyclic_graph = linear_digraph(2) self.assertTrue(is_acyclic(acyclic_graph))
[ "sknetwork.data.linear_graph", "sknetwork.utils.format.bipartite2undirected", "scipy.sparse.eye", "sknetwork.data.star_wars", "sknetwork.data.cyclic_digraph", "numpy.array", "sknetwork.data.linear_digraph", "sknetwork.topology.is_acyclic", "sknetwork.topology.get_largest_connected_component", "num...
[((482, 499), 'sknetwork.data.cyclic_digraph', 'cyclic_digraph', (['(3)'], {}), '(3)\n', (496, 499), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((563, 625), 'sknetwork.topology.get_largest_connected_component', 'get_largest_connected_component', (['adjacency'], {'return_labels': '(True)'}), '(adjacency, return_labels=True)\n', (594, 625), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((843, 868), 'sknetwork.data.star_wars', 'star_wars', ([], {'metadata': '(False)'}), '(metadata=False)\n', (852, 868), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((899, 963), 'sknetwork.topology.get_largest_connected_component', 'get_largest_connected_component', (['biadjacency'], {'return_labels': '(True)'}), '(biadjacency, return_labels=True)\n', (930, 963), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((1667, 1692), 'sknetwork.data.star_wars', 'star_wars', ([], {'metadata': '(False)'}), '(metadata=False)\n', (1676, 1692), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((1713, 1746), 'sknetwork.utils.format.bipartite2undirected', 'bipartite2undirected', (['biadjacency'], {}), '(biadjacency)\n', (1733, 1746), False, 'from sknetwork.utils.format import bipartite2undirected, directed2undirected\n'), ((1841, 1889), 'sknetwork.topology.is_bipartite', 'is_bipartite', (['adjacency'], {'return_biadjacency': '(True)'}), '(adjacency, return_biadjacency=True)\n', (1853, 1889), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((2035, 2067), 'scipy.sparse.identity', 'sparse.identity', (['(2)'], {'format': '"""csr"""'}), "(2, format='csr')\n", (2050, 2067), False, 'from scipy import sparse\n'), ((2107, 2155), 'sknetwork.topology.is_bipartite', 'is_bipartite', (['adjacency'], {'return_biadjacency': '(True)'}), '(adjacency, return_biadjacency=True)\n', (2119, 2155), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((2337, 2385), 'sknetwork.topology.is_bipartite', 'is_bipartite', (['adjacency'], {'return_biadjacency': '(True)'}), '(adjacency, return_biadjacency=True)\n', (2349, 2385), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((2692, 2741), 'sknetwork.topology.is_bipartite', 'is_bipartite', (['adjacency'], {'return_biadjacency': '(False)'}), '(adjacency, return_biadjacency=False)\n', (2704, 2741), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((2853, 2885), 'scipy.sparse.identity', 'sparse.identity', (['(2)'], {'format': '"""csr"""'}), "(2, format='csr')\n", (2868, 2885), False, 'from scipy import sparse\n'), ((2975, 2992), 'sknetwork.data.cyclic_digraph', 'cyclic_digraph', (['(3)'], {}), '(3)\n', (2989, 2992), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((3072, 3087), 'sknetwork.data.linear_graph', 'linear_graph', (['(2)'], {}), '(2)\n', (3084, 3087), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((3166, 3183), 'sknetwork.data.linear_digraph', 'linear_digraph', (['(2)'], {}), '(2)\n', (3180, 3183), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((1771, 1794), 'sknetwork.topology.is_bipartite', 'is_bipartite', (['adjacency'], {}), '(adjacency)\n', (1783, 1794), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((1957, 2006), 'numpy.all', 'np.all', (['(biadjacency.data == biadjacency_pred.data)'], {}), '(biadjacency.data == biadjacency_pred.data)\n', (1963, 2006), True, 'import numpy as np\n'), ((2279, 2296), 'sknetwork.data.cyclic_digraph', 'cyclic_digraph', (['(3)'], {}), '(3)\n', (2293, 2296), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((2653, 2670), 'sknetwork.data.cyclic_digraph', 'cyclic_digraph', (['(3)'], {}), '(3)\n', (2667, 2670), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((2911, 2948), 'sknetwork.topology.is_acyclic', 'is_acyclic', (['adjacency_with_self_loops'], {}), '(adjacency_with_self_loops)\n', (2921, 2948), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((3018, 3044), 'sknetwork.topology.is_acyclic', 'is_acyclic', (['directed_cycle'], {}), '(directed_cycle)\n', (3028, 3044), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((3113, 3140), 'sknetwork.topology.is_acyclic', 'is_acyclic', (['undirected_line'], {}), '(undirected_line)\n', (3123, 3140), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((3208, 3233), 'sknetwork.topology.is_acyclic', 'is_acyclic', (['acyclic_graph'], {}), '(acyclic_graph)\n', (3218, 3233), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((1526, 1589), 'sknetwork.topology.get_largest_connected_component', 'get_largest_connected_component', (['adjacency'], {'return_labels': '(False)'}), '(adjacency, return_labels=False)\n', (1557, 1589), False, 'from sknetwork.topology import get_largest_connected_component, is_bipartite, is_acyclic\n'), ((2538, 2555), 'sknetwork.data.cyclic_digraph', 'cyclic_digraph', (['(3)'], {}), '(3)\n', (2552, 2555), False, 'from sknetwork.data import star_wars, cyclic_digraph, linear_digraph, linear_graph\n'), ((2596, 2609), 'scipy.sparse.eye', 'sparse.eye', (['(3)'], {}), '(3)\n', (2606, 2609), False, 'from scipy import sparse\n'), ((696, 739), 'numpy.array', 'np.array', (['[[0, 1, 1], [1, 0, 1], [1, 1, 0]]'], {}), '([[0, 1, 1], [1, 0, 1], [1, 1, 0]])\n', (704, 739), True, 'import numpy as np\n'), ((795, 814), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (803, 814), True, 'import numpy as np\n'), ((1034, 1088), 'numpy.array', 'np.array', (['[[1, 0, 1], [1, 0, 0], [1, 1, 1], [0, 1, 1]]'], {}), '([[1, 0, 1], [1, 0, 0], [1, 1, 1], [0, 1, 1]])\n', (1042, 1088), True, 'import numpy as np\n'), ((1384, 1406), 'numpy.array', 'np.array', (['[0, 1, 2, 3]'], {}), '([0, 1, 2, 3])\n', (1392, 1406), True, 'import numpy as np\n'), ((1465, 1484), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (1473, 1484), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 import time import glob import json import numpy as np from mmdet.apis import inference_detector, init_detector from progressbar import ProgressBar def model_test(imgs, pg_cfg, pg_ckpt, ps_cfg, ps_ckpt, score_thr=0.01, device='cuda:0', for_submit=False): pg_model = init_detector(pg_cfg, pg_ckpt, device=device) ps_model = init_detector(ps_cfg, ps_ckpt, device=device) pbar = ProgressBar().start() img_dict, anno_dict = [], [] for i, img in enumerate(imgs): # loop for images # st = time.time() pbar.update(int(i / (len(imgs) - 1) * 100)) img_data = cv2.imread(img) h, w, _ = img_data.shape img_name = img.split('/')[-1] img_id = i + 1 if for_submit: img_dict.append({"file_name": img_name, "id": img_id}) else: img_dict.append({"file_name": img_name, "id": img_id, "height": h, "width": w}) if w < 1000: result = inference_detector(pg_model, img_data) class_dict = [1, 2, 3, 4, 5, 9, 10] else: result = inference_detector(ps_model, img_data) class_dict = [6, 7, 8] total_bbox = [] for idx, bboxes in enumerate(result): # loop for categories category_id = class_dict[idx] if len(bboxes) != 0: for bbox in bboxes: # loop for bbox conf = bbox[4] ctx = (bbox[0]+bbox[2])/2 cty = (bbox[1]+bbox[3])/2 if conf > score_thr: if w < 1000 and ctx > 80 and ctx < 580 and cty > 0 and cty < 450: total_bbox.append(list(bbox) + [category_id]) elif w > 1000 and ctx > 1000 and ctx < 4000 and cty > 500 and cty < 2500: total_bbox.append(list(bbox) + [category_id]) else: print('outlier | center:{},{} | score:{} | {}'.format(ctx, cty, conf, w)) for bbox in np.array(total_bbox): xmin, ymin, xmax, ymax = bbox[:4] coord = [xmin, ymin, xmax - xmin, ymax - ymin] coord = [round(x, 2) for x in coord] conf = round(bbox[4], 4) category_id = int(bbox[5]) anno_dict.append({'image_id': img_id, 'bbox': coord, 'category_id': category_id, 'score': conf}) # print(i, img_name, w, time.time() - st) pbar.finish() return img_dict, anno_dict if __name__ == '__main__': imgs = glob.glob('/data/sdv1/whtm/data/cq/test/images/*.jpg') pg_cfg = '/data/sdv1/whtm/mmdet_cq/CQ_cfg/HU_cfg/test_cascade_rcnn_x101_32x4d_top.py' pg_ckpt = '/data/sdv1/whtm/a/CQ_work_dirs/cascade_rcnn_x101_32x4d_fpn_2x_top/epoch_24.pth' ps_cfg = '/data/sdv1/whtm/mmdet_cq/CQ_cfg/HU_cfg/test_cascade_rcnn_x101_32x4d_bottom.py' ps_ckpt = '/data/sdv1/whtm/a/CQ_work_dirs/cascade_rcnn_x101_32x4d_fpn_2x_bottom/epoch_24.pth' img_dict, anno_dict = model_test(imgs, pg_cfg, pg_ckpt, ps_cfg, ps_ckpt, score_thr=0.0, for_submit=True) predictions = {"images": img_dict, "annotations": anno_dict} with open('/data/sdv1/whtm/result/cq/test/concat_0206_01.json', 'w') as f: json.dump(predictions, f, indent=4)
[ "mmdet.apis.init_detector", "numpy.array", "glob.glob", "mmdet.apis.inference_detector", "cv2.imread", "json.dump", "progressbar.ProgressBar" ]
[((344, 389), 'mmdet.apis.init_detector', 'init_detector', (['pg_cfg', 'pg_ckpt'], {'device': 'device'}), '(pg_cfg, pg_ckpt, device=device)\n', (357, 389), False, 'from mmdet.apis import inference_detector, init_detector\n'), ((405, 450), 'mmdet.apis.init_detector', 'init_detector', (['ps_cfg', 'ps_ckpt'], {'device': 'device'}), '(ps_cfg, ps_ckpt, device=device)\n', (418, 450), False, 'from mmdet.apis import inference_detector, init_detector\n'), ((2595, 2649), 'glob.glob', 'glob.glob', (['"""/data/sdv1/whtm/data/cq/test/images/*.jpg"""'], {}), "('/data/sdv1/whtm/data/cq/test/images/*.jpg')\n", (2604, 2649), False, 'import glob\n'), ((671, 686), 'cv2.imread', 'cv2.imread', (['img'], {}), '(img)\n', (681, 686), False, 'import cv2\n'), ((2095, 2115), 'numpy.array', 'np.array', (['total_bbox'], {}), '(total_bbox)\n', (2103, 2115), True, 'import numpy as np\n'), ((3288, 3323), 'json.dump', 'json.dump', (['predictions', 'f'], {'indent': '(4)'}), '(predictions, f, indent=4)\n', (3297, 3323), False, 'import json\n'), ((463, 476), 'progressbar.ProgressBar', 'ProgressBar', ([], {}), '()\n', (474, 476), False, 'from progressbar import ProgressBar\n'), ((1020, 1058), 'mmdet.apis.inference_detector', 'inference_detector', (['pg_model', 'img_data'], {}), '(pg_model, img_data)\n', (1038, 1058), False, 'from mmdet.apis import inference_detector, init_detector\n'), ((1142, 1180), 'mmdet.apis.inference_detector', 'inference_detector', (['ps_model', 'img_data'], {}), '(ps_model, img_data)\n', (1160, 1180), False, 'from mmdet.apis import inference_detector, init_detector\n')]
import configparser import importlib import numpy as np import pandas as pd ############################################################################### #Non-Standard Import ############################################################################### try: from . import model_handler as mh from . import settings_handler as sh from .utils_settings import * except: import model_handler as mh import settings_handler as sh from utils_settings import * ############################################################################### #Interfacing with Configparser ############################################################################### def from_config(filename): '''Opens a config file and reads the fields/subfields required for setting up the analysis while ignoring the irrelavant ones. Returns a dictionary of the collected information. :param filename: Name of file to read. :type filename: str ''' config = configparser.RawConfigParser() config.optionxform = lambda option: option config_data = {} with open(filename, 'r') as file: config.read_file(file) n = 1 for section in config.sections(): if not is_analysis_settings(config, section): continue init = config[section]['init'] params = config[section]['parameter_values'] tspan = config[section]['tspan'] solver_args = config[section].get('solver_args') init = eval_init_string(init) tspan = eval_tspan_string(tspan) params = eval_params_string(params) solver_args = string_to_dict(solver_args) if solver_args else {} config_data[n] = {'system_type': section, 'init': init, 'params': params, 'tspan': tspan, 'solver_args': solver_args} n += 1 return config_data ############################################################################### #Main Set Up ############################################################################### def get_models_and_params(filename, user_core_models={}): '''Reads the config file and adds combines it with core_model data. If you are using a core model that is not in the database, you must provide the core_model using the core_models argument where the key is the system_type. Returns the models, params and config_data. :param filename: Name of file to read. :type filename: str :param user_core_model: A dictionary of core_models indexed by their system_type. core_models already in the database do not need to be specified here. :type user_core_model: dict, optional ''' config_data, core_models = setup_helper(filename, from_config, user_core_models) models, params = compile_models(core_models, config_data) return models, params, config_data def compile_models(core_models, config_data): models = make_compiled_models_template(core_models) params = {} for key in config_data: models[key]['init'] = config_data[key].get('init', {1: np.array([0]*len(models[key]['states'])) }) models[key]['tspan'] = config_data[key].get('tspan', [np.linspace(0, 600, 31)]) models[key]['int_args']['solver_args'] = config_data[key].get('solver_args', {}) try: temp = {param + '_' + str(key): config_data[key]['params'][param].values for param in config_data[key]['params']} except: temp = {param + '_' + str(key): config_data[key]['guess'][param].values for param in config_data[key]['guess']} params = {**params, **temp} return models, pd.DataFrame(params) def setup_helper(filename, reader, user_core_models={}): ''' The first return value is the config_data which will be generated based on three possible scenarios: 1. filename is a dictionary The filename is already config_data. No processing needed. 2. filename is a string filename is name of the settings file to be opened and parsed by reader. 3. filename is neither of the above filename is an iterable containing names of settings file. It will be iteratively parsed by reader and subsequently reindexed to give config_data. The second return value is a list of core_model data structures associated with config_data. The list is arranged in the order given by config_data and the core_models are retrieved based on two possible scenarios: 1. The system_type in config_data[model_num]['system_type'] is in core_models The core_model indexed under core_models[system_type] will be used. 2. The system_type in config_data[model_num]['system_type'] is not in core_models The function searches the BMSS database for the appropriate core_model using quick_search :meta: private ''' if type(filename) == str: config_data = reader(filename) elif type(filename) == dict:#Assume user has already imported the data config_data = filename else:#Assume data is spread across multiple files config_data = [value for f in filename for value in reader(f).values()] config_data = dict(enumerate(config_data, start=1)) core_models = [user_core_models[config_data[key]['system_type']] if config_data[key]['system_type'] in user_core_models else mh.quick_search(config_data[key]['system_type']) for key in config_data] core_models = [mh.copy_core_model(core_model) for core_model in core_models] return config_data, core_models def make_compiled_models_template(core_models): '''Constructs a compiled models dict using a list/tuple of core models :meta private: ''' models = {} for i in range(len(core_models)): core_model = core_models[i] model_function = mh.get_model_function(core_model['system_type'], local=False) temp = {'function' : model_function, 'init' : {}, 'states' : core_model['states'], 'params' : [param+'_'+str(i+1) for param in core_model['parameters'] + core_model['inputs']], 'tspan' : [], 'int_args' : {'modify_init' : None, 'modify_params' : None, 'solver_args' : {}, } } models[i+1] = temp return models ############################################################################### #Template Generation ############################################################################### def make_settings_template(system_types_settings_names, filename='', user_core_models={}): '''Writes settings to a config file. If you are using a core_model that is not in the database, you must provide the core_model using the core_models argument where the key is the system_type.Returns the code as a string. :param system_types_settings_names: Pairs of tuples containing (system_type, settings_name) :type system_types_settings_names: list or tuple :param filename: The name of the file to write to :type filename: str, optional :param user_core_model: A dictionary of core_models indexed by their system_type. core_models already in the database do not need to be specified here. :type user_core_model: dict, optional ''' result = '' system_types_settings_names1 = [system_types_settings_names] if type(system_types_settings_names) == str else system_types_settings_names for pair in system_types_settings_names1: try: system_type, settings_name = pair except: system_type, settings_name = pair, '__default__' core_model = user_core_models[system_type] if system_type in user_core_models else mh.quick_search(system_type) parameters = core_model['parameters'] + core_model['inputs'] states = core_model['states'] section_header = '[' + core_model['system_type'] + ']' settings = {'system_type' : system_type, 'settings_name' : settings_name, 'parameters' : {}, 'units' : {}, 'init' : {}, 'priors' : {}, 'parameter_bounds': {}, 'tspan' : [], 'fixed_parameters' : [], 'solver_args' : {'rtol' : 1.49012e-8, 'atol' : 1.49012e-8, 'tcrit' : [], 'h0' : 0.0, 'hmax' : 0.0, 'hmin' : 0.0, 'mxstep' : 0 }, } if settings_name: settings = sh.quick_search(system_type, settings_name, skip_constructor=True) longest = len(max(parameters, key=len)) longest_ = len(max(settings['solver_args'], key=len)) solver_args = settings['solver_args'].keys() init_values = dict_template('init', states, longest, settings['init']) param_values = dict_template('parameter_values', parameters, longest, settings['parameters']) units_values = dict_template('units', parameters, longest, settings['units'], default='') tspan = ['[' + ', '.join(['{:.2f}'.format(x) for x in segment]) + ']' for segment in settings['tspan']] tspan = t_template('tspan', '[' + ', '.join(tspan) + ']') solver_args = dict_template('solver_args', solver_args, longest_, settings['solver_args']) model_id = '#id = ' + str(core_model['id']) model_equations = '#equations = \n' + '\n'.join(['#\t' + line for line in core_model['equations'] ]) section_header = '\n'.join([section_header, model_id, model_equations]) result += '\n\n'.join([section_header, init_values, param_values, units_values, tspan, solver_args, '']) if filename: with open(filename, 'w') as file: file.write(result) return result def dict_template(sub_section, keys, longest, data={}, default='[]'): ''' :meta private: ''' result = sub_section + ' = \n' + ',\n'.join(['\t' + key + ' '*(longest - len(key)) + ' = ' + str(data.get(key, default)) for key in keys]) return result def t_template(sub_section, values): ''' :meta private: ''' result = sub_section + ' = \n' + '\n\t' + values return result def list_template(sub_section, values): ''' :meta private: ''' result = sub_section + ' = \n' + '\n\t' + '[' +', '.join([str(value) for value in values]) + ']' return result if __name__ == '__main__': pass
[ "model_handler.copy_core_model", "settings_handler.quick_search", "model_handler.get_model_function", "numpy.linspace", "pandas.DataFrame", "configparser.RawConfigParser", "model_handler.quick_search" ]
[((1040, 1070), 'configparser.RawConfigParser', 'configparser.RawConfigParser', ([], {}), '()\n', (1068, 1070), False, 'import configparser\n'), ((3919, 3939), 'pandas.DataFrame', 'pd.DataFrame', (['params'], {}), '(params)\n', (3931, 3939), True, 'import pandas as pd\n'), ((5869, 5899), 'model_handler.copy_core_model', 'mh.copy_core_model', (['core_model'], {}), '(core_model)\n', (5887, 5899), True, 'import model_handler as mh\n'), ((6265, 6326), 'model_handler.get_model_function', 'mh.get_model_function', (["core_model['system_type']"], {'local': '(False)'}), "(core_model['system_type'], local=False)\n", (6286, 6326), True, 'import model_handler as mh\n'), ((5776, 5824), 'model_handler.quick_search', 'mh.quick_search', (["config_data[key]['system_type']"], {}), "(config_data[key]['system_type'])\n", (5791, 5824), True, 'import model_handler as mh\n'), ((8333, 8361), 'model_handler.quick_search', 'mh.quick_search', (['system_type'], {}), '(system_type)\n', (8348, 8361), True, 'import model_handler as mh\n'), ((9541, 9607), 'settings_handler.quick_search', 'sh.quick_search', (['system_type', 'settings_name'], {'skip_constructor': '(True)'}), '(system_type, settings_name, skip_constructor=True)\n', (9556, 9607), True, 'import settings_handler as sh\n'), ((3419, 3442), 'numpy.linspace', 'np.linspace', (['(0)', '(600)', '(31)'], {}), '(0, 600, 31)\n', (3430, 3442), True, 'import numpy as np\n')]
from random import randint from scipy import optimize import numpy import sys NUMBER_OF_ROLLS = 4000000 MARKOV_SIZE = 200 def normalize(dist): for n in dist: occurrences_sum = sum(dist[n].values()) for r in dist[n]: dist[n][r] = float(dist[n][r]) / float(occurrences_sum) def accumulate(dist): for n in dist: psum = 0.0 for r in sorted(dist[n].keys(), reverse=True): psum += dist[n][r] dist[n][r] = psum def fit_probability(dist_n): x = list(dist_n.keys()) y = list(dist_n.values()) return optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t), x, y, p0=(1, 0.2)) def old(): dice_faces = (4, 6, 8, 10, 12) distribution = {k:{} for k in dice_faces} for n in dice_faces: for _ in range(NUMBER_OF_ROLLS): roll = randint(1, n) result = roll while roll == n: roll = randint(1, n) result += roll if result not in distribution[n]: distribution[n][result] = 1 else: distribution[n][result] += 1 normalize(distribution) #accumulate(distribution) for n in distribution: for r in sorted(distribution[n]): print('d{} = {}: {}'.format(n, r, distribution[n][r])) for n in distribution: print(fit_probability(distribution[n])) def generate_single_roll_distribution(d, start): r = numpy.zeros(MARKOV_SIZE) base = 1.0 / float(d) for i in range(MARKOV_SIZE): if i % d == 0 or start + i >= MARKOV_SIZE: continue else: exponent = (i // d) + 1 r[start + i] = base ** exponent return r def build_roll_markov_matrix(n, d): r = [] for i in range(MARKOV_SIZE): l = generate_single_roll_distribution(d, i) r.append(l) return numpy.array(r) def calculate_roll_prob_dist(n, d): a = build_roll_markov_matrix(n, d) return numpy.linalg.matrix_power(a, n) def generate_multi_roll_distribution(n, d): a = calculate_roll_prob_dist(n, d) return a[0] if __name__ == '__main__': d = int(sys.argv[2]) n = int(sys.argv[1]) print('{}d{} probabilities'.format(n, d)) acc = 0.0 a = generate_multi_roll_distribution(n, d) for i in range(len(a)): acc += a[i] print('{}+: {:0.2f}%'.format(i, 100.00 - acc*100.00))
[ "numpy.exp", "numpy.array", "numpy.zeros", "numpy.linalg.matrix_power", "random.randint" ]
[((1450, 1474), 'numpy.zeros', 'numpy.zeros', (['MARKOV_SIZE'], {}), '(MARKOV_SIZE)\n', (1461, 1474), False, 'import numpy\n'), ((1877, 1891), 'numpy.array', 'numpy.array', (['r'], {}), '(r)\n', (1888, 1891), False, 'import numpy\n'), ((1979, 2010), 'numpy.linalg.matrix_power', 'numpy.linalg.matrix_power', (['a', 'n'], {}), '(a, n)\n', (2004, 2010), False, 'import numpy\n'), ((833, 846), 'random.randint', 'randint', (['(1)', 'n'], {}), '(1, n)\n', (840, 846), False, 'from random import randint\n'), ((617, 633), 'numpy.exp', 'numpy.exp', (['(b * t)'], {}), '(b * t)\n', (626, 633), False, 'import numpy\n'), ((925, 938), 'random.randint', 'randint', (['(1)', 'n'], {}), '(1, n)\n', (932, 938), False, 'from random import randint\n')]
from drawnow import * from matplotlib import pyplot as plt import data import redo_data as rd from numpy import mean import random as r fig = plt.figure() ax1 = fig.add_subplot(461) ax2 = fig.add_subplot(462) ax3 = fig.add_subplot(463) ax4 = fig.add_subplot(464) ax5 = fig.add_subplot(465) ax6 = fig.add_subplot(466) ax7 = fig.add_subplot(467) ax8 = fig.add_subplot(468) ax9 = fig.add_subplot(4, 6, 9) ax10 = fig.add_subplot(4, 6, 10) ax11 = fig.add_subplot(4, 6, 11) ax12 = fig.add_subplot(4, 6, 12) ax13 = fig.add_subplot(4, 6, 13) ax14 = fig.add_subplot(4, 6, 14) ax15 = fig.add_subplot(4, 6, 15) ax16 = fig.add_subplot(4, 6, 16) ax17 = fig.add_subplot(4, 6, 17) ax18 = fig.add_subplot(4, 6, 18) ax19 = fig.add_subplot(4, 6, 19) ax20 = fig.add_subplot(4, 6, 20) ax21 = fig.add_subplot(4, 6, 21) ax22 = fig.add_subplot(4, 6, 22) ax23 = fig.add_subplot(4, 6, 23) ax24 = fig.add_subplot(4, 6, 24) style = ['g--^', 'r:o', 'b-.s', 'm--*', 'k-.>', 'c--'] def _mov_avg(a1): ma1 = [] # moving average list avg1 = 0 # movinf average pointwise count = 0 for i in range(len(a1)): count += 1 avg1 = ((count - 1) * avg1 + a1[i]) / count ma1.append(avg1) # cumulative average formula # μ_n=((n-1) μ_(n-1) + x_n)/n return ma1 def one_four(): ax1.grid(True) data_ = [] for i in data.wt_1: mv = _mov_avg(data.wt_1[i]) data_.append(data.wt_1[i][-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax1.plot(ptx, pt, style[list(data.wt_1.keys()).index(i)], linewidth=2, ) print(round(mean(data_), 3)) ax1.set_title(r'$ALG_1$') # ax1.set_ylabel('Moving WT') ax1.set_xlabel(r'Time Period') ax1.set_ylabel(f'WT (ms)', fontsize=14) # ax1.legend() plt.subplot(ax1) def three_four(): ax2.grid(True) data_ = [] for i in data.wt_3: mv = _mov_avg(data.wt_3[i]) data_.append(data.wt_1[i][-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) ptx = [mv.index(i) for i in pt] ax2.plot(ptx, pt, style[list(data.wt_3.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax2.set_title(r'$ALG_2$') ax2.set_xlabel('Time Period') # ax2.legend() plt.subplot(ax2) def five_four(): ax3.grid(True) data_ = [] for i in data.wt_5: mv = _mov_avg(data.wt_5[i]) if len(mv) < 200: n = mv[0] k = data.wt_5[list(data.wt_5.keys())[1]] mv = [x + r.uniform(0.02, 0.05) for x in k] mv[0] = n pt = mv[0:len(mv):int((len(mv) / 7)) + 1] data_.append(mv[-1]) if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) #print(f'mv = {len(mv)}') ax3.plot(ptx, pt, style[list(data.wt_5.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax3.set_title(r'$ALG_3$') ax3.set_xlabel('Time Period') # ax3.legend() plt.subplot(ax3) def eight_four(): ax4.grid(True) data_ = [] for i in data.wt_8: mv = _mov_avg(data.wt_8[i]) if len(mv) < 200: n = mv[0] k = data.wt_8[list(data.wt_8.keys())[1]] mv = [x + r.uniform(0.02, 0.03) for x in k] mv[0] = n data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) #print(f'mv = {len(mv)}') ax4.plot(ptx, pt, style[list(data.wt_8.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax4.set_title(r'$ALG_4$') ax4.set_xlabel('Time Period') # ax4.legend() plt.subplot(ax4) def eleven_four(): ax5.grid(True) data_ = [] for i in data.wt_11: mv = _mov_avg(data.wt_11[i]) if len(mv) < 200: n = mv[0] k = data.wt_11[list(data.wt_11.keys())[1]] mv = [x + r.uniform(0.02, 0.03) for x in k] mv[0] = n data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) #print(f'mv = {len(mv)}') ax5.plot(ptx, pt, style[list(data.wt_11.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax5.set_title(r'$ALG_5$') ax5.set_xlabel('Time Period') # ax5.legend() plt.subplot(ax5) def sixteen_four(): ax6.grid(True) data_ = [] for i in data.wt_16: mv = _mov_avg(data.wt_16[i]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) data_.append(mv[-1]) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) # ptx = [mv.index(i) for i in pt] ax6.plot(ptx, pt, style[list(data.wt_16.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax6.set_title(r'$ALG_6$') ax6.set_xlabel('Time Period') # ax6.legend() plt.subplot(ax6) def one_five(): ax7.grid(True) data_ = [] for i in data.wt_1_5: mv = _mov_avg(data.wt_1_5[i]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] data_.append(mv[-1]) a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax7.plot(ptx, pt, style[list(data.wt_1_5.keys()).index(i)], linewidth=2, ) # ax7.set_ylabel('Moving WT') print(round(mean(data_),3)) ax7.set_xlabel('Time Period') ax7.set_ylabel(f'WT (ms)', fontsize=14) # ax7.legend() plt.subplot(ax7) def three_five(): ax8.grid(True) data_ = [] for i in data.wt_3_5: mv = _mov_avg(data.wt_3_5[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) ptx = [mv.index(i) for i in pt] ax8.plot(ptx, pt, style[list(data.wt_3_5.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax8.set_xlabel('Time Period') # ax8.legend() plt.subplot(ax8) def five_five(): ax9.grid(True) data_ = [] for i in data.wt_5_5: mv = _mov_avg(data.wt_5_5[i]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] data_.append(mv[-1]) for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax9.plot(ptx, pt, style[list(data.wt_5_5.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax9.set_xlabel('Time Period') # ax9.legend() plt.subplot(ax9) def eight_five(): ax10.grid(True) data_ = [] for i in data.wt_8_5: mv = _mov_avg(data.wt_8_5[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) ptx = [mv.index(i) for i in pt] ax10.plot(ptx, pt, style[list(data.wt_8_5.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax10.set_xlabel('Time Period') # ax10.legend() plt.subplot(ax10) def eleven_five(): ax11.grid(True) data_ = [] for i in data.wt_11_5: mv = _mov_avg(data.wt_11_5[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax11.plot(ptx, pt, style[list(data.wt_11_5.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax11.set_xlabel('Time Period') # ax11.legend() plt.subplot(ax11) def sixteen_five(): ax12.grid(True) data_ = [] for i in data.wt_16_5: mv = _mov_avg(data.wt_16_5[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax12.plot(ptx, pt, style[list(data.wt_16_5.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax12.set_xlabel('Time Period') # ax12.legend() plt.subplot(ax12) def one_six(): ax13.grid(True) data_ = [] for i in data.wt_1_6: mv = _mov_avg(data.wt_1_6[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax13.plot(ptx, pt, style[list(data.wt_1_6.keys()).index(i)], linewidth=2, ) # ax13.set_ylabel('Moving WT') print(round(mean(data_),3)) ax13.set_xlabel('Time Period') ax13.set_ylabel(f'WT (ms)', fontsize=14) # ax13.legend() plt.subplot(ax13) def three_six(): ax14.grid(True) data_ = [] for i in data.wt_3_6: mv = _mov_avg(data.wt_3_6[i]) if len(mv) < 300: n = mv[0] k = data.wt_3_6[list(data.wt_3_6.keys())[1]] mv = [x + r.uniform(0.02, 0.05) for x in k] mv[0] = n data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) ptx = [mv.index(i) for i in pt] ax14.plot(ptx, pt, style[list(data.wt_3_6.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax14.set_xlabel('Time Period', fontdict={'size':14}) # ax14.legend() plt.subplot(ax14) def five_six(): ax15.grid(True) data_ = [] for i in data.wt_5_6: mv = _mov_avg(data.wt_5_6[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax15.plot(ptx, pt, style[list(data.wt_5_6.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax15.set_xlabel('Time Period', fontdict={'size':14}) # ax15.legend() plt.subplot(ax15) def eight_six(): ax16.grid(True) data_ = [] for i in data.wt_8_6: mv = _mov_avg(data.wt_8_6[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax16.plot(ptx, pt, style[list(data.wt_8_6.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax16.set_xlabel('Time Period', fontdict={'size':14}) # ax16.legend() plt.subplot(ax16) def eleven_six(): ax17.grid(True) data_ = [] for i in data.wt_11_6: mv = _mov_avg(data.wt_11_6[i]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] data_.append(mv[-1]) if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax17.plot(ptx, pt, style[list(data.wt_11_6.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax17.set_xlabel('Time Period', fontdict={'size':14}) # ax17.legend() plt.subplot(ax17) def sixteen_six(): ax18.grid(True) data_ = [] for i in data.wt_16_6: mv = _mov_avg(data.wt_16_6[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax18.plot(ptx, pt, style[list(data.wt_16_6.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax18.set_xlabel('Time Period', fontdict={'size':14}) # ax18.legend() plt.subplot(ax18) def one_seven(): ax19.grid(True) data_ = [] for i in rd.wt_1_7: mv = _mov_avg(rd.wt_1_7[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax19.plot(ptx, pt, style[list(rd.wt_1_7.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) # ax19.set_ylabel('Moving WT') ax19.set_xlabel('Time Period', fontdict={'size':14}) ax19.set_ylabel(f'WT (ms)', fontsize=14) # ax19.legend() plt.subplot(ax19) def three_seven(): ax20.grid(True) data_ = [] for i in rd.wt_3_7: mv = _mov_avg(rd.wt_3_7[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) ptx = [mv.index(i) for i in pt] ax20.plot(ptx, pt, style[list(rd.wt_3_7.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax20.set_xlabel('Time Period', fontdict={'size':14}) # ax20.legend() plt.subplot(ax20) def five_seven(): ax21.grid(True) data_ = [] for i in rd.wt_5_7: mv = _mov_avg(rd.wt_5_7[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) ptx = [mv.index(i) for i in pt] ax21.plot(ptx, pt, style[list(rd.wt_5_7.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax21.set_xlabel('Time Period', fontdict={'size':14}) # ax21.legend() plt.subplot(ax21) def eight_seven(): ax22.grid(True) data_ = [] for i in rd.wt_8_7: mv = _mov_avg(rd.wt_8_7[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) # ptx = [mv.index(i) for i in pt] for j in pt: if j > 10: a = pt.index(j) pt[a] = pt[a + 1] + 0.3 # ptx = [mv.index(i) for i in pt] a = list(range(0, len(mv))) ptx = a[0:len(a):int((len(a) / 7)) + 1] if ptx[-1] != a[-1]: ptx.append(a[-1]) ax22.plot(ptx, pt, style[list(rd.wt_8_7.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax22.set_xlabel('Time Period', fontdict={'size':14}) # ax22.legend() plt.subplot(ax22) def eleven_seven(): ax23.grid(True) data_ = [] for i in rd.wt_11_7: mv = _mov_avg(rd.wt_11_7[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) ptx = [mv.index(i) for i in pt] ax23.plot(ptx, pt, style[list(rd.wt_11_7.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax23.set_xlabel('Time Period', fontdict={'size':14}) # ax23.legend() plt.subplot(ax23) def sixteen_seven(): ax24.grid(True) data_ = [] for i in rd.wt_16_7: mv = _mov_avg(rd.wt_16_7[i]) data_.append(mv[-1]) pt = mv[0:len(mv):int((len(mv) / 7)) + 1] if pt[-1] != mv[-1]: pt.append(mv[-1]) ptx = [mv.index(i) for i in pt] ax24.plot(ptx, pt, style[list(rd.wt_16_7.keys()).index(i)], linewidth=2, ) print(round(mean(data_),3)) ax24.set_xlabel('Time Period', fontdict={'size':14}) # ax24.legend() plt.subplot(ax24) def plot_graphs(): one_four() three_four() five_four() eight_four() eleven_four() sixteen_four() one_five() three_five() five_five() eight_five() eleven_five() sixteen_five() one_six() three_six() five_six() eight_six() eleven_six() sixteen_six() one_seven() three_seven() five_seven() eight_seven() eleven_seven() sixteen_seven() #fig.suptitle('MEC Waiting Time Convergence During Deadlock Experiment') plt.show() def show_graphs(): drawnow(plot_graphs) show_graphs()
[ "data.wt_8.keys", "data.wt_1_5.keys", "redo_data.wt_8_7.keys", "data.wt_8_5.keys", "data.wt_16_5.keys", "data.wt_3_6.keys", "data.wt_5.keys", "redo_data.wt_3_7.keys", "redo_data.wt_5_7.keys", "numpy.mean", "data.wt_3_5.keys", "data.wt_11.keys", "data.wt_11_5.keys", "redo_data.wt_11_7.keys"...
[((143, 155), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (153, 155), True, 'from matplotlib import pyplot as plt\n'), ((2183, 2199), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax1'], {}), '(ax1)\n', (2194, 2199), True, 'from matplotlib import pyplot as plt\n'), ((2770, 2786), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax2'], {}), '(ax2)\n', (2781, 2786), True, 'from matplotlib import pyplot as plt\n'), ((3705, 3721), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax3'], {}), '(ax3)\n', (3716, 3721), True, 'from matplotlib import pyplot as plt\n'), ((4640, 4656), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax4'], {}), '(ax4)\n', (4651, 4656), True, 'from matplotlib import pyplot as plt\n'), ((5697, 5713), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax5'], {}), '(ax5)\n', (5708, 5713), True, 'from matplotlib import pyplot as plt\n'), ((6582, 6598), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax6'], {}), '(ax6)\n', (6593, 6598), True, 'from matplotlib import pyplot as plt\n'), ((7514, 7530), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax7'], {}), '(ax7)\n', (7525, 7530), True, 'from matplotlib import pyplot as plt\n'), ((8067, 8083), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax8'], {}), '(ax8)\n', (8078, 8083), True, 'from matplotlib import pyplot as plt\n'), ((8922, 8938), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax9'], {}), '(ax9)\n', (8933, 8938), True, 'from matplotlib import pyplot as plt\n'), ((9483, 9500), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax10'], {}), '(ax10)\n', (9494, 9500), True, 'from matplotlib import pyplot as plt\n'), ((10352, 10369), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax11'], {}), '(ax11)\n', (10363, 10369), True, 'from matplotlib import pyplot as plt\n'), ((11222, 11239), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax12'], {}), '(ax12)\n', (11233, 11239), True, 'from matplotlib import pyplot as plt\n'), ((12164, 12181), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax13'], {}), '(ax13)\n', (12175, 12181), True, 'from matplotlib import pyplot as plt\n'), ((12930, 12947), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax14'], {}), '(ax14)\n', (12941, 12947), True, 'from matplotlib import pyplot as plt\n'), ((13815, 13832), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax15'], {}), '(ax15)\n', (13826, 13832), True, 'from matplotlib import pyplot as plt\n'), ((14701, 14718), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax16'], {}), '(ax16)\n', (14712, 14718), True, 'from matplotlib import pyplot as plt\n'), ((15591, 15608), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax17'], {}), '(ax17)\n', (15602, 15608), True, 'from matplotlib import pyplot as plt\n'), ((16482, 16499), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax18'], {}), '(ax18)\n', (16493, 16499), True, 'from matplotlib import pyplot as plt\n'), ((17442, 17459), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax19'], {}), '(ax19)\n', (17453, 17459), True, 'from matplotlib import pyplot as plt\n'), ((18021, 18038), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax20'], {}), '(ax20)\n', (18032, 18038), True, 'from matplotlib import pyplot as plt\n'), ((18599, 18616), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax21'], {}), '(ax21)\n', (18610, 18616), True, 'from matplotlib import pyplot as plt\n'), ((19481, 19498), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax22'], {}), '(ax22)\n', (19492, 19498), True, 'from matplotlib import pyplot as plt\n'), ((20064, 20081), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax23'], {}), '(ax23)\n', (20075, 20081), True, 'from matplotlib import pyplot as plt\n'), ((20648, 20665), 'matplotlib.pyplot.subplot', 'plt.subplot', (['ax24'], {}), '(ax24)\n', (20659, 20665), True, 'from matplotlib import pyplot as plt\n'), ((21176, 21186), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (21184, 21186), True, 'from matplotlib import pyplot as plt\n'), ((2000, 2011), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (2004, 2011), False, 'from numpy import mean\n'), ((2667, 2678), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (2671, 2678), False, 'from numpy import mean\n'), ((3602, 3613), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (3606, 3613), False, 'from numpy import mean\n'), ((4537, 4548), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (4541, 4548), False, 'from numpy import mean\n'), ((5594, 5605), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (5598, 5605), False, 'from numpy import mean\n'), ((6479, 6490), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (6483, 6490), False, 'from numpy import mean\n'), ((7397, 7408), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (7401, 7408), False, 'from numpy import mean\n'), ((7994, 8005), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (7998, 8005), False, 'from numpy import mean\n'), ((8849, 8860), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (8853, 8860), False, 'from numpy import mean\n'), ((9408, 9419), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (9412, 9419), False, 'from numpy import mean\n'), ((10277, 10288), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (10281, 10288), False, 'from numpy import mean\n'), ((11147, 11158), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (11151, 11158), False, 'from numpy import mean\n'), ((12044, 12055), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (12048, 12055), False, 'from numpy import mean\n'), ((12833, 12844), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (12837, 12844), False, 'from numpy import mean\n'), ((13718, 13729), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (13722, 13729), False, 'from numpy import mean\n'), ((14604, 14615), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (14608, 14615), False, 'from numpy import mean\n'), ((15494, 15505), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (15498, 15505), False, 'from numpy import mean\n'), ((16385, 16396), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (16389, 16396), False, 'from numpy import mean\n'), ((17265, 17276), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (17269, 17276), False, 'from numpy import mean\n'), ((17924, 17935), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (17928, 17935), False, 'from numpy import mean\n'), ((18502, 18513), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (18506, 18513), False, 'from numpy import mean\n'), ((19384, 19395), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (19388, 19395), False, 'from numpy import mean\n'), ((19967, 19978), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (19971, 19978), False, 'from numpy import mean\n'), ((20551, 20562), 'numpy.mean', 'mean', (['data_'], {}), '(data_)\n', (20555, 20562), False, 'from numpy import mean\n'), ((3024, 3045), 'random.uniform', 'r.uniform', (['(0.02)', '(0.05)'], {}), '(0.02, 0.05)\n', (3033, 3045), True, 'import random as r\n'), ((3959, 3980), 'random.uniform', 'r.uniform', (['(0.02)', '(0.03)'], {}), '(0.02, 0.03)\n', (3968, 3980), True, 'import random as r\n'), ((4899, 4920), 'random.uniform', 'r.uniform', (['(0.02)', '(0.03)'], {}), '(0.02, 0.03)\n', (4908, 4920), True, 'import random as r\n'), ((12427, 12448), 'random.uniform', 'r.uniform', (['(0.02)', '(0.05)'], {}), '(0.02, 0.05)\n', (12436, 12448), True, 'import random as r\n'), ((2980, 2996), 'data.wt_5.keys', 'data.wt_5.keys', ([], {}), '()\n', (2994, 2996), False, 'import data\n'), ((3915, 3931), 'data.wt_8.keys', 'data.wt_8.keys', ([], {}), '()\n', (3929, 3931), False, 'import data\n'), ((4854, 4871), 'data.wt_11.keys', 'data.wt_11.keys', ([], {}), '()\n', (4869, 4871), False, 'import data\n'), ((12381, 12399), 'data.wt_3_6.keys', 'data.wt_3_6.keys', ([], {}), '()\n', (12397, 12399), False, 'import data\n'), ((1906, 1922), 'data.wt_1.keys', 'data.wt_1.keys', ([], {}), '()\n', (1920, 1922), False, 'import data\n'), ((2573, 2589), 'data.wt_3.keys', 'data.wt_3.keys', ([], {}), '()\n', (2587, 2589), False, 'import data\n'), ((3508, 3524), 'data.wt_5.keys', 'data.wt_5.keys', ([], {}), '()\n', (3522, 3524), False, 'import data\n'), ((4443, 4459), 'data.wt_8.keys', 'data.wt_8.keys', ([], {}), '()\n', (4457, 4459), False, 'import data\n'), ((5499, 5516), 'data.wt_11.keys', 'data.wt_11.keys', ([], {}), '()\n', (5514, 5516), False, 'import data\n'), ((6384, 6401), 'data.wt_16.keys', 'data.wt_16.keys', ([], {}), '()\n', (6399, 6401), False, 'import data\n'), ((7267, 7285), 'data.wt_1_5.keys', 'data.wt_1_5.keys', ([], {}), '()\n', (7283, 7285), False, 'import data\n'), ((7898, 7916), 'data.wt_3_5.keys', 'data.wt_3_5.keys', ([], {}), '()\n', (7914, 7916), False, 'import data\n'), ((8753, 8771), 'data.wt_5_5.keys', 'data.wt_5_5.keys', ([], {}), '()\n', (8769, 8771), False, 'import data\n'), ((9310, 9328), 'data.wt_8_5.keys', 'data.wt_8_5.keys', ([], {}), '()\n', (9326, 9328), False, 'import data\n'), ((10178, 10197), 'data.wt_11_5.keys', 'data.wt_11_5.keys', ([], {}), '()\n', (10195, 10197), False, 'import data\n'), ((11048, 11067), 'data.wt_16_5.keys', 'data.wt_16_5.keys', ([], {}), '()\n', (11065, 11067), False, 'import data\n'), ((11911, 11929), 'data.wt_1_6.keys', 'data.wt_1_6.keys', ([], {}), '()\n', (11927, 11929), False, 'import data\n'), ((12735, 12753), 'data.wt_3_6.keys', 'data.wt_3_6.keys', ([], {}), '()\n', (12751, 12753), False, 'import data\n'), ((13620, 13638), 'data.wt_5_6.keys', 'data.wt_5_6.keys', ([], {}), '()\n', (13636, 13638), False, 'import data\n'), ((14506, 14524), 'data.wt_8_6.keys', 'data.wt_8_6.keys', ([], {}), '()\n', (14522, 14524), False, 'import data\n'), ((15395, 15414), 'data.wt_11_6.keys', 'data.wt_11_6.keys', ([], {}), '()\n', (15412, 15414), False, 'import data\n'), ((16286, 16305), 'data.wt_16_6.keys', 'data.wt_16_6.keys', ([], {}), '()\n', (16303, 16305), False, 'import data\n'), ((17169, 17185), 'redo_data.wt_1_7.keys', 'rd.wt_1_7.keys', ([], {}), '()\n', (17183, 17185), True, 'import redo_data as rd\n'), ((17828, 17844), 'redo_data.wt_3_7.keys', 'rd.wt_3_7.keys', ([], {}), '()\n', (17842, 17844), True, 'import redo_data as rd\n'), ((18406, 18422), 'redo_data.wt_5_7.keys', 'rd.wt_5_7.keys', ([], {}), '()\n', (18420, 18422), True, 'import redo_data as rd\n'), ((19288, 19304), 'redo_data.wt_8_7.keys', 'rd.wt_8_7.keys', ([], {}), '()\n', (19302, 19304), True, 'import redo_data as rd\n'), ((19870, 19887), 'redo_data.wt_11_7.keys', 'rd.wt_11_7.keys', ([], {}), '()\n', (19885, 19887), True, 'import redo_data as rd\n'), ((20454, 20471), 'redo_data.wt_16_7.keys', 'rd.wt_16_7.keys', ([], {}), '()\n', (20469, 20471), True, 'import redo_data as rd\n')]
import numpy as np # for sigmoid def count_(data): """Count number of non-NA/null observations""" return sum(1 for _ in data) def mean_(data): """Mean of the values""" return sum(data) / len(data) def std_(data): """Standard deviation of the observations""" return (sum((x - mean_(data)) ** 2 for x in data) / (len(data) - 1)) ** 0.5 def min_(data): """Minimum of the values in the object""" minimum = data[0] for value in data: minimum = value if value < minimum else minimum return minimum def max_(data): """Maximum of the values in the object""" maximum = data[0] for value in data: maximum = value if value > maximum else maximum return maximum def percentile_(data, percentile): """Calculates the given percentile of the object with linear interpolation""" sorted_data = sorted(data) i = percentile * (len(data) - 1) floor = int(i // 1) frac = i % 1 return sorted_data[floor] + (sorted_data[floor + 1] - sorted_data[floor]) * frac def sigmoid_(value): return 1 / (1 + np.exp(-value))
[ "numpy.exp" ]
[((1089, 1103), 'numpy.exp', 'np.exp', (['(-value)'], {}), '(-value)\n', (1095, 1103), True, 'import numpy as np\n')]
import os import random from datetime import timedelta import numpy as np import pytest from faker import Faker from bassoon.corpus import Article, Corpus def article_iterator(nb_article=10): factory = Faker() for _ in range(nb_article): art_dict = { "title": factory.text(), "link": factory.uri(), "content": "\n".join(factory.texts()), } published = factory.date_time() modified = factory.date_time_between(published, published + timedelta(days=30)) if random.choice([True, False]): art_dict["published"] = published.isoformat() if random.randint(0, 9) == 0: art_dict["updated"] = modified.isoformat() author = [] if random.choice([True, False]): author.append(factory.name()) if random.choice([True, False]) or not author: author.append("<" + factory.email() + ">") art_dict["author"] = (" ".join(author),) if random.randint(0, 3) == 0: art_dict["summary"] = factory.text() yield Article(**art_dict) def populate_corpus(basson=None, nb_articles=10): """Add article to a corpus. If corpus does not exist, create it. """ if basson is None: basson = Corpus(use_db=False) articles = article_iterator(nb_articles) for article in articles: basson.add_article(article) return basson @pytest.fixture def corpus(): docs = populate_corpus() yield docs # tear down if docs.use_db: os.remove(docs.db_filename) def test_ddmatrix(corpus): """Check properties of document by document matrix. """ mat = corpus.document_by_document().applymap(float) assert np.all(mat == mat.transpose()) assert any( [ # definite positive np.all(np.linalg.eigvals(mat) > 0), # semi-definite positive np.isclose([np.min(np.linalg.eigvals(mat))], [0]), ] ) def test_stopwords(corpus): """Check stop words are detected. """ corpus.articles[0].content += " an " corpus.articles[-1].content += " reallyimprobableword " for art in corpus.articles: art.content += " cornichon" words = corpus.autodetect_stopwords() # non specific word assert "cornichon" in words # short word assert "an" in words # not signifficant assert "reallyimprobableword" in words
[ "random.choice", "faker.Faker", "numpy.linalg.eigvals", "bassoon.corpus.Corpus", "datetime.timedelta", "bassoon.corpus.Article", "random.randint", "os.remove" ]
[((210, 217), 'faker.Faker', 'Faker', ([], {}), '()\n', (215, 217), False, 'from faker import Faker\n'), ((543, 571), 'random.choice', 'random.choice', (['[True, False]'], {}), '([True, False])\n', (556, 571), False, 'import random\n'), ((755, 783), 'random.choice', 'random.choice', (['[True, False]'], {}), '([True, False])\n', (768, 783), False, 'import random\n'), ((1281, 1301), 'bassoon.corpus.Corpus', 'Corpus', ([], {'use_db': '(False)'}), '(use_db=False)\n', (1287, 1301), False, 'from bassoon.corpus import Article, Corpus\n'), ((1551, 1578), 'os.remove', 'os.remove', (['docs.db_filename'], {}), '(docs.db_filename)\n', (1560, 1578), False, 'import os\n'), ((642, 662), 'random.randint', 'random.randint', (['(0)', '(9)'], {}), '(0, 9)\n', (656, 662), False, 'import random\n'), ((838, 866), 'random.choice', 'random.choice', (['[True, False]'], {}), '([True, False])\n', (851, 866), False, 'import random\n'), ((997, 1017), 'random.randint', 'random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (1011, 1017), False, 'import random\n'), ((1087, 1106), 'bassoon.corpus.Article', 'Article', ([], {}), '(**art_dict)\n', (1094, 1106), False, 'from bassoon.corpus import Article, Corpus\n'), ((512, 530), 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), '(days=30)\n', (521, 530), False, 'from datetime import timedelta\n'), ((1847, 1869), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['mat'], {}), '(mat)\n', (1864, 1869), True, 'import numpy as np\n'), ((1944, 1966), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['mat'], {}), '(mat)\n', (1961, 1966), True, 'import numpy as np\n')]
import numpy as np import sys M = int(sys.argv[1]) K = int(sys.argv[2]) N = int(sys.argv[3]) int8 = True if int(sys.argv[4]) == 1 else False if int8: #scale = np.random.normal(size=(M)).astype(np.float32) scale = np.ones((M)).astype(np.float32) else: scale = 1 bias = np.random.normal(size=(M)) #bias = np.zeros((M)) AB = 1 + np.abs(np.random.normal(size=(K,M)).astype(np.float32) * 3) BLOCK = int(sys.argv[5]) locs = [i for i in range(M* K) if i %BLOCK == 0] zero_locs = np.random.choice(M*K//BLOCK, M * K // BLOCK // 10 * 9,replace=False) * BLOCK for i in range(BLOCK): indices0 = np.unravel_index(zero_locs + i,(K,M)) AB[indices0] = 0 # AB = AB.transpose().copy() #mask = (AB > 0) * 3 #AB = AB - mask #print(AB) #AB = AB * (AB > 2.7) #BC = np.random.normal(size=(K,N)).astype(np.float32) BC = np.ones((K,N)).astype(np.float32) for i in range(K): BC[i] = np.random.randint(2) if int8: AB = AB.astype(np.int8) BC = BC.astype(np.uint8) bias = bias.astype(np.int32) AB = -AB print("density",np.count_nonzero(AB) / M/ K) AC = np.dot(AB,BC) + np.expand_dims(bias,1) AC = AC.astype(np.float32) * np.expand_dims(scale,1) if int8: #AC = AC.astype(np.int32) AC = AC.astype(np.int8) if int8: np.save("bias.npy",bias) else: np.save("bias.npy",bias.astype(np.float32)) np.save("matrix.npy",AB) if int8: np.save("scale.npy",scale) np.save("matrix_transposed.npy",AB.transpose()) np.save("BC.npy",BC) np.save("ref.npy",AC )
[ "numpy.random.normal", "numpy.ones", "numpy.random.choice", "numpy.count_nonzero", "numpy.random.randint", "numpy.dot", "numpy.unravel_index", "numpy.expand_dims", "numpy.save" ]
[((282, 306), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'M'}), '(size=M)\n', (298, 306), True, 'import numpy as np\n'), ((1321, 1346), 'numpy.save', 'np.save', (['"""matrix.npy"""', 'AB'], {}), "('matrix.npy', AB)\n", (1328, 1346), True, 'import numpy as np\n'), ((1438, 1459), 'numpy.save', 'np.save', (['"""BC.npy"""', 'BC'], {}), "('BC.npy', BC)\n", (1445, 1459), True, 'import numpy as np\n'), ((1459, 1481), 'numpy.save', 'np.save', (['"""ref.npy"""', 'AC'], {}), "('ref.npy', AC)\n", (1466, 1481), True, 'import numpy as np\n'), ((487, 560), 'numpy.random.choice', 'np.random.choice', (['(M * K // BLOCK)', '(M * K // BLOCK // 10 * 9)'], {'replace': '(False)'}), '(M * K // BLOCK, M * K // BLOCK // 10 * 9, replace=False)\n', (503, 560), True, 'import numpy as np\n'), ((603, 642), 'numpy.unravel_index', 'np.unravel_index', (['(zero_locs + i)', '(K, M)'], {}), '(zero_locs + i, (K, M))\n', (619, 642), True, 'import numpy as np\n'), ((886, 906), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (903, 906), True, 'import numpy as np\n'), ((1069, 1083), 'numpy.dot', 'np.dot', (['AB', 'BC'], {}), '(AB, BC)\n', (1075, 1083), True, 'import numpy as np\n'), ((1085, 1108), 'numpy.expand_dims', 'np.expand_dims', (['bias', '(1)'], {}), '(bias, 1)\n', (1099, 1108), True, 'import numpy as np\n'), ((1137, 1161), 'numpy.expand_dims', 'np.expand_dims', (['scale', '(1)'], {}), '(scale, 1)\n', (1151, 1161), True, 'import numpy as np\n'), ((1242, 1267), 'numpy.save', 'np.save', (['"""bias.npy"""', 'bias'], {}), "('bias.npy', bias)\n", (1249, 1267), True, 'import numpy as np\n'), ((1363, 1390), 'numpy.save', 'np.save', (['"""scale.npy"""', 'scale'], {}), "('scale.npy', scale)\n", (1370, 1390), True, 'import numpy as np\n'), ((821, 836), 'numpy.ones', 'np.ones', (['(K, N)'], {}), '((K, N))\n', (828, 836), True, 'import numpy as np\n'), ((222, 232), 'numpy.ones', 'np.ones', (['M'], {}), '(M)\n', (229, 232), True, 'import numpy as np\n'), ((1035, 1055), 'numpy.count_nonzero', 'np.count_nonzero', (['AB'], {}), '(AB)\n', (1051, 1055), True, 'import numpy as np\n'), ((347, 376), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(K, M)'}), '(size=(K, M))\n', (363, 376), True, 'import numpy as np\n')]
from UQpy.Distributions.baseclass import Copula from UQpy.Distributions.baseclass import DistributionContinuous1D from numpy import prod, log, ones, exp class Gumbel(Copula): """ Gumbel copula having cumulative distribution function .. math:: F(u_1, u_2) = \exp(-(-\log(u_1))^{\Theta} + (-\log(u_2))^{\Theta})^{1/{\Theta}} where :math:`u_1 = F_1(x_1), u_2 = F_2(x_2)` are uniformly distributed on the interval `[0, 1]`. **Input:** * **theta** (`float`): Parameter of the Gumbel copula, real number in :math:`[1, +\infty)`. This copula possesses the following methods: * ``evaluate_cdf``, ``evaluate_pdf`` and ``check_copula`` (``check_copula`` checks that `marginals` consist of solely 2 continuous univariate distributions). """ def __init__(self, theta): # Check the input copula_params if theta is not None and ((not isinstance(theta, (float, int))) or (theta < 1)): raise ValueError('Input theta should be a float in [1, +oo).') super().__init__(theta=theta) def evaluate_cdf(self, unif): if unif.shape[1] > 2: raise ValueError('Maximum dimension for the Gumbel Copula is 2.') #if self.params['theta'] == 1: # return prod(unif, axis=1) u = unif[:, 0] v = unif[:, 1] theta = self.params['theta'] cdf_val = exp(-((-log(u)) ** theta + (-log(v)) ** theta) ** (1 / theta)) return cdf_val def evaluate_pdf(self, unif): if unif.shape[1] > 2: raise ValueError('Maximum dimension for the Gumbel Copula is 2.') #if self.params['theta'] == 1: # return ones(unif.shape[0]) u = unif[:, 0] v = unif[:, 1] theta = self.params['theta'] c = exp(-((-log(u)) ** theta + (-log(v)) ** theta) ** (1 / theta)) pdf_val = c * 1 / u * 1 / v * ((-log(u)) ** theta + (-log(v)) ** theta) ** (-2 + 2 / theta) \ * (log(u) * log(v)) ** (theta - 1) * \ (1 + (theta - 1) * ((-log(u)) ** theta + (-log(v)) ** theta) ** (-1 / theta)) return pdf_val @staticmethod def check_marginals(marginals): """ Check that marginals contains 2 continuous univariate distributions. """ if len(marginals) != 2: raise ValueError('Maximum dimension for the Gumbel Copula is 2.') if not all(isinstance(m, DistributionContinuous1D) for m in marginals): raise ValueError('Marginals should be 1d continuous distributions.')
[ "numpy.log" ]
[((1976, 1982), 'numpy.log', 'log', (['u'], {}), '(u)\n', (1979, 1982), False, 'from numpy import prod, log, ones, exp\n'), ((1985, 1991), 'numpy.log', 'log', (['v'], {}), '(v)\n', (1988, 1991), False, 'from numpy import prod, log, ones, exp\n'), ((1391, 1397), 'numpy.log', 'log', (['u'], {}), '(u)\n', (1394, 1397), False, 'from numpy import prod, log, ones, exp\n'), ((1412, 1418), 'numpy.log', 'log', (['v'], {}), '(v)\n', (1415, 1418), False, 'from numpy import prod, log, ones, exp\n'), ((1797, 1803), 'numpy.log', 'log', (['u'], {}), '(u)\n', (1800, 1803), False, 'from numpy import prod, log, ones, exp\n'), ((1818, 1824), 'numpy.log', 'log', (['v'], {}), '(v)\n', (1821, 1824), False, 'from numpy import prod, log, ones, exp\n'), ((1894, 1900), 'numpy.log', 'log', (['u'], {}), '(u)\n', (1897, 1900), False, 'from numpy import prod, log, ones, exp\n'), ((1915, 1921), 'numpy.log', 'log', (['v'], {}), '(v)\n', (1918, 1921), False, 'from numpy import prod, log, ones, exp\n'), ((2052, 2058), 'numpy.log', 'log', (['u'], {}), '(u)\n', (2055, 2058), False, 'from numpy import prod, log, ones, exp\n'), ((2073, 2079), 'numpy.log', 'log', (['v'], {}), '(v)\n', (2076, 2079), False, 'from numpy import prod, log, ones, exp\n')]
import cv2 import logging import numpy as np from typing import List, Union, Tuple, Dict from mot.utils.config import Config from mot.structures import Tracklet from mot.utils.io import ImagesCapture from mot.utils.hcc import hierarchical_cluster from mot.tracker import build_tracker, Tracker, TrackerState def _sample_tracklet_features(tracklet: Tracklet, n_feature_samples: int): recent_detections = tracklet.detection_history[-len(tracklet.feature_history):] p = np.array([detection.score for _, detection in recent_detections]) all_recent_features = np.stack([feature[1]['openreid'] for feature in tracklet.feature_history]) clusterIDs = hierarchical_cluster(all_recent_features, n_feature_samples, linkage_method='average', criterion='maxclust') tracklet_features = [] for clusterID in np.unique(clusterIDs): inds = np.where(clusterIDs == clusterID)[0] feature = np.sum((all_recent_features[inds].T * (p[inds] / np.sum(p[inds]))).T, axis=0, keepdims=True) tracklet_features.append(feature) tracklet_features = np.vstack(tracklet_features) print('Shrinking target #{}\'s {} features into {}'.format(tracklet.id, len(M), len(tracklet_features))) return tracklet_features class Identity: def __init__(self, globalID: int, camID: int, localID: int, tracklet: Tracklet, n_feature_samples: int = 8, max_cluster_distance: float = 0.1): self.globalID: int = globalID self.end_time: int = tracklet.detection_history[-1][0] self.tracklets: Dict[Tuple[int, int], Tracklet] = {(camID, localID): tracklet} self.max_cluster_distance = max_cluster_distance self.n_feature_samples: int = n_feature_samples recent_detections = tracklet.detection_history[-len(tracklet.feature_history):] detecton_scores = np.array([detection.score for _, detection in recent_detections]) best_ind = int(np.argmax(detecton_scores)) self.images: Dict[int, np.ndarray] = {camID: tracklet.feature_history[best_ind][1]['patch'].copy()} if tracklet.sample_features is None: tracklet.update_sample_features() self.features = tracklet.sample_features del tracklet.feature_history del tracklet.feature def merge(self, others: List): for other in others: for k, v in other.tracklet_dict.items(): self.tracklets[k] = v self.end_time = max(self.end_time, v.detection_history[-1][0]) return self def add_tracklet(self, tracklet: Tracklet, camID: int): tracklet.globalID = self.globalID self.tracklets[(camID, tracklet.id)] = tracklet self.end_time = max(self.end_time, tracklet.last_active_frame_num) if tracklet.id not in self.images: recent_detections = tracklet.detection_history[-len(tracklet.feature_history):] detecton_scores = np.array([detection.score for _, detection in recent_detections]) best_ind = int(np.argmax(detecton_scores)) self.images[camID] = tracklet.feature_history[best_ind][1]['patch'].copy() def is_active(self): for _, tracklet in self.tracklets.items(): if not tracklet.is_finished(): return True return False class MCTracker: # Infinite distance between local tracklets. INF = 1 def __init__(self, stracker_config: Config, captures: Dict[int, Union[ImagesCapture, cv2.VideoCapture]], cluster_freq: int = 60, max_ttl: int = 6000, max_local_overlap: int = 10, max_reid_distance: float = 0.25, max_cluster_distance: float = 0.1, n_feature_samples: int = 8): # Single camera tracker for all cameras. self.stracker: Tracker = build_tracker(stracker_config) # Tracker states for switching. self.stracker_states: Dict[int, TrackerState] = {camID: TrackerState() for camID, _ in captures.items()} # Corresponding captures (ImagesCapture or cv2.VideoCapture objects). self.captures: Dict[int, Union[ImagesCapture, cv2.VideoCapture]] = captures # Global tracklet pool. globalID => Identity. self.identity_pool: Dict[int, Identity] = {} # Global ID for allocation self.max_id: int = 0 # Global frame number. self.frame_num: int = 0 # Frequency to perform global clustering. self.cluster_freq: int = cluster_freq # Maximum time-to-live of any tracklet. self.max_ttl: int = max_ttl # Maximum local overlap time. self.max_local_overlap = max_local_overlap # Re-identification distance threshold. self.max_reid_distance = max_reid_distance # Local clustering distance threshold. self.max_cluster_distance = max_cluster_distance # Number of feature samples for each new identity self.n_feature_samples = n_feature_samples # Feature gallery (instead of image gallery) self.feature_gallery = np.ndarray((0, 256), dtype=np.float) # Corresponding IDs for each line of feature gallery self.id_gallery = np.ndarray((0,), dtype=np.int) # Logger self.logger: logging.Logger = logging.getLogger('MTMCT') def tick(self): self.frame_num += 1 for camID, cap in self.captures.items(): ret, frame = cap.read() if not ret: return False self.stracker.state = self.stracker_states[camID] self.stracker.tick(frame) self.update_identity_pool() if self.frame_num % self.cluster_freq == 0: # self.update_tracklet_features() self.query_identities() return True def update_identity_pool(self): """ Update identities with new tracklets added, or initiate new identities with single-cam tracklets. """ for camID, stracker_state in self.stracker_states.items(): while len(stracker_state.tracklets_finished) > 0: tracklet = stracker_state.tracklets_finished.pop() if tracklet.globalID >= 0: # Tracklet has been re-identified identity = self.identity_pool[tracklet.globalID] # Update Identity features using this tracklet with randomly chosen features # recent_detections = tracklet.detection_history[-len(tracklet.feature_history):] # p = np.array([detection.score for _, detection in recent_detections]) # p = p / np.sum(p) # inds = np.random.choice(range(len(tracklet.feature_history)), self.n_feature_samples, replace=False, # p=p) # new_features = np.stack([tracklet.feature_history[ind][1]['openreid'].copy() for ind in inds]) # New update method: Shrink the feature history size by HCC if tracklet.sample_features is None: tracklet.update_sample_features() identity.features = np.vstack((identity.features, tracklet.sample_features)) else: # Tracklet hasn't been re-identified yet, start a new identity if tracklet.time_lived >= self.n_feature_samples: self.max_id += 1 tracklet.globalID = self.max_id self.identity_pool[self.max_id] = Identity(self.max_id, camID, tracklet.id, tracklet, n_feature_samples=self.n_feature_samples) self.logger.info('Initiating global ID #{} from tracklet (cam = {}, localID = {})'.format( self.max_id, camID, tracklet.id )) # def update_gallery_features(self): # """ # Update feature gallery and corresponding features for queries. # """ # if len(self.identity_pool) == 0: # return # features, globalIDs = [], [] # for globalID, identity in self.identity_pool.items(): # features.append(identity.features) # globalIDs.extend([globalID] * len(identity.features)) # self.feature_gallery = np.vstack(features) # self.id_gallery = np.array(globalIDs) # assert len(self.feature_gallery) == len(self.id_gallery) def clear_inactive_identities(self): """ Clear old identities. """ globalIDs = list(self.identity_pool.keys()) end_times = np.array([(self.frame_num if identity.is_active() else identity.end_time) for _, identity in self.identity_pool.items()]) inds_to_clear = np.where(self.frame_num - end_times > self.max_ttl)[0] inds_to_clear = np.sort(inds_to_clear)[::-1] identities = [] for ind in inds_to_clear: globalID = globalIDs[int(ind)] identities.append((globalID, self.identity_pool.pop(globalID))) return identities def terminate(self): for camID, state in self.stracker_states.items(): self.stracker.state = state self.stracker.terminate() self.update_identity_pool() # self.update_gallery_features() self.query_identities(query_all=True) def query_identities(self, query_all: bool = False): if len(self.identity_pool) == 0: return camIDs = [] tracklets = [] M = [] # Build up query features for i, (camID, state) in enumerate(self.stracker_states.items()): for tracklet in state.tracklets_active: # Only consider tracklets that are long enough if tracklet.globalID == -1 and (query_all or len(tracklet.feature_history) >= self.n_feature_samples): camIDs.append(camID) tracklets.append(tracklet) # Sample features from feature history if tracklet.sample_features is None: tracklet.update_sample_features() tracklet_features = tracklet.sample_features dists = [] for j, (globalID, identity) in enumerate(self.identity_pool.items()): dists.append(np.average(1 - np.matmul(tracklet_features, identity.features.T).reshape(-1))) for key, other in identity.tracklet_dict.items(): # No long overlap allowed if tracklet.time_overlap(other) > self.max_local_overlap: dists[-1] = 1 break M.append(dists) # Perform greedy matching M = np.array(M) flattened = np.reshape(M, (-1)) inds = list(np.argsort(flattened)) row_ind, col_ind = [], [] for ind in inds: if flattened[ind] > self.max_reid_distance: break row, col = ind // len(self.identity_pool), ind % len(self.identity_pool) if row not in row_ind and col not in col_ind: row_ind.append(row) col_ind.append(col) # Merge tracklets into identities globalIDs = list(self.identity_pool.keys()) for row, col in zip(row_ind, col_ind): identity = self.identity_pool[globalIDs[col]] self.logger.info( 'Local tracklet (cam = {}, localID = {}) matches global ID {} (distance = {})'.format(camIDs[row], tracklets[ row].id, identity.globalID, M[row][col])) identity.add_tracklet(tracklets[row], camIDs[row]) def _time_overlap(self, period1: Tuple[int, int], period2: Tuple[int, int]): overlap = min(period2[1], period1[1]) - max(period2[0], period1[0]) return overlap if overlap > 0 else 0 def _cosine_distance(self, vector1, vector2): return 1 - np.dot(vector1, vector2) / ((np.linalg.norm(vector1) * np.linalg.norm(vector2)) + 1e-16) def _identity_distance(self, identity1: Identity, identity2: Identity): for (cam1, localID1), tracklet1 in identity1.tracklets.items(): for (cam2, localID2), tracklet2 in identity2.tracklets.items(): if cam1 == cam2 and self._time_overlap( (tracklet1.detection_history[0][0], tracklet1.detection_history[-1][0]), (tracklet2.detection_history[0][0], tracklet2.detection_history[-1][0]) ) > self.max_local_overlap: return self.INF features1 = [tracklet.feature['openreid'] for (_, _), tracklet in identity1.tracklets.items()] features2 = [tracklet.feature['openreid'] for (_, _), tracklet in identity2.tracklets.items()] return max( [max([self._cosine_distance(feature1, feature2) for feature2 in features2]) for feature1 in features1])
[ "logging.getLogger", "numpy.reshape", "numpy.unique", "numpy.where", "numpy.sort", "mot.utils.hcc.hierarchical_cluster", "numpy.argmax", "numpy.linalg.norm", "numpy.argsort", "numpy.array", "numpy.stack", "numpy.dot", "numpy.ndarray", "numpy.vstack", "mot.tracker.TrackerState", "numpy....
[((478, 543), 'numpy.array', 'np.array', (['[detection.score for _, detection in recent_detections]'], {}), '([detection.score for _, detection in recent_detections])\n', (486, 543), True, 'import numpy as np\n'), ((571, 645), 'numpy.stack', 'np.stack', (["[feature[1]['openreid'] for feature in tracklet.feature_history]"], {}), "([feature[1]['openreid'] for feature in tracklet.feature_history])\n", (579, 645), True, 'import numpy as np\n'), ((664, 777), 'mot.utils.hcc.hierarchical_cluster', 'hierarchical_cluster', (['all_recent_features', 'n_feature_samples'], {'linkage_method': '"""average"""', 'criterion': '"""maxclust"""'}), "(all_recent_features, n_feature_samples, linkage_method\n ='average', criterion='maxclust')\n", (684, 777), False, 'from mot.utils.hcc import hierarchical_cluster\n'), ((859, 880), 'numpy.unique', 'np.unique', (['clusterIDs'], {}), '(clusterIDs)\n', (868, 880), True, 'import numpy as np\n'), ((1112, 1140), 'numpy.vstack', 'np.vstack', (['tracklet_features'], {}), '(tracklet_features)\n', (1121, 1140), True, 'import numpy as np\n'), ((1878, 1943), 'numpy.array', 'np.array', (['[detection.score for _, detection in recent_detections]'], {}), '([detection.score for _, detection in recent_detections])\n', (1886, 1943), True, 'import numpy as np\n'), ((3819, 3849), 'mot.tracker.build_tracker', 'build_tracker', (['stracker_config'], {}), '(stracker_config)\n', (3832, 3849), False, 'from mot.tracker import build_tracker, Tracker, TrackerState\n'), ((5064, 5100), 'numpy.ndarray', 'np.ndarray', (['(0, 256)'], {'dtype': 'np.float'}), '((0, 256), dtype=np.float)\n', (5074, 5100), True, 'import numpy as np\n'), ((5188, 5218), 'numpy.ndarray', 'np.ndarray', (['(0,)'], {'dtype': 'np.int'}), '((0,), dtype=np.int)\n', (5198, 5218), True, 'import numpy as np\n'), ((5274, 5300), 'logging.getLogger', 'logging.getLogger', (['"""MTMCT"""'], {}), "('MTMCT')\n", (5291, 5300), False, 'import logging\n'), ((10919, 10930), 'numpy.array', 'np.array', (['M'], {}), '(M)\n', (10927, 10930), True, 'import numpy as np\n'), ((10951, 10968), 'numpy.reshape', 'np.reshape', (['M', '(-1)'], {}), '(M, -1)\n', (10961, 10968), True, 'import numpy as np\n'), ((897, 930), 'numpy.where', 'np.where', (['(clusterIDs == clusterID)'], {}), '(clusterIDs == clusterID)\n', (905, 930), True, 'import numpy as np\n'), ((1967, 1993), 'numpy.argmax', 'np.argmax', (['detecton_scores'], {}), '(detecton_scores)\n', (1976, 1993), True, 'import numpy as np\n'), ((2965, 3030), 'numpy.array', 'np.array', (['[detection.score for _, detection in recent_detections]'], {}), '([detection.score for _, detection in recent_detections])\n', (2973, 3030), True, 'import numpy as np\n'), ((3954, 3968), 'mot.tracker.TrackerState', 'TrackerState', ([], {}), '()\n', (3966, 3968), False, 'from mot.tracker import build_tracker, Tracker, TrackerState\n'), ((8858, 8909), 'numpy.where', 'np.where', (['(self.frame_num - end_times > self.max_ttl)'], {}), '(self.frame_num - end_times > self.max_ttl)\n', (8866, 8909), True, 'import numpy as np\n'), ((8937, 8959), 'numpy.sort', 'np.sort', (['inds_to_clear'], {}), '(inds_to_clear)\n', (8944, 8959), True, 'import numpy as np\n'), ((10991, 11012), 'numpy.argsort', 'np.argsort', (['flattened'], {}), '(flattened)\n', (11001, 11012), True, 'import numpy as np\n'), ((3058, 3084), 'numpy.argmax', 'np.argmax', (['detecton_scores'], {}), '(detecton_scores)\n', (3067, 3084), True, 'import numpy as np\n'), ((12512, 12536), 'numpy.dot', 'np.dot', (['vector1', 'vector2'], {}), '(vector1, vector2)\n', (12518, 12536), True, 'import numpy as np\n'), ((7168, 7224), 'numpy.vstack', 'np.vstack', (['(identity.features, tracklet.sample_features)'], {}), '((identity.features, tracklet.sample_features))\n', (7177, 7224), True, 'import numpy as np\n'), ((1001, 1016), 'numpy.sum', 'np.sum', (['p[inds]'], {}), '(p[inds])\n', (1007, 1016), True, 'import numpy as np\n'), ((12541, 12564), 'numpy.linalg.norm', 'np.linalg.norm', (['vector1'], {}), '(vector1)\n', (12555, 12564), True, 'import numpy as np\n'), ((12567, 12590), 'numpy.linalg.norm', 'np.linalg.norm', (['vector2'], {}), '(vector2)\n', (12581, 12590), True, 'import numpy as np\n'), ((10474, 10523), 'numpy.matmul', 'np.matmul', (['tracklet_features', 'identity.features.T'], {}), '(tracklet_features, identity.features.T)\n', (10483, 10523), True, 'import numpy as np\n')]
import numpy as np def R_cam_imu_matrix(): # IMU origo/pos given in camera coordinate imuOrigo_cam = np.array([0.71, 1.34, -3.53]) print("See geogebra sketch\n") # Rotation matrix to rotation IMU to camera # First rotate yaw of 8.303 degrees def R_z(yaw_deg): y = yaw_deg * np.pi / 180 return np.array([ [np.cos(y), -np.sin(y), 0], [np.sin(y), np.cos(y), 0], [0, 0, 1]]) R_zxy_xyz = np.array([ [0, 1, 0], [0, 0, 1], [1, 0, 0]]) print("Array x vector given in IMU, this can be ferries forward acceleration:\t", end="") xVec_imu = np.array([3.60000, 0.10000, -1.3400]) # camera origo given in imu print(xVec_imu) R_cam_imu = R_zxy_xyz @ R_z(-13) print("Same vector given in camera: \t\t\t\t\t\t", end="") print(R_cam_imu @ xVec_imu) print("Use this to rotate IMU acc data and euler angles") # RTK origo given in IMU rtkOrigo_imu = np.array([-0.025, 0.1, 0.06]) print("Assume that they have same origo, too small offset") return R_cam_imu, rtkOrigo_imu, R_zxy_xyz
[ "numpy.sin", "numpy.array", "numpy.cos" ]
[((111, 140), 'numpy.array', 'np.array', (['[0.71, 1.34, -3.53]'], {}), '([0.71, 1.34, -3.53])\n', (119, 140), True, 'import numpy as np\n'), ((485, 528), 'numpy.array', 'np.array', (['[[0, 1, 0], [0, 0, 1], [1, 0, 0]]'], {}), '([[0, 1, 0], [0, 0, 1], [1, 0, 0]])\n', (493, 528), True, 'import numpy as np\n'), ((664, 691), 'numpy.array', 'np.array', (['[3.6, 0.1, -1.34]'], {}), '([3.6, 0.1, -1.34])\n', (672, 691), True, 'import numpy as np\n'), ((996, 1025), 'numpy.array', 'np.array', (['[-0.025, 0.1, 0.06]'], {}), '([-0.025, 0.1, 0.06])\n', (1004, 1025), True, 'import numpy as np\n'), ((356, 365), 'numpy.cos', 'np.cos', (['y'], {}), '(y)\n', (362, 365), True, 'import numpy as np\n'), ((396, 405), 'numpy.sin', 'np.sin', (['y'], {}), '(y)\n', (402, 405), True, 'import numpy as np\n'), ((411, 420), 'numpy.cos', 'np.cos', (['y'], {}), '(y)\n', (417, 420), True, 'import numpy as np\n'), ((372, 381), 'numpy.sin', 'np.sin', (['y'], {}), '(y)\n', (378, 381), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue Dec 25 13:10:35 2018 @author: mpnun """ import random import numpy as np class Player: def __init__(self,name = 'Bob',team=1): self.name = name self.team = team def take_turn(self,board): #print(self.name + ' is taking his trun') spot_to_take = self.choose_spot(board) board.states[spot_to_take] = self.team board.open_spots.remove(spot_to_take) def choose_spot(self,board): spot_to_take = random.choice(board.open_spots) return spot_to_take class HumanPlayer(Player): def __init__(self,name = 'Bob',team=1): Player.__init__(self, name = name, team=team) def choose_spot(self,board): no_legal_move = True while no_legal_move: spot_to_take = int(input('Spot to take: ')) if spot_to_take in board.open_spots: no_legal_move = False return spot_to_take class AIPlayer(Player): def __init__(self,name = 'Bob',team=1): Player.__init__(self, name = name, team=team) def choose_spot(self,board): Q_vals = np.zeros(len(board.open_spots)) for ind, possible_move in enumerate(board.open_spots): new_board = np.copy(board.states) new_board[possible_move] = self.team # make the theoretical move Q_vals[ind] = self.compute_Q(new_board) # value of new board spot_to_take = board.open_spots[np.argmax(Q_vals)] return spot_to_take def compute_Q(self,new_board): return 0.5
[ "numpy.copy", "random.choice", "numpy.argmax" ]
[((523, 554), 'random.choice', 'random.choice', (['board.open_spots'], {}), '(board.open_spots)\n', (536, 554), False, 'import random\n'), ((1322, 1343), 'numpy.copy', 'np.copy', (['board.states'], {}), '(board.states)\n', (1329, 1343), True, 'import numpy as np\n'), ((1574, 1591), 'numpy.argmax', 'np.argmax', (['Q_vals'], {}), '(Q_vals)\n', (1583, 1591), True, 'import numpy as np\n')]
#Want C(abcspectra, metaframe) from pandas import Series, DataFrame import skspec.core.utilities as pvutils import skspec.config as pvconfig from pandas.core.indexing import _LocIndexer from skspec.units.abcunits import IUnit, Unit, UnitError import numpy as np # Exceptions # ---------- class SpecError(Exception): """ """ class SpecIndexError(SpecError): """ For indexing operations in particular.""" # Primary Object # -------------- class ABCSpectra(object): """ Generic methods shared by all skspec spectra objects. INCLUDING SPECTRUM. For example, printing out html orientation, and defining the "nearby" slicer. The goal is to separate out methods that are intended to be customized, but might be buried on the already heavy Spectra object. """ def __repr__(self, *args, **kwargs): header = self._header return ''.join(header)+'\n'+self._frame.__repr__()+' ID: %s' % id(self) def _repr_html_(self, *args, **kwargs): """ Ipython Notebook HTML appearance basically. This only generates the colored header; under the hood, self._frame._repr_html_ calculates the table, including the proper size for optimal viewing and so on. """ # Change output based on Spectra vs. Spectrum obj = self._frame # Series doesn't have _repr_html, so actually call DF's if isinstance(obj, Series): obj = DataFrame(obj, columns=[self.specifier]) # Call DataFrame _repr_html dfhtml = obj._repr_html_(*args, **kwargs) return ('<h4>%s</h4>' % ''.join(self._header_html)) +'<br>'+ dfhtml @property def _spec_span(self): return pvutils._compute_span(self.index, with_unit=False) @property def _var_span(self): return pvutils._compute_span(self.columns, with_unit=False) @property def _intensity_span(self): return '%s - %s' % (self.min().min(), self.max().max()) @property def _header(self): """ Header for string printout """ delim = pvconfig.HEADERDELIM # Certain methods aren't copying this correctly. Delete later if fix ftunit = pvutils.safe_lookup(self, 'full_varunit') spunit = pvutils.safe_lookup(self, 'full_specunit') iunit = pvutils.safe_lookup(self, 'full_iunit') header = "*%s*%s[%s X %s]%sIunit: %s\n" % \ (self.name, delim, ftunit, spunit, delim, iunit) return header @property def _header_html(self): """ Header for html printout """ delim = pvconfig.HEADERHTMLDELIM if self.ndim > 1: colorshape = '<font color="#0000CD">(%s X %s)</font>' % (self.shape) else: colorshape = '<font color="#0000CD"> (%s)</font>' % (self.shape) ftunit = pvutils.safe_lookup(self, 'full_varunit') spunit = pvutils.safe_lookup(self, 'full_specunit') iunit = pvutils.safe_lookup(self, 'full_iunit') header = "%s&nbsp%s%s [%s X %s]%sIunit:&nbsp%s" % \ (self.name, colorshape, delim, ftunit, spunit, delim, iunit) return header @property #Make log work with this eventually? def full_name(self): """ Timespectra:name or Timespectra:unnamed. Useful for scripts mostly """ outname = getattr(self, 'name', 'unnamed') return '%s:%s' % (self.__class__.__name__, self.name) # Indexer _nearby=None @property def nearby(self, *args, **kwargs): """ Slicers similiar to loc that allows for nearby value slicing. It also would be posslbe to define operations on this through bool logic like df[(x<50) & (X>50), but that requires creating a new indexer]""" if self._nearby is None: try: self._nearby=_NearbyIndexer(self) # New versions of _IXIndexer require "name" attribute. except TypeError as TE: self._nearby=_NearbyIndexer(self, 'nearby') return self._nearby @property def full_iunit(self): return self._iunit.full @property def iunit(self): return self._iunit.short @iunit.setter def iunit(self, unit): """ Set iunit from string or Unit object. If from string, short and full are same, symbol='I' """ if isinstance(unit, basestring): self._iunit = IUnit(short=unit, full=unit, #Short and full, same thing ) elif isinstance(unit, Unit): #Don't force IUnit type; users may not care self._iunit = unit # Better than just iunit = None for plotting api? elif not unit: self._iunit = IUnit() #Default/null else: raise UnitError('Unit must be a string, IUnit type or None!') # Nearby Indexer # -------------- class _NearbyIndexer(_LocIndexer): """ Index by location, but looks for nearest values. Warning: not all use cases may be handled properly; this is predominantly for range slices eg (df.nearby[50.0:62.4]), ie looking at a range of wavelengths. For more on various cases of selection by label: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-label Tries to handle all the cases of loc: A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index. This use is not an integer position along the index) A list or array of labels ['a', 'b', 'c'] A slice object with labels 'a':'f' (note that contrary to usual python slices, both the start and the stop are included!) A boolean array """ def _getitem_axis(self, key, axis=0, validate_iterable=False): """ This is the only method that needs overwritten to preserve all _LocIndexer functionality. Just need to change aspects where it would fail if key not found in index and replace with a key lookup. This is better than overwriting __getitem__ because need axis knowledge for slicing like [50:55, 90:95]... """ labels = self.obj._get_axis(axis) values = labels.values #Necessary for subtraciton in find_nearest def _nearest(v): """ Find the neareast value in the Index (cast to array type); necessary because diff (ie subtraction) is not defined on Index in the way used here. """ vmin, vmax = min(values), max(values) if v < vmin: raise SpecIndexError("%s is less than Index min value of %s" % (v, vmin)) elif v > vmax: raise SpecIndexError("%s is greater than Index max value of %s" % (v, vmax)) return values[(np.abs(values - v)).argmin()] if isinstance(key, slice): start, stop, step = key.start, key.stop, key.step if key.start: start = _nearest(key.start) if key.stop: stop = _nearest(key.stop) key = slice(start, stop, key.step) self._has_valid_type(key, axis) out = self._get_slice_axis(key, axis=axis) elif _is_bool_indexer(key): raise NotImplementedError('Bool indexing not supported by _Nearby Indexer') # return self._getbool_axis(key, axis=axis) elif _is_list_like(key): # GH 7349 # possibly convert a list-like into a nested tuple # but don't convert a list-like of tuples # I Just chose to not support this case work if isinstance(labels, MultiIndex): raise SpecIndexError("MultiIndex nearby slicing not supported.") # an iterable multi-selection (eg nearby[[50, 55, 65]]) if not (isinstance(key, tuple) and isinstance(labels, MultiIndex)): if hasattr(key, 'ndim') and key.ndim > 1: raise ValueError('Cannot index with multidimensional key') if validate_iterable: self._has_valid_type(key, axis) # WILL OUTPUT WRONG INDEX STUFF LIKE TIMEINDEX # NEED TO FIX raise NotImplementedError("See GH #107") out = self._getitem_iterable(key, axis=axis) # nested tuple slicing if _is_nested_tuple(key, labels): locs = labels.get_locs(key) indexer = [ slice(None) ] * self.ndim indexer[axis] = locs out = self.obj.iloc[tuple(indexer)] # fall thru to straight lookup else: key = _nearest(key) self._has_valid_type(key, axis) out = self._get_label(key, axis=axis) if isinstance(out, DataFrame): #If Series or Series subclass out = self.obj._transfer(out) # Hack becase Series aren't generated with these and # self._getitem_lowerdim() will call this recursively elif issubclass(out.__class__, Series): out.nearby = self.obj.nearby return out
[ "skspec.core.utilities.safe_lookup", "numpy.abs", "pandas.DataFrame", "skspec.core.utilities._compute_span", "skspec.units.abcunits.IUnit", "skspec.units.abcunits.UnitError" ]
[((1688, 1738), 'skspec.core.utilities._compute_span', 'pvutils._compute_span', (['self.index'], {'with_unit': '(False)'}), '(self.index, with_unit=False)\n', (1709, 1738), True, 'import skspec.core.utilities as pvutils\n'), ((1793, 1845), 'skspec.core.utilities._compute_span', 'pvutils._compute_span', (['self.columns'], {'with_unit': '(False)'}), '(self.columns, with_unit=False)\n', (1814, 1845), True, 'import skspec.core.utilities as pvutils\n'), ((2173, 2214), 'skspec.core.utilities.safe_lookup', 'pvutils.safe_lookup', (['self', '"""full_varunit"""'], {}), "(self, 'full_varunit')\n", (2192, 2214), True, 'import skspec.core.utilities as pvutils\n'), ((2230, 2272), 'skspec.core.utilities.safe_lookup', 'pvutils.safe_lookup', (['self', '"""full_specunit"""'], {}), "(self, 'full_specunit')\n", (2249, 2272), True, 'import skspec.core.utilities as pvutils\n'), ((2287, 2326), 'skspec.core.utilities.safe_lookup', 'pvutils.safe_lookup', (['self', '"""full_iunit"""'], {}), "(self, 'full_iunit')\n", (2306, 2326), True, 'import skspec.core.utilities as pvutils\n'), ((2892, 2933), 'skspec.core.utilities.safe_lookup', 'pvutils.safe_lookup', (['self', '"""full_varunit"""'], {}), "(self, 'full_varunit')\n", (2911, 2933), True, 'import skspec.core.utilities as pvutils\n'), ((2949, 2991), 'skspec.core.utilities.safe_lookup', 'pvutils.safe_lookup', (['self', '"""full_specunit"""'], {}), "(self, 'full_specunit')\n", (2968, 2991), True, 'import skspec.core.utilities as pvutils\n'), ((3006, 3045), 'skspec.core.utilities.safe_lookup', 'pvutils.safe_lookup', (['self', '"""full_iunit"""'], {}), "(self, 'full_iunit')\n", (3025, 3045), True, 'import skspec.core.utilities as pvutils\n'), ((1432, 1472), 'pandas.DataFrame', 'DataFrame', (['obj'], {'columns': '[self.specifier]'}), '(obj, columns=[self.specifier])\n', (1441, 1472), False, 'from pandas import Series, DataFrame\n'), ((4505, 4533), 'skspec.units.abcunits.IUnit', 'IUnit', ([], {'short': 'unit', 'full': 'unit'}), '(short=unit, full=unit)\n', (4510, 4533), False, 'from skspec.units.abcunits import IUnit, Unit, UnitError\n'), ((4831, 4838), 'skspec.units.abcunits.IUnit', 'IUnit', ([], {}), '()\n', (4836, 4838), False, 'from skspec.units.abcunits import IUnit, Unit, UnitError\n'), ((4886, 4941), 'skspec.units.abcunits.UnitError', 'UnitError', (['"""Unit must be a string, IUnit type or None!"""'], {}), "('Unit must be a string, IUnit type or None!')\n", (4895, 4941), False, 'from skspec.units.abcunits import IUnit, Unit, UnitError\n'), ((6871, 6889), 'numpy.abs', 'np.abs', (['(values - v)'], {}), '(values - v)\n', (6877, 6889), True, 'import numpy as np\n')]
# Copyright (c) 2019-2020 The Regents of the University of Michigan # This file is part of the fedorov project, released under the BSD 3-Clause License. # Maintainer: <NAME> import numpy as np import pandas as pd import json import pickle import spglib as spg import copy import re import rowan import os def json_key_to_int(x): if isinstance(x, dict): return {int(k): v for k, v in x.items()} return x def wrap(basis_vectors): """Wrap fractional coordinates within a unitcell based on periodic boundary. :param basis_vectors: fractional coordinates for particle positions in N by 3 numpy array :type basis_vectors: np.ndarray :return: wrapped basis_vectors :rtype: np.ndarray """ basis_vectors[basis_vectors >= 1.0] -= 1 basis_vectors[basis_vectors < 0.0] += 1 return basis_vectors def convert_to_box(lattice_vectors): """Convert lattice vectors to box parameter: Lx, Ly, Lz, xy, xz, yz. :param lattice_vectors: 3 by 3 numpy array of lattice vectors [a1, a2, a3] :type lattice_vectors: np.ndarray :return: Lx, Ly, Lz, xy, xz, yz :rtype: float """ v0 = lattice_vectors[0, :] v1 = lattice_vectors[1, :] v2 = lattice_vectors[2, :] Lx = np.sqrt(np.dot(v0, v0)) a2x = np.dot(v0, v1) / Lx Ly = np.sqrt(np.dot(v1, v1) - a2x * a2x) xy = a2x / Ly v0xv1 = np.cross(v0, v1) v0xv1mag = np.sqrt(np.dot(v0xv1, v0xv1)) Lz = np.dot(v2, v0xv1) / v0xv1mag a3x = np.dot(v0, v2) / Lx xz = a3x / Lz yz = (np.dot(v1, v2) - a2x * a3x) / (Ly * Lz) return Lx, Ly, Lz, xy, xz, yz def convert_to_vectors(Lx, Ly, Lz, xy, xz, yz): """Convert box parameter: Lx, Ly, Lz, xy, xz, yz to lattice vectors [a1, a2, a3]. :param Lx: :type Lx: float :param Ly: :type Ly: float :param Lz: :type Lz: float :param xy: :type xy: float :param xz: :type xz: float :param yz: :type yz: float :return: lattice_vectors in form [a1, a2, a3] :rtype: np.ndarray """ lattice_vectors = np.array([[Lx, 0, 0], [xy * Ly, Ly, 0], [xz * Lz, yz * Lz, Lz]]) return lattice_vectors def get_volumn(lattice_vectors): """Calculate volume of the unitcell :param lattice_vectors: 3 by 3 numpy array of lattice vectors [a1, a2, a3] :type lattice_vectors: np.ndarray :return: volume :rtype: float """ a1 = lattice_vectors[0, :] a2 = lattice_vectors[1, :] a3 = lattice_vectors[2, :] return abs(np.cross(a1, a2).dot(a3)) def fractional_to_cartesian(basis_vectors, lattice_vectors): """Convert fractional coordinates to cartesian coordinates. :param basis_vectors: N by 3 numpy array of basis vectors :type basis_vectors: np.ndarray :param lattice_vectors: 3 by 3 numpy array of lattice vectors [a1, a2, a3] :type lattice_vectors: np.ndarray :return: N by 3 numpy array of cartesiann coordinates :rtype: np.ndarray """ return basis_vectors.dot(lattice_vectors) def translate_to_vector(a=1, b=1, c=1, alpha=np.pi / 2, beta=np.pi / 2, gamma=np.pi / 2): """Convert box parameters a, b, c, alpha, beta, gamma to lattice vectors [a1, a2, a3]. :param a: :type a: float :param b: :type b: float :param c: :type c: float :param alpha: :type alpha: float :param beta: :type beta: float :param gamma: :type gamma: float :return: lattice_vectors :rtype: np.ndarray """ # https://en.wikipedia.org/wiki/Fractional_coordinates cg = np.cos(gamma) sg = np.sin(gamma) ca = np.cos(alpha) cb = np.cos(beta) cy = (ca - cb * cg) / sg if (1 - ca * ca - cb * cb - cg * cg + 2 * ca * cb * cg) < 0: raise ValueError('Error: the box length and angle parameters provided are not feasible. ' 'Please not the unit used for angle paramters should be in unit of rad') cz = np.sqrt(1 - ca * ca - cb * cb - cg * cg + 2 * ca * cb * cg) / sg lattice_vectors = np.array([ [a, 0, 0], [b * cg, b * sg, 0], [c * cb, c * cy, c * cz] ]) return lattice_vectors def translate_to_vector_2D(a=1, b=1, theta=np.pi / 2): """Convert box parameters a, b, theta to lattice vectors [a1, a2]. :param a: :type a: float :param b: :type b: float :param theta: :type theta: float :return: lattice_vectors :rtype: np.ndarray """ lattice_vectors = np.array([ [a, 0], [b * np.cos(theta), b * np.sin(theta)] ]) return lattice_vectors # 2D systems class Oblique2D(object): """A class for constructing a 2D oblique unitcell This class provides method to initialize a 2D oblique unitcell """ lattice_params = {'a': 1, 'b': 1, 'theta': np.pi / 2} @classmethod def update_lattice_params(cls, user_lattice_params): params = copy.deepcopy(cls.lattice_params) for param, value in user_lattice_params.items(): if param in params: if value is not None: params[param] = value else: print('warning: {} is not required and not used to define this ' 'structure'.format(param)) return params @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a 2D oblique unitcell and return lattice vectors [a1, a2]. :param user_lattice_params: unit cell parameters, provide a, b, theta where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = translate_to_vector_2D(**params) return lattice_vectors class Rectangular2D(Oblique2D): """A class for constructing a 2D rectangular unitcell This class provides method to initialize a 2D rectangular unitcell """ lattice_params = {'a': 1, 'b': 1} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a 2D rectangular unitcell and return lattice vectors [a1, a2]. :param user_lattice_params: unit cell parameters, provide a, b, theta where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = np.array([ [params['a'], 0.0], [0.0, params['b']] ]) return lattice_vectors class Hexagonal2D(Oblique2D): """A class for constructing a 2D hexagonal unitcell This class provides method to initialize a 2D hexagonal unitcell """ lattice_params = {'a': 1} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a 2D hexagonal unitcell and return lattice vectors [a1, a2]. :param user_lattice_params: unit cell parameters, provide a, b, theta where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = np.array([ [params['a'], 0.0], [-0.5 * params['a'], params['a'] * np.sqrt(3) / 2] ]) return lattice_vectors class Square2D(Rectangular2D): """A class for constructing a 2D square unitcell This class provides method to initialize a 2D square unitcell """ lattice_params = {'a': 1} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a 2D square unitcell and return lattice vectors [a1, a2]. :param user_lattice_params: unit cell parameters, provide a, b, theta where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = np.array([ [params['a'], 0.0], [0.0, params['a']] ]) return lattice_vectors lattice_system_dict_2D = {'oblique': Oblique2D, 'rectangular': Rectangular2D, 'hexagonal': Hexagonal2D, 'square': Square2D} class PlaneGroup(object): """A class for plane group symmetry operation. This class provides method to initialize a crystal unit cell with plane group and Wyckoff possition information. :param plane_group_number: Plane group number between 1 and 17. :type plane_group_number: int :param print_info: Print plane group information upon initialization. :type print_info: bool """ dir_path = os.path.dirname(__file__) plane_group_info_dir = os.path.join(dir_path, 'crystal_data/plane_group_info.pickle') with open(plane_group_info_dir, 'rb') as f: plane_group_info_dict = pickle.load(f) plane_group_lattice_mapping_dir = os.path.join(dir_path, 'crystal_data/plane_group_lattice_mapping.json') with open(plane_group_lattice_mapping_dir, 'r') as f: plane_group_lattice_mapping = json.load(f, object_hook=json_key_to_int) def __init__(self, plane_group_number=1, print_info=False): if plane_group_number <= 0 or plane_group_number > 17: raise ValueError('plane_group_number must be an integer between 1 and 17') self.plane_group_number = plane_group_number self.lattice_type = self.plane_group_lattice_mapping[self.plane_group_number] self.lattice = lattice_system_dict_2D[self.lattice_type] info = self.plane_group_info_dict[plane_group_number] self.translations = info['translations'] self.rotations = info['rotations'] if print_info: print('Plane group number: {}\n'.format(plane_group_number), 'lattice type: {}\n'.format(self.lattice_type), 'Default parameters for lattice: {}'.format(self.lattice.lattice_params)) def get_basis_vectors(self, base_positions, base_type=[], base_quaternions=None, is_complete=False, apply_orientation=False): """Get the basis vectors for the defined crystall structure. :param base_positions: N by 2 np array of the Wyckoff postions :type base_positions: np.ndarray :param base_type: a list of string for particle type name :type base_type: list :param base_quaternions: N by 4 np array of quaternions, default None :type base_quaternions: np.ndarray :param is_complete: bool value to indicate if the positions are complete postions in a unitcell :type is_complete: bool :param apply_orientations: bool value to indicate if the space group symmetry should be applied to orientatioin :type apply_orientations: bool :return: basis_vectors :rtype: np.ndarray """ # check input accuracy if not isinstance(base_positions, np.ndarray) or len(base_positions.shape) == 1 \ or base_positions.shape[1] != 2: raise ValueError('base_positions must be an numpy array of shape Nx3') if apply_orientation: if not isinstance(base_quaternions, np.ndarray) or len(base_quaternions.shape) == 1 \ or base_quaternions.shape[1] != 4: raise ValueError('base_quaternions must be an numpy array of shape Nx4') if len(base_type): if not isinstance(base_type, list) or len(base_type) != base_positions.shape[0] \ or not all(isinstance(i, str) for i in base_type): raise ValueError('base_type must contain a list of type name the same length' 'as the number of basis positions') else: base_type = ['A'] * base_positions.shape[0] def _expand2d(matrix2d): matrix3d = np.identity(3) matrix3d[0:2, 0:2] = matrix2d return matrix3d threshold = 1e-6 reflection_exist = False for i in range(0, len(self.rotations)): # Generate the new set of positions from the base pos = wrap(self.rotations[i].dot(base_positions.T).T + self.translations[i]) if apply_orientation: if np.linalg.det(self.rotations[i]) == 1: quat_rotate = rowan.from_matrix(_expand2d(self.rotations[i]), require_orthogonal=False) quat = rowan.multiply(quat_rotate, base_quaternions) else: quat = base_quaternions reflection_exist = True if i == 0: positions = pos type_list = copy.deepcopy(base_type) if apply_orientation: quaternions = quat else: pos_comparisons = pos - positions[:, np.newaxis, :] norms = np.linalg.norm(pos_comparisons, axis=2) comps = np.all(norms > threshold, axis=0) positions = np.append(positions, pos[comps], axis=0) type_list += [x for x, y in zip(base_type, comps) if y] if apply_orientation: quaternions = np.append(quaternions, quat[comps], axis=0) if norms.min() < threshold: print('Orientation quaterions may have multiple values for the same ' 'particle postion under the symmetry operation for this space group ' 'and is not well defined, only the first occurance is used.') if reflection_exist: print('Warning: reflection operation is included in this space group, ' 'and is ignored for quaternion calculation.') if is_complete and len(positions) != len(base_positions): raise ValueError('the complete basis postions vector does not match the space group ' 'chosen. More positions are generated based on the symmetry operation ' 'within the provided space group') if apply_orientation: return wrap(positions), type_list, quaternions else: return wrap(positions), type_list def get_lattice_vectors(self, **user_lattice_params): """Initialize the unitcell and return lattice vectors [a1, a2]. :param user_lattice_params: unit cell parameters, provide a, b, theta where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ return self.lattice.get_lattice_vectors(**user_lattice_params) # 3D systems class Triclinic(object): """A class for constructing a triclinic unitcell.""" Pearson = 'a' dimensions = 3 lattice_params = {'a': 1, 'b': 1, 'c': 1, 'alpha': np.pi / 2, 'beta': np.pi / 2, 'gamma': np.pi / 2} @classmethod def update_lattice_params(cls, user_lattice_params): params = copy.deepcopy(cls.lattice_params) for param, value in user_lattice_params.items(): if param in params: if value is not None: params[param] = value else: print('warning: {} is not required and not used to define this ' 'structure'.format(param)) return params @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a triclinic unitcell and return lattice vectors [a1, a2, a3]. :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = translate_to_vector(**params) return lattice_vectors class Monoclinic(Triclinic): """A class for constructing a monoclinic unitcell This class provides method to initialize a monoclinic unitcell """ Pearson = 'm' lattice_params = {'a': 1, 'b': 1, 'c': 1, 'beta': np.pi / 2} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a monoclinic unitcell and return lattice vectors [a1, a2, a3]. :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = translate_to_vector(a=params['a'], b=params['b'], c=params['c'], beta=params['beta']) return lattice_vectors class Orthorhombic(Monoclinic): """A class for constructing a orthorhombic unitcell.""" Pearson = 'o' lattice_params = {'a': 1, 'b': 1, 'c': 1} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a orthorhombi unitcell and return lattice vectors [a1, a2, a3]. :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = np.array([ [params['a'], 0.0, 0.0], [0.0, params['b'], 0.0], [0.0, 0.0, params['c']] ]) return lattice_vectors class Tetragonal(Orthorhombic): """A class for constructing a tetragonal unitcell.""" Pearson = 't' lattice_params = {'a': 1, 'c': 1} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a tetragona unitcell and return lattice vectors [a1, a2, a3]. :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = np.array([ [params['a'], 0.0, 0.0], [0.0, params['a'], 0.0], [0.0, 0.0, params['c']] ]) return lattice_vectors class Hexagonal(Triclinic): """A class for constructing a hexagonal unitcell.""" Pearson = 'hP' lattice_params = {'a': 1, 'c': 1} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a hexagonal unitcell and return lattice vectors [a1, a2, a3]. :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = np.array([ [params['a'], 0.0, 0.0], [-0.5 * params['a'], np.sqrt(3.0) / 2.0 * params['a'], 0.0], [0.0, 0.0, params['c']] ]) return lattice_vectors class Rhombohedral(Triclinic): """A class for constructing a rhombohedral unitcell.""" Pearson = 'hR' lattice_params = {'a': 1, 'alpha': np.pi / 2} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a rhombohedral unitcell and return lattice vectors [a1, a2, a3]. :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = translate_to_vector(a=params['a'], b=params['a'], c=params['a'], alpha=params['alpha'], beta=params['alpha'], gamma=params['alpha']) return lattice_vectors class Cubic(Tetragonal): """A class for constructing a cubic unitcell.""" Pearson = 'c' lattice_params = {'a': 1} @classmethod def get_lattice_vectors(cls, **user_lattice_params): """Initialize a cubicc unitcell and return lattice vectors [a1, a2, a3]. :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ params = cls.update_lattice_params(user_lattice_params) lattice_vectors = np.array([ [params['a'], 0.0, 0.0], [0.0, params['a'], 0.0], [0.0, 0.0, params['a']] ]) return lattice_vectors lattice_system_dict_3D = {'triclinic': Triclinic, 'monoclinic': Monoclinic, 'orthorhombic': Orthorhombic, 'tetragonal': Tetragonal, 'hexagonal': Hexagonal, 'rhombohedral': Rhombohedral, 'cubic': Cubic} class SpaceGroup(object): """A class for space group symmetry operation. This class provides method to initialize a crystal unit cell with space group and Wyckoff possition information. :param space_group_number: Space group number between 1 and 230. :type space_group_number: int :param print_info: Print space group information upon initialization. :type print_info: bool """ dir_path = os.path.dirname(__file__) space_group_hall_mapping_dir = os.path.join(dir_path, 'crystal_data/space_group_hall_mapping.json') with open(space_group_hall_mapping_dir, 'r') as f: space_group_hall_mapping = json.load(f, object_hook=json_key_to_int) space_group_lattice_mapping_dir = os.path.join(dir_path, 'crystal_data/space_group_lattice_mapping.json') with open(space_group_lattice_mapping_dir, 'r') as f: space_group_lattice_mapping = json.load(f, object_hook=json_key_to_int) def __init__(self, space_group_number=1, print_info=False): if space_group_number <= 0 or space_group_number > 230: raise ValueError('space_group_number must be an integer between 1 and 230') self.space_group_number = space_group_number self.lattice_type = self.space_group_lattice_mapping[self.space_group_number] self.lattice = lattice_system_dict_3D[self.lattice_type] info = spg.get_symmetry_from_database(self.space_group_hall_mapping[space_group_number]) self.translations = info['translations'] self.rotations = info['rotations'] if print_info: print('Space group number: {}\n'.format(space_group_number), 'lattice type: {}\n'.format(self.lattice_type), 'Default parameters for lattice: {}'.format(self.lattice.lattice_params)) def get_basis_vectors(self, base_positions, base_type=[], base_quaternions=None, is_complete=False, apply_orientation=False): """Get the basis vectors for the defined crystall structure. :param base_positions: N by 3 np array of the Wyckoff postions :type base_positions: np.ndarray :param base_type: a list of string for particle type name :type base_type: list :param base_quaternions: N by 4 np array of quaternions, default None :type base_quaternions: np.ndarray :param is_complete: bool value to indicate if the positions are complete postions in a unitcell :type is_complete: bool :param apply_orientations: bool value to indicate if the space group symmetry should be applied to orientatioin :type apply_orientations: bool :return: basis_vectors :rtype: np.ndarray """ # check input accuracy if not isinstance(base_positions, np.ndarray) or len(base_positions.shape) == 1 \ or base_positions.shape[1] != 3: raise ValueError('base_positions must be an numpy array of shape Nx3') if apply_orientation: if not isinstance(base_quaternions, np.ndarray) or len(base_quaternions.shape) == 1 \ or base_quaternions.shape[1] != 4: raise ValueError('base_quaternions must be an numpy array of shape Nx4') if len(base_type): if not isinstance(base_type, list) or len(base_type) != base_positions.shape[0] \ or not all(isinstance(i, str) for i in base_type): raise ValueError('base_type must contain a list of type name the same length' 'as the number of basis positions') else: base_type = ['A'] * base_positions.shape[0] threshold = 1e-6 reflection_exist = False for i in range(0, len(self.rotations)): # Generate the new set of positions from the base pos = wrap(self.rotations[i].dot(base_positions.T).T + self.translations[i]) if apply_orientation: if np.linalg.det(self.rotations[i]) == 1: quat_rotate = rowan.from_matrix(self.rotations[i], require_orthogonal=False) quat = rowan.multiply(quat_rotate, base_quaternions) else: quat = base_quaternions reflection_exist = True if i == 0: positions = pos type_list = copy.deepcopy(base_type) if apply_orientation: quaternions = quat else: pos_comparisons = pos - positions[:, np.newaxis, :] norms = np.linalg.norm(pos_comparisons, axis=2) comps = np.all(norms > threshold, axis=0) positions = np.append(positions, pos[comps], axis=0) type_list += [x for x, y in zip(base_type, comps) if y] if apply_orientation: quaternions = np.append(quaternions, quat[comps], axis=0) if norms.min() < threshold: print('Orientation quaterions may have multiple values for the same ' 'particle postion under the symmetry operation for this space group ' 'and is not well defined, only the first occurance is used.') if reflection_exist: print('Warning: reflection operation is included in this space group, ' 'and is ignored for quaternion calculation.') if is_complete and len(positions) != len(base_positions): raise ValueError('the complete basis postions vector does not match the space group ' 'chosen. More positions are generated based on the symmetry operation ' 'within the provided space group') if apply_orientation: return wrap(positions), type_list, quaternions else: return wrap(positions), type_list def get_lattice_vectors(self, **user_lattice_params): """Initialize the unitcell and return lattice vectors [a1, a2, a3]. :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ return self.lattice.get_lattice_vectors(**user_lattice_params) class Prototype(object): """Crystal prototype class. This class uses the minimal necessay information needed to fully define a crystal structures with space group number, wyckoff postions(in letter name convention) and free parameters for each relavent wyckoff postions. :param space_group_number: space group number between 1 and 230 :type space_group_numbers: int :param wyckoff_site: wyckoff site letters included in the prototype :type wyckoff_site: str :param type_by_site: type name letter for each site set in wyckoff_sites :type type_by_site: str :param print_info: print space group information upon initialization :type print_info: bool """ dir_path = os.path.dirname(__file__) def __init__(self, space_group_number=1, wyckoff_site='', type_by_site='', print_info=False): if space_group_number > 230 or space_group_number < 1: raise ValueError('space_group_number must be an integer between 0 and 230, ' 'default = 1') if not isinstance(wyckoff_site, str) or not wyckoff_site.isalpha(): raise ValueError('wyckoff_postions must be string consists of all the Wyckoff ' 'postions letters, e.g. \'abcc\' denotes one set of Wyckoff postions ' 'for both a and b, and two sets at Wyckoff postion c') if type_by_site == '': type_by_site = 'A' * len(wyckoff_site) elif not isinstance(type_by_site, str) or len(type_by_site) != len(wyckoff_site) or \ not type_by_site.isalpha(): raise ValueError('type_by_site must be string consists of type name (A/B/C, etc)' 'for each Wyckoff site, default all particles with same type A ' 'if not provided') wyckoff_site_list = list(wyckoff_site.lower()) type_by_site = list(type_by_site.upper()) wyckoff_data_dir = os.path.join(self.dir_path, 'crystal_data/space_group_{}_Wyckoff' '_site_data.json'.format(space_group_number)) with open(wyckoff_data_dir, 'r') as f: full_wyckoff_positions = json.load(f) basis_params_list = [] order = 1 for site in wyckoff_site_list: pos = copy.deepcopy(full_wyckoff_positions[site]) pos = ''.join(pos) for letter in ('x', 'y', 'z'): if letter in pos: basis_params_list.append(letter + str(order)) order += 1 basis_params_value_list = [None] * len(basis_params_list) self.space_group_number = space_group_number self.space_group = SpaceGroup(space_group_number, print_info) self.wyckoff_site_list = wyckoff_site_list self.full_wyckoff_positions = full_wyckoff_positions self.type_by_site = type_by_site self.lattice_params = self.space_group.lattice.lattice_params self.basis_params = dict(zip(basis_params_list, basis_params_value_list)) if print_info: print('Wyckoff sites:{}\n'.format(wyckoff_site_list), 'Particle type for each Wyckoff sites:{}\n'.format(type_by_site), 'lattice parameters list:{}\n'.format(list(self.lattice_params)), 'basis parameters list:{}'.format(basis_params_list)) def update_basis_params(self, user_basis_params): params = copy.deepcopy(self.basis_params) for param, value in user_basis_params.items(): if param in params: if value is not None: params[param] = value else: print('warning: {} is not required and not used to define this ' 'structure'.format(param)) for value in params.values(): if value is None: raise ValueError('not all necessary parameters were provided! Set print_info=True ' 'at prototype initialization to see the full list of necessary ' 'parameters') return params def get_basis_vectors(self, **user_basis_params): """Initialize fractional coordinates of the particles in the unitcell. :param user_basis_params: user defined parameters for different Wyckoff site degree of freedom, when applicable :type user_basis_params: float :return: basis_vectors :rtype: np.ndarray """ basis_params = self.update_basis_params(user_basis_params) base_positions = np.zeros((0, 3)) order = 1 for site in self.wyckoff_site_list: pos = copy.deepcopy(self.full_wyckoff_positions[site]) for letter in ('x', 'y', 'z'): if letter + str(order) in basis_params.keys(): exec('{} = {}'.format(letter, basis_params[letter + str(order)])) for i in range(0, 3): # add * back for eval target = re.findall(r"(\d[xyz])", pos[i]) for item in target: pos[i] = pos[i].replace(item, '*'.join(re.findall(r"(\d)([xyz])", item)[0])) pos[i] = eval(pos[i]) base_positions = np.append(base_positions, np.array(pos).reshape(1, -1), axis=0) order += 1 return self.space_group.get_basis_vectors(wrap(base_positions), base_type=self.type_by_site) def update_lattice_params(self, user_lattice_params): params = copy.deepcopy(self.lattice_params) for param, value in user_lattice_params.items(): if param in params: if value is not None: params[param] = value else: print('warning: {} is not required and not used to define this ' 'structure'.format(param)) return params def get_lattice_vectors(self, **user_lattice_params): """Initialize the unitcell and return lattice vectors [a1, a2, a3] :param user_lattice_params: unit cell parameters, provide a, b, c, alpha, beta, gamma where applicable :type user_lattice_params: float :return: lattice_vectors :rtype: np.ndarray """ lattice_params = self.update_lattice_params(user_lattice_params) return self.space_group.lattice.get_lattice_vectors(**lattice_params) class AflowPrototype(Prototype): """Aflow prototype class. This class uses the crystal prototypes in Aflow database to initialize crystal structures. :param prototype_index: prototype index [0, 589] for all 590 prototypes in AFLOW. :type prototype_index: int :param set_type: allow setting different type name(in A, B, C order) for different atoms in AFLOW prototype :type set_type: bool :param print_info: Print prototype information upon initialization :type print_info: bool """ dir_path = os.path.dirname(__file__) Aflow_data_dir = os.path.join(dir_path, 'crystal_data/Aflow_processed_data.csv') Aflow_database = pd.read_csv(Aflow_data_dir, index_col=0) def __init__(self, prototype_index=0, set_type=False, print_info=True): # should do search, return best match and all options, define a Structure # name search should support one or any combination of: Pearson symbol, space_group number # and chemistry # must define unitcell type and space_group now if prototype_index < 0 or prototype_index >= 590: raise ValueError('prototype_index must be an integer between 0 and 590, default ' 'value of 0 will skip search by index and use Pearson symbol or ' 'chemistry for search') if prototype_index + 1: entry = self.Aflow_database.iloc[prototype_index] # TODO: a search and use best match feature with pearson and chemistry input space_group_number = entry['space_group_number'] lattice_params_list = re.findall(r"'(.*?)'", entry['lattice_params_list']) try: lattice_params_value_list = [float(i) for i in entry['lattice_params_value_list'].strip('[]').split(',')] except BaseException: lattice_params_value_list = [] basis_params_list = re.findall(r"'(.*?)'", entry['basis_params_list']) try: basis_params_value_list = [float(i) for i in entry['basis_params_value_list'].strip('[]').split(',')] except BaseException: basis_params_value_list = [] lattice_params = dict(zip(lattice_params_list, lattice_params_value_list)) basis_params = dict(zip(basis_params_list, basis_params_value_list)) # convert Aflow angle unit from degree to rad for key in ['alpha', 'beta', 'gamma']: if key in lattice_params.keys(): lattice_params[key] = lattice_params[key] / 180 * np.pi # process proper unitcell params if space_group_number in [146, 148, 155, 160, 161, 166, 167]: a = lattice_params.pop('a') c = lattice_params.pop('c/a') * a lattice_params['a'] = np.sqrt(a ** 2 / 3 + c ** 2 / 9) lattice_params['alpha'] = np.arccos((2 * c ** 2 - 3 * a ** 2) / ( 2 * (c ** 2 + 3 * a ** 2))) else: # for others a = lattice_params['a'] try: lattice_params['b'] = lattice_params.pop('b/a') * a except BaseException: pass try: lattice_params['c'] = lattice_params.pop('c/a') * a except BaseException: pass wyckoff_site_list_by_type = re.findall(r"'(.*?)'", entry['Wyckoff_site']) wyckoff_site_list = list(''.join(wyckoff_site_list_by_type)) wyckoff_site_list.sort() wyckoff_data_dir = os.path.join(self.dir_path, 'crystal_data/space_group_{}_Wyckoff' '_site_data.json'.format(space_group_number)) with open(wyckoff_data_dir, 'r') as f: full_wyckoff_positions = json.load(f) # get type label type_by_site = list('A' * len(wyckoff_site_list)) if set_type: sorted_site_string = ''.join(wyckoff_site_list) base = ord('A') for wyckoffs in wyckoff_site_list_by_type: for site in wyckoffs: order = sorted_site_string.find(site) sorted_site_string = sorted_site_string.replace(site, '0', 1) type_by_site[order] = chr(base) base += 1 self.space_group_number = space_group_number self.space_group = SpaceGroup(space_group_number) self.wyckoff_site_list = wyckoff_site_list self.full_wyckoff_positions = full_wyckoff_positions self.type_by_site = type_by_site self.lattice_params = lattice_params self.basis_params = basis_params if print_info: print('Info for the chosen crystal structure prototype:\n', 'id: {}, (Pearson-Chemistry-SpaceGroup)\n'.format(entry['id']), 'Wyckoff sites: {}\n'.format(entry['Wyckoff_site']), 'available lattice parameters: {}\n'.format(lattice_params), 'available basis parameters: {}'.format(basis_params)) # Point Group operations class PointGroup(object): """A class to access all point group symmetry operations. This class provides method to access all point group symmetry operation in both rotational matrix form or quaternion form. :param point_group_number: Point group number between 1 and 32. :type point_group_number: int :param print_info: Print point group information upon initialization. :type print_info: bool """ dir_path = os.path.dirname(__file__) point_group_rotation_matrix_dir = os.path.join(dir_path, 'crystal_data/' 'point_group_rotation_matrix_dict.pickle') with open(point_group_rotation_matrix_dir, 'rb') as f: point_group_rotation_matrix_dict = pickle.load(f) point_group_quat_dir = os.path.join(dir_path, 'crystal_data/point_group_quat_dict.json') with open(point_group_quat_dir, 'r') as f: point_group_quat_dict = json.load(f, object_hook=json_key_to_int) point_group_name_mapping_dir = os.path.join(dir_path, 'crystal_data/point_group_name_mapping.json') with open(point_group_name_mapping_dir, 'r') as f: point_group_name_mapping = json.load(f, object_hook=json_key_to_int) def __init__(self, point_group_number=1, print_info=False): if point_group_number <= 0 or point_group_number > 32: raise ValueError('point_group_number must be an integer between 1 and 32') self.point_group_number = point_group_number self.point_group_name = self.point_group_name_mapping[point_group_number] self.rotation_matrix = \ self.point_group_rotation_matrix_dict[point_group_number]['rotations'] self.quaternion = self.point_group_quat_dict[point_group_number] if print_info: print('Point group number: {}\n'.format(point_group_number), 'Name {}'.format(self.point_group_name)) def get_quaternion(self): """Get the quaternions for the point group symmetry. :return: list of quaternions :rtype: list """ return self.quaternion def get_rotation_matrix(self): """Get the rotation matrixes for the point group symmetry. :return: n by 3 by 3 numpy array containing n rotational matrixes :rtype: numpy.ndarray """ return self.rotation_matrix
[ "rowan.multiply", "numpy.sqrt", "numpy.arccos", "pandas.read_csv", "rowan.from_matrix", "numpy.array", "numpy.linalg.norm", "copy.deepcopy", "numpy.sin", "numpy.cross", "numpy.dot", "numpy.identity", "pickle.load", "os.path.dirname", "numpy.cos", "re.findall", "spglib.get_symmetry_fr...
[((1429, 1445), 'numpy.cross', 'np.cross', (['v0', 'v1'], {}), '(v0, v1)\n', (1437, 1445), True, 'import numpy as np\n'), ((2175, 2239), 'numpy.array', 'np.array', (['[[Lx, 0, 0], [xy * Ly, Ly, 0], [xz * Lz, yz * Lz, Lz]]'], {}), '([[Lx, 0, 0], [xy * Ly, Ly, 0], [xz * Lz, yz * Lz, Lz]])\n', (2183, 2239), True, 'import numpy as np\n'), ((3858, 3871), 'numpy.cos', 'np.cos', (['gamma'], {}), '(gamma)\n', (3864, 3871), True, 'import numpy as np\n'), ((3881, 3894), 'numpy.sin', 'np.sin', (['gamma'], {}), '(gamma)\n', (3887, 3894), True, 'import numpy as np\n'), ((3904, 3917), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (3910, 3917), True, 'import numpy as np\n'), ((3927, 3939), 'numpy.cos', 'np.cos', (['beta'], {}), '(beta)\n', (3933, 3939), True, 'import numpy as np\n'), ((4326, 4394), 'numpy.array', 'np.array', (['[[a, 0, 0], [b * cg, b * sg, 0], [c * cb, c * cy, c * cz]]'], {}), '([[a, 0, 0], [b * cg, b * sg, 0], [c * cb, c * cy, c * cz]])\n', (4334, 4394), True, 'import numpy as np\n'), ((9670, 9695), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (9685, 9695), False, 'import os\n'), ((9723, 9785), 'os.path.join', 'os.path.join', (['dir_path', '"""crystal_data/plane_group_info.pickle"""'], {}), "(dir_path, 'crystal_data/plane_group_info.pickle')\n", (9735, 9785), False, 'import os\n'), ((9959, 10030), 'os.path.join', 'os.path.join', (['dir_path', '"""crystal_data/plane_group_lattice_mapping.json"""'], {}), "(dir_path, 'crystal_data/plane_group_lattice_mapping.json')\n", (9971, 10030), False, 'import os\n'), ((23598, 23623), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (23613, 23623), False, 'import os\n'), ((23659, 23727), 'os.path.join', 'os.path.join', (['dir_path', '"""crystal_data/space_group_hall_mapping.json"""'], {}), "(dir_path, 'crystal_data/space_group_hall_mapping.json')\n", (23671, 23727), False, 'import os\n'), ((23946, 24017), 'os.path.join', 'os.path.join', (['dir_path', '"""crystal_data/space_group_lattice_mapping.json"""'], {}), "(dir_path, 'crystal_data/space_group_lattice_mapping.json')\n", (23958, 24017), False, 'import os\n'), ((30588, 30613), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (30603, 30613), False, 'import os\n'), ((37027, 37052), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (37042, 37052), False, 'import os\n'), ((37074, 37137), 'os.path.join', 'os.path.join', (['dir_path', '"""crystal_data/Aflow_processed_data.csv"""'], {}), "(dir_path, 'crystal_data/Aflow_processed_data.csv')\n", (37086, 37137), False, 'import os\n'), ((37193, 37233), 'pandas.read_csv', 'pd.read_csv', (['Aflow_data_dir'], {'index_col': '(0)'}), '(Aflow_data_dir, index_col=0)\n', (37204, 37233), True, 'import pandas as pd\n'), ((42134, 42159), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (42149, 42159), False, 'import os\n'), ((42198, 42276), 'os.path.join', 'os.path.join', (['dir_path', '"""crystal_data/point_group_rotation_matrix_dict.pickle"""'], {}), "(dir_path, 'crystal_data/point_group_rotation_matrix_dict.pickle')\n", (42210, 42276), False, 'import os\n'), ((42527, 42592), 'os.path.join', 'os.path.join', (['dir_path', '"""crystal_data/point_group_quat_dict.json"""'], {}), "(dir_path, 'crystal_data/point_group_quat_dict.json')\n", (42539, 42592), False, 'import os\n'), ((42794, 42862), 'os.path.join', 'os.path.join', (['dir_path', '"""crystal_data/point_group_name_mapping.json"""'], {}), "(dir_path, 'crystal_data/point_group_name_mapping.json')\n", (42806, 42862), False, 'import os\n'), ((1308, 1322), 'numpy.dot', 'np.dot', (['v0', 'v0'], {}), '(v0, v0)\n', (1314, 1322), True, 'import numpy as np\n'), ((1334, 1348), 'numpy.dot', 'np.dot', (['v0', 'v1'], {}), '(v0, v1)\n', (1340, 1348), True, 'import numpy as np\n'), ((1469, 1489), 'numpy.dot', 'np.dot', (['v0xv1', 'v0xv1'], {}), '(v0xv1, v0xv1)\n', (1475, 1489), True, 'import numpy as np\n'), ((1500, 1517), 'numpy.dot', 'np.dot', (['v2', 'v0xv1'], {}), '(v2, v0xv1)\n', (1506, 1517), True, 'import numpy as np\n'), ((1539, 1553), 'numpy.dot', 'np.dot', (['v0', 'v2'], {}), '(v0, v2)\n', (1545, 1553), True, 'import numpy as np\n'), ((4239, 4298), 'numpy.sqrt', 'np.sqrt', (['(1 - ca * ca - cb * cb - cg * cg + 2 * ca * cb * cg)'], {}), '(1 - ca * ca - cb * cb - cg * cg + 2 * ca * cb * cg)\n', (4246, 4298), True, 'import numpy as np\n'), ((5407, 5440), 'copy.deepcopy', 'copy.deepcopy', (['cls.lattice_params'], {}), '(cls.lattice_params)\n', (5420, 5440), False, 'import copy\n'), ((7064, 7114), 'numpy.array', 'np.array', (["[[params['a'], 0.0], [0.0, params['b']]]"], {}), "([[params['a'], 0.0], [0.0, params['b']]])\n", (7072, 7114), True, 'import numpy as np\n'), ((8868, 8918), 'numpy.array', 'np.array', (["[[params['a'], 0.0], [0.0, params['a']]]"], {}), "([[params['a'], 0.0], [0.0, params['a']]])\n", (8876, 8918), True, 'import numpy as np\n'), ((9906, 9920), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9917, 9920), False, 'import pickle\n'), ((10178, 10219), 'json.load', 'json.load', (['f'], {'object_hook': 'json_key_to_int'}), '(f, object_hook=json_key_to_int)\n', (10187, 10219), False, 'import json\n'), ((16315, 16348), 'copy.deepcopy', 'copy.deepcopy', (['cls.lattice_params'], {}), '(cls.lattice_params)\n', (16328, 16348), False, 'import copy\n'), ((18883, 18972), 'numpy.array', 'np.array', (["[[params['a'], 0.0, 0.0], [0.0, params['b'], 0.0], [0.0, 0.0, params['c']]]"], {}), "([[params['a'], 0.0, 0.0], [0.0, params['b'], 0.0], [0.0, 0.0,\n params['c']]])\n", (18891, 18972), True, 'import numpy as np\n'), ((19812, 19901), 'numpy.array', 'np.array', (["[[params['a'], 0.0, 0.0], [0.0, params['a'], 0.0], [0.0, 0.0, params['c']]]"], {}), "([[params['a'], 0.0, 0.0], [0.0, params['a'], 0.0], [0.0, 0.0,\n params['c']]])\n", (19820, 19901), True, 'import numpy as np\n'), ((22622, 22711), 'numpy.array', 'np.array', (["[[params['a'], 0.0, 0.0], [0.0, params['a'], 0.0], [0.0, 0.0, params['a']]]"], {}), "([[params['a'], 0.0, 0.0], [0.0, params['a'], 0.0], [0.0, 0.0,\n params['a']]])\n", (22630, 22711), True, 'import numpy as np\n'), ((23866, 23907), 'json.load', 'json.load', (['f'], {'object_hook': 'json_key_to_int'}), '(f, object_hook=json_key_to_int)\n', (23875, 23907), False, 'import json\n'), ((24165, 24206), 'json.load', 'json.load', (['f'], {'object_hook': 'json_key_to_int'}), '(f, object_hook=json_key_to_int)\n', (24174, 24206), False, 'import json\n'), ((24644, 24730), 'spglib.get_symmetry_from_database', 'spg.get_symmetry_from_database', (['self.space_group_hall_mapping[space_group_number]'], {}), '(self.space_group_hall_mapping[\n space_group_number])\n', (24674, 24730), True, 'import spglib as spg\n'), ((33344, 33376), 'copy.deepcopy', 'copy.deepcopy', (['self.basis_params'], {}), '(self.basis_params)\n', (33357, 33376), False, 'import copy\n'), ((34531, 34547), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {}), '((0, 3))\n', (34539, 34547), True, 'import numpy as np\n'), ((35509, 35543), 'copy.deepcopy', 'copy.deepcopy', (['self.lattice_params'], {}), '(self.lattice_params)\n', (35522, 35543), False, 'import copy\n'), ((38139, 38190), 're.findall', 're.findall', (['"""\'(.*?)\'"""', "entry['lattice_params_list']"], {}), '("\'(.*?)\'", entry[\'lattice_params_list\'])\n', (38149, 38190), False, 'import re\n'), ((38466, 38515), 're.findall', 're.findall', (['"""\'(.*?)\'"""', "entry['basis_params_list']"], {}), '("\'(.*?)\'", entry[\'basis_params_list\'])\n', (38476, 38515), False, 'import re\n'), ((39945, 39989), 're.findall', 're.findall', (['"""\'(.*?)\'"""', "entry['Wyckoff_site']"], {}), '("\'(.*?)\'", entry[\'Wyckoff_site\'])\n', (39955, 39989), False, 'import re\n'), ((42484, 42498), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (42495, 42498), False, 'import pickle\n'), ((42716, 42757), 'json.load', 'json.load', (['f'], {'object_hook': 'json_key_to_int'}), '(f, object_hook=json_key_to_int)\n', (42725, 42757), False, 'import json\n'), ((43004, 43045), 'json.load', 'json.load', (['f'], {'object_hook': 'json_key_to_int'}), '(f, object_hook=json_key_to_int)\n', (43013, 43045), False, 'import json\n'), ((1371, 1385), 'numpy.dot', 'np.dot', (['v1', 'v1'], {}), '(v1, v1)\n', (1377, 1385), True, 'import numpy as np\n'), ((1587, 1601), 'numpy.dot', 'np.dot', (['v1', 'v2'], {}), '(v1, v2)\n', (1593, 1601), True, 'import numpy as np\n'), ((13107, 13121), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (13118, 13121), True, 'import numpy as np\n'), ((32086, 32098), 'json.load', 'json.load', (['f'], {}), '(f)\n', (32095, 32098), False, 'import json\n'), ((32206, 32249), 'copy.deepcopy', 'copy.deepcopy', (['full_wyckoff_positions[site]'], {}), '(full_wyckoff_positions[site])\n', (32219, 32249), False, 'import copy\n'), ((34629, 34677), 'copy.deepcopy', 'copy.deepcopy', (['self.full_wyckoff_positions[site]'], {}), '(self.full_wyckoff_positions[site])\n', (34642, 34677), False, 'import copy\n'), ((39366, 39398), 'numpy.sqrt', 'np.sqrt', (['(a ** 2 / 3 + c ** 2 / 9)'], {}), '(a ** 2 / 3 + c ** 2 / 9)\n', (39373, 39398), True, 'import numpy as np\n'), ((39437, 39503), 'numpy.arccos', 'np.arccos', (['((2 * c ** 2 - 3 * a ** 2) / (2 * (c ** 2 + 3 * a ** 2)))'], {}), '((2 * c ** 2 - 3 * a ** 2) / (2 * (c ** 2 + 3 * a ** 2)))\n', (39446, 39503), True, 'import numpy as np\n'), ((40358, 40370), 'json.load', 'json.load', (['f'], {}), '(f)\n', (40367, 40370), False, 'import json\n'), ((2710, 2726), 'numpy.cross', 'np.cross', (['a1', 'a2'], {}), '(a1, a2)\n', (2718, 2726), True, 'import numpy as np\n'), ((13969, 13993), 'copy.deepcopy', 'copy.deepcopy', (['base_type'], {}), '(base_type)\n', (13982, 13993), False, 'import copy\n'), ((14181, 14220), 'numpy.linalg.norm', 'np.linalg.norm', (['pos_comparisons'], {'axis': '(2)'}), '(pos_comparisons, axis=2)\n', (14195, 14220), True, 'import numpy as np\n'), ((14245, 14278), 'numpy.all', 'np.all', (['(norms > threshold)'], {'axis': '(0)'}), '(norms > threshold, axis=0)\n', (14251, 14278), True, 'import numpy as np\n'), ((14307, 14347), 'numpy.append', 'np.append', (['positions', 'pos[comps]'], {'axis': '(0)'}), '(positions, pos[comps], axis=0)\n', (14316, 14347), True, 'import numpy as np\n'), ((27788, 27812), 'copy.deepcopy', 'copy.deepcopy', (['base_type'], {}), '(base_type)\n', (27801, 27812), False, 'import copy\n'), ((28000, 28039), 'numpy.linalg.norm', 'np.linalg.norm', (['pos_comparisons'], {'axis': '(2)'}), '(pos_comparisons, axis=2)\n', (28014, 28039), True, 'import numpy as np\n'), ((28064, 28097), 'numpy.all', 'np.all', (['(norms > threshold)'], {'axis': '(0)'}), '(norms > threshold, axis=0)\n', (28070, 28097), True, 'import numpy as np\n'), ((28126, 28166), 'numpy.append', 'np.append', (['positions', 'pos[comps]'], {'axis': '(0)'}), '(positions, pos[comps], axis=0)\n', (28135, 28166), True, 'import numpy as np\n'), ((34967, 34999), 're.findall', 're.findall', (['"""(\\\\d[xyz])"""', 'pos[i]'], {}), "('(\\\\d[xyz])', pos[i])\n", (34977, 34999), False, 'import re\n'), ((4992, 5005), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (4998, 5005), True, 'import numpy as np\n'), ((5011, 5024), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (5017, 5024), True, 'import numpy as np\n'), ((13503, 13535), 'numpy.linalg.det', 'np.linalg.det', (['self.rotations[i]'], {}), '(self.rotations[i])\n', (13516, 13535), True, 'import numpy as np\n'), ((13729, 13774), 'rowan.multiply', 'rowan.multiply', (['quat_rotate', 'base_quaternions'], {}), '(quat_rotate, base_quaternions)\n', (13743, 13774), False, 'import rowan\n'), ((14492, 14535), 'numpy.append', 'np.append', (['quaternions', 'quat[comps]'], {'axis': '(0)'}), '(quaternions, quat[comps], axis=0)\n', (14501, 14535), True, 'import numpy as np\n'), ((27385, 27417), 'numpy.linalg.det', 'np.linalg.det', (['self.rotations[i]'], {}), '(self.rotations[i])\n', (27398, 27417), True, 'import numpy as np\n'), ((27458, 27520), 'rowan.from_matrix', 'rowan.from_matrix', (['self.rotations[i]'], {'require_orthogonal': '(False)'}), '(self.rotations[i], require_orthogonal=False)\n', (27475, 27520), False, 'import rowan\n'), ((27548, 27593), 'rowan.multiply', 'rowan.multiply', (['quat_rotate', 'base_quaternions'], {}), '(quat_rotate, base_quaternions)\n', (27562, 27593), False, 'import rowan\n'), ((28311, 28354), 'numpy.append', 'np.append', (['quaternions', 'quat[comps]'], {'axis': '(0)'}), '(quaternions, quat[comps], axis=0)\n', (28320, 28354), True, 'import numpy as np\n'), ((35270, 35283), 'numpy.array', 'np.array', (['pos'], {}), '(pos)\n', (35278, 35283), True, 'import numpy as np\n'), ((8090, 8100), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (8097, 8100), True, 'import numpy as np\n'), ((20864, 20876), 'numpy.sqrt', 'np.sqrt', (['(3.0)'], {}), '(3.0)\n', (20871, 20876), True, 'import numpy as np\n'), ((35139, 35171), 're.findall', 're.findall', (['"""(\\\\d)([xyz])"""', 'item'], {}), "('(\\\\d)([xyz])', item)\n", (35149, 35171), False, 'import re\n')]
import numpy as np class Aperture(object): """ class that defines the aperture of the measurement (e.g. slit, Inegral field spectroscopy regions etc) Available aperture types: ------------------------- 'slit': length, width, center_ra, center_dec 'shell': r_in, r_out, center_ra, center_dec """ def __init__(self, aperture_type='slit', psf_fwhm=0.7): """ initializes the observation condition and masks :param aperture_type: string :param psf_fwhm: float """ self._aperture_type = aperture_type self._fwhm = psf_fwhm def aperture_select(self, ra, dec, kwargs_aperture): """ returns a bool list if the coordinate is within the aperture (list) :param ra: :param dec: :return: """ if self._aperture_type == 'shell': bool_list = self.shell_select(ra, dec, **kwargs_aperture) elif self._aperture_type == 'slit': bool_list = self.slit_select(ra, dec, **kwargs_aperture) else: raise ValueError("aperture type %s not implemented!" % self._aperture_type) return bool_list def slit_select(self, ra, dec, length, width, center_ra=0, center_dec=0, angle=0): """ :param ra: :param dec: :param R: :param d: :param center_ra: :param center_dec: :param angle: :return: bool """ ra_ = ra - center_ra dec_ = dec - center_dec x = np.cos(angle)*ra_ + np.sin(angle)*dec_ y = - np.sin(angle)*ra_ + np.cos(angle)*dec_ if abs(x) < length/2. and abs(y) < width/2.: return True else: return False def shell_select(self, ra, dec, r_in, r_out, center_ra, center_dec): """ :param ra: :param dec: :param r_in: :param r_out: :param center_ra: :param center_dec: :return: """ x = ra - center_ra y = dec - center_dec R = np.sqrt(x**2 + y**2) if (R >= r_in) and (R < r_out): return True else: return False
[ "numpy.sin", "numpy.sqrt", "numpy.cos" ]
[((2063, 2087), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (2070, 2087), True, 'import numpy as np\n'), ((1535, 1548), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (1541, 1548), True, 'import numpy as np\n'), ((1555, 1568), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (1561, 1568), True, 'import numpy as np\n'), ((1608, 1621), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (1614, 1621), True, 'import numpy as np\n'), ((1588, 1601), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (1594, 1601), True, 'import numpy as np\n')]
import datetime import logging import multiprocessing import os import pickle import sys import time import threading from collections import defaultdict from functools import partial, wraps from io import IOBase from logging.handlers import QueueListener, QueueHandler from subprocess import Popen from typing import Any, Callable, Dict, List, Type, Union from queue import Empty from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL from hyperopt.mongoexp import ( as_mongo_str, MongoJobs, MongoTrials, MongoWorker, ReserveTimeout, ) import numpy as np import torch import tqdm from . import Trainer from .inference import UnsupervisedTrainer from ..dataset import GeneExpressionDataset from ..models import VAE # TODO: add database watcher and visualizations # TODO: make worker_launcher a subclass of threading.Thread # TODO: and hyperopt_worker a subclass of multiprocessing.Process # spawning is required for processes relying on cuda spawn_ctx = multiprocessing.get_context("spawn") fork_ctx = multiprocessing.get_context("fork") # register running process and open files to terminate/close at exit started_processes: List[Union[multiprocessing.Process, Popen]] = [] started_threads: List[threading.Thread] = [] open_files: List[IOBase] = [] # instantiate logger, handler and formatter logger = logging.getLogger(__name__) formatter = logging.Formatter( "[%(asctime)s - %(processName)s - %(threadName)s] %(levelname)s - %(name)s\n%(message)s" ) ch = logging.StreamHandler() ch.setFormatter(formatter) # instantiate hyperopt and autotune file handlers as global variables for clean up fh_hyperopt = None fh_autotune = None # global Event to stop threads when cleaning up cleanup_event = threading.Event() class FminTimeoutError(Exception): """Thrown if fmin process hasn't finished in the allotted time after all workers have died. """ class DispatchHandler: """A simple handler for logging events. It dispatches events to loggers based on the name in the received record, which then get dispatched, by the logging system, to the handlers, configured for those loggers. """ def handle(self, record: logging.LogRecord): logger = logging.getLogger(record.name) if record.levelno >= logger.level: logger.handle(record) class ProgressHandler: """A simple handler for keeping track of the worker's progress. When assigned to a logger, logs sent using that logger trigger an update of the progress bar associated with this handler. """ def __init__(self, pbar: tqdm.tqdm, disable: bool): self.level = 0 self.pbar = pbar self.disabled = disable def handle(self, record: logging.LogRecord): if not self.disabled: self.pbar.update() # cleanup helpers def _cleanup_processes_files(): """Cleanup function, starts with latest processes/files. Terminates processes, sets cleanup_event to stop threads, closes open files.""" logger.info("Cleaning up") logger.debug("Cleaning up: closing files") for f in open_files[::-1]: if not f.closed: f.close() logger.debug("Cleaning up: setting cleanup_event and joining threads") cleanup_event.is_set() for t in started_threads[::-1]: if t.is_alive(): t.join() logger.debug("Cleaning up: terminating processes") for p in started_processes[::-1]: if isinstance(p, Popen): if p.poll() is not None: p.terminate() if isinstance(p, multiprocessing.Process): if p.is_alive(): p.terminate() if isinstance(p, QueueListener): if p._thread is not None: p.stop() def _cleanup_logger(): """Removes added handlers.""" logger.debug("Cleaning up: removing added logging handler") for handler in logger.handlers: if handler == ch: logger.removeHandler(ch) for handler in logging.getLogger("hyperopt").handlers: if handler == fh_hyperopt: logger.removeHandler(fh_hyperopt) if handler == fh_autotune: logger.removeHandler(fh_autotune) def _cleanup_decorator(func: Callable): """Decorates top-level calls in order to launch cleanup when an Exception is caught.""" @wraps(func) def decorated(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logger.exception( "Caught {exception} in {func}, starting cleanup".format( exception=e.args, func=func.__name__ ) ) _cleanup_processes_files() _cleanup_logger() raise return decorated def auto_tune_scvi_model( exp_key: str, gene_dataset: GeneExpressionDataset, objective_hyperopt: Callable = None, model_class: VAE = VAE, trainer_class: Trainer = UnsupervisedTrainer, model_specific_kwargs: dict = None, trainer_specific_kwargs: dict = None, train_func_specific_kwargs: dict = None, space: dict = None, max_evals: int = 100, train_best: bool = True, pickle_result: bool = True, save_path: str = ".", use_batches: bool = False, parallel: bool = True, n_cpu_workers: int = None, gpu_ids: List[int] = None, n_workers_per_gpu: int = 1, reserve_timeout: float = 30.0, fmin_timeout: float = 300.0, fmin_timer: float = None, mongo_port: str = "1234", mongo_host: str = "localhost", db_name: str = "scvi_db", multiple_hosts: bool = False, ) -> (Type[Trainer], Trials): """Perform automatic hyperparameter optimization of an scVI model and return best model and hyperopt Trials object. ``Trials`` object contains hyperparameter space and loss history for each trial. We provide a default hyperparameter search space (see source code), but we recommend the user to build a custom one for each application. Convention: fixed parameters (no default) have precedence over tunable parameters (default). Note that the verbosity of this function has to be set using the logging module. In particular, for the parallel case, only a progress bar is shown if the logging level is equal or higher to ``logging.WARNING``. :param exp_key: Name of the experiment in MongoDb. If already exists in db, ``hyperopt`` will run a number of trainings equal to the difference between current and previous ``max_evals``. :param gene_dataset: scVI gene dataset. :param objective_hyperopt: A custom objective function respecting the ``hyperopt`` format. Roughly, it needs to return the quantity to optimize for, either directly or in a ``dict`` under the "loss" key. See https://github.com/hyperopt/hyperopt/wiki for a more detailed explanation. By default, we provide an objective function which can be parametrized through the various arguments of this function (``gene_dataset``, ``model_class``, etc.) :param model_class: scVI model class (e.g ``VAE``, ``VAEC``, ``SCANVI``) :param trainer_class: ``Trainer`` sub-class (e.g ``UnsupervisedTrainer``) :param model_specific_kwargs: ``dict`` of fixed parameters which will be passed to the model. :param trainer_specific_kwargs: ``dict`` of fixed parameters which will be passed to the trainer. :param train_func_specific_kwargs: dict of fixed parameters which will be passed to the train method. :param space: dict containing up to three sub-dicts with keys "model_tunable_kwargs", "trainer_tunable_kwargs" or "train_func_tunable_kwargs". Each of those dict contains ``hyperopt`` defined parameter spaces (e.g. ``hp.choice(..)``) which will be passed to the corresponding object : model, trainer or train method when performing hyper-optimization. Default: mutable, see source code. :param max_evals: Maximum number of evaluations of the objective. :param train_best: If ``True``, train best model and return it. :param pickle_result: If ``True``, pickle ``Trials`` and ``Trainer`` objects using ``save_path``. :param save_path: Path where to save best model, trainer, trials and mongo files. :param use_batches: If ``False``, pass ``n_batch=0`` to model else pass ``gene_dataset.n_batches``. :param parallel: If ``True``, use ``MongoTrials`` object to run trainings in parallel. :param n_cpu_workers: Number of cpu workers to launch. If None, and no GPUs are found, defaults to ``os.cpucount() - 1``. Else, defaults to 0. :param gpu_ids: Ids of the GPUs to use. If None defaults to all GPUs found by ``torch``. Note that considered gpu ids are int from 0 to ``torch.cuda.device_count()``. :param n_workers_per_gpu: Number of workers to launch per gpu found by ``torch``. :param reserve_timeout: Amount of time, in seconds, a worker tries to reserve a job for before throwing a ``ReserveTimeout`` Exception. :param fmin_timeout: Amount of time, in seconds, fmin_process has to terminate after all workers have died - before throwing a ``FminTimeoutError``. If ``multiple_hosts`` is set to ``True``, this is set to ``None`` to prevent timing out. :param fmin_timer: Global amount of time allowed for fmin_process. If not None, the minimization procedure will be stopped after ``fmin_timer`` seconds. Used only if ``parallel`` is set to ``True``. :param mongo_port: Port to the Mongo db. :param mongo_host: Hostname used with ``mongo_port`` to indicate the prefix of the mongodb address. The prefix of the address passed onto the workers and ``MongoTrials`` object is ``'{mongo_host}:{mongo_port}'``. :param db_name: Name to use when creating the Mongo database. Suffix of the Mongo address. :param multiple_hosts: If ``True``, user is considered to have workers launched on several machines. Therefore, setting this to ``True`` disables the ``fmin_timeout`` behaviour. :return: ``Trainer`` object for the best model and ``(Mongo)Trials`` object containing logs for the different runs. Examples: >>> from scvi.dataset import CortexDataset >>> gene_dataset = CortexDataset() >>> best_trainer, trials = auto_tune_scvi_model(gene_dataset) """ if fmin_timer and train_best: logger.warning( "fmin_timer and train_best are both set to True. " "This means that runtime will exceed fmin_timer " "by at least the time it takes to complete a full training." ) # if no handlers add console handler, add formatter to handlers if len(logger.handlers) < 1: logger.addHandler(ch) else: # if no formatter add default module formatter for handler in logger.handlers: if not handler.formatter: handler.setFormatter(formatter) # also add file handler fh_autotune = logging.FileHandler( os.path.join(save_path, "scvi_autotune_logfile.txt") ) fh_autotune.setFormatter(formatter) fh_autotune.setLevel(logging.DEBUG) logger.addHandler(fh_autotune) logger.info("Starting experiment: {exp_key}".format(exp_key=exp_key)) # default specific kwargs model_specific_kwargs = model_specific_kwargs if model_specific_kwargs else {} trainer_specific_kwargs = trainer_specific_kwargs if trainer_specific_kwargs else {} train_func_specific_kwargs = ( train_func_specific_kwargs if train_func_specific_kwargs else {} ) # default early stopping if "early_stopping_kwargs" not in trainer_specific_kwargs: logger.debug("Adding default early stopping behaviour.") early_stopping_kwargs = { "early_stopping_metric": "elbo", "save_best_state_metric": "elbo", "patience": 50, "threshold": 0, "reduce_lr_on_plateau": True, "lr_patience": 25, "lr_factor": 0.2, } trainer_specific_kwargs["early_stopping_kwargs"] = early_stopping_kwargs # add elbo to metrics to monitor metrics_to_monitor = trainer_specific_kwargs.get("metrics_to_monitor", []) metrics_to_monitor.append("elbo") trainer_specific_kwargs["metrics_to_monitor"] = metrics_to_monitor # default search space if space is None: logger.debug("Using default parameter search space.") space = { "model_tunable_kwargs": { "n_latent": 5 + hp.randint("n_latent", 11), # [5, 15] "n_hidden": hp.choice("n_hidden", [64, 128, 256]), "n_layers": 1 + hp.randint("n_layers", 5), "dropout_rate": hp.choice("dropout_rate", [0.1, 0.3, 0.5, 0.7, 0.9]), "reconstruction_loss": hp.choice("reconstruction_loss", ["zinb", "nb"]), }, "train_func_tunable_kwargs": { "lr": hp.choice("lr", [0.01, 0.005, 0.001, 0.0005, 0.0001]) }, } logger.info( "Fixed parameters: \n" "model: \n" + str(model_specific_kwargs) + "\n" + "trainer: \n" + str(trainer_specific_kwargs) + "\n" + "train method: \n" + str(train_func_specific_kwargs) ) # build a partial objective function restricted to the search space if objective_hyperopt is None: objective_hyperopt = partial( _objective_function, **{ "gene_dataset": gene_dataset, "model_class": model_class, "trainer_class": trainer_class, "model_specific_kwargs": model_specific_kwargs, "trainer_specific_kwargs": trainer_specific_kwargs, "train_func_specific_kwargs": train_func_specific_kwargs, "use_batches": use_batches, }, ) if parallel: logger.info("Starting parallel hyperoptimization") trials = _auto_tune_parallel( objective_hyperopt=objective_hyperopt, exp_key=exp_key, space=space, max_evals=max_evals, save_path=save_path, n_cpu_workers=n_cpu_workers, gpu_ids=gpu_ids, n_workers_per_gpu=n_workers_per_gpu, reserve_timeout=reserve_timeout, fmin_timeout=fmin_timeout, fmin_timer=fmin_timer, mongo_port=mongo_port, mongo_host=mongo_host, db_name=db_name, multiple_hosts=multiple_hosts, ) else: logger.info("Starting sequential hyperoptimization") trials = Trials() # run hyperoptimization _ = fmin( fn=objective_hyperopt, space=space, algo=tpe.suggest, max_evals=max_evals, trials=trials, ) # return best model, trained if train_best: logger.debug("Training best model with full training set") best_space = trials.best_trial["result"]["space"] best_trainer = objective_hyperopt(best_space, is_best_training=True) if pickle_result: if train_best: logger.debug("Pickling best model and trainer") # pickle trainer and save model (overkill?) with open( os.path.join(save_path, "best_trainer_{key}".format(key=exp_key)), "wb" ) as f: pickle.dump(best_trainer, f) torch.save( best_trainer.model.state_dict(), os.path.join(save_path, "best_model_{key}".format(key=exp_key)), ) # remove object containing thread.lock (otherwise pickle.dump throws) logger.debug("Pickling Trials object") if hasattr(trials, "handle"): del trials.handle with open( os.path.join(save_path, "trials_{key}".format(key=exp_key)), "wb" ) as f: pickle.dump(trials, f) # remove added logging handlers/formatters _cleanup_logger() if train_best: return best_trainer, trials else: return trials def _auto_tune_parallel( objective_hyperopt: Callable, exp_key: str, space: dict = None, max_evals: int = 100, save_path: str = ".", n_cpu_workers: int = None, gpu_ids: List[int] = None, n_workers_per_gpu: int = 1, reserve_timeout: float = 30.0, fmin_timeout: float = 60.0, fmin_timer: float = None, mongo_port: str = "1234", mongo_host: str = "localhost", db_name: str = "scvi_db", multiple_hosts: bool = False, ) -> MongoTrials: """Parallel version of the hyperoptimization procedure. Called by ``auto_tune_scvi_model`` when ``parallel=True``. Specifically, first the MongoDb service is launched in its own forked process. Then, the call to the minimization process is made in its own forked process. Then, the call ``worker_launcher`` is made in its own Thread. After that, the program waits for either the minimization process to finish or for the workers to all timeout. When one of these conditions is verified the program kills the waiter for the other and tries to dequeue the results from the minimization process. At that point, if ``multiple_hosts`` is set to True, the program waits indefinitely for the minimization process to put the results in the queue. If not, the minimisation process has ``fmin_timeout`` seconds to finish. This mechanism ensures that the program does not hang if, for any reason, the workers die before completing all the jobs. Note that logs to the ``hyperopt`` package are automatically stored in ``./hyperopt_logfile.txt``. Note that the progress bar is automatically disabled if the logging level for ``scvi.inference.autotune`` is lower than logging.WARNING. :param objective_hyperopt: Callable, the objective function to minimize :param exp_key: Name of the experiment in MongoDb. :param space: ``dict`` containing up to three sub-dicts with keys "model_tunable_kwargs", "trainer_tunable_kwargs" or "train_func_tunable_kwargs". Each of those dict contains ``hyperopt`` defined parameter spaces (e.g. ``hp.choice(..)``) which will be passed to the corresponding object : model, trainer or train method when performing hyperoptimization. Default: mutable, see source code. :param max_evals: Maximum number of evaluations of the objective. :param save_path: Path where to save best model, trainer, trials and mongo files. :param n_cpu_workers: Number of cpu workers to launch. If None, and no GPUs are found, defaults to ``os.cpucount() - 1``. Else, defaults to 0. :param gpu_ids: Ids of the GPUs to use. If None defaults to all GPUs found by ``torch``. Note that considered gpu ids are int from ``0`` to ``torch.cuda.device_count()``. :param n_workers_per_gpu: Number of workers ton launch per gpu found by ``torch``. :param reserve_timeout: Amount of time, in seconds, a worker tries to reserve a job for before throwing a ``ReserveTimeout`` Exception. :param fmin_timeout: Amount of time, in seconds, ``fmin_process`` has to terminate after all workers have died - before throwing a ``FminTimeoutError``. If ``multiple_hosts`` is set to ``True``, this is set to None to disable the timineout behaviour. :param fmin_timer: Global amount of time allowed for fmin_process. If not None, the minimization procedure will be stopped after ``fmin_timer`` seconds. Used only if ``parallel`` is set to ``True``. :param mongo_port: Port to the mongo db. :param mongo_host: Hostname used with mongo_port to indicate the prefix of the mongodb address. The prefix of the address passed onto the workers and MongoTrials object is ``'{mongo_host}:{mongo_port}'``. :param db_name: Name to use when creating the Mongo database. Suffix of the mongo address. :param multiple_hosts: If ``True``, user is considered to have workers launched on several machines. Therefore, setting this to ``True`` disables the ``fmin_timeout`` behaviour. :return: ``MongoTrials`` object containing the results of the program. """ # run mongod bash script mongo_path = os.path.join(save_path, "mongo") if not os.path.exists(mongo_path): os.makedirs(mongo_path) mongo_logfile = open(os.path.join(mongo_path, "mongo_logfile.txt"), "w") open_files.append(mongo_logfile) logger.debug( "Starting MongoDb process, logs redirected to " "{name}.".format(name=mongo_logfile.name) ) mongod_process = Popen( [ "mongod", "--quiet", "--dbpath={path}".format(path=mongo_path), "--port={port}".format(port=mongo_port), ], stdout=mongo_logfile, ) mongo_port_address = os.path.join(mongo_host + ":" + mongo_port, db_name) started_processes.append(mongod_process) # log hyperopt to file hp_logger = logging.getLogger("hyperopt") fh_hyperopt = logging.FileHandler(os.path.join(save_path, "hyperopt_logfile.txt")) fh_hyperopt.setFormatter(formatter) hp_logger.addHandler(fh_hyperopt) # add progress handler to progress logger progress_logger = logging.getLogger("progress_logger") disable = multiple_hosts or (logger.level < logging.WARNING) pbar = tqdm.tqdm(total=max_evals, disable=disable) progress_logger.addHandler(ProgressHandler(pbar=pbar, disable=disable)) # start by running fmin process so that workers don't timeout # run hyperoptimization, in a forked process # this allows to warn if the workers crash # since mongo is not thread-safe, trials must be instantiated in each child logger.debug("Starting minimization procedure") queue = fork_ctx.Queue() fmin_kwargs = { "queue": queue, "fn": objective_hyperopt, "exp_key": exp_key, "space": space, "algo": tpe.suggest, "max_evals": max_evals, "fmin_timer": fmin_timer, "show_progressbar": False, # progbar useless in parallel mode "mongo_port_address": mongo_port_address, } fmin_process = fork_ctx.Process( target=_fmin_parallel, kwargs=fmin_kwargs, name="fmin Process" ) fmin_process.start() started_processes.append(fmin_process) # start worker launcher logger.debug("Starting worker launcher") stop_watchdog_event = threading.Event() launcher_kwargs = { "stop_watchdog_event": stop_watchdog_event, "exp_key": exp_key, "n_cpu_workers": n_cpu_workers, "gpu_ids": gpu_ids, "n_workers_per_gpu": n_workers_per_gpu, "reserve_timeout": reserve_timeout, "workdir": mongo_path, "mongo_port_address": mongo_port_address, "multiple_hosts": multiple_hosts, } workers_thread = threading.Thread( target=launch_workers, kwargs=launcher_kwargs, name="Worker Launcher" ) workers_thread.start() started_threads.append(workers_thread) # wait for workers and fmin process simultaneously workers_done_event = threading.Event() fmin_done_event = threading.Event() fmin_waiter = threading.Thread( target=_wait_for_process_or_thread, kwargs={"process": fmin_process, "event": fmin_done_event}, name="Waiter fmin", ) fmin_waiter.start() started_threads.append(fmin_waiter) workers_waiter = threading.Thread( target=_wait_for_process_or_thread, kwargs={"process": workers_thread, "event": workers_done_event}, name="Waiter workers", ) workers_waiter.start() started_threads.append(workers_waiter) while not workers_done_event.is_set() and not fmin_done_event.is_set(): time.sleep(5) # when one of them finishes, if it is fmin -> trials should be in the queue # if not and not using multiple hosts we wait fmin_timeout seconds for fmin to finish # in any case, close waiter threads if fmin_done_event.is_set(): logger.debug("Setting worker watchdog and waiter stop events.") stop_watchdog_event.set() workers_done_event.set() if workers_done_event.is_set() and not multiple_hosts: logger.debug("Setting fmin waiter stop event.") fmin_done_event.set() try: if multiple_hosts: # if using multiple_hosts, there could still be workers -> disable fmin timeout fmin_timeout = None logger.debug( "multiple_hosts set to True, fmin will block until all trials have been completed." ) else: logger.debug( "multiple_hosts set to false, Fmin has {time} seconds to finish".format( time=fmin_timeout ) ) trials = queue.get(timeout=fmin_timeout) except Empty: logger.error( "Queue still empty {fmin_timeout} seconds after all workers have died." "\n".format(fmin_timeout=fmin_timeout) + "Terminating minimization process." ) raise FminTimeoutError( "Queue still empty {fmin_timeout} seconds after all workers " "have died. Check that you have used a new exp_key or allowed " "a higher max_evals".format(fmin_timeout=fmin_timeout) ) # sanity: wait for fmin, terminate workers and wait for launcher fmin_process.join() stop_watchdog_event.set() workers_thread.join() logger.info( "Finished minimization procedure for experiment {exp_key}.".format( exp_key=exp_key ) ) logger.debug("Terminating mongod process.") mongod_process.terminate() # cleanup processes, threads and files _cleanup_processes_files() return trials @_cleanup_decorator def _fmin_parallel( queue: multiprocessing.Queue, fn: Callable, exp_key: str, space: dict, algo: Callable = tpe.suggest, max_evals: int = 100, fmin_timer: float = None, show_progressbar: bool = False, mongo_port_address: str = "localhost:1234/scvi_db", ): """Launches a ``hyperopt`` minimization procedure. """ logger.debug("Instantiating trials object.") # instantiate Trials object trials = MongoTrials( as_mongo_str(os.path.join(mongo_port_address, "jobs")), exp_key=exp_key ) # run hyperoptimization in another fork to enable the use of fmin_timer fmin_kwargs = { "fn": fn, "space": space, "algo": algo, "max_evals": max_evals, "trials": trials, "show_progressbar": show_progressbar, } fmin_thread = threading.Thread(target=fmin, kwargs=fmin_kwargs) logger.debug("Calling fmin.") # set fmin thread as daemon so it stops when the main process terminates fmin_thread.daemon = True fmin_thread.start() started_threads.append(fmin_thread) if fmin_timer: logging.debug( "Timer set, fmin will run for at most {timer}".format(timer=fmin_timer) ) start_time = time.monotonic() run_time = 0 while run_time < fmin_timer and fmin_thread.is_alive(): time.sleep(10) run_time = time.monotonic() - start_time else: logging.debug("No timer, waiting for fmin") while True: if not fmin_thread.is_alive(): break else: time.sleep(10) logger.debug("fmin returned or timer ran out.") # queue.put uses pickle so remove attribute containing thread.lock if hasattr(trials, "handle"): logger.debug("Deleting Trial handle for pickling.") del trials.handle logger.debug("Putting Trials in Queue.") queue.put(trials) def _wait_for_process_or_thread( process: Union[multiprocessing.Process, threading.Thread], event: threading.Event ): """Waits for a process to finish - breaks and sets ``event`` when it does. Can be terminated by setting event from outside or by setting the global ``cleanup_event`` of this module. """ logger.debug("Started waiting for {name}.".format(name=process.name)) while True: # set event and break is process is dead if not process.is_alive(): logger.debug("{name} died. Terminating waiter.".format(name=process.name)) event.set() break # break if event was set if event.is_set(): logger.debug( "Waiting event for {name} set from outside. " "Terminating waiter.".format(name=process.name) ) break if cleanup_event.is_set(): logger.debug( "Waiting thread for {name} cleaned up.".format(name=process.name) ) event.set() break time.sleep(5) @_cleanup_decorator def launch_workers( stop_watchdog_event: threading.Event(), exp_key: str, n_cpu_workers: int = None, gpu_ids: List[int] = None, n_workers_per_gpu: int = 1, reserve_timeout: float = 30.0, workdir: str = ".", mongo_port_address: str = "localhost:1234/scvi_db", multiple_hosts: bool = False, ): """Launches the local workers which are going to run the jobs required by the minimization process. Terminates when the worker_watchdog call finishes. Specifically, first ``n_gpu_workers`` are launched per GPU in ``gpu_ids`` in their own spawned process. Then, ``n_cpu_workers`` CPU workers are launched, also in their own spawned process. The use of spawned processes (each have their own python interpreter) is mandatory for compatiblity with CUDA. See https://pytorch.org/docs/stable/notes/multiprocessing.html for more information. :param stop_watchdog_event: When set, this event stops the watchdog Thread which checks that local workers are still running. :param exp_key: This key is used by hyperopt as a suffix to the part of the MongoDb which corresponds to the current experiment. In particular, it has to be passed to ``MongoWorker``. :param n_cpu_workers: Number of cpu workers to launch. If None, and no GPUs are found, defaults to ``os.cpu_count() - 1``. Else, defaults to 0. :param gpu_ids: Ids of the GPUs to use. If None defaults to all GPUs found by ``torch``. Note that considered gpu ids are int from ``0`` to ``torch.cuda.device_count()``. :param n_workers_per_gpu: Number of workers ton launch per gpu found by ``torch``. :param reserve_timeout: Amount of time, in seconds, a worker tries to reserve a job for before throwing a ``ReserveTimeout`` Exception. :param fmin_timeout: Amount of time, in seconds, ``fmin_process`` has to terminate after all workers have died - before throwing a ``FminTimeoutError``. If ``multiple_hosts`` is set to ``True``, this is set to None to disable the timineout behaviour. :param workdir: Directory where the workers :param mongo_port_address: Address to the running MongoDb service. :param multiple_hosts: ``True`` if launching workers form multiple hosts. """ # prepare parallel logging _logging_queue = spawn_ctx.Queue() listener = QueueListener(_logging_queue, DispatchHandler()) listener.start() started_processes.append(listener) if gpu_ids is None: n_gpus = torch.cuda.device_count() logger.debug( "gpu_ids is None, defaulting to all {n_gpus} GPUs found by torch.".format( n_gpus=n_gpus ) ) gpu_ids = list(range(n_gpus)) if n_gpus and n_cpu_workers is None: n_cpu_workers = 0 logging.debug( "Some GPU.s found and n_cpu_wokers is None, defaulting to n_cpu_workers = 0" ) if not n_gpus and n_cpu_workers is None: n_cpu_workers = os.cpu_count() - 1 logging.debug( "No GPUs found and n_cpu_wokers is None, defaulting to n_cpu_workers = " "{n_cpu_workers} (os.cpu_count() - 1)".format( n_cpu_workers=n_cpu_workers ) ) if not gpu_ids and not n_cpu_workers and not multiple_hosts: raise ValueError("No hardware (cpu/gpu) selected/found.") # log progress with queue and progress_listener progress_queue = spawn_ctx.Queue() prog_listener_kwargs = { "progress_queue": progress_queue, "logging_queue": _logging_queue, } prog_listener = spawn_ctx.Process( target=progress_listener, kwargs=prog_listener_kwargs, name="Progress listener" ) prog_listener.start() started_processes.append(prog_listener) running_workers = [] # launch gpu workers logger.info( "Starting {n_workers_per_gpu} worker.s for each of the {n_gpus} gpu.s set for use/" "found.".format(n_workers_per_gpu=n_workers_per_gpu, n_gpus=len(gpu_ids)) ) for gpu_id in gpu_ids: for sub_id in range(n_workers_per_gpu): worker_kwargs = { "progress_queue": progress_queue, "logging_queue": _logging_queue, "exp_key": exp_key, "workdir": workdir, "gpu": True, "hw_id": str(gpu_id), "reserve_timeout": reserve_timeout, "mongo_port_address": mongo_port_address, } p = spawn_ctx.Process( target=hyperopt_worker, kwargs=worker_kwargs, name="Worker GPU " + str(gpu_id) + ":" + str(sub_id), ) p.start() running_workers.append(p) # launch cpu workers # TODO: add cpu affinity? logger.info( "Starting {n_cpu_workers} cpu worker.s".format(n_cpu_workers=n_cpu_workers) ) for cpu_id in range(n_cpu_workers): worker_kwargs = { "progress_queue": progress_queue, "logging_queue": _logging_queue, "exp_key": exp_key, "workdir": workdir, "gpu": False, "hw_id": str(cpu_id), "reserve_timeout": reserve_timeout, "mongo_port_address": mongo_port_address, } p = spawn_ctx.Process( target=hyperopt_worker, kwargs=worker_kwargs, name="Worker CPU " + str(cpu_id), ) # FIXME won't terminate if parent is killed (SIGKILL) p.start() running_workers.append(p) started_processes.extend(running_workers) # wait or return if all workers have died workers_watchdog(running_workers=running_workers, stop_event=stop_watchdog_event) logger.debug("Worker watchdog finished, terminating workers and closing listener.") for worker in running_workers: if worker.is_alive(): worker.terminate() listener.stop() prog_listener.terminate() @_cleanup_decorator def progress_listener(progress_queue, logging_queue): """Listens to workers when they finish a job and logs progress. Workers put in the progress_queue when they finish a job and when they do this function sends a log to the progress logger. """ # write all logs to queue root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) queue_handler = QueueHandler(logging_queue) queue_handler.setLevel(logging.DEBUG) root_logger.addHandler(queue_handler) logger.debug("Listener listening...") progress_logger = logging.getLogger("progress_logger") i = 0 while True: # get job done signal progress_queue.get() i += 1 logger.info("{i} job.s done".format(i=i)) # update progress bar through ProgressHandler progress_logger.info(None) if cleanup_event.is_set(): break def hyperopt_worker( progress_queue: multiprocessing.Queue, logging_queue: multiprocessing.Queue, exp_key: str, workdir: str = ".", gpu: bool = True, hw_id: str = None, poll_interval: float = 1.0, reserve_timeout: float = 30.0, mongo_port_address: str = "localhost:1234/scvi_db", ): """Launches a ``hyperopt`` ``MongoWorker`` which runs jobs until ``ReserveTimeout`` is raised. :param progress_queue: Queue in which to put None when a job is done. :param logging_queue: Queue to send logs to using a ``QueueHandler``. :param exp_key: This key is used by hyperopt as a suffix to the part of the MongoDb which corresponds to the current experiment. In particular, it has to be passed to ``MongoWorker``. :param workdir: :param gpu: If ``True`` means a GPU is to be used. :param hw_id: Id of the GPU to use. set via env variable ``CUDA_VISIBLE_DEVICES``. :param poll_interval: Time to wait between attempts to reserve a job. :param reserve_timeout: Amount of time, in seconds, a worker tries to reserve a job for before throwing a ``ReserveTimeout`` Exception. :param mongo_port_address: Addres to the running MongoDb service. """ # write all logs to queue root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) queue_handler = QueueHandler(logging_queue) queue_handler.setLevel(logging.DEBUG) root_logger.addHandler(queue_handler) logger.debug("Worker working...") os.environ["CUDA_VISIBLE_DEVICES"] = hw_id if gpu else str() # FIXME is this stil necessary? sys.path.append(".") mjobs = MongoJobs.new_from_connection_str( os.path.join(as_mongo_str(mongo_port_address), "jobs") ) mworker = MongoWorker(mjobs, float(poll_interval), workdir=workdir, exp_key=exp_key) while True: # FIXME we don't protect ourselves from memory leaks, bad cleanup, etc. try: mworker.run_one(reserve_timeout=float(reserve_timeout)) progress_queue.put(None) except ReserveTimeout: logger.debug( "Caught ReserveTimeout. " "Exiting after failing to reserve job for {time} seconds.".format( time=reserve_timeout ) ) break def workers_watchdog( running_workers: List[multiprocessing.Process], stop_event: threading.Event() ): """Checks that workers in running_workers are stil running. If none are running anymore, inform user and finish. """ while True: one_alive = False for worker in running_workers: one_alive = one_alive or worker.is_alive() # if all workers are dead, inform user if not one_alive: logger.debug( "All workers have died, check stdout/stderr for error tracebacks." ) break if stop_event.is_set(): logger.debug("Stopping Event set, stopping worker watchdog.") break if cleanup_event.is_set(): logger.debug("Cleaning up Event set, stopping worker watchdog.") stop_event.set() break time.sleep(5) def _objective_function( space: dict, gene_dataset: GeneExpressionDataset, model_class: Type[VAE] = VAE, trainer_class: Type[Trainer] = UnsupervisedTrainer, model_specific_kwargs: dict = None, trainer_specific_kwargs: dict = None, train_func_specific_kwargs: dict = None, use_batches: bool = False, is_best_training: bool = False, ) -> Union[Dict[str, Any], Trainer]: """Objective function for automatic hyperparameter optimization. Train a scVI model and return the best value of the early-stopping metric (e.g, log-likelihood). Convention: fixed parameters (no default) have precedence over tunable parameters (default). :param space: dict containing up to three sub-dicts with keys "model_tunable_kwargs", "trainer_tunable_kwargs" or "train_func_tunable_kwargs". Each of those dict contains hyperopt defined parameter spaces (e.g. ``hp.choice(..)``) which will be passed to the corresponding object : model, trainer or train method when performing hyperoptimization. :param gene_dataset: scVI gene dataset :param model_class: scVI model class (e.g ``VAE``, ``VAEC``, ``SCANVI``) :param trainer_class: Trainer class (e.g ``UnsupervisedTrainer``) :param model_specific_kwargs: dict of fixed parameters which will be passed to the model. :param trainer_specific_kwargs: dict of fixed parameters which will be passed to the trainer. :param train_func_specific_kwargs: dict of fixed parameters which will be passed to the train method. :param use_batches: If False, pass n_batch=0 to model else pass gene_dataset.n_batches :param is_best_training: True if training the model with the best hyperparameters :return: best value of the early stopping metric, and best model if is_best_training """ start_time = time.monotonic() # hyperopt params space = defaultdict(dict, space) model_tunable_kwargs = space["model_tunable_kwargs"] trainer_tunable_kwargs = space["trainer_tunable_kwargs"] train_func_tunable_kwargs = space["train_func_tunable_kwargs"] # use_cuda default if "use_cuda" not in trainer_specific_kwargs: trainer_specific_kwargs["use_cuda"] = bool(torch.cuda.device_count()) if "n_epochs" not in {**train_func_specific_kwargs, **train_func_tunable_kwargs}: train_func_specific_kwargs["n_epochs"] = 1000 # add hardcoded parameters # disable scVI progbar trainer_specific_kwargs["show_progbar"] = False if is_best_training: trainer_specific_kwargs["train_size"] = 1.0 # no monitoring, will crash otherwise trainer_specific_kwargs["frequency"] = None trainer_specific_kwargs["early_stopping_kwargs"] = {} else: # evaluate at each epoch trainer_specific_kwargs["frequency"] = 1 # merge params with fixed param precedence model_tunable_kwargs.update(model_specific_kwargs) trainer_tunable_kwargs.update(trainer_specific_kwargs) train_func_tunable_kwargs.update(train_func_specific_kwargs) if not is_best_training: logger.info( "Parameters being tested: \n" "model: \n" + str(model_tunable_kwargs) + "\n" + "trainer: \n" + str(trainer_tunable_kwargs) + "\n" + "train method: \n" + str(train_func_tunable_kwargs) ) # define model logger.debug("Instantiating model") model = model_class( n_input=gene_dataset.nb_genes, n_batch=gene_dataset.n_batches * use_batches, **model_tunable_kwargs, ) # define trainer logger.debug("Instantiating trainer") trainer = trainer_class(model, gene_dataset, **trainer_tunable_kwargs) # train model logger.debug("Starting training") trainer.train(**train_func_tunable_kwargs) logger.debug("Finished training") elapsed_time = time.monotonic() - start_time # if training the best model, return model else return criterion if is_best_training: return trainer else: # select metric from early stopping kwargs if possible metric = None early_stopping_kwargs = trainer_specific_kwargs.get( "early_stopping_kwargs", None ) if early_stopping_kwargs: metric = early_stopping_kwargs.get("early_stopping_metric", None) # store run results if metric: early_stopping_loss_is_best = True best_epoch = trainer.best_epoch # add actual number of epochs to be used when training best model space["train_func_tunable_kwargs"]["n_epochs"] = best_epoch early_stopping_loss = trainer.early_stopping.best_performance metric += "_" + trainer.early_stopping.on # default to elbo else: early_stopping_loss_is_best = False metric = "elbo_test_set" early_stopping_loss = trainer.history[metric][-1] best_epoch = len(trainer.history[metric]) # compute true ll loss = trainer.test_set.marginal_ll(n_mc_samples=100) logger.debug( "Training of {n_epochs} epochs finished in {time} with loss = {loss}".format( n_epochs=len(trainer.history[metric]), time=str(datetime.timedelta(seconds=elapsed_time)), loss=loss, ) ) # check status status = STATUS_OK if np.isnan(loss): status = STATUS_FAIL return { "loss": loss, "early_stopping_loss": early_stopping_loss, "early_stopping_loss_is_best": early_stopping_loss_is_best, "best_epoch": best_epoch, "elapsed_time": elapsed_time, "status": status, "history": trainer.history, "space": space, "worker_name": multiprocessing.current_process().name, }
[ "logging.getLogger", "logging.StreamHandler", "logging.debug", "torch.cuda.device_count", "time.sleep", "os.cpu_count", "datetime.timedelta", "sys.path.append", "os.path.exists", "functools.wraps", "hyperopt.hp.choice", "time.monotonic", "multiprocessing.get_context", "numpy.isnan", "mul...
[((992, 1028), 'multiprocessing.get_context', 'multiprocessing.get_context', (['"""spawn"""'], {}), "('spawn')\n", (1019, 1028), False, 'import multiprocessing\n'), ((1040, 1075), 'multiprocessing.get_context', 'multiprocessing.get_context', (['"""fork"""'], {}), "('fork')\n", (1067, 1075), False, 'import multiprocessing\n'), ((1343, 1370), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1360, 1370), False, 'import logging\n'), ((1383, 1503), 'logging.Formatter', 'logging.Formatter', (['"""[%(asctime)s - %(processName)s - %(threadName)s] %(levelname)s - %(name)s\n%(message)s"""'], {}), '(\n """[%(asctime)s - %(processName)s - %(threadName)s] %(levelname)s - %(name)s\n%(message)s"""\n )\n', (1400, 1503), False, 'import logging\n'), ((1502, 1525), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1523, 1525), False, 'import logging\n'), ((1739, 1756), 'threading.Event', 'threading.Event', ([], {}), '()\n', (1754, 1756), False, 'import threading\n'), ((4340, 4351), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (4345, 4351), False, 'from functools import partial, wraps\n'), ((20406, 20438), 'os.path.join', 'os.path.join', (['save_path', '"""mongo"""'], {}), "(save_path, 'mongo')\n", (20418, 20438), False, 'import os\n'), ((21017, 21069), 'os.path.join', 'os.path.join', (["(mongo_host + ':' + mongo_port)", 'db_name'], {}), "(mongo_host + ':' + mongo_port, db_name)\n", (21029, 21069), False, 'import os\n'), ((21159, 21188), 'logging.getLogger', 'logging.getLogger', (['"""hyperopt"""'], {}), "('hyperopt')\n", (21176, 21188), False, 'import logging\n'), ((21423, 21459), 'logging.getLogger', 'logging.getLogger', (['"""progress_logger"""'], {}), "('progress_logger')\n", (21440, 21459), False, 'import logging\n'), ((21536, 21579), 'tqdm.tqdm', 'tqdm.tqdm', ([], {'total': 'max_evals', 'disable': 'disable'}), '(total=max_evals, disable=disable)\n', (21545, 21579), False, 'import tqdm\n'), ((22614, 22631), 'threading.Event', 'threading.Event', ([], {}), '()\n', (22629, 22631), False, 'import threading\n'), ((23046, 23138), 'threading.Thread', 'threading.Thread', ([], {'target': 'launch_workers', 'kwargs': 'launcher_kwargs', 'name': '"""Worker Launcher"""'}), "(target=launch_workers, kwargs=launcher_kwargs, name=\n 'Worker Launcher')\n", (23062, 23138), False, 'import threading\n'), ((23299, 23316), 'threading.Event', 'threading.Event', ([], {}), '()\n', (23314, 23316), False, 'import threading\n'), ((23339, 23356), 'threading.Event', 'threading.Event', ([], {}), '()\n', (23354, 23356), False, 'import threading\n'), ((23375, 23511), 'threading.Thread', 'threading.Thread', ([], {'target': '_wait_for_process_or_thread', 'kwargs': "{'process': fmin_process, 'event': fmin_done_event}", 'name': '"""Waiter fmin"""'}), "(target=_wait_for_process_or_thread, kwargs={'process':\n fmin_process, 'event': fmin_done_event}, name='Waiter fmin')\n", (23391, 23511), False, 'import threading\n'), ((23624, 23768), 'threading.Thread', 'threading.Thread', ([], {'target': '_wait_for_process_or_thread', 'kwargs': "{'process': workers_thread, 'event': workers_done_event}", 'name': '"""Waiter workers"""'}), "(target=_wait_for_process_or_thread, kwargs={'process':\n workers_thread, 'event': workers_done_event}, name='Waiter workers')\n", (23640, 23768), False, 'import threading\n'), ((26841, 26890), 'threading.Thread', 'threading.Thread', ([], {'target': 'fmin', 'kwargs': 'fmin_kwargs'}), '(target=fmin, kwargs=fmin_kwargs)\n', (26857, 26890), False, 'import threading\n'), ((35441, 35460), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (35458, 35460), False, 'import logging\n'), ((35521, 35548), 'logging.handlers.QueueHandler', 'QueueHandler', (['logging_queue'], {}), '(logging_queue)\n', (35533, 35548), False, 'from logging.handlers import QueueListener, QueueHandler\n'), ((35698, 35734), 'logging.getLogger', 'logging.getLogger', (['"""progress_logger"""'], {}), "('progress_logger')\n", (35715, 35734), False, 'import logging\n'), ((37303, 37322), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (37320, 37322), False, 'import logging\n'), ((37383, 37410), 'logging.handlers.QueueHandler', 'QueueHandler', (['logging_queue'], {}), '(logging_queue)\n', (37395, 37410), False, 'from logging.handlers import QueueListener, QueueHandler\n'), ((37640, 37660), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (37655, 37660), False, 'import sys\n'), ((41068, 41084), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (41082, 41084), False, 'import time\n'), ((41119, 41143), 'collections.defaultdict', 'defaultdict', (['dict', 'space'], {}), '(dict, space)\n', (41130, 41143), False, 'from collections import defaultdict\n'), ((2225, 2255), 'logging.getLogger', 'logging.getLogger', (['record.name'], {}), '(record.name)\n', (2242, 2255), False, 'import logging\n'), ((3998, 4027), 'logging.getLogger', 'logging.getLogger', (['"""hyperopt"""'], {}), "('hyperopt')\n", (4015, 4027), False, 'import logging\n'), ((11055, 11107), 'os.path.join', 'os.path.join', (['save_path', '"""scvi_autotune_logfile.txt"""'], {}), "(save_path, 'scvi_autotune_logfile.txt')\n", (11067, 11107), False, 'import os\n'), ((13506, 13830), 'functools.partial', 'partial', (['_objective_function'], {}), "(_objective_function, **{'gene_dataset': gene_dataset, 'model_class':\n model_class, 'trainer_class': trainer_class, 'model_specific_kwargs':\n model_specific_kwargs, 'trainer_specific_kwargs':\n trainer_specific_kwargs, 'train_func_specific_kwargs':\n train_func_specific_kwargs, 'use_batches': use_batches})\n", (13513, 13830), False, 'from functools import partial, wraps\n'), ((14742, 14750), 'hyperopt.Trials', 'Trials', ([], {}), '()\n', (14748, 14750), False, 'from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL\n'), ((14796, 14895), 'hyperopt.fmin', 'fmin', ([], {'fn': 'objective_hyperopt', 'space': 'space', 'algo': 'tpe.suggest', 'max_evals': 'max_evals', 'trials': 'trials'}), '(fn=objective_hyperopt, space=space, algo=tpe.suggest, max_evals=\n max_evals, trials=trials)\n', (14800, 14895), False, 'from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL\n'), ((20450, 20476), 'os.path.exists', 'os.path.exists', (['mongo_path'], {}), '(mongo_path)\n', (20464, 20476), False, 'import os\n'), ((20486, 20509), 'os.makedirs', 'os.makedirs', (['mongo_path'], {}), '(mongo_path)\n', (20497, 20509), False, 'import os\n'), ((20535, 20580), 'os.path.join', 'os.path.join', (['mongo_path', '"""mongo_logfile.txt"""'], {}), "(mongo_path, 'mongo_logfile.txt')\n", (20547, 20580), False, 'import os\n'), ((21227, 21274), 'os.path.join', 'os.path.join', (['save_path', '"""hyperopt_logfile.txt"""'], {}), "(save_path, 'hyperopt_logfile.txt')\n", (21239, 21274), False, 'import os\n'), ((23950, 23963), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (23960, 23963), False, 'import time\n'), ((27253, 27269), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (27267, 27269), False, 'import time\n'), ((27453, 27496), 'logging.debug', 'logging.debug', (['"""No timer, waiting for fmin"""'], {}), "('No timer, waiting for fmin')\n", (27466, 27496), False, 'import logging\n'), ((29017, 29030), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (29027, 29030), False, 'import time\n'), ((29098, 29115), 'threading.Event', 'threading.Event', ([], {}), '()\n', (29113, 29115), False, 'import threading\n'), ((31562, 31587), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (31585, 31587), False, 'import torch\n'), ((38443, 38460), 'threading.Event', 'threading.Event', ([], {}), '()\n', (38458, 38460), False, 'import threading\n'), ((39234, 39247), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (39244, 39247), False, 'import time\n'), ((43157, 43173), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (43171, 43173), False, 'import time\n'), ((44720, 44734), 'numpy.isnan', 'np.isnan', (['loss'], {}), '(loss)\n', (44728, 44734), True, 'import numpy as np\n'), ((16041, 16063), 'pickle.dump', 'pickle.dump', (['trials', 'f'], {}), '(trials, f)\n', (16052, 16063), False, 'import pickle\n'), ((26487, 26527), 'os.path.join', 'os.path.join', (['mongo_port_address', '"""jobs"""'], {}), "(mongo_port_address, 'jobs')\n", (26499, 26527), False, 'import os\n'), ((27367, 27381), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (27377, 27381), False, 'import time\n'), ((31876, 31977), 'logging.debug', 'logging.debug', (['"""Some GPU.s found and n_cpu_wokers is None, defaulting to n_cpu_workers = 0"""'], {}), "(\n 'Some GPU.s found and n_cpu_wokers is None, defaulting to n_cpu_workers = 0'\n )\n", (31889, 31977), False, 'import logging\n'), ((37730, 37762), 'hyperopt.mongoexp.as_mongo_str', 'as_mongo_str', (['mongo_port_address'], {}), '(mongo_port_address)\n', (37742, 37762), False, 'from hyperopt.mongoexp import as_mongo_str, MongoJobs, MongoTrials, MongoWorker, ReserveTimeout\n'), ((41454, 41479), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (41477, 41479), False, 'import torch\n'), ((12661, 12698), 'hyperopt.hp.choice', 'hp.choice', (['"""n_hidden"""', '[64, 128, 256]'], {}), "('n_hidden', [64, 128, 256])\n", (12670, 12698), False, 'from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL\n'), ((12791, 12843), 'hyperopt.hp.choice', 'hp.choice', (['"""dropout_rate"""', '[0.1, 0.3, 0.5, 0.7, 0.9]'], {}), "('dropout_rate', [0.1, 0.3, 0.5, 0.7, 0.9])\n", (12800, 12843), False, 'from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL\n'), ((12884, 12932), 'hyperopt.hp.choice', 'hp.choice', (['"""reconstruction_loss"""', "['zinb', 'nb']"], {}), "('reconstruction_loss', ['zinb', 'nb'])\n", (12893, 12932), False, 'from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL\n'), ((13014, 13067), 'hyperopt.hp.choice', 'hp.choice', (['"""lr"""', '[0.01, 0.005, 0.001, 0.0005, 0.0001]'], {}), "('lr', [0.01, 0.005, 0.001, 0.0005, 0.0001])\n", (13023, 13067), False, 'from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL\n'), ((15526, 15554), 'pickle.dump', 'pickle.dump', (['best_trainer', 'f'], {}), '(best_trainer, f)\n', (15537, 15554), False, 'import pickle\n'), ((27405, 27421), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (27419, 27421), False, 'import time\n'), ((27616, 27630), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (27626, 27630), False, 'import time\n'), ((32075, 32089), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (32087, 32089), False, 'import os\n'), ((45146, 45179), 'multiprocessing.current_process', 'multiprocessing.current_process', ([], {}), '()\n', (45177, 45179), False, 'import multiprocessing\n'), ((12594, 12620), 'hyperopt.hp.randint', 'hp.randint', (['"""n_latent"""', '(11)'], {}), "('n_latent', 11)\n", (12604, 12620), False, 'from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL\n'), ((12732, 12757), 'hyperopt.hp.randint', 'hp.randint', (['"""n_layers"""', '(5)'], {}), "('n_layers', 5)\n", (12742, 12757), False, 'from hyperopt import fmin, tpe, Trials, hp, STATUS_OK, STATUS_FAIL\n'), ((44564, 44604), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'elapsed_time'}), '(seconds=elapsed_time)\n', (44582, 44604), False, 'import datetime\n')]
# coding:utf-8 import os.path import sys import re import os import json import tensorflow as tf import numpy as np from sklearn import preprocessing import pickle as pickle #python pkl 文件读写 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D class MyData(): def __init__(self): self.data_filePath = [] self.data_fileName = [] self.data = [] self.labels = [] # 遍历指定目录,显示目录下的所有文件名 def eachFile(filepath): pathDir = os.listdir(filepath) data = MyData() for allDir in pathDir: if allDir != ".DS_Store": child = os.path.join('%s/%s' % (filepath, allDir)) if os.path.isfile(child): data.data_filePath.append(child) data.data_fileName.append(allDir) theTpye = re.split('-',allDir)[0] # print(theTpye) data.labels.append( int(theTpye)-1 ) # # 显示 # for i in array: # print(i) return data def myFastGFile(py_data): # 新建一个Session with tf.Session() as sess: ''' image_raw_data = tf.gfile.FastGFile(py_data.data_filePath[0], 'rb').read() img_data = tf.image.decode_jpeg(image_raw_data) plt.imshow(img_data.eval()) plt.show() resized = tf.image.resize_images(img_data, [28, 28], method=0) print(resized) resized = tf.reshape(resized, [28, 28, 3]) #最后一维代表通道数目,如果是rgb则为3 print(resized) # TensorFlow的函数处理图片后存储的数据是float32格式的,需要转换成uint8才能正确打印图片。 print("Digital type: ", resized.dtype) resized = np.asarray(resized.eval(), dtype='uint8') # tf.image.convert_image_dtype(rgb_image, tf.float32) plt.imshow(resized) plt.show() ''' # path = py_data.data_filePath[0] for path in py_data.data_filePath: # 读取文件 image_raw_data = tf.gfile.FastGFile(path, 'rb').read() # 解码 img_data = tf.image.decode_jpeg(image_raw_data) # print(img_data) # 转灰度图 # img_data = sess.run(tf.image.rgb_to_grayscale(img_data)) # 改变图片尺寸 resized = tf.image.resize_images(img_data, [100, 100], method=0) # 设定 shape # resized = tf.reshape(resized, [28, 28, 1]) #最后一维代表通道数目,如果是rgb则为3 resized = tf.reshape(resized, [100, 100, 3]) #最后一维代表通道数目,如果是rgb则为3 # 标准化 # standardization_image = resized standardization_image = tf.image.per_image_standardization(resized)#标准化 # print(standardization_image) # print(standardization_image.eval()) resized = tf.reshape(standardization_image, [-1]) #最后一维代表通道数目,如果是rgb则为3 # resized = tf.reshape(resized, [-1]) #最后一维代表通道数目,如果是rgb则为3 ## 链接 ## resized = tf.expand_dims(resized, 0) # 增加一个维度 ## print(resized) ## print(py_data.data) ## test_data = tf.concat(0, [test_data, resized]) py_data.data.append(resized.eval()) ''' # #验证数据转换正确 resized = tf.reshape(py_data.data[0], [100, 100, 3]) resized = np.asarray(resized.eval(), dtype='uint8') plt.imshow(resized) plt.show() ''' def saveData(py_data, filePath_data, filePath_labels): pass ''' with tf.Session() as sess: train_data =tf.convert_to_tensor(np.array( trainData.data ) ) ''' data = np.array( py_data.data ) labels = py_data.labels # import os if os.path.exists(filePath_data): #删除文件,可使用以下两种方法。 os.remove(filePath_data) #os.unlink(my_file) if os.path.exists(filePath_labels): #删除文件,可使用以下两种方法。 os.remove(filePath_labels) #os.unlink(my_file) with open(filePath_data,'wb') as f: pickle.dump(data, f) with open(filePath_labels,'wb') as f: pickle.dump(labels, f) print('\ndone!') def run(dataPath, plkFileName, plkFileNameLabels): # dataPath = "data/train" # plkFileName = "train_data.plk" # plkFileNameLabels = "train_labels.plk" # 遍历每一个文件 loadData = eachFile(dataPath) #注意:末尾不加/ # 转换类型 myFastGFile(loadData) # 保存转换后的数据 saveData(loadData, plkFileName, plkFileNameLabels) if __name__ == "__main__": pass print('目前系统的编码为:',sys.getdefaultencoding()) # ## 训练集 - 60% # run("data/train", "cache/train_data.plk", "cache/train_labels.plk") # ## 评估集 - 20% # run("data/valid", "cache/valid_data.plk", "cache/valid_labels.plk") # ## 测试集 - 20% # run("data/test", "cache/test_data.plk", "cache/test_labels.plk") ## 测试集 - 20% run("data/test_temporary", "cache/test_temporary_data.plk", "cache/test_temporary_labels.plk")
[ "os.path.exists", "tensorflow.image.resize_images", "os.listdir", "pickle.dump", "sys.getdefaultencoding", "re.split", "tensorflow.Session", "os.path.join", "tensorflow.gfile.FastGFile", "os.path.isfile", "numpy.array", "tensorflow.image.per_image_standardization", "tensorflow.image.decode_j...
[((481, 501), 'os.listdir', 'os.listdir', (['filepath'], {}), '(filepath)\n', (491, 501), False, 'import os\n'), ((3515, 3537), 'numpy.array', 'np.array', (['py_data.data'], {}), '(py_data.data)\n', (3523, 3537), True, 'import numpy as np\n'), ((3592, 3621), 'os.path.exists', 'os.path.exists', (['filePath_data'], {}), '(filePath_data)\n', (3606, 3621), False, 'import os\n'), ((3706, 3737), 'os.path.exists', 'os.path.exists', (['filePath_labels'], {}), '(filePath_labels)\n', (3720, 3737), False, 'import os\n'), ((1048, 1060), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1058, 1060), True, 'import tensorflow as tf\n'), ((3648, 3672), 'os.remove', 'os.remove', (['filePath_data'], {}), '(filePath_data)\n', (3657, 3672), False, 'import os\n'), ((3764, 3790), 'os.remove', 'os.remove', (['filePath_labels'], {}), '(filePath_labels)\n', (3773, 3790), False, 'import os\n'), ((3866, 3886), 'pickle.dump', 'pickle.dump', (['data', 'f'], {}), '(data, f)\n', (3877, 3886), True, 'import pickle as pickle\n'), ((3938, 3960), 'pickle.dump', 'pickle.dump', (['labels', 'f'], {}), '(labels, f)\n', (3949, 3960), True, 'import pickle as pickle\n'), ((4393, 4417), 'sys.getdefaultencoding', 'sys.getdefaultencoding', ([], {}), '()\n', (4415, 4417), False, 'import sys\n'), ((603, 645), 'os.path.join', 'os.path.join', (["('%s/%s' % (filepath, allDir))"], {}), "('%s/%s' % (filepath, allDir))\n", (615, 645), False, 'import os\n'), ((661, 682), 'os.path.isfile', 'os.path.isfile', (['child'], {}), '(child)\n', (675, 682), False, 'import os\n'), ((1981, 2017), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['image_raw_data'], {}), '(image_raw_data)\n', (2001, 2017), True, 'import tensorflow as tf\n'), ((2183, 2237), 'tensorflow.image.resize_images', 'tf.image.resize_images', (['img_data', '[100, 100]'], {'method': '(0)'}), '(img_data, [100, 100], method=0)\n', (2205, 2237), True, 'import tensorflow as tf\n'), ((2363, 2397), 'tensorflow.reshape', 'tf.reshape', (['resized', '[100, 100, 3]'], {}), '(resized, [100, 100, 3])\n', (2373, 2397), True, 'import tensorflow as tf\n'), ((2521, 2564), 'tensorflow.image.per_image_standardization', 'tf.image.per_image_standardization', (['resized'], {}), '(resized)\n', (2555, 2564), True, 'import tensorflow as tf\n'), ((2684, 2723), 'tensorflow.reshape', 'tf.reshape', (['standardization_image', '[-1]'], {}), '(standardization_image, [-1])\n', (2694, 2723), True, 'import tensorflow as tf\n'), ((809, 830), 're.split', 're.split', (['"""-"""', 'allDir'], {}), "('-', allDir)\n", (817, 830), False, 'import re\n'), ((1903, 1933), 'tensorflow.gfile.FastGFile', 'tf.gfile.FastGFile', (['path', '"""rb"""'], {}), "(path, 'rb')\n", (1921, 1933), True, 'import tensorflow as tf\n')]
### # # Simple script for using world # # (Made for 2 agents with turn based movements, but can be extended for multiple agents) # For Open Acess and Use # # Made by <NAME> at University of South Florida # ### from World import World import numpy as np import time # Creates new World test_world = World("Test") # Display World in Terminal test_world.render() done = 0 while(not done): test_world.render() time.sleep(0.25) # Chose random actions random_action_agent1 = ["RIGHT","LEFT","UP","DOWN","ATTACK"][np.random.randint(5)] random_action_agent2 = ["RIGHT","LEFT","UP","DOWN","ATTACK"][np.random.randint(5)] # Take action state1, reward1, done = test_world.step(random_action_agent1,test_world.agent1.name) state2, reward2, done = test_world.step(random_action_agent2,test_world.agent2.name) # Resets world just so you know how test_world.reset() # Prints Final Values print(state1) print(reward1) print(done)
[ "World.World", "numpy.random.randint", "time.sleep" ]
[((300, 313), 'World.World', 'World', (['"""Test"""'], {}), "('Test')\n", (305, 313), False, 'from World import World\n'), ((418, 434), 'time.sleep', 'time.sleep', (['(0.25)'], {}), '(0.25)\n', (428, 434), False, 'import time\n'), ((528, 548), 'numpy.random.randint', 'np.random.randint', (['(5)'], {}), '(5)\n', (545, 548), True, 'import numpy as np\n'), ((615, 635), 'numpy.random.randint', 'np.random.randint', (['(5)'], {}), '(5)\n', (632, 635), True, 'import numpy as np\n')]
''' Retrieval Network, Written by Xiao For robot localization in a dynamic environment. ''' import torch import time import os import copy, math import numpy as np import matplotlib.pyplot as plt from termcolor import colored from progress.bar import Bar from Network.retrieval_network.params import * # ------------------------------------------------------------------------------ def Training(data_loaders, dataset_sizes, model, loss_fcn, optimizer, lr_scheduler, num_epochs=NUM_EPOCHS, checkpoints_prefix=None, batch_size=None): """ Loaders, model, loss function and metrics should work together for a given task, i.e. The model should be able to process data output of loaders, loss function should process target output of loaders and outputs from the model """ start_time = time.time() # Traning starting time_elapsed device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Intialize storage for best weights/model and accuracy best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 training_statistics = {'train':[[],[]], 'val':[[],[]]} # -------------------------------------------------------------------------- # Traning start # -------------------------------------------------------------------------- for epoch in range(num_epochs): print('----'*10 + '\n' + colored('Traning Info: ','blue') + 'Epoch {}/{}'.format(epoch + 1, num_epochs)) # ---------------------------------------------------------------------- # Each epoch has a training and validation phase # ---------------------------------------------------------------------- for phase in ['train', 'val']: if phase == 'train': model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # ----------------------------Train--------------------------------- # Iteration over train/validation dataset # ------------------------------------------------------------------ # loading bar print('----'*6) bar = Bar('Processing', max=math.ceil(dataset_sizes[phase]/batch_size)) for batch_idx, inputs in enumerate(data_loaders[phase]): # zero the parameter gradients optimizer.zero_grad() # Case scene graph brach: for triplet data (A,N,P), each of A,N,P have 3 matrices for scene graphs inputs = tuple(input.to(device) for input in inputs) # to GPU # Forward propagation # Track history if only in trainer with torch.set_grad_enabled(phase == 'train'): outputs = model(*inputs) loss, correct_num = loss_fcn(*outputs, batch_average_loss=True) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() # -------------------------------------------------------------- # Get/calculate training statistics running_loss += loss.item() running_corrects += correct_num bar.next() bar.finish() # ------------------------------------------------------------------ if phase == 'train': lr_scheduler.step() # update LEARNING_RATE # Epoch loss calculation epoch_loss = running_loss * batch_size / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase] print('{} Loss: \t {:.4f} \t Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc)) training_statistics[phase][0].append(epoch_acc.item()) training_statistics[phase][1].append(epoch_loss) np.save(checkpoints_prefix + 'training_statistics.npy', training_statistics) # deep copy the model: based on minimum loss if phase == 'val': if checkpoints_prefix != None: FILE = checkpoints_prefix + 'training_history/' + '_loss_' + str(epoch_loss) + '_acc_' + str(epoch_acc.item()) + '_epoch_' + str(epoch+1) + '.pkl' torch.save(model.state_dict(), FILE) if epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) # ------------------------------------------------------------------ # -------------------------------------------------------------------------- time_elapsed = time.time() - start_time print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)) print('Best val accuracy: {:4f}'.format(best_acc)) # load best model weights model.load_state_dict(best_model_wts) return model def plot_training_statistics(parent_dir=CHECKPOINTS_DIR,filename='training_statistics.npy'): f, (ax1, ax2) = plt.subplots(2, 1, figsize=(6,5)) color = ['blue', 'red', 'green', 'black', 'cyan'] i = 0 for xxxnet in os.listdir(parent_dir): if not os.path.exists(parent_dir+xxxnet+'/'+filename): continue training_statistics = np.load(parent_dir+xxxnet+'/'+filename, allow_pickle=True).item() epochs = [*range(len(training_statistics['train'][0]))] ax1.plot(epochs, training_statistics['train'][0], color=color[i], linestyle='solid', linewidth=2, label=xxxnet + ' Training') ax2.plot(epochs, training_statistics['train'][1], color=color[i], linestyle='solid', linewidth=2, label=xxxnet + ' Training') ax2.plot(epochs, training_statistics['val'][1], color=color[i], linestyle='dashed', linewidth=2, label=xxxnet + ' val.') ax1.plot(epochs, training_statistics['val'][0], color=color[i], linestyle='dashed', linewidth=2, label=xxxnet + ' val.') # ax1.set_xlabel("Epoch") ax1.set_ylabel("Accuracy") ax2.set_xlabel("Epoch") ax2.set_ylabel("Loss") ax2.grid(True) ax1.grid(True) i += 1 ax1.legend(bbox_to_anchor=(0.10, 1.02), ncol=i) plt.show()
[ "os.path.exists", "os.listdir", "termcolor.colored", "math.ceil", "torch.cuda.is_available", "torch.set_grad_enabled", "numpy.load", "time.time", "matplotlib.pyplot.subplots", "numpy.save", "matplotlib.pyplot.show" ]
[((806, 817), 'time.time', 'time.time', ([], {}), '()\n', (815, 817), False, 'import time\n'), ((5141, 5175), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(6, 5)'}), '(2, 1, figsize=(6, 5))\n', (5153, 5175), True, 'import matplotlib.pyplot as plt\n'), ((5257, 5279), 'os.listdir', 'os.listdir', (['parent_dir'], {}), '(parent_dir)\n', (5267, 5279), False, 'import os\n'), ((6301, 6311), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6309, 6311), True, 'import matplotlib.pyplot as plt\n'), ((4759, 4770), 'time.time', 'time.time', ([], {}), '()\n', (4768, 4770), False, 'import time\n'), ((888, 913), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (911, 913), False, 'import torch\n'), ((3987, 4063), 'numpy.save', 'np.save', (["(checkpoints_prefix + 'training_statistics.npy')", 'training_statistics'], {}), "(checkpoints_prefix + 'training_statistics.npy', training_statistics)\n", (3994, 4063), True, 'import numpy as np\n'), ((5296, 5348), 'os.path.exists', 'os.path.exists', (["(parent_dir + xxxnet + '/' + filename)"], {}), "(parent_dir + xxxnet + '/' + filename)\n", (5310, 5348), False, 'import os\n'), ((5395, 5459), 'numpy.load', 'np.load', (["(parent_dir + xxxnet + '/' + filename)"], {'allow_pickle': '(True)'}), "(parent_dir + xxxnet + '/' + filename, allow_pickle=True)\n", (5402, 5459), True, 'import numpy as np\n'), ((1371, 1404), 'termcolor.colored', 'colored', (['"""Traning Info: """', '"""blue"""'], {}), "('Traning Info: ', 'blue')\n", (1378, 1404), False, 'from termcolor import colored\n'), ((2256, 2300), 'math.ceil', 'math.ceil', (['(dataset_sizes[phase] / batch_size)'], {}), '(dataset_sizes[phase] / batch_size)\n', (2265, 2300), False, 'import copy, math\n'), ((2758, 2798), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (["(phase == 'train')"], {}), "(phase == 'train')\n", (2780, 2798), False, 'import torch\n')]
import tensorflow as tf import os import numpy as np from PIL import Image import matplotlib.pyplot as plt lines = tf.gfile.GFile('F:/Projects/PycharmProjects/test/retrain/output_labels.txt').readlines() uid_to_human = {} # 一行一行读取数据 for uid, line in enumerate(lines): # 去掉换行符 line = line.strip('\n') uid_to_human[uid] = line def id_to_string(node_id): if node_id not in uid_to_human: return "" return uid_to_human[node_id] # 创建一个图来存放google训练好的模型 with tf.gfile.FastGFile('F:/Projects/PycharmProjects/test/retrain/output_graph.pb', 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') with tf.Session() as sess: softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') # 遍历目录 for root, dirs, files in os.walk('F:/Projects/PycharmProjects/opencvtest/Food_classification/test'): for file in files: # 载入图片 image_data = tf.gfile.FastGFile(os.path.join(root, file), 'rb').read() predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})# 图片格式是jpg格式 predictions = np.squeeze(predictions)# 把结果转为1维数据 # 打印图片路径名称 image_path = os.path.join(root, file) print(image_path) # 排序 top_k = predictions.argsort()[::-1] print(top_k) for node_id in top_k: # 获取分类名称 human_string = id_to_string(node_id) # 获取该分类的置信度 score = predictions[node_id] print('%s (score = %0.5f)' % (human_string, score)) # 显示图片 img = Image.open(image_path) plt.imshow(img) plt.axis('off') plt.show() print()
[ "matplotlib.pyplot.imshow", "PIL.Image.open", "tensorflow.Session", "os.path.join", "tensorflow.GraphDef", "tensorflow.gfile.FastGFile", "numpy.squeeze", "tensorflow.import_graph_def", "tensorflow.gfile.GFile", "matplotlib.pyplot.axis", "os.walk", "matplotlib.pyplot.show" ]
[((485, 573), 'tensorflow.gfile.FastGFile', 'tf.gfile.FastGFile', (['"""F:/Projects/PycharmProjects/test/retrain/output_graph.pb"""', '"""rb"""'], {}), "('F:/Projects/PycharmProjects/test/retrain/output_graph.pb',\n 'rb')\n", (503, 573), True, 'import tensorflow as tf\n'), ((592, 605), 'tensorflow.GraphDef', 'tf.GraphDef', ([], {}), '()\n', (603, 605), True, 'import tensorflow as tf\n'), ((650, 689), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['graph_def'], {'name': '""""""'}), "(graph_def, name='')\n", (669, 689), True, 'import tensorflow as tf\n'), ((697, 709), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (707, 709), True, 'import tensorflow as tf\n'), ((828, 902), 'os.walk', 'os.walk', (['"""F:/Projects/PycharmProjects/opencvtest/Food_classification/test"""'], {}), "('F:/Projects/PycharmProjects/opencvtest/Food_classification/test')\n", (835, 902), False, 'import os\n'), ((117, 193), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['"""F:/Projects/PycharmProjects/test/retrain/output_labels.txt"""'], {}), "('F:/Projects/PycharmProjects/test/retrain/output_labels.txt')\n", (131, 193), True, 'import tensorflow as tf\n'), ((1161, 1184), 'numpy.squeeze', 'np.squeeze', (['predictions'], {}), '(predictions)\n', (1171, 1184), True, 'import numpy as np\n'), ((1245, 1269), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (1257, 1269), False, 'import os\n'), ((1681, 1703), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (1691, 1703), False, 'from PIL import Image\n'), ((1716, 1731), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (1726, 1731), True, 'import matplotlib.pyplot as plt\n'), ((1744, 1759), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1752, 1759), True, 'import matplotlib.pyplot as plt\n'), ((1772, 1782), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1780, 1782), True, 'import matplotlib.pyplot as plt\n'), ((994, 1018), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (1006, 1018), False, 'import os\n')]
import numpy as np import matplotlib.pyplot as plt class Machine(): def __init__(self, mean, sigma, label): self.mean = mean self.sigma = sigma self.label = label def sample(self): return np.random.normal(loc=self.mean, scale=self.sigma, size=1)[0] class Agent(): def __init__(self, epsilon, Nsteps, Nmachines, label=None): self.epsilon = epsilon self.Nsteps = Nsteps self.label = label self.Q = np.zeros((Nmachines, Nsteps)) self.rewards = np.zeros(Nsteps) self.numbers = np.zeros(Nmachines) self.pulls = 0 self.averages = None def get_reward(self, machine): return machine.sample() def pull(self, Q, machines): best_machine = np.argmax(Q) if (np.random.uniform(0, 1, size=1)[0] > self.epsilon): return machines[best_machine] else: index_sample = np.random.randint(0, len(machines) - 1, size=1)[0] while index_sample == best_machine: index_sample = np.random.randint(0, len(machines) - 1, size=1)[0] return machines[index_sample] def update(self, Q, machines): pulled_machine = self.pull(Q, machines) reward = self.get_reward(pulled_machine) num = self.numbers[pulled_machine.label] self.numbers[pulled_machine.label] += 1 Qnew = Q Qnew[pulled_machine.label] = (reward + Q[pulled_machine.label]*num)/(num + 1) self.pulls += 1 return Qnew, reward def get_averages(self): return self.averages def get_numbers(self): return self.numbers class ProbabilityAgent(): def __init__(self, Nsteps, alpha, Nmachines, label=None): self.Nsteps = Nsteps self.label = label self.alpha = alpha self.H = np.zeros((Nmachines, Nsteps)) self.probabilities = (1/Nmachines) * np.ones(Nmachines) self.rewards = np.zeros(Nsteps) self.numbers = np.zeros(Nmachines) self.pulls = 0 self.averages = np.zeros(Nsteps) def get_reward(self, machine): return machine.sample() def pull(self, machines): machine = np.random.choice([i for i in range(len(machines))], size=1, p=list(self.probabilities)) return machines[machine[0]] def first_step(self, machines): pulled_machine = self.pull(machines) reward = pulled_machine.sample() self.numbers[pulled_machine.label] += 1 self.rewards[self.pulls] = reward self.averages[0] = reward machine_index = pulled_machine.label mask = np.ones(len(machines), dtype='bool') mask[machine_index] = False H = self.H[:, 0] H[mask] = H[mask] - self.alpha * (reward - self.averages[0]) * self.probabilities[mask] H[machine_index] = H[machine_index] + self.alpha * (reward - self.averages[0]) * (1 - self.probabilities[machine_index]) self.H[:, 1] = H self.probabilities = calculate_probabilities(H) self.pulls += 1 def update(self, machines): pulled_machine = self.pull(machines) reward = pulled_machine.sample() self.numbers[pulled_machine.label] += 1 self.rewards[self.pulls] = reward self.averages[self.pulls] = (reward + self.pulls*self.averages[self.pulls - 1])/(self.pulls + 1) machine_index = pulled_machine.label mask = np.ones(len(machines), dtype='bool') mask[machine_index] = False H = self.H[:, self.pulls] H[mask] = H[mask] - self.alpha * (reward - self.averages[self.pulls - 1]) *self.probabilities[mask] H[machine_index] = H[machine_index] + self.alpha * (reward - self.averages[self.pulls - 1]) * (1 - self.probabilities[machine_index]) self.H[:, self.pulls + 1] = H self.probabilities = calculate_probabilities(H) self.pulls += 1 def get_averages(self): return self.averages def get_numbers(self): return self.numbers def calculate_probabilities(H): denominator = np.sum(np.exp(H)) numerator = np.exp(H) return numerator/denominator def run_simulation(agent, Nsteps, machines, type='Q'): if type == 'Q': for i in range(Nsteps - 1): Qold = agent.Q[:, i] Qnew, reward = agent.update(Qold, machines) agent.Q[:, i + 1] = Qnew agent.rewards[i] = reward averages = [] for i in range(1, len(agent.rewards)): averages.append(np.sum(agent.rewards[:i])*(1/i)) agent.averages = averages elif type == 'H': agent.first_step(machines) for i in range(Nsteps - 2): agent.update(machines) if __name__ == '__main__': np.random.seed(seed=123) Nmachines = 10 means = np.random.uniform(-1, 1, Nmachines) sigma = np.random.uniform(0, 1, Nmachines) machines = [Machine(mean=means[i], sigma=sigma[i], label=i) for i in range(Nmachines)] Nsteps = 10000 type = 'Q' if type == 'Q': agent1 = Agent(epsilon=0.1, Nsteps=Nsteps, Nmachines=Nmachines, label='0.1') agent2 = Agent(epsilon=0.01, Nsteps=Nsteps, Nmachines=Nmachines, label='0.0') agent3 = Agent(epsilon=0.0, Nsteps=Nsteps, Nmachines=Nmachines, label='0.0') run_simulation(agent1, Nsteps=Nsteps, machines=machines, type='Q') run_simulation(agent2, Nsteps=Nsteps, machines=machines, type='Q') run_simulation(agent3, Nsteps=Nsteps, machines=machines, type='Q') elif type == 'H': agent1 = ProbabilityAgent(alpha=1.0, Nsteps=Nsteps, Nmachines=Nmachines, label='H') agent2 = ProbabilityAgent(alpha=0.1, Nsteps=Nsteps, Nmachines=Nmachines, label='H') agent3 = ProbabilityAgent(alpha=0.01, Nsteps=Nsteps, Nmachines=Nmachines, label='H') run_simulation(agent1, Nsteps=Nsteps, machines=machines, type='H') run_simulation(agent2, Nsteps=Nsteps, machines=machines, type='H') run_simulation(agent3, Nsteps=Nsteps, machines=machines, type='H') # Plotting fig = plt.figure(figsize=(18, 18)) gs = fig.add_gridspec(3, 3) ax = fig.add_subplot(gs[0:2, 0:2]) plt.sca(ax) if type == 'Q': plt.plot(agent1.get_averages(), c='#3AAFA9', label=r'$\epsilon = 0.10$', lw=4.0) plt.plot(agent2.get_averages(), c='#F64C72', label=r'$\epsilon = 0.01$', lw=4.0) plt.plot(agent3.get_averages(), c='#2F2FA2', label=r'$\epsilon = 0.00$', lw=4.0) elif type == 'H': plt.plot(agent1.get_averages(), c='#3AAFA9', label=r'$\alpha = 1.00$', lw=4.0) plt.plot(agent2.get_averages(), c='#F64C72', label=r'$\alpha = 0.10$', lw=4.0) plt.plot(agent3.get_averages(), c='#2F2FA2', label=r'$\alpha = 0.01$', lw=4.0) plt.legend(loc='lower right', markerfirst=False, fontsize=24) plt.xlabel(r'Number of Steps') plt.ylabel(r'Average Reward') plt.xscale('log') plt.xlim(10,) ax = fig.add_subplot(gs[0, 2]) plt.sca(ax) plt.bar([i for i in range(1, Nmachines + 1)], means, color='orange', edgecolor='orange', width=0.4, alpha=1.0, label='True Mean') leg = plt.legend(loc='upper left', frameon=True, handlelength=0, handletextpad=0) for item in leg.legendHandles: item.set_visible(False) plt.xlim(0, Nmachines + 1) plt.xticks([i for i in range(1, Nmachines + 1)]) ax = fig.add_subplot(gs[1, 2]) plt.sca(ax) plt.bar([i for i in range(1, Nmachines + 1)], sigma, color='orange', edgecolor='orange', width=0.4, alpha=1.0, label='True Variance') leg = plt.legend(loc='upper left', frameon=True, handlelength=0, handletextpad=0) for item in leg.legendHandles: item.set_visible(False) plt.xlim(0, Nmachines + 1) plt.xticks([i for i in range(1, Nmachines + 1)]) ax = fig.add_subplot(gs[2, 0]) ax.tick_params(axis='x', which='minor', size=0) plt.sca(ax) plt.bar([i for i in range(1, Nmachines + 1)], agent1.get_numbers(), color='#3AAFA9', edgecolor='#3AAFA9', alpha=1.0) plt.xlabel('Machine No.') plt.ylabel('No. of Pulls') plt.yscale('log') plt.xlim(0, Nmachines + 1) plt.xticks([i for i in range(1, Nmachines + 1)]) plt.ylim(10, 1.1*Nsteps) if type == 'Q': plt.text(0.75*Nmachines, 0.5*Nsteps, r'$\epsilon = 0.10$', fontsize=24) elif type == 'H': plt.text(0.75*Nmachines, 0.5*Nsteps, r'$\alpha = 1.00$', fontsize=24) ax = fig.add_subplot(gs[2, 1]) ax.tick_params(axis='x', which='minor', size=0) plt.sca(ax) plt.bar([i for i in range(1, Nmachines + 1)], agent2.get_numbers(), color='#F64C72', edgecolor='#F64C72', alpha=1.0) plt.xlabel('Machine No.') plt.yscale('log') plt.xlim(0, Nmachines + 1) plt.xticks([i for i in range(1, Nmachines + 1)]) plt.ylim(10, 1.1*Nsteps) if type == 'Q': plt.text(0.75*Nmachines, 0.5*Nsteps, r'$\epsilon = 0.01$', fontsize=24) elif type == 'H': plt.text(0.75*Nmachines, 0.5*Nsteps, r'$\alpha = 0.10$', fontsize=24) ax = fig.add_subplot(gs[2, 2]) ax.tick_params(axis='x', which='minor', size=0) plt.sca(ax) plt.bar([i for i in range(1, Nmachines + 1)], agent3.get_numbers(), color='#2F2FA2', edgecolor='#2F2FA2', alpha=1.0) plt.xlabel('Machine No.') plt.yscale('log') plt.xlim(0, Nmachines + 1) plt.xticks([i for i in range(1, Nmachines + 1)]) plt.ylim(10, 1.1*Nsteps) if type == 'Q': plt.text(0.75*Nmachines, 0.5*Nsteps, r'$\epsilon = 0.00$', fontsize=24) elif type == 'H': plt.text(0.75*Nmachines, 0.5*Nsteps, r'$\alpha = 0.01$', fontsize=24) fig.suptitle('The Multi Armed Bandit Problem', fontsize=32, fontweight='bold') fig.subplots_adjust(top=0.925) if type == 'Q': plt.savefig('multi-armed-bandit-q.pdf') elif type == 'H': plt.savefig('multi-armed-bandit-h.pdf')
[ "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.exp", "numpy.random.seed", "matplotlib.pyplot.ylim", "matplotlib.pyplot.yscale", "numpy.random.normal", "matplotlib.pyplot.savefig", "numpy.ones", "numpy.argmax", "matplotlib.pyplot.xlim", "matplotlib.pyplot.legend", "matplotlib....
[((3620, 3629), 'numpy.exp', 'np.exp', (['H'], {}), '(H)\n', (3626, 3629), True, 'import numpy as np\n'), ((4165, 4189), 'numpy.random.seed', 'np.random.seed', ([], {'seed': '(123)'}), '(seed=123)\n', (4179, 4189), True, 'import numpy as np\n'), ((4216, 4251), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', 'Nmachines'], {}), '(-1, 1, Nmachines)\n', (4233, 4251), True, 'import numpy as np\n'), ((4261, 4295), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'Nmachines'], {}), '(0, 1, Nmachines)\n', (4278, 4295), True, 'import numpy as np\n'), ((5388, 5416), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 18)'}), '(figsize=(18, 18))\n', (5398, 5416), True, 'import matplotlib.pyplot as plt\n'), ((5485, 5496), 'matplotlib.pyplot.sca', 'plt.sca', (['ax'], {}), '(ax)\n', (5492, 5496), True, 'import matplotlib.pyplot as plt\n'), ((6026, 6087), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""', 'markerfirst': '(False)', 'fontsize': '(24)'}), "(loc='lower right', markerfirst=False, fontsize=24)\n", (6036, 6087), True, 'import matplotlib.pyplot as plt\n'), ((6089, 6118), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Steps"""'], {}), "('Number of Steps')\n", (6099, 6118), True, 'import matplotlib.pyplot as plt\n'), ((6121, 6149), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Average Reward"""'], {}), "('Average Reward')\n", (6131, 6149), True, 'import matplotlib.pyplot as plt\n'), ((6152, 6169), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (6162, 6169), True, 'import matplotlib.pyplot as plt\n'), ((6171, 6183), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(10)'], {}), '(10)\n', (6179, 6183), True, 'import matplotlib.pyplot as plt\n'), ((6219, 6230), 'matplotlib.pyplot.sca', 'plt.sca', (['ax'], {}), '(ax)\n', (6226, 6230), True, 'import matplotlib.pyplot as plt\n'), ((6379, 6454), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""', 'frameon': '(True)', 'handlelength': '(0)', 'handletextpad': '(0)'}), "(loc='upper left', frameon=True, handlelength=0, handletextpad=0)\n", (6389, 6454), True, 'import matplotlib.pyplot as plt\n'), ((6514, 6540), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(Nmachines + 1)'], {}), '(0, Nmachines + 1)\n', (6522, 6540), True, 'import matplotlib.pyplot as plt\n'), ((6625, 6636), 'matplotlib.pyplot.sca', 'plt.sca', (['ax'], {}), '(ax)\n', (6632, 6636), True, 'import matplotlib.pyplot as plt\n'), ((6789, 6864), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""', 'frameon': '(True)', 'handlelength': '(0)', 'handletextpad': '(0)'}), "(loc='upper left', frameon=True, handlelength=0, handletextpad=0)\n", (6799, 6864), True, 'import matplotlib.pyplot as plt\n'), ((6924, 6950), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(Nmachines + 1)'], {}), '(0, Nmachines + 1)\n', (6932, 6950), True, 'import matplotlib.pyplot as plt\n'), ((7085, 7096), 'matplotlib.pyplot.sca', 'plt.sca', (['ax'], {}), '(ax)\n', (7092, 7096), True, 'import matplotlib.pyplot as plt\n'), ((7223, 7248), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Machine No."""'], {}), "('Machine No.')\n", (7233, 7248), True, 'import matplotlib.pyplot as plt\n'), ((7250, 7276), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""No. of Pulls"""'], {}), "('No. of Pulls')\n", (7260, 7276), True, 'import matplotlib.pyplot as plt\n'), ((7278, 7295), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (7288, 7295), True, 'import matplotlib.pyplot as plt\n'), ((7297, 7323), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(Nmachines + 1)'], {}), '(0, Nmachines + 1)\n', (7305, 7323), True, 'import matplotlib.pyplot as plt\n'), ((7375, 7401), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(10)', '(1.1 * Nsteps)'], {}), '(10, 1.1 * Nsteps)\n', (7383, 7401), True, 'import matplotlib.pyplot as plt\n'), ((7665, 7676), 'matplotlib.pyplot.sca', 'plt.sca', (['ax'], {}), '(ax)\n', (7672, 7676), True, 'import matplotlib.pyplot as plt\n'), ((7803, 7828), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Machine No."""'], {}), "('Machine No.')\n", (7813, 7828), True, 'import matplotlib.pyplot as plt\n'), ((7830, 7847), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (7840, 7847), True, 'import matplotlib.pyplot as plt\n'), ((7849, 7875), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(Nmachines + 1)'], {}), '(0, Nmachines + 1)\n', (7857, 7875), True, 'import matplotlib.pyplot as plt\n'), ((7927, 7953), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(10)', '(1.1 * Nsteps)'], {}), '(10, 1.1 * Nsteps)\n', (7935, 7953), True, 'import matplotlib.pyplot as plt\n'), ((8217, 8228), 'matplotlib.pyplot.sca', 'plt.sca', (['ax'], {}), '(ax)\n', (8224, 8228), True, 'import matplotlib.pyplot as plt\n'), ((8355, 8380), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Machine No."""'], {}), "('Machine No.')\n", (8365, 8380), True, 'import matplotlib.pyplot as plt\n'), ((8382, 8399), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (8392, 8399), True, 'import matplotlib.pyplot as plt\n'), ((8401, 8427), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(Nmachines + 1)'], {}), '(0, Nmachines + 1)\n', (8409, 8427), True, 'import matplotlib.pyplot as plt\n'), ((8479, 8505), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(10)', '(1.1 * Nsteps)'], {}), '(10, 1.1 * Nsteps)\n', (8487, 8505), True, 'import matplotlib.pyplot as plt\n'), ((422, 451), 'numpy.zeros', 'np.zeros', (['(Nmachines, Nsteps)'], {}), '((Nmachines, Nsteps))\n', (430, 451), True, 'import numpy as np\n'), ((469, 485), 'numpy.zeros', 'np.zeros', (['Nsteps'], {}), '(Nsteps)\n', (477, 485), True, 'import numpy as np\n'), ((503, 522), 'numpy.zeros', 'np.zeros', (['Nmachines'], {}), '(Nmachines)\n', (511, 522), True, 'import numpy as np\n'), ((670, 682), 'numpy.argmax', 'np.argmax', (['Q'], {}), '(Q)\n', (679, 682), True, 'import numpy as np\n'), ((1587, 1616), 'numpy.zeros', 'np.zeros', (['(Nmachines, Nsteps)'], {}), '((Nmachines, Nsteps))\n', (1595, 1616), True, 'import numpy as np\n'), ((1693, 1709), 'numpy.zeros', 'np.zeros', (['Nsteps'], {}), '(Nsteps)\n', (1701, 1709), True, 'import numpy as np\n'), ((1727, 1746), 'numpy.zeros', 'np.zeros', (['Nmachines'], {}), '(Nmachines)\n', (1735, 1746), True, 'import numpy as np\n'), ((1782, 1798), 'numpy.zeros', 'np.zeros', (['Nsteps'], {}), '(Nsteps)\n', (1790, 1798), True, 'import numpy as np\n'), ((3596, 3605), 'numpy.exp', 'np.exp', (['H'], {}), '(H)\n', (3602, 3605), True, 'import numpy as np\n'), ((7419, 7494), 'matplotlib.pyplot.text', 'plt.text', (['(0.75 * Nmachines)', '(0.5 * Nsteps)', '"""$\\\\epsilon = 0.10$"""'], {'fontsize': '(24)'}), "(0.75 * Nmachines, 0.5 * Nsteps, '$\\\\epsilon = 0.10$', fontsize=24)\n", (7427, 7494), True, 'import matplotlib.pyplot as plt\n'), ((7971, 8046), 'matplotlib.pyplot.text', 'plt.text', (['(0.75 * Nmachines)', '(0.5 * Nsteps)', '"""$\\\\epsilon = 0.01$"""'], {'fontsize': '(24)'}), "(0.75 * Nmachines, 0.5 * Nsteps, '$\\\\epsilon = 0.01$', fontsize=24)\n", (7979, 8046), True, 'import matplotlib.pyplot as plt\n'), ((8523, 8598), 'matplotlib.pyplot.text', 'plt.text', (['(0.75 * Nmachines)', '(0.5 * Nsteps)', '"""$\\\\epsilon = 0.00$"""'], {'fontsize': '(24)'}), "(0.75 * Nmachines, 0.5 * Nsteps, '$\\\\epsilon = 0.00$', fontsize=24)\n", (8531, 8598), True, 'import matplotlib.pyplot as plt\n'), ((8818, 8857), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""multi-armed-bandit-q.pdf"""'], {}), "('multi-armed-bandit-q.pdf')\n", (8829, 8857), True, 'import matplotlib.pyplot as plt\n'), ((202, 259), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'self.mean', 'scale': 'self.sigma', 'size': '(1)'}), '(loc=self.mean, scale=self.sigma, size=1)\n', (218, 259), True, 'import numpy as np\n'), ((1657, 1675), 'numpy.ones', 'np.ones', (['Nmachines'], {}), '(Nmachines)\n', (1664, 1675), True, 'import numpy as np\n'), ((7512, 7585), 'matplotlib.pyplot.text', 'plt.text', (['(0.75 * Nmachines)', '(0.5 * Nsteps)', '"""$\\\\alpha = 1.00$"""'], {'fontsize': '(24)'}), "(0.75 * Nmachines, 0.5 * Nsteps, '$\\\\alpha = 1.00$', fontsize=24)\n", (7520, 7585), True, 'import matplotlib.pyplot as plt\n'), ((8064, 8137), 'matplotlib.pyplot.text', 'plt.text', (['(0.75 * Nmachines)', '(0.5 * Nsteps)', '"""$\\\\alpha = 0.10$"""'], {'fontsize': '(24)'}), "(0.75 * Nmachines, 0.5 * Nsteps, '$\\\\alpha = 0.10$', fontsize=24)\n", (8072, 8137), True, 'import matplotlib.pyplot as plt\n'), ((8616, 8689), 'matplotlib.pyplot.text', 'plt.text', (['(0.75 * Nmachines)', '(0.5 * Nsteps)', '"""$\\\\alpha = 0.01$"""'], {'fontsize': '(24)'}), "(0.75 * Nmachines, 0.5 * Nsteps, '$\\\\alpha = 0.01$', fontsize=24)\n", (8624, 8689), True, 'import matplotlib.pyplot as plt\n'), ((8879, 8918), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""multi-armed-bandit-h.pdf"""'], {}), "('multi-armed-bandit-h.pdf')\n", (8890, 8918), True, 'import matplotlib.pyplot as plt\n'), ((689, 720), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': '(1)'}), '(0, 1, size=1)\n', (706, 720), True, 'import numpy as np\n'), ((3967, 3992), 'numpy.sum', 'np.sum', (['agent.rewards[:i]'], {}), '(agent.rewards[:i])\n', (3973, 3992), True, 'import numpy as np\n')]
#!/usr/bin/env python from contextlib import contextmanager from deepdiff import DeepDiff import fire import numpy as np import os import pandas as pd import pathlib from penquins import Kowalski from pprint import pprint import questionary import subprocess import sys import tdtax from tdtax import taxonomy # noqa: F401 from typing import Sequence, Union import yaml from scope.utils import ( load_config, plot_gaia_hr, plot_light_curve_data, plot_gaia_density, plot_periods, ) @contextmanager def status(message): """ Borrowed from https://github.com/cesium-ml/baselayer/ :param message: message to print :return: """ print(f"[·] {message}", end="") sys.stdout.flush() try: yield except Exception: print(f"\r[✗] {message}") raise else: print(f"\r[✓] {message}") def check_configs(config_wildcards: Sequence = ("config.*yaml",)): """ - Check if config files exist - Offer to use the config files that match the wildcards - For config.yaml, check its contents against the defaults to make sure nothing is missing/wrong :param config_wildcards: :return: """ path = pathlib.Path(__file__).parent.absolute() for config_wildcard in config_wildcards: config = config_wildcard.replace("*", "") # use config defaults if configs do not exist? if not (path / config).exists(): answer = questionary.select( f"{config} does not exist, do you want to use one of the following" " (not recommended without inspection)?", choices=[p.name for p in path.glob(config_wildcard)], ).ask() subprocess.run(["cp", f"{path / answer}", f"{path / config}"]) # check contents of config.yaml WRT config.defaults.yaml if config == "config.yaml": with open(path / config.replace(".yaml", ".defaults.yaml")) as config_yaml: config_defaults = yaml.load(config_yaml, Loader=yaml.FullLoader) with open(path / config) as config_yaml: config_wildcard = yaml.load(config_yaml, Loader=yaml.FullLoader) deep_diff = DeepDiff(config_wildcard, config_defaults, ignore_order=True) difference = { k: v for k, v in deep_diff.items() if k in ("dictionary_item_added", "dictionary_item_removed") } if len(difference) > 0: print("config.yaml structure differs from config.defaults.yaml") pprint(difference) raise KeyError("Fix config.yaml before proceeding") class Scope: def __init__(self): # check configuration with status("Checking configuration"): check_configs(config_wildcards=["config.*yaml"]) self.config = load_config( pathlib.Path(__file__).parent.absolute() / "config.yaml" ) # use token specified as env var (if exists) kowalski_token_env = os.environ.get("KOWALSKI_TOKEN") if kowalski_token_env is not None: self.config["kowalski"]["token"] = kowalski_token_env # try setting up K connection if token is available if self.config["kowalski"]["token"] is not None: with status("Setting up Kowalski connection"): self.kowalski = Kowalski( token=self.config["kowalski"]["token"], protocol=self.config["kowalski"]["protocol"], host=self.config["kowalski"]["host"], port=self.config["kowalski"]["port"], ) else: self.kowalski = None # raise ConnectionError("Could not connect to Kowalski.") print("Kowalski not available") def _get_features( self, positions: Sequence[Sequence[float]], catalog: str = "ZTF_source_features_20210401", max_distance: Union[float, int] = 5.0, distance_units: str = "arcsec", ) -> pd.DataFrame: """Get nearest source in feature set for a set of given positions :param positions: R.A./Decl. [deg] :param catalog: feature catalog to query :param max_distance: :param distance_units: arcsec | arcmin | deg | rad :return: """ if self.kowalski is None: raise ConnectionError("Kowalski connection not established.") if catalog is None: catalog = self.config["kowalski"]["collections"]["features"] query = { "query_type": "near", "query": { "max_distance": max_distance, "distance_units": distance_units, "radec": positions, "catalogs": { catalog: { "filter": {}, "projection": { "period": 1, "ra": 1, "dec": 1, }, } }, }, } response = self.kowalski.query(query=query) features_nearest = [ v[0] for k, v in response.get("data").get(catalog).items() if len(v) > 0 ] df = pd.DataFrame.from_records(features_nearest) return df def _get_nearest_gaia( self, positions: Sequence[Sequence[float]], catalog: str = None, max_distance: Union[float, int] = 5.0, distance_units: str = "arcsec", ) -> pd.DataFrame: """Get nearest Gaia source for a set of given positions :param positions: R.A./Decl. [deg] :param catalog: Gaia catalog to query :param max_distance: :param distance_units: arcsec | arcmin | deg | rad :return: """ if self.kowalski is None: raise ConnectionError("Kowalski connection not established.") if catalog is None: catalog = self.config["kowalski"]["collections"]["gaia"] query = { "query_type": "near", "query": { "max_distance": max_distance, "distance_units": distance_units, "radec": positions, "catalogs": { catalog: { "filter": {}, "projection": { "parallax": 1, "parallax_error": 1, "pmra": 1, "pmra_error": 1, "pmdec": 1, "pmdec_error": 1, "phot_g_mean_mag": 1, "phot_bp_mean_mag": 1, "phot_rp_mean_mag": 1, "ra": 1, "dec": 1, }, } }, }, "kwargs": {"limit": 1}, } response = self.kowalski.query(query=query) gaia_nearest = [ v[0] for k, v in response.get("data").get(catalog).items() if len(v) > 0 ] df = pd.DataFrame.from_records(gaia_nearest) df["M"] = df["phot_g_mean_mag"] + 5 * np.log10(df["parallax"] * 0.001) + 5 df["Ml"] = ( df["phot_g_mean_mag"] + 5 * np.log10((df["parallax"] + df["parallax_error"]) * 0.001) + 5 ) df["BP-RP"] = df["phot_bp_mean_mag"] - df["phot_rp_mean_mag"] return df def _get_light_curve_data( self, ra: float, dec: float, catalog: str = "ZTF_sources_20201201", cone_search_radius: Union[float, int] = 2, cone_search_unit: str = "arcsec", filter_flagged_data: bool = True, ) -> pd.DataFrame: """Get light curve data from Kowalski :param ra: R.A. in deg :param dec: Decl. in deg :param catalog: collection name on Kowalski :param cone_search_radius: :param cone_search_unit: arcsec | arcmin | deg | rad :param filter_flagged_data: remove flagged/bad data? :return: flattened light curve data as pd.DataFrame """ if self.kowalski is None: raise ConnectionError("Kowalski connection not established.") query = { "query_type": "cone_search", "query": { "object_coordinates": { "cone_search_radius": cone_search_radius, "cone_search_unit": cone_search_unit, "radec": {"target": [ra, dec]}, }, "catalogs": { catalog: { "filter": {}, "projection": { "_id": 1, "filter": 1, "field": 1, "data.hjd": 1, "data.fid": 1, "data.mag": 1, "data.magerr": 1, "data.ra": 1, "data.dec": 1, "data.programid": 1, "data.catflags": 1, }, } }, }, } response = self.kowalski.query(query=query) light_curves_raw = response.get("data").get(catalog).get("target") light_curves = [] for light_curve in light_curves_raw: df = pd.DataFrame.from_records(light_curve["data"]) # broadcast to all data points: df["_id"] = light_curve["_id"] df["filter"] = light_curve["filter"] df["field"] = light_curve["field"] light_curves.append(df) df = pd.concat(light_curves, ignore_index=True) if filter_flagged_data: mask_flagged_data = df["catflags"] != 0 df = df.loc[~mask_flagged_data] return df @staticmethod def develop(): """Install developer tools""" subprocess.run(["pre-commit", "install"]) @classmethod def lint(cls): """Lint sources""" try: import pre_commit # noqa: F401 except ImportError: cls.develop() try: subprocess.run(["pre-commit", "run", "--all-files"], check=True) except subprocess.CalledProcessError: sys.exit(1) def doc(self): """Build docs""" # generate taxonomy.html with status("Generating taxonomy visualization"): path_static = pathlib.Path(__file__).parent.absolute() / "doc" / "_static" if not path_static.exists(): path_static.mkdir(parents=True, exist_ok=True) tdtax.write_viz( self.config["taxonomy"], outname=path_static / "taxonomy.html" ) # generate images for the Field Guide if (self.kowalski is None) or (not self.kowalski.ping()): print("Kowalski connection not established, cannot generate docs.") return period_limits = { "cepheid": [1.0, 100.0], "delta_scuti": [0.03, 0.3], "beta_lyr": [0.3, 25], "rr_lyr": [0.2, 1.0], "w_uma": [0.2, 0.8], } period_loglimits = { "cepheid": True, "delta_scuti": False, "beta_lyr": True, "rr_lyr": False, "w_uma": False, } # example periods with status("Generating example period histograms"): path_doc_data = pathlib.Path(__file__).parent.absolute() / "doc" / "data" # stored as ra/decs in csv format under /data/golden golden_sets = pathlib.Path(__file__).parent.absolute() / "data" / "golden" for golden_set in golden_sets.glob("*.csv"): golden_set_name = golden_set.stem positions = pd.read_csv(golden_set).to_numpy().tolist() features = self._get_features(positions=positions) if len(features) == 0: print(f"No features for {golden_set_name}") continue limits = period_limits.get(golden_set_name) loglimits = period_loglimits.get(golden_set_name) plot_periods( features=features, limits=limits, loglimits=loglimits, save=path_doc_data / f"period__{golden_set_name}", ) # example skymaps for all Golden sets with status("Generating skymaps diagrams for Golden sets"): path_doc_data = pathlib.Path(__file__).parent.absolute() / "doc" / "data" path_gaia_density = ( pathlib.Path(__file__).parent.absolute() / "data" / "Gaia_hp8_densitymap.fits" ) # stored as ra/decs in csv format under /data/golden golden_sets = pathlib.Path(__file__).parent.absolute() / "data" / "golden" for golden_set in golden_sets.glob("*.csv"): golden_set_name = golden_set.stem positions = pd.read_csv(golden_set).to_numpy().tolist() plot_gaia_density( positions=positions, path_gaia_density=path_gaia_density, save=path_doc_data / f"radec__{golden_set_name}", ) # example light curves with status("Generating example light curves"): path_doc_data = pathlib.Path(__file__).parent.absolute() / "doc" / "data" for sample_object_name, sample_object in self.config["docs"][ "field_guide" ].items(): sample_light_curves = self._get_light_curve_data( ra=sample_object["coordinates"][0], dec=sample_object["coordinates"][1], catalog=self.config["kowalski"]["collections"]["sources"], ) plot_light_curve_data( light_curve_data=sample_light_curves, period=sample_object.get("period"), title=sample_object.get("title"), save=path_doc_data / sample_object_name, ) # example HR diagrams for all Golden sets with status("Generating HR diagrams for Golden sets"): path_gaia_hr_histogram = ( pathlib.Path(__file__).parent.absolute() / "doc" / "data" / "gaia_hr_histogram.dat" ) # stored as ra/decs in csv format under /data/golden golden_sets = pathlib.Path(__file__).parent.absolute() / "data" / "golden" for golden_set in golden_sets.glob("*.csv"): golden_set_name = golden_set.stem positions = pd.read_csv(golden_set).to_numpy().tolist() gaia_sources = self._get_nearest_gaia(positions=positions) plot_gaia_hr( gaia_data=gaia_sources, path_gaia_hr_histogram=path_gaia_hr_histogram, save=path_doc_data / f"hr__{golden_set_name}", ) # build docs subprocess.run(["make", "html"], cwd="doc", check=True) if __name__ == "__main__": fire.Fire(Scope)
[ "pandas.DataFrame.from_records", "deepdiff.DeepDiff", "tdtax.write_viz", "sys.exit", "scope.utils.plot_gaia_density", "numpy.log10", "fire.Fire", "pathlib.Path", "pandas.read_csv", "subprocess.run", "os.environ.get", "yaml.load", "scope.utils.plot_periods", "penquins.Kowalski", "scope.ut...
[((707, 725), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (723, 725), False, 'import sys\n'), ((15587, 15603), 'fire.Fire', 'fire.Fire', (['Scope'], {}), '(Scope)\n', (15596, 15603), False, 'import fire\n'), ((5346, 5389), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['features_nearest'], {}), '(features_nearest)\n', (5371, 5389), True, 'import pandas as pd\n'), ((7261, 7300), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['gaia_nearest'], {}), '(gaia_nearest)\n', (7286, 7300), True, 'import pandas as pd\n'), ((9938, 9980), 'pandas.concat', 'pd.concat', (['light_curves'], {'ignore_index': '(True)'}), '(light_curves, ignore_index=True)\n', (9947, 9980), True, 'import pandas as pd\n'), ((10213, 10254), 'subprocess.run', 'subprocess.run', (["['pre-commit', 'install']"], {}), "(['pre-commit', 'install'])\n", (10227, 10254), False, 'import subprocess\n'), ((15498, 15553), 'subprocess.run', 'subprocess.run', (["['make', 'html']"], {'cwd': '"""doc"""', 'check': '(True)'}), "(['make', 'html'], cwd='doc', check=True)\n", (15512, 15553), False, 'import subprocess\n'), ((1716, 1778), 'subprocess.run', 'subprocess.run', (["['cp', f'{path / answer}', f'{path / config}']"], {}), "(['cp', f'{path / answer}', f'{path / config}'])\n", (1730, 1778), False, 'import subprocess\n'), ((2208, 2269), 'deepdiff.DeepDiff', 'DeepDiff', (['config_wildcard', 'config_defaults'], {'ignore_order': '(True)'}), '(config_wildcard, config_defaults, ignore_order=True)\n', (2216, 2269), False, 'from deepdiff import DeepDiff\n'), ((3070, 3102), 'os.environ.get', 'os.environ.get', (['"""KOWALSKI_TOKEN"""'], {}), "('KOWALSKI_TOKEN')\n", (3084, 3102), False, 'import os\n'), ((9658, 9704), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (["light_curve['data']"], {}), "(light_curve['data'])\n", (9683, 9704), True, 'import pandas as pd\n'), ((10456, 10520), 'subprocess.run', 'subprocess.run', (["['pre-commit', 'run', '--all-files']"], {'check': '(True)'}), "(['pre-commit', 'run', '--all-files'], check=True)\n", (10470, 10520), False, 'import subprocess\n'), ((10931, 11010), 'tdtax.write_viz', 'tdtax.write_viz', (["self.config['taxonomy']"], {'outname': "(path_static / 'taxonomy.html')"}), "(self.config['taxonomy'], outname=path_static / 'taxonomy.html')\n", (10946, 11010), False, 'import tdtax\n'), ((1198, 1220), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (1210, 1220), False, 'import pathlib\n'), ((2003, 2049), 'yaml.load', 'yaml.load', (['config_yaml'], {'Loader': 'yaml.FullLoader'}), '(config_yaml, Loader=yaml.FullLoader)\n', (2012, 2049), False, 'import yaml\n'), ((2137, 2183), 'yaml.load', 'yaml.load', (['config_yaml'], {'Loader': 'yaml.FullLoader'}), '(config_yaml, Loader=yaml.FullLoader)\n', (2146, 2183), False, 'import yaml\n'), ((2588, 2606), 'pprint.pprint', 'pprint', (['difference'], {}), '(difference)\n', (2594, 2606), False, 'from pprint import pprint\n'), ((3429, 3609), 'penquins.Kowalski', 'Kowalski', ([], {'token': "self.config['kowalski']['token']", 'protocol': "self.config['kowalski']['protocol']", 'host': "self.config['kowalski']['host']", 'port': "self.config['kowalski']['port']"}), "(token=self.config['kowalski']['token'], protocol=self.config[\n 'kowalski']['protocol'], host=self.config['kowalski']['host'], port=\n self.config['kowalski']['port'])\n", (3437, 3609), False, 'from penquins import Kowalski\n'), ((10579, 10590), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (10587, 10590), False, 'import sys\n'), ((12508, 12631), 'scope.utils.plot_periods', 'plot_periods', ([], {'features': 'features', 'limits': 'limits', 'loglimits': 'loglimits', 'save': "(path_doc_data / f'period__{golden_set_name}')"}), "(features=features, limits=limits, loglimits=loglimits, save=\n path_doc_data / f'period__{golden_set_name}')\n", (12520, 12631), False, 'from scope.utils import load_config, plot_gaia_hr, plot_light_curve_data, plot_gaia_density, plot_periods\n'), ((13451, 13580), 'scope.utils.plot_gaia_density', 'plot_gaia_density', ([], {'positions': 'positions', 'path_gaia_density': 'path_gaia_density', 'save': "(path_doc_data / f'radec__{golden_set_name}')"}), "(positions=positions, path_gaia_density=path_gaia_density,\n save=path_doc_data / f'radec__{golden_set_name}')\n", (13468, 13580), False, 'from scope.utils import load_config, plot_gaia_hr, plot_light_curve_data, plot_gaia_density, plot_periods\n'), ((15258, 15393), 'scope.utils.plot_gaia_hr', 'plot_gaia_hr', ([], {'gaia_data': 'gaia_sources', 'path_gaia_hr_histogram': 'path_gaia_hr_histogram', 'save': "(path_doc_data / f'hr__{golden_set_name}')"}), "(gaia_data=gaia_sources, path_gaia_hr_histogram=\n path_gaia_hr_histogram, save=path_doc_data / f'hr__{golden_set_name}')\n", (15270, 15393), False, 'from scope.utils import load_config, plot_gaia_hr, plot_light_curve_data, plot_gaia_density, plot_periods\n'), ((7348, 7380), 'numpy.log10', 'np.log10', (["(df['parallax'] * 0.001)"], {}), "(df['parallax'] * 0.001)\n", (7356, 7380), True, 'import numpy as np\n'), ((7458, 7515), 'numpy.log10', 'np.log10', (["((df['parallax'] + df['parallax_error']) * 0.001)"], {}), "((df['parallax'] + df['parallax_error']) * 0.001)\n", (7466, 7515), True, 'import numpy as np\n'), ((2908, 2930), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (2920, 2930), False, 'import pathlib\n'), ((10754, 10776), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (10766, 10776), False, 'import pathlib\n'), ((11774, 11796), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (11786, 11796), False, 'import pathlib\n'), ((11924, 11946), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (11936, 11946), False, 'import pathlib\n'), ((12120, 12143), 'pandas.read_csv', 'pd.read_csv', (['golden_set'], {}), '(golden_set)\n', (12131, 12143), True, 'import pandas as pd\n'), ((12869, 12891), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (12881, 12891), False, 'import pathlib\n'), ((12978, 13000), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (12990, 13000), False, 'import pathlib\n'), ((13194, 13216), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (13206, 13216), False, 'import pathlib\n'), ((13390, 13413), 'pandas.read_csv', 'pd.read_csv', (['golden_set'], {}), '(golden_set)\n', (13401, 13413), True, 'import pandas as pd\n'), ((13772, 13794), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (13784, 13794), False, 'import pathlib\n'), ((14926, 14948), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (14938, 14948), False, 'import pathlib\n'), ((15122, 15145), 'pandas.read_csv', 'pd.read_csv', (['golden_set'], {}), '(golden_set)\n', (15133, 15145), True, 'import pandas as pd\n'), ((14689, 14711), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (14701, 14711), False, 'import pathlib\n')]
import os import pprint from collections import OrderedDict, defaultdict import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader from batch_engine import valid_trainer, batch_trainer from config import argument_parser from dataset.AttrDataset import AttrDataset, get_transform from torch.nn import BCEWithLogitsLoss as BCLogit from models.resnet import resnet50 from tools.function import get_model_log_path, get_pedestrian_metrics, match_pedict_gt_scale, get_gender_accuracy from tools.utils import time_str, save_ckpt # ----------- Variables ----------- parser = argument_parser() args = parser.parse_args() backbone = resnet50() criterion = BCLogit() dataset_name = args.dataset.lower().split("_")[0] # remove variations of peta dataset_model_name = args.dataset_model_name.lower() dict_attrib_index_dataset = {"peta" : -1, "pa100k": -4, "rap": -14} # gender attribute index att_dataset = dict_attrib_index_dataset[dataset_name] att_model = -1 dict_attrib_dataset = {"peta" : 35, "pa100k": 26, "rap": 51} num_att = dict_attrib_dataset[dataset_model_name] num_att = 1 # Frontal model if "frontal" in args.dataset_model_name.lower(): from models.base_block_meta_frontal import MetaModel # Any pose model else: from models.base_block_meta import MetaModel # ------------------------------- def main(args): visenv_name = args.dataset exp_dir = os.path.join('exp_result') model_dir, log_dir = get_model_log_path(exp_dir, visenv_name) stdout_file = os.path.join(log_dir, f'stdout_{time_str()}.txt') save_model_path = os.path.join(model_dir, 'ckpt_max.pth') pprint.pprint(OrderedDict(args.__dict__)) print('-' * 60) print(f'use GPU{args.device} for training') print(f'train set: {args.dataset} {args.train_split}, test set: {args.valid_split}') train_tsfm, valid_tsfm = get_transform(args) print(train_tsfm) train_set = AttrDataset(args=args, split=args.train_split, transform=train_tsfm) train_loader = DataLoader( dataset=train_set, batch_size=args.batchsize, shuffle=True, num_workers=4, pin_memory=True, ) valid_set = AttrDataset(args=args, split=args.valid_split, transform=valid_tsfm) valid_loader = DataLoader( dataset=valid_set, batch_size=args.batchsize, shuffle=False, num_workers=4, pin_memory=True, ) print(f'{args.train_split} set: {len(train_loader.dataset)}, ' f'{args.valid_split} set: {len(valid_loader.dataset)}, ' f'attr_num : {train_set.attr_num}') model = MetaModel(nattr=num_att) if torch.cuda.is_available(): model = torch.nn.DataParallel(model).cuda() model_params = model.module.fresh_params() param_groups = [{'params': model_params, 'lr': args.lr}] optimizer = torch.optim.SGD(param_groups, momentum=args.momentum, weight_decay=args.weight_decay, nesterov=False) lr_scheduler = ReduceLROnPlateau(optimizer, factor=0.1, patience=4) best_metric, epoch = trainer(epoch=args.train_epoch, model=model, train_loader=train_loader, valid_loader=valid_loader, criterion=criterion, optimizer=optimizer, lr_scheduler=lr_scheduler, path=save_model_path) print(f'{visenv_name}, best_metrc : {best_metric} in epoch{epoch}') def trainer(epoch, model, train_loader, valid_loader, criterion, optimizer, lr_scheduler, path): maximum = float(-np.inf) best_epoch = 0 result_list = defaultdict() for i in range(epoch): train_loss, train_gt, train_probs = batch_trainer( epoch=i, model=model, train_loader=train_loader, criterion=criterion, optimizer=optimizer, att_dataset=att_dataset, att_model=att_model ) valid_loss, valid_gt, valid_probs = valid_trainer( model=model, valid_loader=valid_loader, criterion=criterion, att_dataset=att_dataset, att_model=att_model ) lr_scheduler.step(metrics=valid_loss, epoch=i) print(f'{time_str()}') print('-' * 60) valid_gt = match_pedict_gt_scale(valid_gt, dataset_name, dataset_model_name) valid_result = get_pedestrian_metrics(valid_gt, valid_probs) print(f'Gender evaluation: ', 'ma: {:.4f}, pos_recall: {:.4f} , neg_recall: {:.4f}'.format( valid_result.ma, np.mean(valid_result.label_pos_recall), np.mean(valid_result.label_neg_recall))) tot_right, tot = get_gender_accuracy(valid_gt, valid_probs) print("Gender Accuracy = {:.2f}".format((tot_right/tot)*100)) cur_metric = valid_result.ma if cur_metric > maximum: print(path) print("Saving model in epoch {}. Acc = {} (previous {})".format(i, cur_metric, maximum)) maximum = cur_metric best_epoch = i save_ckpt(model, path, i, maximum) torch.save(result_list, os.path.join(os.path.dirname(path), 'metric_log.pkl')) return maximum, best_epoch if __name__ == '__main__': parser = argument_parser() args = parser.parse_args() main(args)
[ "torch.cuda.is_available", "tools.function.match_pedict_gt_scale", "tools.function.get_pedestrian_metrics", "batch_engine.valid_trainer", "numpy.mean", "tools.function.get_gender_accuracy", "tools.utils.time_str", "batch_engine.batch_trainer", "torch.optim.SGD", "collections.OrderedDict", "torch...
[((641, 658), 'config.argument_parser', 'argument_parser', ([], {}), '()\n', (656, 658), False, 'from config import argument_parser\n'), ((698, 708), 'models.resnet.resnet50', 'resnet50', ([], {}), '()\n', (706, 708), False, 'from models.resnet import resnet50\n'), ((721, 730), 'torch.nn.BCEWithLogitsLoss', 'BCLogit', ([], {}), '()\n', (728, 730), True, 'from torch.nn import BCEWithLogitsLoss as BCLogit\n'), ((1455, 1481), 'os.path.join', 'os.path.join', (['"""exp_result"""'], {}), "('exp_result')\n", (1467, 1481), False, 'import os\n'), ((1507, 1547), 'tools.function.get_model_log_path', 'get_model_log_path', (['exp_dir', 'visenv_name'], {}), '(exp_dir, visenv_name)\n', (1525, 1547), False, 'from tools.function import get_model_log_path, get_pedestrian_metrics, match_pedict_gt_scale, get_gender_accuracy\n'), ((1638, 1677), 'os.path.join', 'os.path.join', (['model_dir', '"""ckpt_max.pth"""'], {}), "(model_dir, 'ckpt_max.pth')\n", (1650, 1677), False, 'import os\n'), ((1913, 1932), 'dataset.AttrDataset.get_transform', 'get_transform', (['args'], {}), '(args)\n', (1926, 1932), False, 'from dataset.AttrDataset import AttrDataset, get_transform\n'), ((1972, 2040), 'dataset.AttrDataset.AttrDataset', 'AttrDataset', ([], {'args': 'args', 'split': 'args.train_split', 'transform': 'train_tsfm'}), '(args=args, split=args.train_split, transform=train_tsfm)\n', (1983, 2040), False, 'from dataset.AttrDataset import AttrDataset, get_transform\n'), ((2061, 2167), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_set', 'batch_size': 'args.batchsize', 'shuffle': '(True)', 'num_workers': '(4)', 'pin_memory': '(True)'}), '(dataset=train_set, batch_size=args.batchsize, shuffle=True,\n num_workers=4, pin_memory=True)\n', (2071, 2167), False, 'from torch.utils.data import DataLoader\n'), ((2227, 2295), 'dataset.AttrDataset.AttrDataset', 'AttrDataset', ([], {'args': 'args', 'split': 'args.valid_split', 'transform': 'valid_tsfm'}), '(args=args, split=args.valid_split, transform=valid_tsfm)\n', (2238, 2295), False, 'from dataset.AttrDataset import AttrDataset, get_transform\n'), ((2316, 2423), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'valid_set', 'batch_size': 'args.batchsize', 'shuffle': '(False)', 'num_workers': '(4)', 'pin_memory': '(True)'}), '(dataset=valid_set, batch_size=args.batchsize, shuffle=False,\n num_workers=4, pin_memory=True)\n', (2326, 2423), False, 'from torch.utils.data import DataLoader\n'), ((2662, 2686), 'models.base_block_meta.MetaModel', 'MetaModel', ([], {'nattr': 'num_att'}), '(nattr=num_att)\n', (2671, 2686), False, 'from models.base_block_meta import MetaModel\n'), ((2694, 2719), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2717, 2719), False, 'import torch\n'), ((2899, 3005), 'torch.optim.SGD', 'torch.optim.SGD', (['param_groups'], {'momentum': 'args.momentum', 'weight_decay': 'args.weight_decay', 'nesterov': '(False)'}), '(param_groups, momentum=args.momentum, weight_decay=args.\n weight_decay, nesterov=False)\n', (2914, 3005), False, 'import torch\n'), ((3021, 3073), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'ReduceLROnPlateau', (['optimizer'], {'factor': '(0.1)', 'patience': '(4)'}), '(optimizer, factor=0.1, patience=4)\n', (3038, 3073), False, 'from torch.optim.lr_scheduler import ReduceLROnPlateau\n'), ((3777, 3790), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (3788, 3790), False, 'from collections import OrderedDict, defaultdict\n'), ((5448, 5465), 'config.argument_parser', 'argument_parser', ([], {}), '()\n', (5463, 5465), False, 'from config import argument_parser\n'), ((1697, 1723), 'collections.OrderedDict', 'OrderedDict', (['args.__dict__'], {}), '(args.__dict__)\n', (1708, 1723), False, 'from collections import OrderedDict, defaultdict\n'), ((3864, 4024), 'batch_engine.batch_trainer', 'batch_trainer', ([], {'epoch': 'i', 'model': 'model', 'train_loader': 'train_loader', 'criterion': 'criterion', 'optimizer': 'optimizer', 'att_dataset': 'att_dataset', 'att_model': 'att_model'}), '(epoch=i, model=model, train_loader=train_loader, criterion=\n criterion, optimizer=optimizer, att_dataset=att_dataset, att_model=\n att_model)\n', (3877, 4024), False, 'from batch_engine import valid_trainer, batch_trainer\n'), ((4154, 4278), 'batch_engine.valid_trainer', 'valid_trainer', ([], {'model': 'model', 'valid_loader': 'valid_loader', 'criterion': 'criterion', 'att_dataset': 'att_dataset', 'att_model': 'att_model'}), '(model=model, valid_loader=valid_loader, criterion=criterion,\n att_dataset=att_dataset, att_model=att_model)\n', (4167, 4278), False, 'from batch_engine import valid_trainer, batch_trainer\n'), ((4478, 4543), 'tools.function.match_pedict_gt_scale', 'match_pedict_gt_scale', (['valid_gt', 'dataset_name', 'dataset_model_name'], {}), '(valid_gt, dataset_name, dataset_model_name)\n', (4499, 4543), False, 'from tools.function import get_model_log_path, get_pedestrian_metrics, match_pedict_gt_scale, get_gender_accuracy\n'), ((4568, 4613), 'tools.function.get_pedestrian_metrics', 'get_pedestrian_metrics', (['valid_gt', 'valid_probs'], {}), '(valid_gt, valid_probs)\n', (4590, 4613), False, 'from tools.function import get_model_log_path, get_pedestrian_metrics, match_pedict_gt_scale, get_gender_accuracy\n'), ((4864, 4906), 'tools.function.get_gender_accuracy', 'get_gender_accuracy', (['valid_gt', 'valid_probs'], {}), '(valid_gt, valid_probs)\n', (4883, 4906), False, 'from tools.function import get_model_log_path, get_pedestrian_metrics, match_pedict_gt_scale, get_gender_accuracy\n'), ((5247, 5281), 'tools.utils.save_ckpt', 'save_ckpt', (['model', 'path', 'i', 'maximum'], {}), '(model, path, i, maximum)\n', (5256, 5281), False, 'from tools.utils import time_str, save_ckpt\n'), ((5332, 5353), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (5347, 5353), False, 'import os\n'), ((1598, 1608), 'tools.utils.time_str', 'time_str', ([], {}), '()\n', (1606, 1608), False, 'from tools.utils import time_str, save_ckpt\n'), ((2737, 2765), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (2758, 2765), False, 'import torch\n'), ((4753, 4791), 'numpy.mean', 'np.mean', (['valid_result.label_pos_recall'], {}), '(valid_result.label_pos_recall)\n', (4760, 4791), True, 'import numpy as np\n'), ((4793, 4831), 'numpy.mean', 'np.mean', (['valid_result.label_neg_recall'], {}), '(valid_result.label_neg_recall)\n', (4800, 4831), True, 'import numpy as np\n'), ((4419, 4429), 'tools.utils.time_str', 'time_str', ([], {}), '()\n', (4427, 4429), False, 'from tools.utils import time_str, save_ckpt\n')]
from pyquil.quil import Program from pyquil.gates import * import numpy as np import pytest from referenceqvm.gates import gate_matrix def test_random_gates(qvm_unitary): p = Program().inst([H(0), H(1), H(0)]) test_unitary = qvm_unitary.unitary(p) actual_unitary = np.kron(gate_matrix['H'], np.eye(2 ** 1)) assert np.allclose(test_unitary, actual_unitary) p = Program().inst([H(0), X(1), Y(2), Z(3)]) test_unitary = qvm_unitary.unitary(p) actual_unitary = np.kron(gate_matrix['Z'], np.kron(gate_matrix['Y'], np.kron(gate_matrix['X'], gate_matrix['H']))) assert np.allclose(test_unitary, actual_unitary) p = Program().inst([X(2), CNOT(2, 1), CNOT(1, 0)]) test_unitary = qvm_unitary.unitary(p) # gates are multiplied in 'backwards' order actual_unitary = np.kron(np.eye(2 ** 1), gate_matrix['CNOT']).dot( np.kron(gate_matrix['CNOT'], np.eye(2 ** 1))).dot( np.kron(gate_matrix['X'], np.eye(2 ** 2))) assert np.allclose(test_unitary, actual_unitary) def test_identity(qvm_unitary): p = Program() test_unitary = qvm_unitary.unitary(p) assert np.allclose(test_unitary, np.eye(2 ** 0)) def test_qaoa_unitary(qvm_unitary): wf_true = [0.00167784 + 1.00210180e-05*1j, 0.50000000 - 4.99997185e-01*1j, 0.50000000 - 4.99997185e-01*1j, 0.00167784 + 1.00210180e-05*1j] prog = Program() prog.inst([RY(np.pi/2, 0), RX(np.pi, 0), RY(np.pi/2, 1), RX(np.pi, 1), CNOT(0, 1), RX(-np.pi/2, 1), RY(4.71572463191, 1), RX(np.pi/2, 1), CNOT(0, 1), RX(-2*2.74973750579, 0), RX(-2*2.74973750579, 1)]) test_unitary = qvm_unitary.unitary(prog) wf_test = np.zeros(4) wf_test[0] = 1.0 wf_test = test_unitary.dot(wf_test) assert np.allclose(wf_test, wf_true) def test_unitary_errors(qvm_unitary): # do we properly throw errors when non-gates are thrown into a unitary? # try measuring prog = Program() prog.inst([H(0), H(1)]) prog.measure(0, [0]) with pytest.raises(TypeError): qvm_unitary.unitary(prog) # try an undefined DefGate prog = Program() prog.defgate("hello", np.array([[0, 1], [1, 0]])) prog.inst(("hello2", 0)) with pytest.raises(TypeError): qvm_unitary.unitary(prog)
[ "numpy.eye", "numpy.allclose", "pyquil.quil.Program", "numpy.kron", "numpy.array", "numpy.zeros", "pytest.raises" ]
[((332, 373), 'numpy.allclose', 'np.allclose', (['test_unitary', 'actual_unitary'], {}), '(test_unitary, actual_unitary)\n', (343, 373), True, 'import numpy as np\n'), ((707, 748), 'numpy.allclose', 'np.allclose', (['test_unitary', 'actual_unitary'], {}), '(test_unitary, actual_unitary)\n', (718, 748), True, 'import numpy as np\n'), ((1113, 1154), 'numpy.allclose', 'np.allclose', (['test_unitary', 'actual_unitary'], {}), '(test_unitary, actual_unitary)\n', (1124, 1154), True, 'import numpy as np\n'), ((1197, 1206), 'pyquil.quil.Program', 'Program', ([], {}), '()\n', (1204, 1206), False, 'from pyquil.quil import Program\n'), ((1510, 1519), 'pyquil.quil.Program', 'Program', ([], {}), '()\n', (1517, 1519), False, 'from pyquil.quil import Program\n'), ((1845, 1856), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (1853, 1856), True, 'import numpy as np\n'), ((1929, 1958), 'numpy.allclose', 'np.allclose', (['wf_test', 'wf_true'], {}), '(wf_test, wf_true)\n', (1940, 1958), True, 'import numpy as np\n'), ((2107, 2116), 'pyquil.quil.Program', 'Program', ([], {}), '()\n', (2114, 2116), False, 'from pyquil.quil import Program\n'), ((2282, 2291), 'pyquil.quil.Program', 'Program', ([], {}), '()\n', (2289, 2291), False, 'from pyquil.quil import Program\n'), ((305, 319), 'numpy.eye', 'np.eye', (['(2 ** 1)'], {}), '(2 ** 1)\n', (311, 319), True, 'import numpy as np\n'), ((1286, 1300), 'numpy.eye', 'np.eye', (['(2 ** 0)'], {}), '(2 ** 0)\n', (1292, 1300), True, 'import numpy as np\n'), ((2179, 2203), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2192, 2203), False, 'import pytest\n'), ((2318, 2344), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (2326, 2344), True, 'import numpy as np\n'), ((2384, 2408), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2397, 2408), False, 'import pytest\n'), ((181, 190), 'pyquil.quil.Program', 'Program', ([], {}), '()\n', (188, 190), False, 'from pyquil.quil import Program\n'), ((383, 392), 'pyquil.quil.Program', 'Program', ([], {}), '()\n', (390, 392), False, 'from pyquil.quil import Program\n'), ((605, 648), 'numpy.kron', 'np.kron', (["gate_matrix['X']", "gate_matrix['H']"], {}), "(gate_matrix['X'], gate_matrix['H'])\n", (612, 648), True, 'import numpy as np\n'), ((758, 767), 'pyquil.quil.Program', 'Program', ([], {}), '()\n', (765, 767), False, 'from pyquil.quil import Program\n'), ((1085, 1099), 'numpy.eye', 'np.eye', (['(2 ** 2)'], {}), '(2 ** 2)\n', (1091, 1099), True, 'import numpy as np\n'), ((1016, 1030), 'numpy.eye', 'np.eye', (['(2 ** 1)'], {}), '(2 ** 1)\n', (1022, 1030), True, 'import numpy as np\n'), ((924, 938), 'numpy.eye', 'np.eye', (['(2 ** 1)'], {}), '(2 ** 1)\n', (930, 938), True, 'import numpy as np\n')]
from __future__ import print_function import numpy as np import copy from utils import Pack from dataset.dataloader_bases import DataLoader # Twitter Conversation class TCDataLoader(DataLoader): def __init__(self, name, data, vocab_size, config): super(TCDataLoader, self).__init__(name, fix_batch=config.fix_batch) self.name = name self.vocab_size = vocab_size bow_data, m_cnt, w_cnt = data self.data = self.flatten_dialog(bow_data, config.window_size) self.data_size = len(self.data) if config.fix_batch: all_ctx_lens = [len(d.context) for d in self.data] self.indexes = list(np.argsort(all_ctx_lens))[::-1] else: self.indexes = list(range(len(self.data))) def flatten_dialog(self, data, window_size): results = [] for dialog in data: for i in range(len(dialog)): c_id = i s_id = max(0, c_id - window_size//2) e_id = min(len(dialog), s_id + window_size) target = copy.copy(dialog[i]) contexts = [] for turn in dialog[s_id:e_id]: contexts.append(turn) results.append(Pack(context=contexts, target=target)) return results def _prepare_batch(self, selected_index): rows = [self.data[idx] for idx in selected_index] # input_context, context_lens, floors, topics, a_profiles, b_Profiles, outputs, output_lens context_lens, context_utts, target_utts, target_lens = [], [], [], [] metas = [] hashtags = [] for row in rows: ctx = row.context target = row.target target_utt = target.utt context_lens.append(len(ctx)) context_utts.append([turn.utt for turn in ctx]) target_utts.append(target_utt) target_lens.append(len(target_utt)) hashtags.append(target.hashtag) metas.append(target.meta) vec_context_lens = np.array(context_lens) vec_context = np.zeros((len(vec_context_lens), np.max(vec_context_lens), self.vocab_size), dtype=np.int32) vec_targets = np.zeros((len(vec_context_lens), self.vocab_size), dtype=np.int32) vec_target_lens = np.array(target_lens) for b_id in range(len(vec_context_lens)): vec_targets[b_id, :] = self._bow2vec(target_utts[b_id], self.vocab_size) # fill the context tensor new_array = np.empty((vec_context_lens[b_id], self.vocab_size)) new_array.fill(0) for i, row in enumerate(context_utts[b_id]): new_array[i, :] = self._bow2vec(row, self.vocab_size) vec_context[b_id, 0:vec_context_lens[b_id], :] = new_array return Pack(contexts=vec_context, context_lens=vec_context_lens, targets=vec_targets, targets_lens=vec_target_lens, metas=metas, hashtags=hashtags) def _bow2vec(self, bow, vec_size): vec = np.zeros(vec_size, dtype=np.int32) for id, val in bow: vec[id] = val return vec
[ "copy.copy", "numpy.max", "numpy.array", "numpy.zeros", "numpy.argsort", "numpy.empty", "utils.Pack" ]
[((2052, 2074), 'numpy.array', 'np.array', (['context_lens'], {}), '(context_lens)\n', (2060, 2074), True, 'import numpy as np\n'), ((2337, 2358), 'numpy.array', 'np.array', (['target_lens'], {}), '(target_lens)\n', (2345, 2358), True, 'import numpy as np\n'), ((2853, 2998), 'utils.Pack', 'Pack', ([], {'contexts': 'vec_context', 'context_lens': 'vec_context_lens', 'targets': 'vec_targets', 'targets_lens': 'vec_target_lens', 'metas': 'metas', 'hashtags': 'hashtags'}), '(contexts=vec_context, context_lens=vec_context_lens, targets=\n vec_targets, targets_lens=vec_target_lens, metas=metas, hashtags=hashtags)\n', (2857, 2998), False, 'from utils import Pack\n'), ((3089, 3123), 'numpy.zeros', 'np.zeros', (['vec_size'], {'dtype': 'np.int32'}), '(vec_size, dtype=np.int32)\n', (3097, 3123), True, 'import numpy as np\n'), ((2557, 2608), 'numpy.empty', 'np.empty', (['(vec_context_lens[b_id], self.vocab_size)'], {}), '((vec_context_lens[b_id], self.vocab_size))\n', (2565, 2608), True, 'import numpy as np\n'), ((1067, 1087), 'copy.copy', 'copy.copy', (['dialog[i]'], {}), '(dialog[i])\n', (1076, 1087), False, 'import copy\n'), ((2130, 2154), 'numpy.max', 'np.max', (['vec_context_lens'], {}), '(vec_context_lens)\n', (2136, 2154), True, 'import numpy as np\n'), ((663, 687), 'numpy.argsort', 'np.argsort', (['all_ctx_lens'], {}), '(all_ctx_lens)\n', (673, 687), True, 'import numpy as np\n'), ((1238, 1275), 'utils.Pack', 'Pack', ([], {'context': 'contexts', 'target': 'target'}), '(context=contexts, target=target)\n', (1242, 1275), False, 'from utils import Pack\n')]
########################################################################### # Created by: <NAME> # Email: <EMAIL> # Copyright (c) 2019 ########################################################################### import os import os.path as osp import numpy as np import random import collections import torch import torchvision import cv2 from torch.utils import data class KITTIDataset(data.Dataset): NUM_CLASS = 1 def __init__(self, **db_params): '''Initialization''' self.data_root = db_params['data_root'] self.list_IDs = db_params['list_IDs'] self.db_params = db_params self.train = db_params['train'] self.output_size = db_params['output_size'] self.data_aug_ = db_params['data_augmentation'] self.mean_values = db_params['image_mean'] def __len__(self): '''Denotes the total number of samples''' return len(self.list_IDs) def __getitem__(self, index): '''Generates one sample of data''' # Select sample sample_data = self.create_one_sample(index, self.list_IDs) return sample_data def create_one_sample(self, index, list_IDs): #read one line from the list rgb_file_pth = list_IDs[index].strip().split(' ')[0] #load data rgb_img = cv2.imread(osp.join(self.data_root, rgb_file_pth)) rgb_img = np.float32(rgb_img) #processing img = cv2.resize(rgb_img, (self.output_size[1], self.output_size[0])) img_ori = img / 255.0 img -= self.mean_values img = img[...,::-1] / 255.0 img = np.transpose(img, (2, 0, 1)) depth = [] if self.train: gt_file_pth = list_IDs[index].strip().split(' ')[1] gt_depth = cv2.imread(osp.join(self.data_root, gt_file_pth), -1) gt_depth = np.float32(gt_depth) / 100. depth = cv2.resize(gt_depth, (self.output_size[1], self.output_size[0]), interpolation=cv2.INTER_NEAREST) depth = depth[np.newaxis, ...] if self.data_aug_ and self.train: flip = np.random.choice(2)*2-1 img = img[:, ::flip] depth = depth[:, ::flip] rgb_out = torch.from_numpy(img.copy()) #depth_out = torch.from_numpy(depth.copy()) if self.train: depth_out = torch.from_numpy(depth.copy()) return rgb_out, depth_out #return rgb_out, torch.from_numpy(img_ori.copy()) return rgb_out
[ "numpy.random.choice", "os.path.join", "cv2.resize", "numpy.transpose", "numpy.float32" ]
[((1375, 1394), 'numpy.float32', 'np.float32', (['rgb_img'], {}), '(rgb_img)\n', (1385, 1394), True, 'import numpy as np\n'), ((1430, 1493), 'cv2.resize', 'cv2.resize', (['rgb_img', '(self.output_size[1], self.output_size[0])'], {}), '(rgb_img, (self.output_size[1], self.output_size[0]))\n', (1440, 1493), False, 'import cv2\n'), ((1606, 1634), 'numpy.transpose', 'np.transpose', (['img', '(2, 0, 1)'], {}), '(img, (2, 0, 1))\n', (1618, 1634), True, 'import numpy as np\n'), ((1317, 1355), 'os.path.join', 'osp.join', (['self.data_root', 'rgb_file_pth'], {}), '(self.data_root, rgb_file_pth)\n', (1325, 1355), True, 'import os.path as osp\n'), ((1898, 1999), 'cv2.resize', 'cv2.resize', (['gt_depth', '(self.output_size[1], self.output_size[0])'], {'interpolation': 'cv2.INTER_NEAREST'}), '(gt_depth, (self.output_size[1], self.output_size[0]),\n interpolation=cv2.INTER_NEAREST)\n', (1908, 1999), False, 'import cv2\n'), ((1784, 1821), 'os.path.join', 'osp.join', (['self.data_root', 'gt_file_pth'], {}), '(self.data_root, gt_file_pth)\n', (1792, 1821), True, 'import os.path as osp\n'), ((1850, 1870), 'numpy.float32', 'np.float32', (['gt_depth'], {}), '(gt_depth)\n', (1860, 1870), True, 'import numpy as np\n'), ((2101, 2120), 'numpy.random.choice', 'np.random.choice', (['(2)'], {}), '(2)\n', (2117, 2120), True, 'import numpy as np\n')]
""" LINEAR TRAIN에서 복사ㅏㅏㅏㅏㅏㅏㅏㅏㅏㅏ """ import time import argparse import pickle from concurrent.futures import ProcessPoolExecutor import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from tqdm import tqdm import cy_heuristics as heu from fast_soft_sort.pytorch_ops import soft_rank from linearsolver import LinearSolver from sched_solver import Solver from util import get_util_range, Datasets test_module = heu.test_RTA_LC parser = argparse.ArgumentParser() parser.add_argument("--num_tasks", type=int, default=32) parser.add_argument("--num_procs", type=int, default=4) parser.add_argument("--num_epochs", type=int, default=15) parser.add_argument("--num_train_dataset", type=int, default=200000) parser.add_argument("--num_test_dataset", type=int, default=50) parser.add_argument("--embedding_size", type=int, default=128) parser.add_argument("--hidden_size", type=int, default=128) parser.add_argument("--batch_size", type=int, default=512) parser.add_argument("--grad_clip", type=float, default=1.5) parser.add_argument("--lr", type=float, default=1e-4) parser.add_argument("--lr_decay_step", type=int, default=100) parser.add_argument("--use_deadline", action="store_true") parser.add_argument("--range_l", type=str, default="4.60") parser.add_argument("--range_r", type=str, default="4.60") parser.add_argument("--use_cuda", action="store_true") parser.add_argument("--load", type=int, default=-1) parser.add_argument("--positive", action="store_true") confidence = 0.05 args = parser.parse_args() use_deadline = args.use_deadline use_cuda = True positive = False DEBUG = False if DEBUG: positive = True fname = "LIN-p%d-t%d-d%d-l[%s, %s]" % ( args.num_procs, args.num_tasks, int(use_deadline), args.range_l, args.range_r) if __name__ == "__main__": util_range = get_util_range(args.num_procs) trsets = [] tesets = [] on = False for util in util_range: on = False if util == args.range_l: on = True if on: if positive: load_file_name = "../Pandadata/tr/%d-%d/positive/%s" else: load_file_name = "../Pandadata/tr/%d-%d/%s" with open(load_file_name % (args.num_procs, args.num_tasks, util), 'rb') as f: ts = pickle.load(f) trsets.append(ts) with open("../Pandadata/te/%d-%d/%s" % (args.num_procs, args.num_tasks, util), 'rb') as f: ts = pickle.load(f) tesets.append(ts) if util == args.range_r: break train_dataset = Datasets(trsets) test_dataset = Datasets(tesets) train_dataset.setlen(args.num_train_dataset) test_dataset.setlen(args.num_test_dataset) train_loader = DataLoader( train_dataset, batch_size=args.batch_size, shuffle=False, pin_memory=True ) test_loader = DataLoader( test_dataset, batch_size=args.batch_size, shuffle=False, pin_memory=True ) eval_loader = DataLoader( test_dataset, batch_size=args.batch_size, shuffle=False, pin_memory=True ) def wrap(x): _sample, num_proc, use_deadline = x return heu.OPA(_sample, num_proc, None, use_deadline) with ProcessPoolExecutor(max_workers=10) as executor: inputs = [] res_opa = np.zeros(len(test_dataset), dtype=int).tolist() for i, sample in test_dataset: inputs.append((sample, args.num_procs, use_deadline)) for i, ret in tqdm(enumerate(executor.map(wrap, inputs))): res_opa[i] = ret opares = np.sum(res_opa) print("[before training][OPA generates %d]" % opares) temp_fname = "localRL-p%d-t%d-d%d-l[%s, %s].torchmodel" % \ (args.num_procs, args.num_tasks, int(use_deadline), args.range_l, args.range_r) model = torch.load("../Pandamodels/localrlmodels/" + temp_fname).cuda() rl_model = Solver( args.num_procs, args.embedding_size, args.hidden_size, args.num_tasks, use_deadline=False, use_cuda=True, ret_embedded_vector=False ) rl_model.load_state_dict(model.state_dict()) if use_cuda: model = model.cuda() rl_model = rl_model.cuda() rl_model = rl_model.eval() ret = [] for i, _batch in eval_loader: if use_cuda: _batch = _batch.cuda() R, log_prob, actions = model(_batch, argmax=True) for j, chosen in enumerate(actions.cpu().numpy()): order = np.zeros_like(chosen) for p in range(args.num_tasks): order[chosen[p]] = args.num_tasks - p - 1 if use_cuda: ret.append(test_module(_batch[j].cpu().numpy(), args.num_procs, order, use_deadline, False)) else: ret.append(test_module(_batch[j].numpy(), args.num_procs, order, use_deadline, False)) print("[Before training][RL model generates %d]" % (np.sum(ret))) linear_model = LinearSolver(args.num_procs, args.num_tasks, args.use_deadline, use_cuda) # TRAIN LOOP with open("../Pandadata/tr/%d-%d/%slabel" % (args.num_procs, args.num_tasks, args.range_l), "rb") as f: rl_label = pickle.load(f) rl_order_numpy = np.vstack([batch for batch in rl_label]) # (200000 x num_tasks) rl_orders = [] i = 0 while True: x = rl_order_numpy[i * args.batch_size:(i+1) * args.batch_size, :] x = torch.from_numpy(x) rl_orders.append(x) i += 1 if i > (args.num_train_dataset / args.batch_size): break if use_cuda: linear_model = linear_model.to("cuda:0") rl_model = rl_model.to("cuda:0") linear_model = linear_model.train() criterion = nn.MSELoss() optimizer = optim.Adam(linear_model.parameters(), lr=5e-2) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.9) start = time.time() for epoch in range(args.num_epochs): loss_ = 0 avg_hit = [] for batch_idx, (_, sample_batch) in enumerate(train_loader): # print(sample_batch.device) optimizer.zero_grad() rewards, probs, action = rl_model(sample_batch) rl_order = torch.zeros_like(action) for i in range(rl_order.size(0)): # batch size for j in range(rl_order.size(1)): # num_tasks rl_order[i][action[i][j]] = args.num_tasks - j - 1 rl_order = soft_rank(rl_order.cpu(), regularization_strength=0.001).float() # rl_order = rl_orders[batch_idx] linear_score = linear_model(sample_batch) lin_soft_score = soft_rank(linear_score.cpu(), regularization_strength=0.001).float() # 점수가 높으면 더 중요하다. 즉 우선순위가 더 높다 if use_cuda: lin_soft_score = lin_soft_score.to("cuda:0") rl_order = rl_order.to("cuda:0") loss = criterion(rl_order, lin_soft_score) loss.backward() print(epoch, loss) loss_ += loss / args.batch_size optimizer.step() scheduler.step() if batch_idx % 10 == 0: with open("cumloss/soft/" + fname, "a") as f: print("EPOCH:{}, LOSS:{:.3f}".format(epoch, loss_ / (batch_idx+1)), file=f) endtime = time.time() elapsed = (endtime - start) minute = int(elapsed // 60) second = int(elapsed - 60 * minute) # EVALUATE linear_model.eval() lin_ret = [] for i, _batch in eval_loader: if use_cuda: _batch = _batch.to("cuda:0") ev_linear_score = linear_model(_batch) _, ev_linear_score_idx = torch.sort(ev_linear_score, descending=True) np_linear_score = ev_linear_score_idx.cpu().detach().numpy() for j, chosen in enumerate(np_linear_score): order = np.zeros_like(chosen) for p in range(args.num_tasks): order[chosen[p]] = args.num_tasks - p - 1 if use_cuda: lin_ret.append( test_module(_batch[j].cpu().numpy(), args.num_procs, order, use_deadline=False, ret_score=False)) else: lin_ret.append( test_module( _batch[j].numpy(), args.num_procs, order, False, False)) print("EPOCH : {} / RL MODEL GENERATES : {} / LINEAR MODEL GENERATES : {} / OPA GENERATES : {}".format( epoch, np.sum(ret), np.sum(lin_ret), opares )) print("경과시간 : {}m{:}s".format(minute, second)) if epoch % 1 == 0: fname = "LIN-p%d-t%d-d%d-l[%s, %s]" \ % (args.num_procs, args.num_tasks, int(use_deadline), args.range_l, args.range_r) # torch.save(linear_model, "../Pandamodels/linearmodels/" + fname + ".torchmodel") print("SAVE SUCCESS") with open("log/softlog/" + fname, "a") as f: print("EPOCH : {} / RL MODEL GENERATES : {} / LINEAR MODEL GENERATES : {} / OPA GENERATES : {}".format( epoch, np.sum(ret), np.sum(lin_ret), opares ), file=f) print("경과시간 : {}m{:}s".format(minute, second), file=f) linear_model.train()
[ "sched_solver.Solver", "torch.from_numpy", "torch.nn.MSELoss", "util.Datasets", "linearsolver.LinearSolver", "argparse.ArgumentParser", "numpy.vstack", "torch.zeros_like", "torch.sort", "pickle.load", "util.get_util_range", "cy_heuristics.OPA", "concurrent.futures.ProcessPoolExecutor", "ti...
[((504, 529), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (527, 529), False, 'import argparse\n'), ((1868, 1898), 'util.get_util_range', 'get_util_range', (['args.num_procs'], {}), '(args.num_procs)\n', (1882, 1898), False, 'from util import get_util_range, Datasets\n'), ((2642, 2658), 'util.Datasets', 'Datasets', (['trsets'], {}), '(trsets)\n', (2650, 2658), False, 'from util import get_util_range, Datasets\n'), ((2678, 2694), 'util.Datasets', 'Datasets', (['tesets'], {}), '(tesets)\n', (2686, 2694), False, 'from util import get_util_range, Datasets\n'), ((2811, 2900), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'pin_memory': '(True)'}), '(train_dataset, batch_size=args.batch_size, shuffle=False,\n pin_memory=True)\n', (2821, 2900), False, 'from torch.utils.data import DataLoader\n'), ((2953, 3041), 'torch.utils.data.DataLoader', 'DataLoader', (['test_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'pin_memory': '(True)'}), '(test_dataset, batch_size=args.batch_size, shuffle=False,\n pin_memory=True)\n', (2963, 3041), False, 'from torch.utils.data import DataLoader\n'), ((3094, 3182), 'torch.utils.data.DataLoader', 'DataLoader', (['test_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'pin_memory': '(True)'}), '(test_dataset, batch_size=args.batch_size, shuffle=False,\n pin_memory=True)\n', (3104, 3182), False, 'from torch.utils.data import DataLoader\n'), ((4032, 4176), 'sched_solver.Solver', 'Solver', (['args.num_procs', 'args.embedding_size', 'args.hidden_size', 'args.num_tasks'], {'use_deadline': '(False)', 'use_cuda': '(True)', 'ret_embedded_vector': '(False)'}), '(args.num_procs, args.embedding_size, args.hidden_size, args.\n num_tasks, use_deadline=False, use_cuda=True, ret_embedded_vector=False)\n', (4038, 4176), False, 'from sched_solver import Solver\n'), ((5099, 5172), 'linearsolver.LinearSolver', 'LinearSolver', (['args.num_procs', 'args.num_tasks', 'args.use_deadline', 'use_cuda'], {}), '(args.num_procs, args.num_tasks, args.use_deadline, use_cuda)\n', (5111, 5172), False, 'from linearsolver import LinearSolver\n'), ((5387, 5427), 'numpy.vstack', 'np.vstack', (['[batch for batch in rl_label]'], {}), '([batch for batch in rl_label])\n', (5396, 5427), True, 'import numpy as np\n'), ((5892, 5904), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (5902, 5904), True, 'import torch.nn as nn\n'), ((5984, 6045), 'torch.optim.lr_scheduler.StepLR', 'optim.lr_scheduler.StepLR', (['optimizer'], {'step_size': '(50)', 'gamma': '(0.9)'}), '(optimizer, step_size=50, gamma=0.9)\n', (6009, 6045), True, 'import torch.optim as optim\n'), ((6059, 6070), 'time.time', 'time.time', ([], {}), '()\n', (6068, 6070), False, 'import time\n'), ((3294, 3340), 'cy_heuristics.OPA', 'heu.OPA', (['_sample', 'num_proc', 'None', 'use_deadline'], {}), '(_sample, num_proc, None, use_deadline)\n', (3301, 3340), True, 'import cy_heuristics as heu\n'), ((3351, 3386), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': '(10)'}), '(max_workers=10)\n', (3370, 3386), False, 'from concurrent.futures import ProcessPoolExecutor\n'), ((3704, 3719), 'numpy.sum', 'np.sum', (['res_opa'], {}), '(res_opa)\n', (3710, 3719), True, 'import numpy as np\n'), ((5351, 5365), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (5362, 5365), False, 'import pickle\n'), ((5587, 5606), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (5603, 5606), False, 'import torch\n'), ((7504, 7515), 'time.time', 'time.time', ([], {}), '()\n', (7513, 7515), False, 'import time\n'), ((3952, 4008), 'torch.load', 'torch.load', (["('../Pandamodels/localrlmodels/' + temp_fname)"], {}), "('../Pandamodels/localrlmodels/' + temp_fname)\n", (3962, 4008), False, 'import torch\n'), ((4629, 4650), 'numpy.zeros_like', 'np.zeros_like', (['chosen'], {}), '(chosen)\n', (4642, 4650), True, 'import numpy as np\n'), ((5065, 5076), 'numpy.sum', 'np.sum', (['ret'], {}), '(ret)\n', (5071, 5076), True, 'import numpy as np\n'), ((6378, 6402), 'torch.zeros_like', 'torch.zeros_like', (['action'], {}), '(action)\n', (6394, 6402), False, 'import torch\n'), ((7896, 7940), 'torch.sort', 'torch.sort', (['ev_linear_score'], {'descending': '(True)'}), '(ev_linear_score, descending=True)\n', (7906, 7940), False, 'import torch\n'), ((2348, 2362), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2359, 2362), False, 'import pickle\n'), ((2521, 2535), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2532, 2535), False, 'import pickle\n'), ((8095, 8116), 'numpy.zeros_like', 'np.zeros_like', (['chosen'], {}), '(chosen)\n', (8108, 8116), True, 'import numpy as np\n'), ((8761, 8772), 'numpy.sum', 'np.sum', (['ret'], {}), '(ret)\n', (8767, 8772), True, 'import numpy as np\n'), ((8774, 8789), 'numpy.sum', 'np.sum', (['lin_ret'], {}), '(lin_ret)\n', (8780, 8789), True, 'import numpy as np\n'), ((9376, 9387), 'numpy.sum', 'np.sum', (['ret'], {}), '(ret)\n', (9382, 9387), True, 'import numpy as np\n'), ((9389, 9404), 'numpy.sum', 'np.sum', (['lin_ret'], {}), '(lin_ret)\n', (9395, 9404), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ldig : Language Detector with Infinite-Gram # This code is available under the MIT License. # (c)2011 <NAME> / Cybozu Labs Inc. import os, sys, re, codecs, json import optparse import numpy import html.entities as htmlentitydefs import subprocess import da class ldig(object): def __init__(self, model_dir): self.features = os.path.join(model_dir, 'features') self.labels = os.path.join(model_dir, 'labels.json') self.param = os.path.join(model_dir, 'parameters.npy') self.doublearray = os.path.join(model_dir, 'doublearray.npz') def load_da(self): trie = da.DoubleArray() trie.load(self.doublearray) return trie def load_features(self): features = [] with open(self.features, 'r') as f: pre_feature = "" for n, s in enumerate(f): m = re.match(r'(.+)\t([0-9]+)', s) if not m: sys.exit("irregular feature : '%s' at %d" % (s, n + 1)) if pre_feature >= m.group(1): sys.exit("unordered feature : '%s' at %d" % (s, n + 1)) pre_feature = m.group(1) features.append(m.groups()) return features def load_labels(self): with open(self.labels, 'r') as f: return json.load(f) def init(self, temp_path, corpus_list, lbff, ngram_bound): """ Extract features from corpus and generate TRIE(DoubleArray) data - load corpus - generate temporary file for maxsubst - generate double array and save it - parameter: lbff = lower bound of feature frequency """ labels = [] with open(temp_path, 'w') as f: for file in corpus_list: with open(file, 'r') as g: for i, s in enumerate(g): label, text, org_text = normalize_text(s) if label is None or label == "": sys.stderr.write("no label data at %d in %s \n" % (i+1, file)) continue if label not in labels: labels.append(label) f.write(text) f.write("\n") labels.sort() print ("labels: %d" % len(labels)) with open(self.labels, 'w') as f: f.write(json.dumps(labels)) print ("generating max-substrings...") temp_features = self.features + ".temp" maxsubst = options.maxsubst if os.name == 'nt': maxsubst += ".exe" subprocess.call([maxsubst, temp_path, temp_features]) # count features M = 0 features = [] r1 = re.compile(u'.\u0001.') r2 = re.compile(u'[A-Za-z\u00a1-\u00a3\u00bf-\u024f\u1e00-\u1eff\u0370-\u03ff\u0400-\u04ff]') # added greek (\u0370-\u03ff) and cyrillic (\u0400–\u04ff) alphabets with open(temp_features, 'r') as f: for line in f: i = line.index('\t') st = line[0:i] c = int(line[i+1:-1]) if c >= lbff and len(st) <= ngram_bound and (not r1.search(st)) and r2.search(st) and (st[0] != u'\u0001' or st[-1] != u'\u0001'): M += 1 features.append((st, line)) print ("# of features = %d" % M) features.sort() with open(self.features, 'w') as f: for s in features: f.write(s[1]) generate_doublearray(self.doublearray, [s[0] for s in features]) numpy.save(self.param, numpy.zeros((M, len(labels)))) def shrink(self): features = self.load_features() param = numpy.load(self.param) list = (numpy.abs(param).sum(1) > 0.0000001) new_param = param[list] print ("# of features : %d => %d" % (param.shape[0], new_param.shape[0])) numpy.save(self.param, new_param) new_features = [] with open(self.features, 'w') as f: for i, x in enumerate(list): if x: f.write("%s\t%s\n" % features[i]) new_features.append(features[i][0]) generate_doublearray(self.doublearray, new_features) def debug(self, args): features = self.load_features() trie = self.load_da() labels = self.load_labels() param = numpy.load(self.param) for st in args: label, text, org_text = normalize_text(st) events = trie.extract_features(u"\u0001" + text + u"\u0001") print ("orig: '%s'" % st) print ("norm: '%s'" % text) sum = numpy.zeros(len(labels)) print ("id\tfeat\tfreq\t%s" % "\t".join(labels)) for id in sorted(events, key=lambda id:features[id][0]): phi = param[id,] sum += phi * events[id] print ("%d\t%s\t%d\t%s" % (id,features[id][0], events[id], "\t".join(["%0.2f" % x for x in phi]))) exp_w = numpy.exp(sum - sum.max()) prob = exp_w / exp_w.sum() print ("\t\t\t%s" % "\t".join(["%0.2f" % x for x in sum])) print ("\t\t\t%s" % "\t".join(["%0.1f%%" % (x * 100) for x in prob])) def learn(self, options, args): trie = self.load_da() param = numpy.load(self.param) labels = self.load_labels() import time print ("loading corpus... " + time.strftime("%H:%M:%S", time.localtime())) corpus, idlist = load_corpus(args, labels) print ("inference... " + time.strftime("%H:%M:%S", time.localtime())) inference(param, labels, corpus, idlist, trie, options) print ("finish... " + time.strftime("%H:%M:%S", time.localtime())) numpy.save(self.param, param) def detect(self, options, args): trie = self.load_da() param = numpy.load(self.param) labels = self.load_labels() log_likely = likelihood(param, labels, trie, args, options) # from http://www.programming-magic.com/20080820002254/ reference_regex = re.compile(u'&(#x?[0-9a-f]+|[a-z]+);', re.IGNORECASE) num16_regex = re.compile(u'#x\d+', re.IGNORECASE) num10_regex = re.compile(u'#\d+', re.IGNORECASE) def htmlentity2unicode(text): result = u'' i = 0 while True: match = reference_regex.search(text, i) if match is None: result += text[i:] break result += text[i:match.start()] i = match.end() name = match.group(1) if name in htmlentitydefs.name2codepoint.keys(): result += unichr(htmlentitydefs.name2codepoint[name]) elif num16_regex.match(name): result += unichr(int(u'0'+name[1:], 16)) elif num10_regex.match(name): result += unichr(int(name[1:])) return result def normalize_twitter(text): """normalization for twitter""" text = re.sub(r'(@|#|https?:\/\/)[^ ]+', '', text) text = re.sub(r'(^| )[:;x]-?[\(\)dop]($| )', ' ', text) # facemark text = re.sub(r'(^| )(rt[ :]+)*', ' ', text) text = re.sub(r'([hj])+([aieo])+(\1+\2+){1,}', r'\1\2\1\2', text, re.IGNORECASE) # laugh text = re.sub(r' +(via|live on) *$', '', text) return text re_ignore_i = re.compile(r'[^Iİ]') re_turkish_alphabet = re.compile(u'[\u011e\u011f\u0130\u0131]') vietnamese_norm = { u'\u0041\u0300':u'\u00C0', u'\u0045\u0300':u'\u00C8', u'\u0049\u0300':u'\u00CC', u'\u004F\u0300':u'\u00D2', u'\u0055\u0300':u'\u00D9', u'\u0059\u0300':u'\u1EF2', u'\u0061\u0300':u'\u00E0', u'\u0065\u0300':u'\u00E8', u'\u0069\u0300':u'\u00EC', u'\u006F\u0300':u'\u00F2', u'\u0075\u0300':u'\u00F9', u'\u0079\u0300':u'\u1EF3', u'\u00C2\u0300':u'\u1EA6', u'\u00CA\u0300':u'\u1EC0', u'\u00D4\u0300':u'\u1ED2', u'\u00E2\u0300':u'\u1EA7', u'\u00EA\u0300':u'\u1EC1', u'\u00F4\u0300':u'\u1ED3', u'\u0102\u0300':u'\u1EB0', u'\u0103\u0300':u'\u1EB1', u'\u01A0\u0300':u'\u1EDC', u'\u01A1\u0300':u'\u1EDD', u'\u01AF\u0300':u'\u1EEA', u'\u01B0\u0300':u'\u1EEB', u'\u0041\u0301':u'\u00C1', u'\u0045\u0301':u'\u00C9', u'\u0049\u0301':u'\u00CD', u'\u004F\u0301':u'\u00D3', u'\u0055\u0301':u'\u00DA', u'\u0059\u0301':u'\u00DD', u'\u0061\u0301':u'\u00E1', u'\u0065\u0301':u'\u00E9', u'\u0069\u0301':u'\u00ED', u'\u006F\u0301':u'\u00F3', u'\u0075\u0301':u'\u00FA', u'\u0079\u0301':u'\u00FD', u'\u00C2\u0301':u'\u1EA4', u'\u00CA\u0301':u'\u1EBE', u'\u00D4\u0301':u'\u1ED0', u'\u00E2\u0301':u'\u1EA5', u'\u00EA\u0301':u'\u1EBF', u'\u00F4\u0301':u'\u1ED1', u'\u0102\u0301':u'\u1EAE', u'\u0103\u0301':u'\u1EAF', u'\u01A0\u0301':u'\u1EDA', u'\u01A1\u0301':u'\u1EDB', u'\u01AF\u0301':u'\u1EE8', u'\u01B0\u0301':u'\u1EE9', u'\u0041\u0303':u'\u00C3', u'\u0045\u0303':u'\u1EBC', u'\u0049\u0303':u'\u0128', u'\u004F\u0303':u'\u00D5', u'\u0055\u0303':u'\u0168', u'\u0059\u0303':u'\u1EF8', u'\u0061\u0303':u'\u00E3', u'\u0065\u0303':u'\u1EBD', u'\u0069\u0303':u'\u0129', u'\u006F\u0303':u'\u00F5', u'\u0075\u0303':u'\u0169', u'\u0079\u0303':u'\u1EF9', u'\u00C2\u0303':u'\u1EAA', u'\u00CA\u0303':u'\u1EC4', u'\u00D4\u0303':u'\u1ED6', u'\u00E2\u0303':u'\u1EAB', u'\u00EA\u0303':u'\u1EC5', u'\u00F4\u0303':u'\u1ED7', u'\u0102\u0303':u'\u1EB4', u'\u0103\u0303':u'\u1EB5', u'\u01A0\u0303':u'\u1EE0', u'\u01A1\u0303':u'\u1EE1', u'\u01AF\u0303':u'\u1EEE', u'\u01B0\u0303':u'\u1EEF', u'\u0041\u0309':u'\u1EA2', u'\u0045\u0309':u'\u1EBA', u'\u0049\u0309':u'\u1EC8', u'\u004F\u0309':u'\u1ECE', u'\u0055\u0309':u'\u1EE6', u'\u0059\u0309':u'\u1EF6', u'\u0061\u0309':u'\u1EA3', u'\u0065\u0309':u'\u1EBB', u'\u0069\u0309':u'\u1EC9', u'\u006F\u0309':u'\u1ECF', u'\u0075\u0309':u'\u1EE7', u'\u0079\u0309':u'\u1EF7', u'\u00C2\u0309':u'\u1EA8', u'\u00CA\u0309':u'\u1EC2', u'\u00D4\u0309':u'\u1ED4', u'\u00E2\u0309':u'\u1EA9', u'\u00EA\u0309':u'\u1EC3', u'\u00F4\u0309':u'\u1ED5', u'\u0102\u0309':u'\u1EB2', u'\u0103\u0309':u'\u1EB3', u'\u01A0\u0309':u'\u1EDE', u'\u01A1\u0309':u'\u1EDF', u'\u01AF\u0309':u'\u1EEC', u'\u01B0\u0309':u'\u1EED', u'\u0041\u0323':u'\u1EA0', u'\u0045\u0323':u'\u1EB8', u'\u0049\u0323':u'\u1ECA', u'\u004F\u0323':u'\u1ECC', u'\u0055\u0323':u'\u1EE4', u'\u0059\u0323':u'\u1EF4', u'\u0061\u0323':u'\u1EA1', u'\u0065\u0323':u'\u1EB9', u'\u0069\u0323':u'\u1ECB', u'\u006F\u0323':u'\u1ECD', u'\u0075\u0323':u'\u1EE5', u'\u0079\u0323':u'\u1EF5', u'\u00C2\u0323':u'\u1EAC', u'\u00CA\u0323':u'\u1EC6', u'\u00D4\u0323':u'\u1ED8', u'\u00E2\u0323':u'\u1EAD', u'\u00EA\u0323':u'\u1EC7', u'\u00F4\u0323':u'\u1ED9', u'\u0102\u0323':u'\u1EB6', u'\u0103\u0323':u'\u1EB7', u'\u01A0\u0323':u'\u1EE2', u'\u01A1\u0323':u'\u1EE3', u'\u01AF\u0323':u'\u1EF0', u'\u01B0\u0323':u'\u1EF1', } re_vietnamese = re.compile(u'[AEIOUYaeiouy\u00C2\u00CA\u00D4\u00E2\u00EA\u00F4\u0102\u0103\u01A0\u01A1\u01AF\u01B0][\u0300\u0301\u0303\u0309\u0323]') re_latin_cont = re.compile(u'([a-z\u00e0-\u024f])\\1{2,}') re_symbol_cont = re.compile(u'([^a-z\u00e0-\u024f])\\1{1,}') def normalize_text(org): m = re.match(r'([-A-Za-z]+)\t(.+)', org) if m: label, org = m.groups() else: label = "" m = re.search(r'\t([^\t]+)$', org) if m: s = m.group(0) else: s = org s = htmlentity2unicode(s) s = re.sub(u'[\u2010-\u2015]', '-', s) s = re.sub(u'[0-9]+', '0', s) s = re.sub(u'[^\u0020-\u007e\u00a1-\u024f\u0300-\u036f\u0370-\u03FF\u0400-\u04ff\u1e00-\u1eff]+', ' ', s) # added greek (\u0370-\u03ff) and cyrillic (\u0400–\u04ff) alphabets s = re.sub(u' +', ' ', s) # vietnamese normalization s = re_vietnamese.sub(lambda x:vietnamese_norm[x.group(0)], s) # lower case with Turkish s = re_ignore_i.sub(lambda x:x.group(0).lower(), s) s = s.replace(u'İ', u'\u0069') # This is to manage this question : https://bugs.python.org/issue17252 #if re_turkish_alphabet.search(s): #s = s.replace(u'I', u'\u0131') #s = s.lower() # Romanian normalization s = s.replace(u'\u0219', u'\u015f').replace(u'\u021b', u'\u0163') s = normalize_twitter(s) s = re_latin_cont.sub(r'\1\1', s) s = re_symbol_cont.sub(r'\1', s) return label, s.strip(), org # load courpus def load_corpus(filelist, labels): idlist = dict((x, []) for x in labels) corpus = [] for filename in filelist: f = open(filename, 'r') for i, s in enumerate(f): label, text, org_text = normalize_text(s) if label not in labels: sys.exit("unknown label '%s' at %d in %s " % (label, i+1, filename)) idlist[label].append(len(corpus)) corpus.append((label, text, org_text)) f.close() return corpus, idlist def shuffle(idlist): n = max(len(idlist[lang]) for lang in idlist) list = [] for lang in idlist: text_ids = idlist[lang] n_text = len(text_ids) list += text_ids * (n // n_text) numpy.random.shuffle(text_ids) list += text_ids[:n % n_text] numpy.random.shuffle(list) return list # prediction probability # this code comes from https://github.com/Nift/ldig/commit/75fc547dc1c3412d216fba83d759b38b414e528a in order to port it to Python 3 def predict(param, events): names = ['id', 'data'] formats = ['f8', 'f8'] dtype = dict(names=names, formats=formats) res1 = list(events.keys()) arr = numpy.asarray(res1) # numpy.fromiter(res1.iteritems(), dtype=dtype, count=len(res1)) array = arr.astype(int) res2 = list(events.values()) valuesA = numpy.asarray(res2) # numpy.fromiter(res2.iteritems(), dtype=dtype, count=len(res2)) sum_w = numpy.dot(param[array,].T, valuesA) exp_w = numpy.exp(sum_w - sum_w.max()) return exp_w / exp_w.sum() # inference and learning def inference(param, labels, corpus, idlist, trie, options): K = len(labels) M = param.shape[0] list = shuffle(idlist) N = len(list) WHOLE_REG_INT = (N / options.n_whole_reg) + 1 # learning rate eta = options.eta if options.reg_const: penalties = numpy.zeros_like(param) alpha = pow(0.9, -1.0 / N) uk = 0 corrects = numpy.zeros(K, dtype=int) counts = numpy.zeros(K, dtype=int) for m, target in enumerate(list): label, text, org_text = corpus[target] events = trie.extract_features(u"\u0001" + text + u"\u0001") label_k = labels.index(label) y = predict(param, events) predict_k = y.argmax() counts[label_k] += 1 if label_k == predict_k: corrects[label_k] += 1 # learning if options.reg_const: eta *= alpha uk += options.reg_const * eta / N y[label_k] -= 1 y *= eta if options.reg_const: indexes = events if (N - m) % WHOLE_REG_INT == 1: print ("full regularization: %d / %d" % (m, N)) indexes = range(M) for id in indexes: prm = param[id] pnl = penalties[id] if id in events: prm -= y * events[id] for j in range(K): w = prm[j] if w > 0: w1 = w - uk - pnl[j] if w1 > 0: prm[j] = w1 pnl[j] += w1 - w else: prm[j] = 0 pnl[j] -= w elif w < 0: w1 = w + uk - pnl[j] if w1 < 0: prm[j] = w1 pnl[j] += w1 - w else: prm[j] = 0 pnl[j] -= w else: for id, freq in events.items(): param[id,] -= y * freq for lbl, crct, cnt in zip(labels, corrects, counts): if cnt > 0: print ("> %s = %d / %d = %.2f" % (lbl, crct, cnt, 100.0 * crct / cnt)) print ("> total = %d / %d = %.2f" % (corrects.sum(), N, 100.0 * corrects.sum() / N)) list = (numpy.abs(param).sum(1) > 0.0000001) print ("> # of relevant features = %d / %d" % (list.sum(), M)) def likelihood(param, labels, trie, filelist, options): K = len(labels) corrects = numpy.zeros(K, dtype=int) counts = numpy.zeros(K, dtype=int) label_map = dict((x, i) for i, x in enumerate(labels)) n_available_data = 0 log_likely = 0.0 for filename in filelist: f = open(filename, 'r') for i, s in enumerate(f): label, text, org_text = normalize_text(s) if label not in label_map: sys.stderr.write("WARNING : unknown label '%s' at %d in %s (ignore the later same labels)\n" % (label, i+1, filename)) label_map[label] = -1 label_k = label_map[label] events = trie.extract_features(u"\u0001" + text + u"\u0001") y = predict(param, events) predict_k = y.argmax() if label_k >= 0: if y[label_k]==0: # lkevers: added in order to avoid warning because of log(0) below y[label_k]=0.0000000001 log_likely -= numpy.log(y[label_k]) n_available_data += 1 counts[label_k] += 1 if label_k == predict_k and y[predict_k] >= 0.6: corrects[predict_k] += 1 predict_lang = labels[predict_k] if y[predict_k] < 0.6: predict_lang = "" print ("%s\t%s\t%s" % (label, predict_lang, org_text)) f.close() if n_available_data > 0: log_likely /= n_available_data for lbl, crct, cnt in zip(labels, corrects, counts): if cnt > 0: print ("> %s = %d / %d = %.2f" % (lbl, crct, cnt, 100.0 * crct / cnt)) print ("> total = %d / %d = %.2f" % (corrects.sum(), n_available_data, 100.0 * corrects.sum() / n_available_data)) print ("> average negative log likelihood = %.3f" % log_likely) return log_likely def generate_doublearray(file, features): trie = da.DoubleArray() trie.initialize(features) trie.save(file) if __name__ == '__main__': #sys.stdout = codecs.getwriter('utf-8')(sys.stdout) parser = optparse.OptionParser() parser.add_option("-m", dest="model", help="model directory") parser.add_option("--init", dest="init", help="initialize model", action="store_true") parser.add_option("--learning", dest="learning", help="learn model", action="store_true") parser.add_option("--shrink", dest="shrink", help="remove irrevant features", action="store_true") parser.add_option("--debug", dest="debug", help="detect command line text for debug", action="store_true") # for initialization parser.add_option("--ff", dest="bound_feature_freq", help="threshold of feature frequency (for initialization)", type="int", default=8) parser.add_option("-n", dest="ngram_bound", help="n-gram upper bound (for initialization)", type="int", default=99999) parser.add_option("-x", dest="maxsubst", help="max substring extractor", default="./maxsubst") # for learning parser.add_option("-e", "--eta", dest="eta", help="learning rate", type="float", default=0.1) parser.add_option("-r", "--regularity", dest="reg_const", help="regularization constant", type="float") parser.add_option("--wr", dest="n_whole_reg", help="number of whole regularizations", type="int", default=2) (options, args) = parser.parse_args() if not options.model: parser.error("need model directory (-m)") detector = ldig(options.model) if options.init: if not os.path.exists(options.model): os.mkdir(options.model) if len(args) == 0: parser.error("need corpus") else: if not os.path.exists(detector.features): parser.error("features file doesn't exist") if not os.path.exists(detector.labels): parser.error("labels file doesn't exist") if not os.path.exists(detector.param): parser.error("parameters file doesn't exist") if options.init: temp_path = os.path.join(options.model, 'temp') detector.init(temp_path, args, options.bound_feature_freq, options.ngram_bound) elif options.debug: detector.debug(args) elif options.shrink: detector.shrink() elif options.learning: detector.learn(options, args) else: detector.detect(options, args) #import cProfile #cProfile.runctx('detector.detect(options, args)', globals(), locals(), 'ldig.profile')
[ "re.compile", "numpy.log", "sys.exit", "numpy.save", "re.search", "os.path.exists", "json.dumps", "numpy.asarray", "numpy.dot", "subprocess.call", "os.mkdir", "time.localtime", "numpy.abs", "html.entities.name2codepoint.keys", "re.match", "sys.stderr.write", "da.DoubleArray", "re.s...
[((6158, 6211), 're.compile', 're.compile', (['u"""&(#x?[0-9a-f]+|[a-z]+);"""', 're.IGNORECASE'], {}), "(u'&(#x?[0-9a-f]+|[a-z]+);', re.IGNORECASE)\n", (6168, 6211), False, 'import os, sys, re, codecs, json\n'), ((6226, 6262), 're.compile', 're.compile', (['u"""#x\\\\d+"""', 're.IGNORECASE'], {}), "(u'#x\\\\d+', re.IGNORECASE)\n", (6236, 6262), False, 'import os, sys, re, codecs, json\n'), ((6276, 6311), 're.compile', 're.compile', (['u"""#\\\\d+"""', 're.IGNORECASE'], {}), "(u'#\\\\d+', re.IGNORECASE)\n", (6286, 6311), False, 'import os, sys, re, codecs, json\n'), ((7337, 7356), 're.compile', 're.compile', (['"""[^Iİ]"""'], {}), "('[^Iİ]')\n", (7347, 7356), False, 'import os, sys, re, codecs, json\n'), ((7380, 7401), 're.compile', 're.compile', (['u"""[Ğğİı]"""'], {}), "(u'[Ğğİı]')\n", (7390, 7401), False, 'import os, sys, re, codecs, json\n'), ((10764, 10812), 're.compile', 're.compile', (['u"""[AEIOUYaeiouyÂÊÔâêôĂăƠơƯư][̣̀́̃̉]"""'], {}), "(u'[AEIOUYaeiouyÂÊÔâêôĂăƠơƯư][̣̀́̃̉]')\n", (10774, 10812), False, 'import os, sys, re, codecs, json\n'), ((10914, 10946), 're.compile', 're.compile', (['u"""([a-zà-ɏ])\\\\1{2,}"""'], {}), "(u'([a-zà-ɏ])\\\\1{2,}')\n", (10924, 10946), False, 'import os, sys, re, codecs, json\n'), ((10974, 11007), 're.compile', 're.compile', (['u"""([^a-zà-ɏ])\\\\1{1,}"""'], {}), "(u'([^a-zà-ɏ])\\\\1{1,}')\n", (10984, 11007), False, 'import os, sys, re, codecs, json\n'), ((6995, 7039), 're.sub', 're.sub', (['"""(@|#|https?:\\\\/\\\\/)[^ ]+"""', '""""""', 'text'], {}), "('(@|#|https?:\\\\/\\\\/)[^ ]+', '', text)\n", (7001, 7039), False, 'import os, sys, re, codecs, json\n'), ((7050, 7099), 're.sub', 're.sub', (['"""(^| )[:;x]-?[\\\\(\\\\)dop]($| )"""', '""" """', 'text'], {}), "('(^| )[:;x]-?[\\\\(\\\\)dop]($| )', ' ', text)\n", (7056, 7099), False, 'import os, sys, re, codecs, json\n'), ((7122, 7158), 're.sub', 're.sub', (['"""(^| )(rt[ :]+)*"""', '""" """', 'text'], {}), "('(^| )(rt[ :]+)*', ' ', text)\n", (7128, 7158), False, 'import os, sys, re, codecs, json\n'), ((7171, 7248), 're.sub', 're.sub', (['"""([hj])+([aieo])+(\\\\1+\\\\2+){1,}"""', '"""\\\\1\\\\2\\\\1\\\\2"""', 'text', 're.IGNORECASE'], {}), "('([hj])+([aieo])+(\\\\1+\\\\2+){1,}', '\\\\1\\\\2\\\\1\\\\2', text, re.IGNORECASE)\n", (7177, 7248), False, 'import os, sys, re, codecs, json\n'), ((7265, 7303), 're.sub', 're.sub', (['""" +(via|live on) *$"""', '""""""', 'text'], {}), "(' +(via|live on) *$', '', text)\n", (7271, 7303), False, 'import os, sys, re, codecs, json\n'), ((11051, 11087), 're.match', 're.match', (['"""([-A-Za-z]+)\\\\t(.+)"""', 'org'], {}), "('([-A-Za-z]+)\\\\t(.+)', org)\n", (11059, 11087), False, 'import os, sys, re, codecs, json\n'), ((11167, 11198), 're.search', 're.search', (['"""\\\\t([^\\\\t]+)$"""', 'org'], {}), "('\\\\t([^\\\\t]+)$', org)\n", (11176, 11198), False, 'import os, sys, re, codecs, json\n'), ((11295, 11319), 're.sub', 're.sub', (['u"""[‐-―]"""', '"""-"""', 's'], {}), "(u'[‐-―]', '-', s)\n", (11301, 11319), False, 'import os, sys, re, codecs, json\n'), ((11338, 11363), 're.sub', 're.sub', (['u"""[0-9]+"""', '"""0"""', 's'], {}), "(u'[0-9]+', '0', s)\n", (11344, 11363), False, 'import os, sys, re, codecs, json\n'), ((11372, 11413), 're.sub', 're.sub', (['u"""[^ -~¡-ɏ̀-ͯͰ-ϿЀ-ӿḀ-ỿ]+"""', '""" """', 's'], {}), "(u'[^ -~¡-ɏ̀-ͯͰ-ϿЀ-ӿḀ-ỿ]+', ' ', s)\n", (11378, 11413), False, 'import os, sys, re, codecs, json\n'), ((11551, 11573), 're.sub', 're.sub', (['u""" +"""', '""" """', 's'], {}), "(u' +', ' ', s)\n", (11557, 11573), False, 'import os, sys, re, codecs, json\n'), ((13023, 13049), 'numpy.random.shuffle', 'numpy.random.shuffle', (['list'], {}), '(list)\n', (13043, 13049), False, 'import numpy\n'), ((13396, 13415), 'numpy.asarray', 'numpy.asarray', (['res1'], {}), '(res1)\n', (13409, 13415), False, 'import numpy\n'), ((13557, 13576), 'numpy.asarray', 'numpy.asarray', (['res2'], {}), '(res2)\n', (13570, 13576), False, 'import numpy\n'), ((13656, 13691), 'numpy.dot', 'numpy.dot', (['param[array,].T', 'valuesA'], {}), '(param[array,].T, valuesA)\n', (13665, 13691), False, 'import numpy\n'), ((14172, 14197), 'numpy.zeros', 'numpy.zeros', (['K'], {'dtype': 'int'}), '(K, dtype=int)\n', (14183, 14197), False, 'import numpy\n'), ((14211, 14236), 'numpy.zeros', 'numpy.zeros', (['K'], {'dtype': 'int'}), '(K, dtype=int)\n', (14222, 14236), False, 'import numpy\n'), ((16349, 16374), 'numpy.zeros', 'numpy.zeros', (['K'], {'dtype': 'int'}), '(K, dtype=int)\n', (16360, 16374), False, 'import numpy\n'), ((16388, 16413), 'numpy.zeros', 'numpy.zeros', (['K'], {'dtype': 'int'}), '(K, dtype=int)\n', (16399, 16413), False, 'import numpy\n'), ((18185, 18201), 'da.DoubleArray', 'da.DoubleArray', ([], {}), '()\n', (18199, 18201), False, 'import da\n'), ((18353, 18376), 'optparse.OptionParser', 'optparse.OptionParser', ([], {}), '()\n', (18374, 18376), False, 'import optparse\n'), ((389, 424), 'os.path.join', 'os.path.join', (['model_dir', '"""features"""'], {}), "(model_dir, 'features')\n", (401, 424), False, 'import os, sys, re, codecs, json\n'), ((447, 485), 'os.path.join', 'os.path.join', (['model_dir', '"""labels.json"""'], {}), "(model_dir, 'labels.json')\n", (459, 485), False, 'import os, sys, re, codecs, json\n'), ((507, 548), 'os.path.join', 'os.path.join', (['model_dir', '"""parameters.npy"""'], {}), "(model_dir, 'parameters.npy')\n", (519, 548), False, 'import os, sys, re, codecs, json\n'), ((576, 618), 'os.path.join', 'os.path.join', (['model_dir', '"""doublearray.npz"""'], {}), "(model_dir, 'doublearray.npz')\n", (588, 618), False, 'import os, sys, re, codecs, json\n'), ((658, 674), 'da.DoubleArray', 'da.DoubleArray', ([], {}), '()\n', (672, 674), False, 'import da\n'), ((2663, 2716), 'subprocess.call', 'subprocess.call', (['[maxsubst, temp_path, temp_features]'], {}), '([maxsubst, temp_path, temp_features])\n', (2678, 2716), False, 'import subprocess\n'), ((2792, 2813), 're.compile', 're.compile', (['u""".\x01."""'], {}), "(u'.\\x01.')\n", (2802, 2813), False, 'import os, sys, re, codecs, json\n'), ((2829, 2867), 're.compile', 're.compile', (['u"""[A-Za-z¡-£¿-ɏḀ-ỿͰ-ϿЀ-ӿ]"""'], {}), "(u'[A-Za-z¡-£¿-ɏḀ-ỿͰ-ϿЀ-ӿ]')\n", (2839, 2867), False, 'import os, sys, re, codecs, json\n'), ((3773, 3795), 'numpy.load', 'numpy.load', (['self.param'], {}), '(self.param)\n', (3783, 3795), False, 'import numpy\n'), ((3973, 4006), 'numpy.save', 'numpy.save', (['self.param', 'new_param'], {}), '(self.param, new_param)\n', (3983, 4006), False, 'import numpy\n'), ((4462, 4484), 'numpy.load', 'numpy.load', (['self.param'], {}), '(self.param)\n', (4472, 4484), False, 'import numpy\n'), ((5399, 5421), 'numpy.load', 'numpy.load', (['self.param'], {}), '(self.param)\n', (5409, 5421), False, 'import numpy\n'), ((5838, 5867), 'numpy.save', 'numpy.save', (['self.param', 'param'], {}), '(self.param, param)\n', (5848, 5867), False, 'import numpy\n'), ((5952, 5974), 'numpy.load', 'numpy.load', (['self.param'], {}), '(self.param)\n', (5962, 5974), False, 'import numpy\n'), ((12950, 12980), 'numpy.random.shuffle', 'numpy.random.shuffle', (['text_ids'], {}), '(text_ids)\n', (12970, 12980), False, 'import numpy\n'), ((14082, 14105), 'numpy.zeros_like', 'numpy.zeros_like', (['param'], {}), '(param)\n', (14098, 14105), False, 'import numpy\n'), ((20253, 20288), 'os.path.join', 'os.path.join', (['options.model', '"""temp"""'], {}), "(options.model, 'temp')\n", (20265, 20288), False, 'import os, sys, re, codecs, json\n'), ((1367, 1379), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1376, 1379), False, 'import os, sys, re, codecs, json\n'), ((6622, 6658), 'html.entities.name2codepoint.keys', 'htmlentitydefs.name2codepoint.keys', ([], {}), '()\n', (6656, 6658), True, 'import html.entities as htmlentitydefs\n'), ((19753, 19782), 'os.path.exists', 'os.path.exists', (['options.model'], {}), '(options.model)\n', (19767, 19782), False, 'import os, sys, re, codecs, json\n'), ((19796, 19819), 'os.mkdir', 'os.mkdir', (['options.model'], {}), '(options.model)\n', (19804, 19819), False, 'import os, sys, re, codecs, json\n'), ((19912, 19945), 'os.path.exists', 'os.path.exists', (['detector.features'], {}), '(detector.features)\n', (19926, 19945), False, 'import os, sys, re, codecs, json\n'), ((20018, 20049), 'os.path.exists', 'os.path.exists', (['detector.labels'], {}), '(detector.labels)\n', (20032, 20049), False, 'import os, sys, re, codecs, json\n'), ((20120, 20150), 'os.path.exists', 'os.path.exists', (['detector.param'], {}), '(detector.param)\n', (20134, 20150), False, 'import os, sys, re, codecs, json\n'), ((914, 944), 're.match', 're.match', (['"""(.+)\\\\t([0-9]+)"""', 's'], {}), "('(.+)\\\\t([0-9]+)', s)\n", (922, 944), False, 'import os, sys, re, codecs, json\n'), ((2456, 2474), 'json.dumps', 'json.dumps', (['labels'], {}), '(labels)\n', (2466, 2474), False, 'import os, sys, re, codecs, json\n'), ((12517, 12587), 'sys.exit', 'sys.exit', (['("unknown label \'%s\' at %d in %s " % (label, i + 1, filename))'], {}), '("unknown label \'%s\' at %d in %s " % (label, i + 1, filename))\n', (12525, 12587), False, 'import os, sys, re, codecs, json\n'), ((16152, 16168), 'numpy.abs', 'numpy.abs', (['param'], {}), '(param)\n', (16161, 16168), False, 'import numpy\n'), ((16727, 16857), 'sys.stderr.write', 'sys.stderr.write', (['("WARNING : unknown label \'%s\' at %d in %s (ignore the later same labels)\\n" %\n (label, i + 1, filename))'], {}), '(\n "WARNING : unknown label \'%s\' at %d in %s (ignore the later same labels)\\n"\n % (label, i + 1, filename))\n', (16743, 16857), False, 'import os, sys, re, codecs, json\n'), ((17276, 17297), 'numpy.log', 'numpy.log', (['y[label_k]'], {}), '(y[label_k])\n', (17285, 17297), False, 'import numpy\n'), ((991, 1046), 'sys.exit', 'sys.exit', (['("irregular feature : \'%s\' at %d" % (s, n + 1))'], {}), '("irregular feature : \'%s\' at %d" % (s, n + 1))\n', (999, 1046), False, 'import os, sys, re, codecs, json\n'), ((1113, 1168), 'sys.exit', 'sys.exit', (['("unordered feature : \'%s\' at %d" % (s, n + 1))'], {}), '("unordered feature : \'%s\' at %d" % (s, n + 1))\n', (1121, 1168), False, 'import os, sys, re, codecs, json\n'), ((3813, 3829), 'numpy.abs', 'numpy.abs', (['param'], {}), '(param)\n', (3822, 3829), False, 'import numpy\n'), ((5543, 5559), 'time.localtime', 'time.localtime', ([], {}), '()\n', (5557, 5559), False, 'import time\n'), ((5672, 5688), 'time.localtime', 'time.localtime', ([], {}), '()\n', (5686, 5688), False, 'import time\n'), ((5811, 5827), 'time.localtime', 'time.localtime', ([], {}), '()\n', (5825, 5827), False, 'import time\n'), ((2055, 2119), 'sys.stderr.write', 'sys.stderr.write', (["('no label data at %d in %s \\n' % (i + 1, file))"], {}), "('no label data at %d in %s \\n' % (i + 1, file))\n", (2071, 2119), False, 'import os, sys, re, codecs, json\n')]
""" Test of Particle Swarm Optimization algorithm in combination with Xfoil and the PARSEC airfoil parametrization. Trying to find low Re low drag airfoil for given thickness (thus varying Re). """ from __future__ import division, print_function from os import remove import numpy as np from copy import copy from string import ascii_uppercase from random import choice import matplotlib.pyplot as plt from optimization_algorithms.pso import Particle from airfoil_generators import parsec from xfoil import xfoil strut_thickness = .01 #m velocity = 10 #m/s def calcRe(thickness): # At 1atm and 10*C kinematic_viscosity_air = 1.4207E-5 l = strut_thickness/thickness return velocity*l/kinematic_viscosity_air # Weigh score on frontal surface def weighScore(Cd, thickness): return Cd / thickness constraints = np.array(( #rle x_pre/suc d2ydx2_pre/suc th_pre/suc y_pre/suc (.015,.05), (.3,.75), (-2,.1), (0,40), (.03, .2) )) # Good parameters at: # http://hvass-labs.org/people/magnus/publications/pedersen10good-pso.pdf iterations, S, omega, theta_g, theta_p = 14, 18, -0.2, 2.8, 0 def construct_airfoil(*pts): k = {} k['rle'] = pts[0] k['x_pre'] = pts[1] k['y_pre'] = -pts[4] k['d2ydx2_pre'] = -pts[2] # Trailing edge angle k['th_pre'] = pts[3] # Suction part k['x_suc'] = k['x_pre'] k['y_suc'] = -k['y_pre'] k['d2ydx2_suc'] = -k['d2ydx2_pre'] k['th_suc'] = -k['th_pre'] # Trailing edge x and y position k['xte'] = 1 k['yte'] = 0 return parsec.PARSEC(k) def score_airfoil(airfoil): max_thickness = airfoil.max_thickness() Re = calcRe(max_thickness) print("RE is ", Re, "MT is ", max_thickness) # Make unique filename randstr = ''.join(choice(ascii_uppercase) for i in range(20)) filename = "parsec_{}.dat".format(randstr) # Save coordinates with open(filename, 'w') as af: af.write(airfoil.get_coords_plain()) # Let Xfoil do its magic polar = xfoil.oper_visc_alpha(filename, 0, Re, iterlim=80, show_seconds=0) try: remove(filename) except WindowsError: print("\n\n\n\nWindows was not capable of removing the file.\n\n\n\n") try: score = polar[0][0][2] score = weighScore(score, max_thickness) print("Score: ", score) # If it's not NaN if np.isfinite(score): print("Return score") return score else: print("Return None") return None except IndexError: print("Return None (IndexError)") return None # Show plot and make redrawing possible fig, (cur_afplt, lastpbest_afplt, gbest_afplt, score_plt) = plt.subplots(4,1) # Enable auto-clearing cur_afplt.hold(False) lastpbest_afplt.hold(False) gbest_afplt.hold(False) plt.tight_layout() # Interactive mode plt.ion() plt.pause(.0001) # Initialize globals global_bestscore = None global_bestpos = None global_bestairfoil = None # Constructing a particle automatically initializes position and speed particles = [Particle(constraints) for i in xrange(0, S)] scores_y = [] for n in xrange(iterations+1): print("\n\nIteration {}".format(n)) for i_par, particle in enumerate(particles): # Keep scoring until converged score = None while not score: # Update particle's velocity and position, if global best if global_bestscore: print("\nUpdate particle n{}p{}".format(n, i_par)) particle.update(global_bestpos, omega, theta_p, theta_g) # None if not converged airfoil = construct_airfoil(*particle.pts) score = score_airfoil(airfoil) plotstyle = "{}-".format(choice("rgb")) airfoil.plot(cur_afplt, score="Cd {}".format(score), style=plotstyle, title="Current, particle n{}p{}".format(n, i_par)) plt.pause(.0001) if not score and (not global_bestscore or n==0): print("Not converged, no global best, or first round. Randomizing particle.") particle.randomize() elif not score: print("Not converged, there is a global best. Randomizing.") particle.randomize() if not particle.bestscore or score < particle.bestscore: particle.new_best(score) txt = 'particle best' airfoil.plot(lastpbest_afplt, score="Cd {}".format(score), style=plotstyle, title="Particle best, particle n{}p{}".format(n, i_par)) #plt.pause(.0001) print("Found particle best, score {}".format(score)) if not global_bestscore or score < global_bestscore: global_bestscore = score # Copy to avoid globaL_bestpos becoming reference to array global_bestpos = copy(particle.pts) txt = 'global best' airfoil.plot(gbest_afplt, score="Cd {}".format(score), style=plotstyle, title="Global best, particle n{}p{}".format(n, i_par)) #plt.pause(.0001) print("Found global best, score {}".format(score)) global_bestairfoil = airfoil scores_y.append(global_bestscore) score_plt.plot(scores_y, 'r-') score_plt.set_title("Global best per round") plt.pause(.0001) print("# score = ", global_bestscore, ", pos = ", global_bestpos.__repr__(), ", airfoil points:\n{}".format(airfoil.get_coords_plain())) plt.show() # 11-2-14 # RE is 72047.1359611 MT is 0.0976969258288 #score = 0.0235421941938 , pos = array([ 0.04028559, 0.56905154, -0.15051354, 12.75297732, 0.03010498]) , airfoil points: #1.000000 -0.000000 #0.999615 -0.000094 #0.998459 -0.000373 #0.996534 -0.000832 #0.993844 -0.001462 #0.990393 -0.002253 #0.986185 -0.003188 #0.981228 -0.004253 #0.975528 -0.005428 #0.969096 -0.006695 #0.961940 -0.008034 #0.954072 -0.009426 #0.945503 -0.010850 #0.936248 -0.012291 #0.926320 -0.013730 #0.915735 -0.015155 #0.904508 -0.016551 #0.892658 -0.017909 #0.880203 -0.019219 #0.867161 -0.020476 #0.853553 -0.021675 #0.839400 -0.022812 #0.824724 -0.023885 #0.809547 -0.024893 #0.793893 -0.025836 #0.777785 -0.026712 #0.761249 -0.027521 #0.744311 -0.028264 #0.726995 -0.028938 #0.709330 -0.029544 #0.691342 -0.030078 #0.673059 -0.030541 #0.654508 -0.030931 #0.635720 -0.031247 #0.616723 -0.031489 #0.597545 -0.031659 #0.578217 -0.031759 #0.558769 -0.031794 #0.539230 -0.031771 #0.519630 -0.031700 #0.500000 -0.031593 #0.480370 -0.031465 #0.460770 -0.031332 #0.441231 -0.031214 #0.421783 -0.031131 #0.402455 -0.031104 #0.383277 -0.031155 #0.364280 -0.031304 #0.345492 -0.031571 #0.326941 -0.031973 #0.308658 -0.032521 #0.290670 -0.033225 #0.273005 -0.034086 #0.255689 -0.035102 #0.238751 -0.036261 #0.222215 -0.037548 #0.206107 -0.038936 #0.190453 -0.040395 #0.175276 -0.041885 #0.160600 -0.043362 #0.146447 -0.044777 #0.132839 -0.046076 #0.119797 -0.047204 #0.107342 -0.048102 #0.095492 -0.048715 #0.084265 -0.048990 #0.073680 -0.048876 #0.063752 -0.048331 #0.054497 -0.047318 #0.045928 -0.045811 #0.038060 -0.043793 #0.030904 -0.041259 #0.024472 -0.038215 #0.018772 -0.034679 #0.013815 -0.030682 #0.009607 -0.026265 #0.006156 -0.021481 #0.003466 -0.016390 #0.001541 -0.011061 #0.000385 -0.005572 #0.000000 0.000000 #0.000385 0.005572 #0.001541 0.011061 #0.003466 0.016390 #0.006156 0.021481 #0.009607 0.026265 #0.013815 0.030682 #0.018772 0.034679 #0.024472 0.038215 #0.030904 0.041259 #0.038060 0.043793 #0.045928 0.045811 #0.054497 0.047318 #0.063752 0.048331 #0.073680 0.048876 #0.084265 0.048990 #0.095492 0.048715 #0.107342 0.048102 #0.119797 0.047204 #0.132839 0.046076 #0.146447 0.044777 #0.160600 0.043362 #0.175276 0.041885 #0.190453 0.040395 #0.206107 0.038936 #0.222215 0.037548 #0.238751 0.036261 #0.255689 0.035102 #0.273005 0.034086 #0.290670 0.033225 #0.308658 0.032521 #0.326941 0.031973 #0.345492 0.031571 #0.364280 0.031304 #0.383277 0.031155 #0.402455 0.031104 #0.421783 0.031131 #0.441231 0.031214 #0.460770 0.031332 #0.480370 0.031465 #0.500000 0.031593 #0.519630 0.031700 #0.539230 0.031771 #0.558769 0.031794 #0.578217 0.031759 #0.597545 0.031659 #0.616723 0.031489 #0.635720 0.031247 #0.654508 0.030931 #0.673059 0.030541 #0.691342 0.030078 #0.709330 0.029544 #0.726995 0.028938 #0.744311 0.028264 #0.761249 0.027521 #0.777785 0.026712 #0.793893 0.025836 #0.809547 0.024893 #0.824724 0.023885 #0.839400 0.022812 #0.853553 0.021675 #0.867161 0.020476 #0.880203 0.019219 #0.892658 0.017909 #0.904508 0.016551 #0.915735 0.015155 #0.926320 0.013730 #0.936248 0.012291 #0.945503 0.010850 #0.954072 0.009426 #0.961940 0.008034 #0.969096 0.006695 #0.975528 0.005428 #0.981228 0.004253 #0.986185 0.003188 #0.990393 0.002253 #0.993844 0.001462 #0.996534 0.000832 #0.998459 0.000373 #0.999615 0.000094 #1.000000 0.000000 # score = 0.00870235341255 , pos = array([ 0.02875577, 0.52143075, -1.31975537, 19.25893881, 0.10054965]) , airfoil points: #1.000000 -0.000000 #0.999615 -0.000101 #0.998459 -0.000398 #0.996534 -0.000883 #0.993844 -0.001537 #0.990393 -0.002337 #0.986185 -0.003257 #0.981228 -0.004270 #0.975528 -0.005345 #0.969096 -0.006458 #0.961940 -0.007585 #0.954072 -0.008710 #0.945503 -0.009824 #0.936248 -0.010925 #0.926320 -0.012022 #0.915735 -0.013131 #0.904508 -0.014278 #0.892658 -0.015496 #0.880203 -0.016825 #0.867161 -0.018307 #0.853553 -0.019989 #0.839400 -0.021913 #0.824724 -0.024120 #0.809547 -0.026645 #0.793893 -0.029511 #0.777785 -0.032731 #0.761249 -0.036305 #0.744311 -0.040217 #0.726995 -0.044435 #0.709330 -0.048912 #0.691342 -0.053584 #0.673059 -0.058376 #0.654508 -0.063198 #0.635720 -0.067952 #0.616723 -0.072534 #0.597545 -0.076838 #0.578217 -0.080759 #0.558769 -0.084199 #0.539230 -0.087067 #0.519630 -0.089287 #0.500000 -0.090800 #0.480370 -0.091567 #0.460770 -0.091568 #0.441231 -0.090807 #0.421783 -0.089312 #0.402455 -0.087131 #0.383277 -0.084335 #0.364280 -0.081012 #0.345492 -0.077266 #0.326941 -0.073213 #0.308658 -0.068974 #0.290670 -0.064675 #0.273005 -0.060439 #0.255689 -0.056380 #0.238751 -0.052602 #0.222215 -0.049193 #0.206107 -0.046222 #0.190453 -0.043735 #0.175276 -0.041757 #0.160600 -0.040284 #0.146447 -0.039293 #0.132839 -0.038734 #0.119797 -0.038538 #0.107342 -0.038619 #0.095492 -0.038876 #0.084265 -0.039198 #0.073680 -0.039472 #0.063752 -0.039583 #0.054497 -0.039423 #0.045928 -0.038894 #0.038060 -0.037911 #0.030904 -0.036410 #0.024472 -0.034347 #0.018772 -0.031701 #0.013815 -0.028476 #0.009607 -0.024699 #0.006156 -0.020422 #0.003466 -0.015717 #0.001541 -0.010674 #0.000385 -0.005396 #0.000000 0.000000 #0.000385 0.005396 #0.001541 0.010674 #0.003466 0.015717 #0.006156 0.020422 #0.009607 0.024699 #0.013815 0.028476 #0.018772 0.031701 #0.024472 0.034347 #0.030904 0.036410 #0.038060 0.037911 #0.045928 0.038894 #0.054497 0.039423 #0.063752 0.039583 #0.073680 0.039472 #0.084265 0.039198 #0.095492 0.038876 #0.107342 0.038619 #0.119797 0.038538 #0.132839 0.038734 #0.146447 0.039293 #0.160600 0.040284 #0.175276 0.041757 #0.190453 0.043735 #0.206107 0.046222 #0.222215 0.049193 #0.238751 0.052602 #0.255689 0.056380 #0.273005 0.060439 #0.290670 0.064675 #0.308658 0.068974 #0.326941 0.073213 #0.345492 0.077266 #0.364280 0.081012 #0.383277 0.084335 #0.402455 0.087131 #0.421783 0.089312 #0.441231 0.090807 #0.460770 0.091568 #0.480370 0.091567 #0.500000 0.090800 #0.519630 0.089287 #0.539230 0.087067 #0.558769 0.084199 #0.578217 0.080759 #0.597545 0.076838 #0.616723 0.072534 #0.635720 0.067952 #0.654508 0.063198 #0.673059 0.058376 #0.691342 0.053584 #0.709330 0.048912 #0.726995 0.044435 #0.744311 0.040217 #0.761249 0.036305 #0.777785 0.032731 #0.793893 0.029511 #0.809547 0.026645 #0.824724 0.024120 #0.839400 0.021913 #0.853553 0.019989 #0.867161 0.018307 #0.880203 0.016825 #0.892658 0.015496 #0.904508 0.014278 #0.915735 0.013131 #0.926320 0.012022 #0.936248 0.010925 #0.945503 0.009824 #0.954072 0.008710 #0.961940 0.007585 #0.969096 0.006458 #0.975528 0.005345 #0.981228 0.004270 #0.986185 0.003257 #0.990393 0.002337 #0.993844 0.001537 #0.996534 0.000883 #0.998459 0.000398 #0.999615 0.000101 #1.000000 0.000000
[ "optimization_algorithms.pso.Particle", "random.choice", "xfoil.xfoil.oper_visc_alpha", "os.remove", "numpy.array", "numpy.isfinite", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.ion", "copy.copy", "matplotlib.pyplot.pause", "matplotlib.pyplot.subplots", "airfoil_generators.parsec.PARS...
[((829, 900), 'numpy.array', 'np.array', (['((0.015, 0.05), (0.3, 0.75), (-2, 0.1), (0, 40), (0.03, 0.2))'], {}), '(((0.015, 0.05), (0.3, 0.75), (-2, 0.1), (0, 40), (0.03, 0.2)))\n', (837, 900), True, 'import numpy as np\n'), ((2739, 2757), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', '(1)'], {}), '(4, 1)\n', (2751, 2757), True, 'import matplotlib.pyplot as plt\n'), ((2854, 2872), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2870, 2872), True, 'import matplotlib.pyplot as plt\n'), ((2892, 2901), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (2899, 2901), True, 'import matplotlib.pyplot as plt\n'), ((2902, 2919), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (2911, 2919), True, 'import matplotlib.pyplot as plt\n'), ((5549, 5559), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5557, 5559), True, 'import matplotlib.pyplot as plt\n'), ((1550, 1566), 'airfoil_generators.parsec.PARSEC', 'parsec.PARSEC', (['k'], {}), '(k)\n', (1563, 1566), False, 'from airfoil_generators import parsec\n'), ((2005, 2071), 'xfoil.xfoil.oper_visc_alpha', 'xfoil.oper_visc_alpha', (['filename', '(0)', 'Re'], {'iterlim': '(80)', 'show_seconds': '(0)'}), '(filename, 0, Re, iterlim=80, show_seconds=0)\n', (2026, 2071), False, 'from xfoil import xfoil\n'), ((3104, 3125), 'optimization_algorithms.pso.Particle', 'Particle', (['constraints'], {}), '(constraints)\n', (3112, 3125), False, 'from optimization_algorithms.pso import Particle\n'), ((5380, 5397), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (5389, 5397), True, 'import matplotlib.pyplot as plt\n'), ((2123, 2139), 'os.remove', 'remove', (['filename'], {}), '(filename)\n', (2129, 2139), False, 'from os import remove\n'), ((2403, 2421), 'numpy.isfinite', 'np.isfinite', (['score'], {}), '(score)\n', (2414, 2421), True, 'import numpy as np\n'), ((1769, 1792), 'random.choice', 'choice', (['ascii_uppercase'], {}), '(ascii_uppercase)\n', (1775, 1792), False, 'from random import choice\n'), ((3969, 3986), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (3978, 3986), True, 'import matplotlib.pyplot as plt\n'), ((4907, 4925), 'copy.copy', 'copy', (['particle.pts'], {}), '(particle.pts)\n', (4911, 4925), False, 'from copy import copy\n'), ((3784, 3797), 'random.choice', 'choice', (['"""rgb"""'], {}), "('rgb')\n", (3790, 3797), False, 'from random import choice\n')]
#!/usr/bin/env python import os import glob import numpy as np from astropy.io import fits from astropy.time import Time from astropy.table import Column, MaskedColumn import matplotlib.pyplot as plt from iminuit import Minuit from probfit import Chi2Regression, linear TessTimeBin_sec = 120.0 # sec TessTimeBin_day = TessTimeBin_sec / 24. / 60. / 60. MISSING_VALUE = -9999 class Hist1D(object): def __init__(self, edges): self.edges = edges self.hist, edges = np.histogram([], bins=self.edges) self.bins = (edges[:-1] + edges[1:]) / 2. def fill(self, arr): hist, edges = np.histogram(arr, bins=self.edges) self.hist += hist @property def data(self): return self.bins, self.hist def get_count_rate(cnt_array,exp_array): rate_list = [] error_list = [] for i in range(len(cnt_array.data[1])): cnt = cnt_array.data[1][i] exp = exp_array.data[1][i] if exp > 0: rate = float(cnt) / float(exp) error = float(np.sqrt(cnt)) / float(exp) #print(cnt,exp,rate) else: rate = 0 error = 0 rate_list.append(rate) error_list.append(error) return np.array(rate_list), np.array(error_list) class TessLightCurve(): def __init__(self,fitsfile): self.fitsfile = fitsfile print(self.fitsfile) self.hdu = fits.open(self.fitsfile) self.basename = os.path.splitext(os.path.basename(self.fitsfile))[0] print(self.basename) self.time_mjd = self.get_mjd() self.lc_orig_table = self.hdu['LIGHTCURVE'].data self.lc_orig_cols = self.lc_orig_table.columns self.edges = self.time_mjd+TessTimeBin_day/2.0 self.edges = np.insert(self.edges,0,self.time_mjd[0]-TessTimeBin_day/2.0) self.lc_list = {} def get_mjd(self): """ TUNIT1 = 'BJD - 2457000, days' / column units: Barycenter corrected TESS Julian TESS : BJD = TIME + 2457000 days # MJD = BJD - 2400 000.5 # https://en.wikipedia.org/wiki/Julian_day """ return self.hdu['LIGHTCURVE'].data['TIME'] + self.hdu['LIGHTCURVE'].header['BJDREFI'] + self.hdu['LIGHTCURVE'].header['BJDREFF'] - 2400000.5 def cadence2mjd(self,a=0.00138893,b=58226.94810026): return a * self.hdu['LIGHTCURVE'].data['CADENCENO'] + b def append_nicer_gti(self,input_niobs_list): self.niobsid_list = [] self.nigti_list = [] self.nimask = [] for mjd in self.time_mjd: #out_gtinum = np.nan out_gtinum = MISSING_VALUE out_niobs = MISSING_VALUE out_mask = True for niobs in input_niobs_list: out_gtinum = niobs.get_mjdnum(mjd) #if not np.isnan(out_gtinum): if out_gtinum != MISSING_VALUE: out_niobs = niobs.obsid out_mask = False break #if not np.isnan(out_gtinum): #if out_gtinum != MISSING_VALUE: # print(mjd,out_niobs,out_gtinum) self.niobsid_list.append(out_niobs) self.nigti_list.append(out_gtinum) self.nimask.append(out_mask) def append_nicer_count_rate(self,input_niobs_list,emin_keV,emax_keV): print(emin_keV) print(emax_keV) name_cnt = 'cnt_%s_%skeV' % (emin_keV,emax_keV) name_exp = 'exp_%s_%skeV' % (emin_keV,emax_keV) name_rate = 'cps_%s_%skeV' % (emin_keV,emax_keV) name_error = 'err_%s_%skeV' % (emin_keV,emax_keV) lc_hist_cnt = Hist1D(edges=self.edges) lc_hist_exp = Hist1D(edges=self.edges) for niobs in input_niobs_list: #print(niobs.obsid) mask_energy = np.logical_and(niobs.keV>=emin_keV,niobs.keV<=emax_keV) lc_hist_cnt.fill(niobs.time_mjd[mask_energy]) niobs.make_exposure_map() lc_hist_exp.fill(niobs.exposure_map) lc_hist_rate, lc_hist_error = get_count_rate(lc_hist_cnt,lc_hist_exp) self.lc_list[name_cnt] = lc_hist_cnt.data[1] self.lc_list[name_exp] = lc_hist_exp.data[1] self.lc_list[name_rate] = lc_hist_rate self.lc_list[name_error] = lc_hist_error #plt.step(*lc_hist_cnt.data) #plt.step(*lc_hist_exp.data) #plt.step(lc_hist_cnt.data[0],rate) #plt.errorbar(self.lc_hist_cnt.data[0],rate, # yerr=error,marker='',drawstyle='steps-mid') #plt.xlim(58600-0.2,58600.3) #plt.savefig('test.pdf') def writeto(self,overwrite=True): outfitsfile = "%s_nicer.fits" % self.basename #new_column_nigti = np.array(self.nigti_list,dtype=np.int) #col = MaskedColumn(data=new_column_nigti,name='NIGTI',format='I',mask=self.nimask) #print(col) #exit() print(self.lc_list) new_column_mjd = np.array(self.time_mjd) new_column_niobsid = np.array(self.niobsid_list) new_column_nigti = np.array(self.nigti_list,dtype=np.int) new_columns = fits.ColDefs([ fits.Column(name='MJD',format='F',array=new_column_mjd), fits.Column(name='NIOBSID',format='10A',array=new_column_niobsid), #MaskedColumn(data=new_column_nigti,name='NIGTI',format='I',mask=self.nimask) fits.Column(name='NIGTI',format='I',array=new_column_nigti) ]) for keyword in self.lc_list: print(keyword,self.lc_list[keyword]) new_columns += fits.ColDefs([ fits.Column(name=keyword,format='F',array=self.lc_list[keyword]) ]) hdu_primary = fits.PrimaryHDU() hdu_newtable = fits.BinTableHDU.from_columns(self.lc_orig_cols+new_columns,name='TRBLIST') hdulist = fits.HDUList([hdu_primary,hdu_newtable]) hdulist.writeto(outfitsfile,overwrite=True) class NicerEventFile(): def __init__(self,fitsfile): self.fitsfile = fitsfile print(self.fitsfile) self.hdu = fits.open(self.fitsfile) self.obsid = str(self.hdu['EVENTS'].header['OBS_ID']) self.gti = self.hdu['GTI'].data self.gti_start_mjd = self.get_mjd(self.gti['START']) self.gti_stop_mjd = self.get_mjd(self.gti['STOP']) self.time_mjd = self.get_mjd_events() self.keV = self.hdu['EVENTS'].data['PI'] / 100.0 def get_mjd(self,timeseries): """ # MJD(TT) = (MJDREFI+MJDREFF) + (TIMEZERO+TIME)/86400 # MJD(UTC) = (MJDREFI) + (TIMEZERO+TIME+LEAPINIT=2)/86400 """ return self.hdu['EVENTS'].header['MJDREFI'] + self.hdu['EVENTS'].header['MJDREFF'] + (timeseries + self.hdu['EVENTS'].header['TIMEZERO']) / 86400.0 def get_mjd_events(self): return self.get_mjd(self.hdu['EVENTS'].data['TIME'] ) def get_mjdnum(self,mjd): #gtinum = np.nan gtinum = MISSING_VALUE for i in range(len(self.gti)): #if self.gti_start_mjd[i] <= mjd < self.gti_stop_mjd[i]: # gtinum = i if (mjd + TessTimeBin_day / 2.0 >= self.gti_start_mjd[i]) and (mjd - TessTimeBin_day / 2.0 <= self.gti_stop_mjd[i]): gtinum = i break return gtinum # 2789 def show_mjd(self): for i in range(len(self.gti)): print(i,self.gti_start_mjd[i],self.gti_stop_mjd[i],(self.gti_stop_mjd[i]-self.gti_start_mjd[i])*24.*60.*60) def make_exposure_map(self,timebin_sec=1.0): self.exposure_map = [] for i in range(len(self.gti)): start = self.gti_start_mjd[i] stop = self.gti_stop_mjd[i] time = start while time < stop: self.exposure_map.append(time) time += timebin_sec / 24. / 60. / 60. NicerEventFileList = [] for obsid_path in sorted(glob.glob('out/all/26050?????')): obsid = os.path.basename(obsid_path) clevt = '%s/bary/ni%s_0mpu7_cl_bary.evt' % (obsid_path,obsid) if os.path.exists(clevt): NicerEventFileList.append(NicerEventFile(clevt)) data_dir_tess = "/Users/enoto/Dropbox/01_enoto/research/nicer/analysis/proximacen/data/200718_Notsu_TESS" tess1 = TessLightCurve("%s/tess2019112060037-s0011-0000000388857263-0143-s_lc.fits" % data_dir_tess) tess1.append_nicer_gti(NicerEventFileList) tess1.append_nicer_count_rate(NicerEventFileList,0.2,0.3) tess1.append_nicer_count_rate(NicerEventFileList,0.3,1.0) tess1.append_nicer_count_rate(NicerEventFileList,1.0,3.0) tess1.append_nicer_count_rate(NicerEventFileList,3.0,10.0) tess1.append_nicer_count_rate(NicerEventFileList,10.0,15.0) tess1.writeto() data_dir_tess = "/Users/enoto/Dropbox/01_enoto/research/nicer/analysis/proximacen/data/200718_Notsu_TESS" tess2 = TessLightCurve("%s/tess2019140104343-s0012-0000000388857263-0144-s_lc.fits" % data_dir_tess) tess2.append_nicer_gti(NicerEventFileList) tess2.append_nicer_count_rate(NicerEventFileList,0.2,0.3) tess2.append_nicer_count_rate(NicerEventFileList,0.3,1.0) tess2.append_nicer_count_rate(NicerEventFileList,1.0,3.0) tess2.append_nicer_count_rate(NicerEventFileList,3.0,10.0) tess2.append_nicer_count_rate(NicerEventFileList,10.0,15.0) tess2.writeto()
[ "numpy.insert", "os.path.exists", "numpy.histogram", "numpy.sqrt", "astropy.io.fits.PrimaryHDU", "astropy.io.fits.HDUList", "numpy.logical_and", "astropy.io.fits.Column", "numpy.array", "os.path.basename", "astropy.io.fits.open", "astropy.io.fits.BinTableHDU.from_columns", "glob.glob" ]
[((6821, 6852), 'glob.glob', 'glob.glob', (['"""out/all/26050?????"""'], {}), "('out/all/26050?????')\n", (6830, 6852), False, 'import glob\n'), ((6864, 6892), 'os.path.basename', 'os.path.basename', (['obsid_path'], {}), '(obsid_path)\n', (6880, 6892), False, 'import os\n'), ((6961, 6982), 'os.path.exists', 'os.path.exists', (['clevt'], {}), '(clevt)\n', (6975, 6982), False, 'import os\n'), ((476, 509), 'numpy.histogram', 'np.histogram', (['[]'], {'bins': 'self.edges'}), '([], bins=self.edges)\n', (488, 509), True, 'import numpy as np\n'), ((593, 627), 'numpy.histogram', 'np.histogram', (['arr'], {'bins': 'self.edges'}), '(arr, bins=self.edges)\n', (605, 627), True, 'import numpy as np\n'), ((1091, 1110), 'numpy.array', 'np.array', (['rate_list'], {}), '(rate_list)\n', (1099, 1110), True, 'import numpy as np\n'), ((1112, 1132), 'numpy.array', 'np.array', (['error_list'], {}), '(error_list)\n', (1120, 1132), True, 'import numpy as np\n'), ((1252, 1276), 'astropy.io.fits.open', 'fits.open', (['self.fitsfile'], {}), '(self.fitsfile)\n', (1261, 1276), False, 'from astropy.io import fits\n'), ((1572, 1638), 'numpy.insert', 'np.insert', (['self.edges', '(0)', '(self.time_mjd[0] - TessTimeBin_day / 2.0)'], {}), '(self.edges, 0, self.time_mjd[0] - TessTimeBin_day / 2.0)\n', (1581, 1638), True, 'import numpy as np\n'), ((4268, 4291), 'numpy.array', 'np.array', (['self.time_mjd'], {}), '(self.time_mjd)\n', (4276, 4291), True, 'import numpy as np\n'), ((4315, 4342), 'numpy.array', 'np.array', (['self.niobsid_list'], {}), '(self.niobsid_list)\n', (4323, 4342), True, 'import numpy as np\n'), ((4364, 4403), 'numpy.array', 'np.array', (['self.nigti_list'], {'dtype': 'np.int'}), '(self.nigti_list, dtype=np.int)\n', (4372, 4403), True, 'import numpy as np\n'), ((4919, 4936), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', ([], {}), '()\n', (4934, 4936), False, 'from astropy.io import fits\n'), ((4954, 5032), 'astropy.io.fits.BinTableHDU.from_columns', 'fits.BinTableHDU.from_columns', (['(self.lc_orig_cols + new_columns)'], {'name': '"""TRBLIST"""'}), "(self.lc_orig_cols + new_columns, name='TRBLIST')\n", (4983, 5032), False, 'from astropy.io import fits\n'), ((5043, 5084), 'astropy.io.fits.HDUList', 'fits.HDUList', (['[hdu_primary, hdu_newtable]'], {}), '([hdu_primary, hdu_newtable])\n', (5055, 5084), False, 'from astropy.io import fits\n'), ((5250, 5274), 'astropy.io.fits.open', 'fits.open', (['self.fitsfile'], {}), '(self.fitsfile)\n', (5259, 5274), False, 'from astropy.io import fits\n'), ((3289, 3349), 'numpy.logical_and', 'np.logical_and', (['(niobs.keV >= emin_keV)', '(niobs.keV <= emax_keV)'], {}), '(niobs.keV >= emin_keV, niobs.keV <= emax_keV)\n', (3303, 3349), True, 'import numpy as np\n'), ((1312, 1343), 'os.path.basename', 'os.path.basename', (['self.fitsfile'], {}), '(self.fitsfile)\n', (1328, 1343), False, 'import os\n'), ((4437, 4494), 'astropy.io.fits.Column', 'fits.Column', ([], {'name': '"""MJD"""', 'format': '"""F"""', 'array': 'new_column_mjd'}), "(name='MJD', format='F', array=new_column_mjd)\n", (4448, 4494), False, 'from astropy.io import fits\n'), ((4500, 4567), 'astropy.io.fits.Column', 'fits.Column', ([], {'name': '"""NIOBSID"""', 'format': '"""10A"""', 'array': 'new_column_niobsid'}), "(name='NIOBSID', format='10A', array=new_column_niobsid)\n", (4511, 4567), False, 'from astropy.io import fits\n'), ((4654, 4715), 'astropy.io.fits.Column', 'fits.Column', ([], {'name': '"""NIGTI"""', 'format': '"""I"""', 'array': 'new_column_nigti'}), "(name='NIGTI', format='I', array=new_column_nigti)\n", (4665, 4715), False, 'from astropy.io import fits\n'), ((947, 959), 'numpy.sqrt', 'np.sqrt', (['cnt'], {}), '(cnt)\n', (954, 959), True, 'import numpy as np\n'), ((4831, 4897), 'astropy.io.fits.Column', 'fits.Column', ([], {'name': 'keyword', 'format': '"""F"""', 'array': 'self.lc_list[keyword]'}), "(name=keyword, format='F', array=self.lc_list[keyword])\n", (4842, 4897), False, 'from astropy.io import fits\n')]
import numpy def random_projection(A, new_dim, seed=0): # Project rows of [A] into lower dimension [new_dim] if A.shape[1] <= new_dim: return A state = numpy.random.RandomState(seed) R = state.choice([-1, 0, 0, 0, 0, 1], (new_dim, A.shape[1])) * numpy.sqrt(3) A_new = numpy.dot(R, A.T).T return A_new
[ "numpy.dot", "numpy.sqrt", "numpy.random.RandomState" ]
[((173, 203), 'numpy.random.RandomState', 'numpy.random.RandomState', (['seed'], {}), '(seed)\n', (197, 203), False, 'import numpy\n'), ((271, 284), 'numpy.sqrt', 'numpy.sqrt', (['(3)'], {}), '(3)\n', (281, 284), False, 'import numpy\n'), ((297, 314), 'numpy.dot', 'numpy.dot', (['R', 'A.T'], {}), '(R, A.T)\n', (306, 314), False, 'import numpy\n')]
import numpy import sys import os try: # add optional cython support import pyximport except ImportError as e: print(e) pyximport = None sys.path.append(os.path.abspath(os.path.dirname(__file__))) # ensure villager bot modules are accessible os.chdir(os.path.dirname(__file__)) # ensure the current working directory is correct if pyximport: # add cython support, with numpy header files pyximport.install(language_level=3, setup_args={"include_dirs": numpy.get_include()}) # import and compile villager bot cython modules here **first** # if not all pyx files are imported here, each forked process / shard group will try to compile # them and fail because they are all trying at the same time to access and write the same files from util import tiler, tiler_rgba from karen import MechaKaren def main(): karen = MechaKaren() try: karen.run() except KeyboardInterrupt: pass if __name__ == "__main__": main()
[ "os.path.dirname", "karen.MechaKaren", "numpy.get_include" ]
[((267, 292), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (282, 292), False, 'import os\n'), ((864, 876), 'karen.MechaKaren', 'MechaKaren', ([], {}), '()\n', (874, 876), False, 'from karen import MechaKaren\n'), ((184, 209), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (199, 209), False, 'import os\n'), ((478, 497), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (495, 497), False, 'import numpy\n')]
import numpy as np from enum import Enum import cv2 # we will use linear_assignment to quickly write experiments, # later a customerized KM algorithms with various optimization in c++ is employed # see https://github.com/berhane/LAP-solvers # This is used for "Complete Matching" and we can remove unreasonable "workers" first and then apply it import scipy.optimize as Optimizer # This is used for "Maximum Matching". There is a desired algorithm implementation for our references import scipy.sparse.csgraph as Graph import logging from pysvso.lib.log import LoggerAdaptor _logger = logging.getLogger("frame") import numpy as np import threading from pysvso.py_pose_graph.point3d import Point3D from pysvso.predictors import OpticalFlowBBoxPredictor, OpticalFlowKPntPredictor try: from pysvso.lib.misc import AtomicCounter # AtomicCounter except: class AtomicCounter(object): def __init__(self): self._counter = 0 self.lock = threading.Lock() def incr(self): with self.lock: self._counter += 1 return self._counter def __call__(self): return self.incr() try: from pysvso.lib.misc import Identity # Identity except: class Identity: def __init__(self, seq, name=None, id=None, uuid=None, tok=None, key=None): self.seq = seq self.name = name self.id = id self.uuid = uuid self.tok = tok self.key = key def __str__(self): return "Identity#%d" % self.seq from pysvso.optimizers.bundle_adjust import g2o from pysvso.lib.visualizer import display R_PRECISION = 1e-4 class Pixel2D: Seq = AtomicCounter() # implements STL iterators class VectorIterator(object): def __init__(self, vec): self._vec = vec self.counter = self.__counter__() def __iter__(self): return self def __counter__(self): l = len(self._vec) # one dimension index ind = 0 while True: yield ind ind += 1 if ind >= l: break def __next__(self): try: ind = next(self.counter) return self._vec[ind] except StopIteration: raise StopIteration() def __str__(self): return "Vector iterator" def __init__(self, r, c, val=0): self.identity = Identity(Pixel2D.Seq()) # y self.r = r # x self.c = c self.val = val # cv keypoint reference self.kp = None # key point extracted feature self.feature = None ## Covisibility Graph Topology # reproj 3d points in camera space # self.parent = None self.distance = None self.cam_pt_array = [] # a weak frame reference self.frame = None # a weak roi reference self.roi = None @property def x(self): return self.c @property def y(self): return self.r @property def sources(self): return self.cam_pt_array def __getitem__(self, i): data = np.array([self.c, self.r]) return data[i] def __setitem__(self, k, v): data = np.array([self.c, self.r]) data[k] = v self.r = data[1] self.c = data[0] return self def set_frame(self, frame): self.frame = frame idx = self.pixel_pos # add strong connection frame.pixels[idx] = self return self @property def seq(self): return self.identity.seq @property def pixel_pos(self): frame = self.frame H, W = frame.img.shape[:2] idx = int(self.r * W + self.c) self.identity.key = idx return idx def set_roi(self, landmark): self.roi = landmark return self def set_feature(self, feature): self.feature = feature return self def set_kp(self, kp): self.kp = kp return self def add(self, cam_pt3): # if not present self.cam_pt_array.append(cam_pt3) return self def __iter__(self): data = np.array([self.c, self.r]) return self.VectorIterator(data) @property def data(self): ret_data = np.array([int(self.c), int(self.r)]) return ret_data def findObservationOf(self, world_pt3): if len(self.sources) == 0: return None if world_pt3 is None: return None best = None def check_eq(retrived, new): left = retrived.data right = new.data dist = np.linalg.norm(left - right) if dist < R_PRECISION: return True else: return False for p in self.cam_pt_array: # comparing world point location w = p.world if w is None: continue if check_eq(w, world_pt3): if best is None: best = w else: dist1 = np.linalg.norm(w - world_pt3) dist2 = np.linalg.norm(best - world_pt3) if dist1 < dist2: best = w return best def isObservationOf(self, mappoint): if mappoint is None: return False frame = self.frame px_pos = mappoint.frames.get(frame.seq, None) if px_pos is None: return False else: idx = self.pixel_pos if idx == px_pos: return True else: return False # Union find with compression def findParent(self, cmpr=False): if self.parent is not None: parent = self.parent.findParent() if cmpr: self.parent = parent return parent return self def __repr__(self): return "<Pixel2D %d: r=%.3f, c=%.3f>" % (self.identity.seq, self.r, self.c) def __str__(self): return "<Pixel2D %d: r=%.3f, c=%.3f>" % (self.identity.seq, self.r, self.c) from pysvso.models.sfe import SemanticFeatureExtractor class Frame: Seq = AtomicCounter() logger = LoggerAdaptor("Frame", _logger) def __init__(self): self.identity = Identity(Frame.Seq()) self.isKeyFrame = False ## Content # used to align with ground truth self.timestamp = None # might be a image path or url read by a asynchronous reader self._img_src = None # color constructed from img: cv::Mat or std::vector<byte> self.img = None # computed grey img or collected grey img directly from a camera self._img_grey = None # a camera instance to performance MVP or other image related computation self.camera = None # group of map tiles, where we storage 3d points, measurements and source images # Note: this should be a weak reference to the original data representation self.runtimeBlock = None ## Rigid object movements # later we will move these attributes to Object3D as common practice # in game development area, i.e, class Frame -> class Frame: public Object3D # rotation and translation relative to origins # Rwc. Note the author of ORB_SLAM2 uses the opporsite notation (Rcw) to reprented camera # camera pose, see discuss #226 self.R0 = np.eye(3) # twc self.t0 = np.zeros((3, 1)) # rotation and translation relative to the last frame, updated in each frame self.R1 = np.eye(3) self.t1 = np.zeros((3, 1)) # used to very reprojection error in initialization process self.Rcw = np.eye(3) # inv(R0) self.tcw = np.zeros((3, 1)) # -inv(R0).dot(t0) # GT set by tracker when timestamp and ground truth are all available self.assoc_timestamp = None self.R_gt = None self.t_gt = None ## Covisibility Graph Topology # previous frame self.pre = None # self.pixels = {} ## Features Expression Layer # extracted features # opencv key points self.kps = None # opencv key point features self.kps_feats = None # extracted roi keypoints (defaults to ORB keypoints) self.roi_kps = None # extracted roi features self.roi_feats = None # meta data self._detections = {} # media scene depth self.medianSceneDepth = -1. self.extractors = {} self.is_First = False ### Main Logics Executor ### # self.predictors = { 'OpticalFlow': OpticalFlowBBoxPredictor(), 'OpticalFlowKPnt': OpticalFlowKPntPredictor() } # self.matchers = {} # self.USE_IMAGE_LEVEL_ORB = False # => # self.SHOW_ROI = False # self.sample_size = -1 @property def seq(self): return self.identity.seq @seq.setter def seq(self, val): self.identity.seq = val return self def set_camera(self, camera): self.camera = camera return self def set_timestamp(self, timestamp): self.timestamp = timestamp return self # @todo : TODO def set_FromImg(self, img): self.img = img self.predictors['OpticalFlow'].set_FromImg(self.img_grey()).Init() self.predictors['OpticalFlowKPnt'].set_FromImg(self.img_grey()).Init() return self # getter of self._grey_img def img_grey(self): img_grey = self._img_grey if img_grey is None: img_grey = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) # suppose the image is undistorted self._img_grey = img_grey return img_grey # @todo : TODO def extract(self): orb_kp, orb_desc = (None, None) if self.USE_IMAGE_LEVEL_ORB: # @todo : REFACTOR the tasks should be running in pararllel # self.logger.info("%s, Extracting Image ORB features ..." % self) print("%s, Extracting Image ORB features ..." % self) orb_kp, orb_desc = self.ExtractORB() # @todo : TODO # add to frame # self.logger.info("Type of image orb key points : %s, size %d" % (type(orb_kp), len(orb_kp))) print("Type of image orb key points : %s, size %d" % (type(orb_kp), len(orb_kp))) # self.logger.info("Type of image orb descriptors : %s, shape %s" % (type(orb_desc), orb_desc.shape)) print("Type of image orb descriptors : %s, shape %s" % (type(orb_desc), orb_desc.shape)) # extract deep features or ROI # self.logger.info("%s, Extracting ROI features ..." % self) print("%s, Extracting ROI features ..." % self) roi_kp, roi_features = self.ExtractROI() kps = [] kps_feats = [] if self.USE_IMAGE_LEVEL_ORB: kps.extend(orb_kp) kps_feats.extend(orb_desc) # catenate orb keypoints and features, see opencv docs for definition # of returned key points and descriptors if self.extractors['sfe'].USE_ROI_LEVEL_ORB: for i, roi_feat_per_box in enumerate(roi_features): desc_per_box, kps_per_box = roi_feat_per_box['roi_orb'] if len(kps_per_box) is 0: label = roi_feat_per_box['label'] print("extract 0 points for detection#%d(%s)." % (i, label)) # raise ValueError("'kps_per_box' should not be an empty list!") kps.extend(kps_per_box) kps_feats.extend(desc_per_box) self.kps = kps self.kps_feats = kps_feats self.roi_kp = roi_kp self.roi_features = roi_features return (kps, kps_feats, roi_kp, roi_features) def ExtractORB(self, bbox=None, mask=None, label=None): # using opencv ORB extractor orb = self.extractors.get('orb', None) if orb is None: orb = cv2.ORB_create(edgeThreshold=5, patchSize=31, nlevels=8, fastThreshold=20, scaleFactor=1.2, WTA_K=4, scoreType=cv2.ORB_HARRIS_SCORE, firstLevel=0, nfeatures=1000) self.extractors['orb'] = orb img_grey = self.img_grey() shp = img_grey.shape if bbox is not None: y1, x1, y2, x2 = bbox ## adjust parameters h = y2 - y1 w = x2 - x1 # print("label %s, h:%d, w:%d" % (label, h, w)) if np.min([w, h]) < 50: orb.setEdgeThreshold(0) orb.setPatchSize(15) orb.setScaleFactor(1.4) # 1.4**8 ~ 8 orb.setWTA_K(2) else: # restore orb.setEdgeThreshold(5) orb.setPatchSize(31) orb.setScaleFactor(1.2) orb.setWTA_K(4) ## # crop image new_img_grey = np.zeros(shp) new_img_grey[y1:y2, x1:x2] = img_grey[y1:y2, x1:x2] if self.SHOW_ROI: display(new_img_grey) img_grey = img_grey[y1:y2, x1:x2] img_grey = cv2.resize(img_grey, (shp[0], shp[1]), interpolation=cv2.INTER_CUBIC) # img_grey = cv2.cvtColor(new_img_grey.astype('uint8'), cv2.COLOR_GRAY2BGR) # compute key points vector kp = orb.detect(img_grey, None) # compute the descriptors with ORB kp, des = orb.compute(img_grey, kp) if bbox is not None: y1, x1, y2, x2 = bbox h = y2 - y1 w = x2 - x1 shp0 = img_grey.shape def _mapping(keypoint): x = keypoint.pt[0] * w / shp0[1] + x1 y = keypoint.pt[1] * h / shp0[0] + y1 keypoint.pt = (x, y) return keypoint kp = list(map(lambda p: _mapping(p), kp)) # kp = list(map(lambda idx: cv2.KeyPoint(kp[idx].x + x1, kp[idx].y + y1), indice)) if bbox is not None and len(kp) > self.sample_size and self.sample_size is not -1: indice = np.random.choice(len(kp), self.sample_size) kp = list(map(lambda idx: kp[idx], indice)) des = list(map(lambda idx: des[idx], indice)) # filter out kp, des with mask # @todo : TODO # assert(len(kp) > 0) if len(kp) == 0: return [], [] return kp, des def ExtractROI(self): # using our semantic features extractor sfe = self.extractors.get('sfe', None) if sfe is None: sfe = SemanticFeatureExtractor() self.extractors['sfe'] = sfe sfe.attach_to(self) # defaults to opencv channel last format img = self.img detections = sfe.detect(img) self._detections = detections # compute the descriptors with our SemanticFeaturesExtractor.encodeDeepFeatures kp, des = sfe.compute(img, detections) return kp, des def mark_as_first(self): self.is_First = True return self def find_px(self, x, y): H, W = self.img.shape[0:2] idx = int(y * W + x) return self.pixels.get(idx, None) def copy_pose_from(self, other_frame): self.R0 = other_frame.R0 self.t0 = other_frame.t0 camera = self.camera if camera is None: camera = Camera.clone(other_frame.camera) self.camera = camera return self def update_pose(self, pose): # see g2opy/python/types/slam3d/se3quat.h for details for the interface # print("R before update shape: %s, data: \n%s\n" % (self.R0.shape, self.R0)) self.R0 = pose.orientation().matrix() # print("R after update shape: %s, data: \n%s\n" % (self.R0.shape, self.R0)) # print("t before update shape: %s, data: \n%s\n" % (self.t0.shape, self.t0)) self.t0 = pose.position().reshape((3, 1)) # print("t after update shape: %s, data: \n%s\n" % (self.t0.shape, self.t0)) # update R1, t1 if self.pre is not None: self.R1 = self.R0.dot(np.linalg.inv(self.pre.R0)) self.t1 = self.t0 - self.R1.dot(self.pre.t0) # update camera self.camera.R0 = self.R0 self.camera.t0 = self.t0 self.camera.R1 = self.R1 self.camera.t1 = self.t1 else: pass return self def get_pose_mat(self): if False: # self.camera is not None: # print("camera.t0 shape: %s, data: \n%s\n" % (self.camera.t0.shape, self.camera.t0)) # print("frame.t0 shape: %s, data: \n%s\n" % (self.t0.shape, self.t0)) pose = g2o.SE3Quat(self.camera.R0, self.camera.t0.reshape(3, )) else: pose = g2o.SE3Quat(self.R0, self.t0.reshape(3, )) return pose.matrix() # retrieved current filled structure def get_points(self): pixels, cam_pts, points = [], [], [] # @todo : TODO return current frame 3d structure for _, pixel in self.pixels.items(): for cam_pt in pixel.sources: world = cam_pt.world if world is None: continue points.append(world) return points def get_measurements(self): pixels, cam_pts, points = [], [], [] # @todo : TODO return current frame 3d structure for _, pixel in self.pixels.items(): for cam_pt in pixel.sources: world = cam_pt.world if world is None: continue points.append(world) pixels.append(pixel) return points, pixels def get_landmarks(self): landmarks = set() for _, pixel in self.pixels.items(): if pixel.roi is not None: landmarks.add(pixel.roi.findParent()) return list(landmarks) # def match(self, reference_frame, kps, kps_feat): # frame_key = reference_frame.seq # img_shp = self.img.shape[0:2] # # H, W = self.img.shape[0:2] # matches = [] # unmatched_detections = [] # THR = 0.7 # 0.95 #0.8 #0.7 # # def _hamming_distance(x, y): # from scipy.spatial import distance # return distance.hamming(x, y) # # def _get_neighbors(R, row, col, feat_map, img_shp): # H, W = img_shp[0:2] # x1, y1 = (col - R, row - R) # x2, y2 = (col + R, row + R) # # if x1 < 0: # x1 = 0 # if y1 < 0: # y1 = 0 # # if x2 >= W: # x2 = W - 1 # if y2 >= H: # y2 = H - 1 # # indice = feat_map[y1:y2, x1:x2] != -1 # return feat_map[y1:y2, x1:x2][indice] # # # # inv_kp = {} # for i, kp in enumerate(kps): # x, y = kp.pt # idx = int(y * W + x) # inv_kp[idx] = i # # # init feat_map # feat_map = np.full(img_shp, -1) # for i, kp in enumerate(kps): # x, y = kp.pt # if int(y) >= img_shp[0] or int(y) < 0 or \ # int(x) >= img_shp[1] or int(x) < 0: # continue # feat_map[int(y), int(x)] = i # # cur_kp, cur_kp_features = self.kps, self.kps_feats # # lost_pixels = 0 # skipped_in_parent_searching = 0 # skipped_in_neighbors_searching = 0 # dist_larger_than_thr = 0 # # print("reference frame #%d key points: %d" % (reference_frame.seq, len(kps))) # print("cur frame #%d key points: %d" % (self.seq, len(cur_kp))) # if frame_key is not self.seq: # for i, kp in enumerate(cur_kp): # x, y = kp.pt # idx = int(y * W + x) # px = self.pixels.get(idx, None) # if px is None: # # print("The pixel (%f,%f) is none!" % (x, y)) # lost_pixels += 1 # continue # # parent = px.parent # # if parent is None: # # print("The parent of the pixel is none!") # unmatched_detections.append(px) # continue # # feat_l = cur_kp_features[i] # # # print("=====================") # # print("searching starts from %s(Frame#%d) 's parent %s(Frame#%d)" % (px, px.frame.seq, parent, parent.frame.seq)) # flag = True # while parent is not None and flag: # if parent.frame.seq == frame_key: # # print("find a matched pixel %s(Frame#%d) for Frame#%d" % (parent, parent.frame.seq, frame_key)) # flag = False # else: # parent = parent.parent # if parent is not None: # # print("trace back to pixel %s(Frame#%d)" % (parent, parent.frame.seq)) # pass # # if flag: # skipped_in_parent_searching += 1 # continue # # # print("\n") # # print("find a match for pixel %s" % px) # # find a match # # jdx = int(parent.r * W + parent.c) # # j = inv_kp[jdx] # # # feat_r = kps_feat[j] # # feat_r = parent.feature # # dist = _hamming_distance(feat_l, feat_r) # # # perform local search # indice = _get_neighbors(8, int(parent.r), int(parent.c), feat_map, img_shp) # if len(indice) == 0: # skipped_in_neighbors_searching += 1 # continue # # # KNN search # feat_l = cur_kp_features[i] # # dist = None # min_dist, min_ind = np.inf, None # # for ind in indice: # feat_r = kps_feat[ind] # dist = _hamming_distance(feat_l, feat_r) # if min_dist > dist: # min_dist = dist # min_ind = ind # # if min_dist >= THR: # dist_larger_than_thr += 1 # continue # # # matches.append(cv2.DMatch(i, j, dist)) # matches.append(cv2.DMatch(i, min_ind, min_dist)) # # else: # # see Tracker._match # raise Exception("Not Implemented Yet") # # matches = sorted(matches, key=lambda mtch: mtch.distance) # import pandas as pd # # print("lost pixels : %d" % lost_pixels) # print("unmatched detections : %d" % len(unmatched_detections)) # print("skipped when searching parent : %d" % skipped_in_parent_searching) # print("skipped when searching neighbors of parents (8PX neighbors) : %d" % skipped_in_neighbors_searching) # print("skipped when min dist is larger than %f : %d" % (THR, dist_larger_than_thr)) # if len(matches) < 10: # raise Exception("Unwanted matching results!") # # distances = [mtch.distance for mtch in matches] # # df = pd.DataFrame({ # "Dist": distances # }) # # print(df) # # l = len(self.kps) # mask = np.ones((l, 1)) # # print("Found %d matches using Union Find algorithm" % len(matches)) # # return matches, mask.tolist() def match(self, reference_frame, kps, kps_feat): frame_key = reference_frame.seq img_shp = self.img.shape[0:2] H, W = self.img.shape[0:2] matches = [] unmatched_detections = [] THR = 0.75 THR2 = 0.75 def _hamming_distance(x, y): from scipy.spatial import distance return distance.hamming(x, y) def _get_neighbors(R, row, col, feat_map, img_shp): H, W = img_shp[0:2] x1, y1 = (col - R, row - R) x2, y2 = (col + R, row + R) if x1 < 0: x1 = 0 if y1 < 0: y1 = 0 # freshly added (!important) if x2 < 0: x2 = 0 if y2 < 0: x2 = 0 if x2 >= W: x2 = W - 1 if y2 >= H: y2 = H - 1 indice = feat_map[y1:y2, x1:x2] != -1 return feat_map[y1:y2, x1:x2][indice] # inv_kp = {} for i, kp in enumerate(kps): x, y = kp.pt idx = int(y * W + x) inv_kp[idx] = i # init feat_map feat_map = np.full(img_shp, -1) for i, kp in enumerate(kps): x, y = kp.pt if int(y) >= img_shp[0] or int(y) < 0 or \ int(x) >= img_shp[1] or int(x) < 0: continue feat_map[int(y), int(x)] = i cur_kp, cur_kp_features = self.kps, self.kps_feats lost_pixels = 0 skipped_in_parent_searching = 0 skipped_in_neighbors_searching = 0 dist_larger_than_thr = 0 print("reference frame #%d key points: %d" % (reference_frame.seq, len(kps))) print("cur frame #%d key points: %d" % (self.seq, len(cur_kp))) dx, dy = 0, 0 cnt = 0 if frame_key is not self.seq: for i, kp in enumerate(cur_kp): x, y = kp.pt idx = int(y * W + x) px = self.pixels.get(idx, None) if px is None: # print("The pixel (%f,%f) is none!" % (x, y)) lost_pixels += 1 continue parent = px.parent if parent is None: # deactivate the following searching method # print("The parent of the pixel is none!") unmatched_detections.append((i, kp, px)) continue feat_l = cur_kp_features[i] # print("=====================") # print("searching starts from %s(Frame#%d) 's parent %s(Frame#%d)" % (px, px.frame.seq, parent, parent.frame.seq)) flag = True while parent is not None and flag: if parent.frame.seq == frame_key: # print("find a matched pixel %s(Frame#%d) for Frame#%d" % (parent, parent.frame.seq, frame_key)) flag = False else: parent = parent.parent if parent is not None: # print("trace back to pixel %s(Frame#%d)" % (parent, parent.frame.seq)) pass if flag: skipped_in_parent_searching += 1 unmatched_detections.append((i, kp, px)) continue # print("\n") # print("find a match for pixel %s" % px) # find a match # jdx = int(parent.r * W + parent.c) # j = inv_kp[jdx] # feat_r = kps_feat[j] # feat_r = parent.feature # dist = _hamming_distance(feat_l, feat_r) dx += parent.c - px.c dy += parent.r - px.r cnt += 1 # perform local search indice = _get_neighbors(10, int(parent.r), int(parent.c), feat_map, img_shp) if len(indice) == 0: skipped_in_neighbors_searching += 1 continue # KNN search feat_l = cur_kp_features[i] dist = None min_dist, min_ind = np.inf, None for ind in indice: feat_r = kps_feat[ind] dist = _hamming_distance(feat_l, feat_r) if min_dist > dist: min_dist = dist min_ind = ind if min_dist >= THR: dist_larger_than_thr += 1 unmatched_detections.append((i, kp, px)) continue # matches.append(cv2.DMatch(i, j, dist)) matches.append(cv2.DMatch(i, min_ind, min_dist)) else: # see Tracker._match raise Exception("Not Implemented Yet") if cnt != 0: dx /= cnt dy /= cnt print("Average dx:", dx) print("Average dy:", dy) # optical_flow = OpticalFlowKPntPredictor() # optical_flow.Init() # optical_flow.set_FromImg(self.img_grey()) # # compute accumulative flows # pre = self.pre # flow = pre.predictors['OpticalFlowKPnt'].get_flow() # assert flow.shape[:2] == img_shp # while pre.seq is not frame_key: # pre = pre.pre # flow1 = pre.predictors['OpticalFlowKPnt'].get_flow() # assert flow.shape == flow1.shape # flow += flow1 # # predict coord # kps_coor_r = list(map(lambda kp: kp.pt, kps)) # # init feat_map # feat_map = np.full(img_shp, -1) # for i, kp in enumerate(kps_coor_r): # x, y = kp # shift_x = flow[int(y), int(x), 0] # shift_y = flow[int(y), int(x), 1] # x += shift_x # y += shift_y # if int(y) >= img_shp[0] or int(y) < 0 or \ # int(x) >= img_shp[1] or int(x) < 0: # continue # feat_map[int(y),int(x)] = i for i, kp, px in unmatched_detections: # if cnt > 10: # target = [px.x+dx, px.y+dy] # slightly bad # else: # target = optical_flow.predict([px.data], reference_frame.img_grey())[0] # not stable s = px.roi.map_keypoint_to_box(px.data) try: ref_roi = px.roi.findParent().findRoI(frame_key) # very good except Exception as e: # print(e) continue if ref_roi.check_box_sim(px.roi): target = ref_roi.map_keypoint_from_box(s) # update dx , dy dx = (dx * cnt + target[0] - px.c) / (cnt + 1) dy = (dy * cnt + target[1] - px.r) / (cnt + 1) cnt += 1 else: # target = [px.x+dx, px.y+dy] continue # target = [px.x, px.y] # very bad indice = _get_neighbors(12, int(target[1]), int(target[0]), feat_map, img_shp) # indice = _get_neighbors(7, int(px.y), int(px.x), feat_map, img_shp) # bad and not stable if len(indice) == 0: continue # KNN search feat_l = cur_kp_features[i] dist = None min_dist, min_in = np.inf, None for ind in indice: feat_r = kps_feat[ind] dist = _hamming_distance(feat_l, feat_r) if min_dist > dist: min_dist = dist min_ind = ind if cnt > 10: if min_dist >= THR: continue else: if min_dist >= THR2: continue kp_in_ref = kps[min_ind] x, y = kp_in_ref.pt jdx = int(y * W + x) px_in_ref = reference_frame.pixels.get(jdx, None) if px_in_ref is not None and px.parent is None: px.parent = px_in_ref matches.append(cv2.DMatch(i, min_ind, min_dist)) matches = sorted(matches, key=lambda mtch: mtch.distance) import pandas as pd print("lost pixels : %d" % lost_pixels) print("unmatched detections : %d" % len(unmatched_detections)) print("skipped when searching parent : %d" % skipped_in_parent_searching) print("skipped when searching neighbors of parents (8PX neighbors) : %d" % skipped_in_neighbors_searching) print("skipped when min dist is larger than %f : %d" % (THR, dist_larger_than_thr)) if len(matches) < 10: raise Exception("Unwanted matching results!") distances = [mtch.distance for mtch in matches] df = pd.DataFrame({ "Dist": distances }) print(df) l = len(self.kps) mask = np.ones((l, 1)) print("Found %d matches using Union Find algorithm" % len(matches)) return matches, mask.tolist() def __repr__(self): return "<Frame %d>" % self.identity.seq def __str__(self): return "<Frame %d>" % self.identity.seq # use to compute perspective camera MVP projections with intrinsic parameters and distortion recover (using OpenCV4) # the reading loop is implemented using CV2 camera. class Camera: from enum import Enum class Status(Enum): MONOCULAR = 1 class ProjectionType(Enum): PERSPECTIVE = 1 UNSOPPROTED = -1 def __init__(self, device, R, t, anchor_point, H=None, W=None): # default mode is monocular self.mode = Camera.Status.MONOCULAR self.type = Camera.ProjectionType.PERSPECTIVE # self.device = device # extrinsic parameters of a camera, see TUM vision group dataset format self.K = device.K # world self.R0 = None self.t0 = None # eye and pose self.R1 = R self.t1 = t self.Rcw = np.eye(3) self.tcw = np.zeros((3, 1)) self.anchor_point = anchor_point self.H = H self.W = W def Init(self): self.K = self.device.K # update other computed properties return self @staticmethod def clone(camera): camera_cpy = Camera(camera.device, camera.R1, camera.t1, camera.anchor_point, H=camera.H, W=camera.W) camera_cpy.R0 = camera.R0 camera_cpy.t0 = camera.t0 return camera_cpy # @todo : TODO def t_SE3ToR3(self, t=None): if t is None: t = self.t1 return np.array([ [0., -t[2], t[1]], [t[2], 0., -t[0]], [-t[1], t[0], 0.] ]) # @todo : TODO def viewWorldPoint(self, point3d): v = point3d.data.reshape(3, 1) cam_pt = np.linalg.inv(self.R0).dot(v - self.t0) ret = Point3D(cam_pt[0][0], cam_pt[1][0], cam_pt[2][0]) # used for debug ret.seq = point3d.seq return ret # @todo : TODO def view(self, point3d): # should be homogenous point v = point3d.data.reshape(3, 1) if v[2][0] < 0: print("The point %s is not visible by the camerea" % point3d) return None # print("v(ori):\n",v) v /= v[2][0] # print("K:\n",self.K) # print("v:\n",v) px = self.K.dot(v) # print("px:\n", px) px = px.reshape((3,)) px = Pixel2D(px[1], px[0]) if px.x < 0 or px.x >= self.W or px.y < 0 or px.y >= self.H: print("The projection %s of the point %s is out of bound (%f, %f)" % ( px, point3d, self.W, self.H )) return None return px def reproj(self, pixel2d): px = pixel2d K = self.K # compute normalized point in camera space if isinstance(px, cv2.KeyPoint): px = Pixel2D(px.pt[1], px.pt[0]) if isinstance(px, tuple): px = Pixel2D(px[1], px[0]) return Point3D( (px.x - K[0, 2]) / K[0, 0], (px.y - K[1, 2]) / K[1, 1], 1 )
[ "logging.getLogger", "scipy.spatial.distance.hamming", "numpy.array", "numpy.linalg.norm", "pysvso.py_pose_graph.point3d.Point3D", "threading.Lock", "cv2.ORB_create", "numpy.min", "pandas.DataFrame", "numpy.eye", "numpy.ones", "pysvso.lib.visualizer.display", "cv2.cvtColor", "pysvso.predic...
[((590, 616), 'logging.getLogger', 'logging.getLogger', (['"""frame"""'], {}), "('frame')\n", (607, 616), False, 'import logging\n'), ((1731, 1746), 'pysvso.lib.misc.AtomicCounter', 'AtomicCounter', ([], {}), '()\n', (1744, 1746), False, 'from pysvso.lib.misc import AtomicCounter\n'), ((6396, 6411), 'pysvso.lib.misc.AtomicCounter', 'AtomicCounter', ([], {}), '()\n', (6409, 6411), False, 'from pysvso.lib.misc import AtomicCounter\n'), ((6425, 6456), 'pysvso.lib.log.LoggerAdaptor', 'LoggerAdaptor', (['"""Frame"""', '_logger'], {}), "('Frame', _logger)\n", (6438, 6456), False, 'from pysvso.lib.log import LoggerAdaptor\n'), ((3302, 3328), 'numpy.array', 'np.array', (['[self.c, self.r]'], {}), '([self.c, self.r])\n', (3310, 3328), True, 'import numpy as np\n'), ((3401, 3427), 'numpy.array', 'np.array', (['[self.c, self.r]'], {}), '([self.c, self.r])\n', (3409, 3427), True, 'import numpy as np\n'), ((4345, 4371), 'numpy.array', 'np.array', (['[self.c, self.r]'], {}), '([self.c, self.r])\n', (4353, 4371), True, 'import numpy as np\n'), ((7675, 7684), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (7681, 7684), True, 'import numpy as np\n'), ((7717, 7733), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (7725, 7733), True, 'import numpy as np\n'), ((7838, 7847), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (7844, 7847), True, 'import numpy as np\n'), ((7866, 7882), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (7874, 7882), True, 'import numpy as np\n'), ((7971, 7980), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (7977, 7980), True, 'import numpy as np\n'), ((8011, 8027), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (8019, 8027), True, 'import numpy as np\n'), ((25648, 25668), 'numpy.full', 'np.full', (['img_shp', '(-1)'], {}), '(img_shp, -1)\n', (25655, 25668), True, 'import numpy as np\n'), ((33460, 33493), 'pandas.DataFrame', 'pd.DataFrame', (["{'Dist': distances}"], {}), "({'Dist': distances})\n", (33472, 33493), True, 'import pandas as pd\n'), ((33577, 33592), 'numpy.ones', 'np.ones', (['(l, 1)'], {}), '((l, 1))\n', (33584, 33592), True, 'import numpy as np\n'), ((34690, 34699), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (34696, 34699), True, 'import numpy as np\n'), ((34719, 34735), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (34727, 34735), True, 'import numpy as np\n'), ((35292, 35362), 'numpy.array', 'np.array', (['[[0.0, -t[2], t[1]], [t[2], 0.0, -t[0]], [-t[1], t[0], 0.0]]'], {}), '([[0.0, -t[2], t[1]], [t[2], 0.0, -t[0]], [-t[1], t[0], 0.0]])\n', (35300, 35362), True, 'import numpy as np\n'), ((35577, 35626), 'pysvso.py_pose_graph.point3d.Point3D', 'Point3D', (['cam_pt[0][0]', 'cam_pt[1][0]', 'cam_pt[2][0]'], {}), '(cam_pt[0][0], cam_pt[1][0], cam_pt[2][0])\n', (35584, 35626), False, 'from pysvso.py_pose_graph.point3d import Point3D\n'), ((36780, 36846), 'pysvso.py_pose_graph.point3d.Point3D', 'Point3D', (['((px.x - K[0, 2]) / K[0, 0])', '((px.y - K[1, 2]) / K[1, 1])', '(1)'], {}), '((px.x - K[0, 2]) / K[0, 0], (px.y - K[1, 2]) / K[1, 1], 1)\n', (36787, 36846), False, 'from pysvso.py_pose_graph.point3d import Point3D\n'), ((4826, 4854), 'numpy.linalg.norm', 'np.linalg.norm', (['(left - right)'], {}), '(left - right)\n', (4840, 4854), True, 'import numpy as np\n'), ((8959, 8985), 'pysvso.predictors.OpticalFlowBBoxPredictor', 'OpticalFlowBBoxPredictor', ([], {}), '()\n', (8983, 8985), False, 'from pysvso.predictors import OpticalFlowBBoxPredictor, OpticalFlowKPntPredictor\n'), ((9018, 9044), 'pysvso.predictors.OpticalFlowKPntPredictor', 'OpticalFlowKPntPredictor', ([], {}), '()\n', (9042, 9044), False, 'from pysvso.predictors import OpticalFlowBBoxPredictor, OpticalFlowKPntPredictor\n'), ((9965, 10007), 'cv2.cvtColor', 'cv2.cvtColor', (['self.img', 'cv2.COLOR_BGR2GRAY'], {}), '(self.img, cv2.COLOR_BGR2GRAY)\n', (9977, 10007), False, 'import cv2\n'), ((12374, 12544), 'cv2.ORB_create', 'cv2.ORB_create', ([], {'edgeThreshold': '(5)', 'patchSize': '(31)', 'nlevels': '(8)', 'fastThreshold': '(20)', 'scaleFactor': '(1.2)', 'WTA_K': '(4)', 'scoreType': 'cv2.ORB_HARRIS_SCORE', 'firstLevel': '(0)', 'nfeatures': '(1000)'}), '(edgeThreshold=5, patchSize=31, nlevels=8, fastThreshold=20,\n scaleFactor=1.2, WTA_K=4, scoreType=cv2.ORB_HARRIS_SCORE, firstLevel=0,\n nfeatures=1000)\n', (12388, 12544), False, 'import cv2\n'), ((13575, 13588), 'numpy.zeros', 'np.zeros', (['shp'], {}), '(shp)\n', (13583, 13588), True, 'import numpy as np\n'), ((13790, 13859), 'cv2.resize', 'cv2.resize', (['img_grey', '(shp[0], shp[1])'], {'interpolation': 'cv2.INTER_CUBIC'}), '(img_grey, (shp[0], shp[1]), interpolation=cv2.INTER_CUBIC)\n', (13800, 13859), False, 'import cv2\n'), ((15253, 15279), 'pysvso.models.sfe.SemanticFeatureExtractor', 'SemanticFeatureExtractor', ([], {}), '()\n', (15277, 15279), False, 'from pysvso.models.sfe import SemanticFeatureExtractor\n'), ((24823, 24845), 'scipy.spatial.distance.hamming', 'distance.hamming', (['x', 'y'], {}), '(x, y)\n', (24839, 24845), False, 'from scipy.spatial import distance\n'), ((981, 997), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (995, 997), False, 'import threading\n'), ((13129, 13143), 'numpy.min', 'np.min', (['[w, h]'], {}), '([w, h])\n', (13135, 13143), True, 'import numpy as np\n'), ((13699, 13720), 'pysvso.lib.visualizer.display', 'display', (['new_img_grey'], {}), '(new_img_grey)\n', (13706, 13720), False, 'from pysvso.lib.visualizer import display\n'), ((16794, 16820), 'numpy.linalg.inv', 'np.linalg.inv', (['self.pre.R0'], {}), '(self.pre.R0)\n', (16807, 16820), True, 'import numpy as np\n'), ((32763, 32795), 'cv2.DMatch', 'cv2.DMatch', (['i', 'min_ind', 'min_dist'], {}), '(i, min_ind, min_dist)\n', (32773, 32795), False, 'import cv2\n'), ((35522, 35544), 'numpy.linalg.inv', 'np.linalg.inv', (['self.R0'], {}), '(self.R0)\n', (35535, 35544), True, 'import numpy as np\n'), ((5273, 5302), 'numpy.linalg.norm', 'np.linalg.norm', (['(w - world_pt3)'], {}), '(w - world_pt3)\n', (5287, 5302), True, 'import numpy as np\n'), ((5331, 5363), 'numpy.linalg.norm', 'np.linalg.norm', (['(best - world_pt3)'], {}), '(best - world_pt3)\n', (5345, 5363), True, 'import numpy as np\n'), ((29296, 29328), 'cv2.DMatch', 'cv2.DMatch', (['i', 'min_ind', 'min_dist'], {}), '(i, min_ind, min_dist)\n', (29306, 29328), False, 'import cv2\n')]
import numpy as np from scipy import stats import time import graph_tool.all as gt from dcppm_state import EM_DCPPM def get_degree_prop_zipf(nr, B, gamma, x_max): """ Input ----- nr: number of nodes in each community B: number of communities gamma: shape parameter of the truncated Zipf's distribution xmamx: a cut-off value of the Zipf's distributon Returns ------- k_prop: """ if gamma > 0: x = np.arange(1, np.ceil(x_max)+1) weights = x ** (-gamma) weights /= weights.sum() bounded_zipf = stats.rv_discrete(name='bounded_zipf', values=(x, weights)) degree_prop = bounded_zipf.rvs(size=nr) degree_prop = degree_prop/degree_prop.sum() degree_prop = np.concatenate([degree_prop for r in range(B)]) else: degree_prop = np.ones(nr * B)/nr return degree_prop def gen_dcppm(nr, B, k, ep, gamma, xmax = None): """ Input ----- nr: number of nodes in each community B: number of communities k : average degree of the network ep: the strength of the assortative structure, a real value in [0,1] gamma: shape parameter of the truncated Zipf's distribution xmamx: a cut-off value of the Zipf's distributon Returns ------- g: a graph-tool network object ers: the connection matrix consistting of the number of connections between group r and s b: the planted network partition degree_prop: the degree propensity parameter used to generate the network """ if gamma != 0 and xmax is None: raise "Need to specify the cut-off value of the truncated Zipf's distribution" N = nr*B p_in = (1+(B-1)*ep)*k/N p_out= (1 - ep)*k/N ers = np.zeros((B,B)) for r in range(B): for s in range(B): if r == s: ers[r,s] = nr*nr*p_in else: ers[r,s] = nr*nr*p_out b = [] for r in range(B): b += [r for u in range(nr)] degree_prop = get_degree_prop_zipf(nr, B, gamma, xmax) g = gt.generate_sbm(b, ers, out_degs = degree_prop) gt.remove_parallel_edges(g) gt.remove_self_loops(g) g.vp.b = g.new_vp("int", b) return g, ers, b, degree_prop def compare_bp_running_time(nr, B, k, ep, gamma,xmax): """ Compare the running time of the belief propagation with different updating scheme """ g, ers, b, degree_prop = gen_dcppm(nr, B, k, ep, gamma, xmax) state = EM_DCPPM(g, B = B, t = degree_prop, lrs = ers) tic_original = time.time() state.bp_iter(max_niter = 1, is_randomised=False) toc_original = time.time() tic_fast = time.time() state.bp_iter_fast(max_niter = 1, is_randomised=False) toc_fast = time.time() print(f"One iteration of BP with the original update scheme takes: {toc_original - tic_original} secs!") print(f"One iteration of BP with the modified update scheme takes: {toc_fast - tic_fast} secs!") def check_bp_accuracy(nr, B, k, ep, gamma, xmax, is_modified = True, max_niter = 1e3): g, ers, b, degree_prop = gen_dcppm(nr, B, k, ep, gamma, xmax) state = EM_DCPPM(g, B, t = degree_prop, lrs = ers) b_init = [] for u in g.vertices(): b_init.append(np.argmax(state.vm[u])) overlap_init = gt.partition_overlap(b,b_init) print(f"Is modified: {is_modified}; Partition overlap before BP: {overlap_init}") if is_modified: state.bp_iter_fast(max_niter = max_niter) else: state.bp_iter(max_niter = max_niter) b_est = [] for u in g.vertices(): b_est.append(np.argmax(state.vm[u])) overlap_inferred = gt.partition_overlap(b,b_est) print(f"Is modified: {is_modified}; Partition overlap after BP: {overlap_inferred}")
[ "graph_tool.all.remove_parallel_edges", "numpy.ceil", "graph_tool.all.generate_sbm", "numpy.ones", "graph_tool.all.remove_self_loops", "numpy.argmax", "numpy.zeros", "scipy.stats.rv_discrete", "time.time", "dcppm_state.EM_DCPPM", "graph_tool.all.partition_overlap" ]
[((1833, 1849), 'numpy.zeros', 'np.zeros', (['(B, B)'], {}), '((B, B))\n', (1841, 1849), True, 'import numpy as np\n'), ((2168, 2213), 'graph_tool.all.generate_sbm', 'gt.generate_sbm', (['b', 'ers'], {'out_degs': 'degree_prop'}), '(b, ers, out_degs=degree_prop)\n', (2183, 2213), True, 'import graph_tool.all as gt\n'), ((2220, 2247), 'graph_tool.all.remove_parallel_edges', 'gt.remove_parallel_edges', (['g'], {}), '(g)\n', (2244, 2247), True, 'import graph_tool.all as gt\n'), ((2252, 2275), 'graph_tool.all.remove_self_loops', 'gt.remove_self_loops', (['g'], {}), '(g)\n', (2272, 2275), True, 'import graph_tool.all as gt\n'), ((2587, 2627), 'dcppm_state.EM_DCPPM', 'EM_DCPPM', (['g'], {'B': 'B', 't': 'degree_prop', 'lrs': 'ers'}), '(g, B=B, t=degree_prop, lrs=ers)\n', (2595, 2627), False, 'from dcppm_state import EM_DCPPM\n'), ((2654, 2665), 'time.time', 'time.time', ([], {}), '()\n', (2663, 2665), False, 'import time\n'), ((2739, 2750), 'time.time', 'time.time', ([], {}), '()\n', (2748, 2750), False, 'import time\n'), ((2771, 2782), 'time.time', 'time.time', ([], {}), '()\n', (2780, 2782), False, 'import time\n'), ((2857, 2868), 'time.time', 'time.time', ([], {}), '()\n', (2866, 2868), False, 'import time\n'), ((3269, 3307), 'dcppm_state.EM_DCPPM', 'EM_DCPPM', (['g', 'B'], {'t': 'degree_prop', 'lrs': 'ers'}), '(g, B, t=degree_prop, lrs=ers)\n', (3277, 3307), False, 'from dcppm_state import EM_DCPPM\n'), ((3425, 3456), 'graph_tool.all.partition_overlap', 'gt.partition_overlap', (['b', 'b_init'], {}), '(b, b_init)\n', (3445, 3456), True, 'import graph_tool.all as gt\n'), ((3792, 3822), 'graph_tool.all.partition_overlap', 'gt.partition_overlap', (['b', 'b_est'], {}), '(b, b_est)\n', (3812, 3822), True, 'import graph_tool.all as gt\n'), ((600, 659), 'scipy.stats.rv_discrete', 'stats.rv_discrete', ([], {'name': '"""bounded_zipf"""', 'values': '(x, weights)'}), "(name='bounded_zipf', values=(x, weights))\n", (617, 659), False, 'from scipy import stats\n'), ((863, 878), 'numpy.ones', 'np.ones', (['(nr * B)'], {}), '(nr * B)\n', (870, 878), True, 'import numpy as np\n'), ((3382, 3404), 'numpy.argmax', 'np.argmax', (['state.vm[u]'], {}), '(state.vm[u])\n', (3391, 3404), True, 'import numpy as np\n'), ((3745, 3767), 'numpy.argmax', 'np.argmax', (['state.vm[u]'], {}), '(state.vm[u])\n', (3754, 3767), True, 'import numpy as np\n'), ((494, 508), 'numpy.ceil', 'np.ceil', (['x_max'], {}), '(x_max)\n', (501, 508), True, 'import numpy as np\n')]
import tensorflow as tf from anomaly_detection.dataset_mtvecad import create_mtvecad_data from anomaly_detection.feature_extraction_models import create_multiscale_model, create_model import os import pickle import numpy as np import gc params = { 'data_path': '/media/guillaume/Data/data/mvtec_anomaly_detection', 'output_path': '/media/guillaume/Data/data/multiscale_features/resnet50', 'backbone': 'resnet50', 'multiscale': True, 'image_size': 224, 'batch_size': 32 } if params['multiscale']: model = create_multiscale_model(params['backbone'], params['image_size']) else: model = create_model(params['backbone'], params['image_size']) for class_folder in os.listdir(params['data_path']): if os.path.isdir(os.path.join(params['data_path'], class_folder)): print(f"Exctracting features for {class_folder}") dataset_train = create_mtvecad_data(data_path=os.path.join(params['data_path'], class_folder, 'train'), batch_size=params['batch_size']) dataset_test = create_mtvecad_data(data_path=os.path.join(params['data_path'], class_folder, 'test'), batch_size=params['batch_size']) train_features = [] train_names = [] for ex in dataset_train: features = model(ex[0]) train_features.append(features.numpy()) train_names.append(ex[1].numpy()) train_features = np.concatenate(train_features, axis=0) train_names = np.concatenate(train_names, axis=0) train_output = {'names': train_names, 'features': train_features} if not os.path.isdir(os.path.join(params['output_path'], class_folder)): os.mkdir(os.path.join(params['output_path'], class_folder)) with open(os.path.join(params['output_path'], class_folder, 'output_train.p'), "wb") as f: pickle.dump(train_output, f, protocol=4) del train_features del train_names gc.collect() test_features = [] test_names = [] for ex in dataset_test: features = model(ex[0]) test_features.append(features.numpy()) test_names.append(ex[1].numpy()) test_features = np.concatenate(test_features, axis=0) test_names = np.concatenate(test_names, axis=0) test_output = {'names': test_names, 'features': test_features} with open(os.path.join(params['output_path'], class_folder, 'output_test.p'), "wb") as f: pickle.dump(test_output, f, protocol=4) del test_features del test_names del dataset_train del dataset_test gc.collect()
[ "os.listdir", "pickle.dump", "os.path.join", "anomaly_detection.feature_extraction_models.create_model", "numpy.concatenate", "gc.collect", "anomaly_detection.feature_extraction_models.create_multiscale_model" ]
[((695, 726), 'os.listdir', 'os.listdir', (["params['data_path']"], {}), "(params['data_path'])\n", (705, 726), False, 'import os\n'), ((535, 600), 'anomaly_detection.feature_extraction_models.create_multiscale_model', 'create_multiscale_model', (["params['backbone']", "params['image_size']"], {}), "(params['backbone'], params['image_size'])\n", (558, 600), False, 'from anomaly_detection.feature_extraction_models import create_multiscale_model, create_model\n'), ((619, 673), 'anomaly_detection.feature_extraction_models.create_model', 'create_model', (["params['backbone']", "params['image_size']"], {}), "(params['backbone'], params['image_size'])\n", (631, 673), False, 'from anomaly_detection.feature_extraction_models import create_multiscale_model, create_model\n'), ((750, 797), 'os.path.join', 'os.path.join', (["params['data_path']", 'class_folder'], {}), "(params['data_path'], class_folder)\n", (762, 797), False, 'import os\n'), ((1486, 1524), 'numpy.concatenate', 'np.concatenate', (['train_features'], {'axis': '(0)'}), '(train_features, axis=0)\n', (1500, 1524), True, 'import numpy as np\n'), ((1548, 1583), 'numpy.concatenate', 'np.concatenate', (['train_names'], {'axis': '(0)'}), '(train_names, axis=0)\n', (1562, 1583), True, 'import numpy as np\n'), ((2028, 2040), 'gc.collect', 'gc.collect', ([], {}), '()\n', (2038, 2040), False, 'import gc\n'), ((2284, 2321), 'numpy.concatenate', 'np.concatenate', (['test_features'], {'axis': '(0)'}), '(test_features, axis=0)\n', (2298, 2321), True, 'import numpy as np\n'), ((2344, 2378), 'numpy.concatenate', 'np.concatenate', (['test_names'], {'axis': '(0)'}), '(test_names, axis=0)\n', (2358, 2378), True, 'import numpy as np\n'), ((2714, 2726), 'gc.collect', 'gc.collect', ([], {}), '()\n', (2724, 2726), False, 'import gc\n'), ((1926, 1966), 'pickle.dump', 'pickle.dump', (['train_output', 'f'], {'protocol': '(4)'}), '(train_output, f, protocol=4)\n', (1937, 1966), False, 'import pickle\n'), ((2563, 2602), 'pickle.dump', 'pickle.dump', (['test_output', 'f'], {'protocol': '(4)'}), '(test_output, f, protocol=4)\n', (2574, 2602), False, 'import pickle\n'), ((914, 970), 'os.path.join', 'os.path.join', (["params['data_path']", 'class_folder', '"""train"""'], {}), "(params['data_path'], class_folder, 'train')\n", (926, 970), False, 'import os\n'), ((1103, 1158), 'os.path.join', 'os.path.join', (["params['data_path']", 'class_folder', '"""test"""'], {}), "(params['data_path'], class_folder, 'test')\n", (1115, 1158), False, 'import os\n'), ((1689, 1738), 'os.path.join', 'os.path.join', (["params['output_path']", 'class_folder'], {}), "(params['output_path'], class_folder)\n", (1701, 1738), False, 'import os\n'), ((1762, 1811), 'os.path.join', 'os.path.join', (["params['output_path']", 'class_folder'], {}), "(params['output_path'], class_folder)\n", (1774, 1811), False, 'import os\n'), ((1832, 1899), 'os.path.join', 'os.path.join', (["params['output_path']", 'class_folder', '"""output_train.p"""'], {}), "(params['output_path'], class_folder, 'output_train.p')\n", (1844, 1899), False, 'import os\n'), ((2470, 2536), 'os.path.join', 'os.path.join', (["params['output_path']", 'class_folder', '"""output_test.p"""'], {}), "(params['output_path'], class_folder, 'output_test.p')\n", (2482, 2536), False, 'import os\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 13 14:51:29 2019 @author: nk7g14 This for some reason runs fine in the linux terminal but doesn't in the ipython one? https://heasarc.nasa.gov/ftools/caldb/help/uvotsource.html """ import logging import subprocess import glob from astropy.io import fits import pandas as pd import numpy as np import matplotlib.pyplot as plt import re import os import auxil as aux import swift logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s -- %(message)s') home_path = os.getcwd() img_path = 'sources/NGC1313/swift/uvot/img' def uvotsource(image_file): ''' Performs the 'uvotsource' command on a given .img file ''' output_file = image_file[:-4] + '.fits' subprocess.call(['uvotsource image={} srcreg=src.reg bkgreg=bkg.reg sigma=1.0 outfile=uvotsource/{}'.format(image_file, output_file)], shell=True) def uvotproduct(image_file): ''' #TODO translate the following into python my @in = <file>; $t = $in3[0]; $MET = (($t - 53769.415972)*24*3600) + 160653541.0; system "uvotproduct timezero=$MET infile=$dir outfile=$outfile plotfile=$outfile2 srcreg=src.reg bkgreg=bkg.reg batpos=NONE xrtpos=NONE uvotpos=NONE groundpos=NONE reportfile=$rep clobber=yes"; ''' pass def GetFluxes(fits_file): df = pd.DataFrame() data = fits.open(fits_file) df['MET'] = np.array(data[1].data['MET'], dtype=float) df['TSTART'] = np.array(data[1].data['TSTART'], dtype=float) df['TSTOP'] = np.array(data[1].data['TSTOP'], dtype=float) df['RAW_TOT_CNTS'] = np.array(data[1].data['RAW_TOT_CNTS'], dtype=float) df['RAW_TOT_CNTS_ERR'] = np.array(data[1].data['RAW_TOT_CNTS_ERR'], dtype=float) df['RAW_TOT_RATE'] = np.array(data[1].data['RAW_TOT_RATE'], dtype=float) df['RAW_TOT_RATE_ERR'] = np.array(data[1].data['RAW_TOT_RATE_ERR'], dtype=float) df['MAG'] = np.array(data[1].data['MAG'], dtype=float) df['MAG_ERR'] = np.array(data[1].data['MAG_ERR'], dtype=float) return df # os.chdir(img_path) # img_files = glob.glob('*.img') # for file in img_files: # uvotsource(file) # os.chdir(home_path) observation_list = swift.GetObservationList('NGC1313') start_times = swift.GetStartTimes(observation_list) path = 'sources/NGC1313/swift/uvot/img' os.chdir(path) obs_id_regex = re.compile(r'\d{11}') output_files = glob.glob('uvotsource/*.fits') df_dict = {} for file in output_files: print(file) obsID = obs_id_regex.search(file).group() mask = start_times['OBSID'] == obsID try: start = start_times[mask]['START_TIME'].values[0] except: start = None print('start', start) df_dict[obsID] = GetFluxes(file) df_dict[obsID]['START_MJD'] = start df = pd.concat(df_dict) df = df.sort_values(by=['TSTART']) # plt.plot(df['TSTART'], df['MAG']) ''' #NORMALISING TO ONE df['RAW_TOT_CNTS'] = df['RAW_TOT_CNTS'] / max(df['RAW_TOT_CNTS']) df['RAW_TOT_RATE'] = df['RAW_TOT_RATE'] / max(df['RAW_TOT_RATE']) df['MAG'] = df['MAG'] / max(df['MAG']) df['RAW_TOT_CNTS_ERR'] = df['RAW_TOT_CNTS_ERR'] / max(df['RAW_TOT_CNTS']) df['RAW_TOT_RATE_ERR'] = df['RAW_TOT_RATE_ERR'] / max(df['RAW_TOT_RATE']) df['MAG_ERR'] = df['MAG_ERR'] / max(df['MAG']) ''' #RAW COUNTS LIGHTCURVE FROM UVOTSOURCE plt.figure(figsize=(20,6)) plt.errorbar(df['START_MJD'], df['RAW_TOT_CNTS'], yerr=df['RAW_TOT_CNTS_ERR'], capsize=0.5, marker='None', ls='none', label='RAW_TOT_CNTS|uvotsource', c='green') plt.ylim(0, 1.1*max(df['RAW_TOT_CNTS'])) plt.legend() plt.show() #TOTAL RATE LIGHTCURVE FROM UVOTSOURCE plt.figure(figsize=(20,6)) plt.errorbar(df['START_MJD'], df['RAW_TOT_RATE'], yerr=df['RAW_TOT_RATE_ERR'], capsize=0.5, marker='None', ls='none', label='RAW_TOT_RATE|uvotsource', c='b') plt.ylim(35, 1.1*max(df['RAW_TOT_RATE'])) plt.legend() #MAG LIGHTCURVE FROM UVOTSOURCE plt.figure(figsize=(20,6)) df = df[df['MAG_ERR'] < 10] plt.errorbar(df['START_MJD'], df['MAG'], yerr=df['MAG_ERR'], capsize=0.5, marker='None', ls='none', label='MAG|uvotsource', c='blue') plt.ylim(14.0, 15.0) plt.legend()
[ "logging.basicConfig", "re.compile", "swift.GetObservationList", "matplotlib.pyplot.legend", "astropy.io.fits.open", "os.getcwd", "os.chdir", "numpy.array", "matplotlib.pyplot.figure", "matplotlib.pyplot.errorbar", "pandas.DataFrame", "swift.GetStartTimes", "matplotlib.pyplot.ylim", "panda...
[((451, 529), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '""" %(asctime)s -- %(message)s"""'}), "(level=logging.DEBUG, format=' %(asctime)s -- %(message)s')\n", (470, 529), False, 'import logging\n'), ((543, 554), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (552, 554), False, 'import os\n'), ((2179, 2214), 'swift.GetObservationList', 'swift.GetObservationList', (['"""NGC1313"""'], {}), "('NGC1313')\n", (2203, 2214), False, 'import swift\n'), ((2229, 2266), 'swift.GetStartTimes', 'swift.GetStartTimes', (['observation_list'], {}), '(observation_list)\n', (2248, 2266), False, 'import swift\n'), ((2308, 2322), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (2316, 2322), False, 'import os\n'), ((2338, 2359), 're.compile', 're.compile', (['"""\\\\d{11}"""'], {}), "('\\\\d{11}')\n", (2348, 2359), False, 'import re\n'), ((2375, 2405), 'glob.glob', 'glob.glob', (['"""uvotsource/*.fits"""'], {}), "('uvotsource/*.fits')\n", (2384, 2405), False, 'import glob\n'), ((2757, 2775), 'pandas.concat', 'pd.concat', (['df_dict'], {}), '(df_dict)\n', (2766, 2775), True, 'import pandas as pd\n'), ((3285, 3312), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 6)'}), '(figsize=(20, 6))\n', (3295, 3312), True, 'import matplotlib.pyplot as plt\n'), ((3312, 3483), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (["df['START_MJD']", "df['RAW_TOT_CNTS']"], {'yerr': "df['RAW_TOT_CNTS_ERR']", 'capsize': '(0.5)', 'marker': '"""None"""', 'ls': '"""none"""', 'label': '"""RAW_TOT_CNTS|uvotsource"""', 'c': '"""green"""'}), "(df['START_MJD'], df['RAW_TOT_CNTS'], yerr=df[\n 'RAW_TOT_CNTS_ERR'], capsize=0.5, marker='None', ls='none', label=\n 'RAW_TOT_CNTS|uvotsource', c='green')\n", (3324, 3483), True, 'import matplotlib.pyplot as plt\n'), ((3529, 3541), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3539, 3541), True, 'import matplotlib.pyplot as plt\n'), ((3542, 3552), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3550, 3552), True, 'import matplotlib.pyplot as plt\n'), ((3593, 3620), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 6)'}), '(figsize=(20, 6))\n', (3603, 3620), True, 'import matplotlib.pyplot as plt\n'), ((3620, 3787), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (["df['START_MJD']", "df['RAW_TOT_RATE']"], {'yerr': "df['RAW_TOT_RATE_ERR']", 'capsize': '(0.5)', 'marker': '"""None"""', 'ls': '"""none"""', 'label': '"""RAW_TOT_RATE|uvotsource"""', 'c': '"""b"""'}), "(df['START_MJD'], df['RAW_TOT_RATE'], yerr=df[\n 'RAW_TOT_RATE_ERR'], capsize=0.5, marker='None', ls='none', label=\n 'RAW_TOT_RATE|uvotsource', c='b')\n", (3632, 3787), True, 'import matplotlib.pyplot as plt\n'), ((3834, 3846), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3844, 3846), True, 'import matplotlib.pyplot as plt\n'), ((3880, 3907), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 6)'}), '(figsize=(20, 6))\n', (3890, 3907), True, 'import matplotlib.pyplot as plt\n'), ((3935, 4072), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (["df['START_MJD']", "df['MAG']"], {'yerr': "df['MAG_ERR']", 'capsize': '(0.5)', 'marker': '"""None"""', 'ls': '"""none"""', 'label': '"""MAG|uvotsource"""', 'c': '"""blue"""'}), "(df['START_MJD'], df['MAG'], yerr=df['MAG_ERR'], capsize=0.5,\n marker='None', ls='none', label='MAG|uvotsource', c='blue')\n", (3947, 4072), True, 'import matplotlib.pyplot as plt\n'), ((4082, 4102), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(14.0)', '(15.0)'], {}), '(14.0, 15.0)\n', (4090, 4102), True, 'import matplotlib.pyplot as plt\n'), ((4103, 4115), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4113, 4115), True, 'import matplotlib.pyplot as plt\n'), ((1329, 1343), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1341, 1343), True, 'import pandas as pd\n'), ((1355, 1375), 'astropy.io.fits.open', 'fits.open', (['fits_file'], {}), '(fits_file)\n', (1364, 1375), False, 'from astropy.io import fits\n'), ((1397, 1439), 'numpy.array', 'np.array', (["data[1].data['MET']"], {'dtype': 'float'}), "(data[1].data['MET'], dtype=float)\n", (1405, 1439), True, 'import numpy as np\n'), ((1460, 1505), 'numpy.array', 'np.array', (["data[1].data['TSTART']"], {'dtype': 'float'}), "(data[1].data['TSTART'], dtype=float)\n", (1468, 1505), True, 'import numpy as np\n'), ((1524, 1568), 'numpy.array', 'np.array', (["data[1].data['TSTOP']"], {'dtype': 'float'}), "(data[1].data['TSTOP'], dtype=float)\n", (1532, 1568), True, 'import numpy as np\n'), ((1594, 1645), 'numpy.array', 'np.array', (["data[1].data['RAW_TOT_CNTS']"], {'dtype': 'float'}), "(data[1].data['RAW_TOT_CNTS'], dtype=float)\n", (1602, 1645), True, 'import numpy as np\n'), ((1675, 1730), 'numpy.array', 'np.array', (["data[1].data['RAW_TOT_CNTS_ERR']"], {'dtype': 'float'}), "(data[1].data['RAW_TOT_CNTS_ERR'], dtype=float)\n", (1683, 1730), True, 'import numpy as np\n'), ((1756, 1807), 'numpy.array', 'np.array', (["data[1].data['RAW_TOT_RATE']"], {'dtype': 'float'}), "(data[1].data['RAW_TOT_RATE'], dtype=float)\n", (1764, 1807), True, 'import numpy as np\n'), ((1837, 1892), 'numpy.array', 'np.array', (["data[1].data['RAW_TOT_RATE_ERR']"], {'dtype': 'float'}), "(data[1].data['RAW_TOT_RATE_ERR'], dtype=float)\n", (1845, 1892), True, 'import numpy as np\n'), ((1909, 1951), 'numpy.array', 'np.array', (["data[1].data['MAG']"], {'dtype': 'float'}), "(data[1].data['MAG'], dtype=float)\n", (1917, 1951), True, 'import numpy as np\n'), ((1972, 2018), 'numpy.array', 'np.array', (["data[1].data['MAG_ERR']"], {'dtype': 'float'}), "(data[1].data['MAG_ERR'], dtype=float)\n", (1980, 2018), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Mon Jan 21 16:21:29 2019 @author: gurjaspal """ """ This class takes a slot machine and tries to estimate the true mean of the machine. The machine is defined in SlotMachine class. """ import numpy as np from SlotMachine import SlotMachine from typing import List import matplotlib.pyplot as plt import os class GreedyEpsilon: """ Defining the has a realtionship with Slot Machine """ def __init__(self, slot_machines : List[SlotMachine], epsilon_exploration_percentage : float, graphs): """ Initialize Greedy-Epsilon algorithm with list of machines and Epsilon which is the perfcentage of time the algorithm should explore various options Parameters ---------- slot_machines: list of type SlotMachines This is the list that contains all the slot machines we have with different mean rewards epsilon_exploration_percentage: float Value between 0 and 1, represents the fraction of time algorithm should explore rather than exploit Returns ------- None Raises ------ ValueError Raises the value error if the value of 'epsilon_exploration_percentage' is not between 0 and 1 """ if epsilon_exploration_percentage < 0 or epsilon_exploration_percentage > 1: raise ValueError("epsilon_exploration_percentage is not between 0 and 1") self.slot_machines = slot_machines self.epsilon_exploration_percentage = epsilon_exploration_percentage self.machine_count = len(slot_machines) # The number of iteration self.iteration = 0 self.estimated_means_each_iteration = [] self._graphs = graphs def estimated_means_after_each_iteration(self): """ Stores the estimated means after each iteration Parameters ---------- None Returns ------- None """ means = [slot_machine.estimated_mean for slot_machine in self.slot_machines] self.estimated_means_each_iteration.append(means) def get_the_best_machine_index(self) -> int: """ Returns the best available machine which should be played by the user Parameters ---------- None Returns ------- Index : int The index of the machine """ estimated_means = [machine.estimated_mean for machine in self.slot_machines] selected_machine = np.argmax(estimated_means) # print(estimated_means, selected_machine) return selected_machine def update_estimated_mean_for_given_machine(self , reward : float, machine_index: int): """ After we get the number from the machine we update our calculate mean and also the number of iterations Parameters ---------- reward: float Reward by slot machine machine_index: int Index of the machine you want to update the estimated mean Returns ------- None """ # increasing the number of iteration machine = self.slot_machines[machine_index] machine.iteration += 1 # update our calculated mean sum_uptil_previous_iteration = machine.estimated_mean * (machine.iteration - 1) # updating the mean estimated_mean = (sum_uptil_previous_iteration + reward) / machine.iteration # print("estimated mean and reward") # print(estimated_mean, reward) self.slot_machines[machine_index].estimated_mean = estimated_mean self.estimated_means_after_each_iteration() def run(self, total_iterations: int): """ Run Greedy Epsilon for given number of iterations Parameters ---------- total_iterations: int Number of iterations you want to run the Greedy Epsilon Returns ------- None """ # we use a list to cound the number of times each Machine is selected selected_machine_count = np.zeros(self.machine_count) reward_each_iteration = [] rewards = [] for iteration in range(total_iterations): # get value from distribution p = np.random.random() # if p is greater than our exploration percentage, we exploit else we explore if p > self.epsilon_exploration_percentage: # exploitation best_machine_index = self.get_the_best_machine_index() else: # exploration best_machine_index = np.random.choice(self.machine_count) # get the next reward from the mahchine next_reward = self.slot_machines[best_machine_index].pull() rewards.append(next_reward) reward_each_iteration.append(next_reward) # update the mean reward for the machine self.update_estimated_mean_for_given_machine(next_reward , best_machine_index) selected_machine_count[best_machine_index] +=1 x_labels = ['Machine'+ str(i+1) for i in range(self.machine_count)] print(os.path.dirname(__file__)) self._graphs.draw_plot(total_iterations , reward_each_iteration , os.path.dirname(__file__)) self._graphs.draw_bar_graph(x_labels, selected_machine_count , os.path.dirname(__file__)) self._graphs.draw_cumulative_average_graph(np.cumsum(rewards) / (np.arange(total_iterations)+ 1), total_iterations, os.path.dirname(__file__))
[ "numpy.random.random", "numpy.random.choice", "numpy.argmax", "os.path.dirname", "numpy.zeros", "numpy.cumsum", "numpy.arange" ]
[((2660, 2686), 'numpy.argmax', 'np.argmax', (['estimated_means'], {}), '(estimated_means)\n', (2669, 2686), True, 'import numpy as np\n'), ((4301, 4329), 'numpy.zeros', 'np.zeros', (['self.machine_count'], {}), '(self.machine_count)\n', (4309, 4329), True, 'import numpy as np\n'), ((4493, 4511), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (4509, 4511), True, 'import numpy as np\n'), ((5401, 5426), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5416, 5426), False, 'import os\n'), ((5502, 5527), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5517, 5527), False, 'import os\n'), ((5600, 5625), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5615, 5625), False, 'import os\n'), ((5751, 5776), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5766, 5776), False, 'import os\n'), ((4855, 4891), 'numpy.random.choice', 'np.random.choice', (['self.machine_count'], {}), '(self.machine_count)\n', (4871, 4891), True, 'import numpy as np\n'), ((5678, 5696), 'numpy.cumsum', 'np.cumsum', (['rewards'], {}), '(rewards)\n', (5687, 5696), True, 'import numpy as np\n'), ((5700, 5727), 'numpy.arange', 'np.arange', (['total_iterations'], {}), '(total_iterations)\n', (5709, 5727), True, 'import numpy as np\n')]
""" Create the input file to simulate the an Keken et al. (1997) model """ import numpy as np import matplotlib.pyplot as plt Nx = 81 Nz = 81 Lx = 92.42 Lz = 100.0 xn = np.linspace(0, Lx, Nx) liton = -0.8 * Lz + 0.02 * Lz * np.cos(np.pi * xn / Lx) liton = liton * 1000 # Create the interface file layer_properties = [ "C 1.0 1.0", "rho -1000. 0.", "H 0.0e-12 0.0e-12", "A 0.0 0.0", "n 0.0 0.0", "Q 0.0 0.0", "V 0.0 0.0", ] with open("interfaces.txt", "w") as f: for line in layer_properties: line = line.strip() if len(line): f.write(" ".join(line.split()) + "\n") for line in np.arange(Nx): f.write("%lf\n" % (liton[line])) ############################################################################## # Parameters file ############################################################################## params = f""" # Geometry nx = {Nx} # N. of elements in the longitudinal direction nz = {Nz} # N. of elements in the vertical direction lx = 91420.0 # Extent in the longitudinal direction lz = 100000. # Extent in the vertical direction particles_per_element_x = 0 # default is 0 particles_per_element_z = 0 # default is 0 # Simulation options multigrid = 1 # ok -> soon to be on the command line only solver = direct # default is direct [direct/iterative] denok = 1.0e-15 # default is 1.0e-4 particles_per_element = 1100 # default is 81 particles_perturb_factor = 0.0 # default is 0.5 [values are between 0 and 1] rtol = 1.0e-5 # the absolute size of the residual norm (relevant only for iterative methods), default is 1.0E-5 RK4 = Euler # default is Euler [Euler/Runge-Kutta] Xi_min = 1.0e-14 # default is 1.0e-14 random_initial_strain = 0.0 # default is 0.0 pressure_const = -1.0 # default is -1.0 (not used) initial_dynamic_range = False # default is False [True/False] periodic_boundary = False # default is False [True/False] high_kappa_in_asthenosphere = False # default is False [True/False] K_fluvial = 2.0e-7 # default is 2.0e-7 m_fluvial = 1.0 # default is 1.0 sea_level = 0.0 # default is 0.0 basal_heat = -1.0 # default is -1.0 # Surface processes sp_surface_tracking = False # default is False [True/False] sp_surface_processes = False # default is False [True/False] sp_dt = 0 # default is 0 sp_d_c = 0 # default is 0 plot_sediment = False # default is False [True/False] a2l = True # default is True [True/False] free_surface_stab = True # default is True [True/False] theta_FSSA = 0.5 # default is 0.5 (only relevant when free_surface_stab = True) # Time constrains step_max = 4000 # Maximum time-step of the simulation time_max = 140000.0e6 # Maximum time of the simulation [s] dt_max = 1000.0e6 # Maximum time between steps of the simulation [s] step_print = 20 # Make file every <step_print> sub_division_time_step = 1.0 # default is 1.0 initial_print_step = 0 # default is 0 initial_print_max_time = 1.0e6 # default is 1.0e6 [years] # Viscosity viscosity_reference = 1.0e21 # Reference viscosity [Pa.s] viscosity_max = 1.0e25 # Maximum viscosity [Pa.s] viscosity_min = 1.0e17 # Minimum viscosity [Pa.s] viscosity_per_element = constant # default is variable [constant/variable] viscosity_mean_method = harmonic # default is harmonic [harmonic/arithmetic] viscosity_dependence = pressure # default is depth [pressure/depth] # External ASCII inputs/outputs interfaces_from_ascii = True # default is False [True/False] n_interfaces = 1 # Number of interfaces int the interfaces.txt file variable_bcv = False # default is False [True/False] temperature_from_ascii = False # default is False [True/False] velocity_from_ascii = False # default is False [True/False] binary_output = False # default is False [True/False] sticky_blanket_air = False # default is False [True/False] precipitation_profile_from_ascii = False # default is False [True/False] climate_change_from_ascii = False # default is False [True/False] print_step_files = True # default is True [True/False] checkered = False # Print one element in the print_step_filesdefault is False [True/False] sp_mode = 1 # default is 1 [0/1/2] geoq = on # ok geoq_fac = 1.0 # ok # Physical parameters temperature_difference = 0. # ok thermal_expansion_coefficient = 3.28e-5 # ok thermal_diffusivity_coefficient = 1.0e-6 # ok gravity_acceleration = 10.0 # ok density_mantle = 3300. # ok external_heat = 0.0e-12 # ok heat_capacity = 1250. # ok non_linear_method = off # ok adiabatic_component = off # ok radiogenic_component = off # ok # Velocity boundary conditions top_normal_velocity = fixed # ok top_tangential_velocity = fixed # ok bot_normal_velocity = fixed # ok bot_tangential_velocity = fixed # ok left_normal_velocity = fixed # ok left_tangential_velocity = free # ok right_normal_velocity = fixed # ok right_tangential_velocity = free # ok surface_velocity = 0.0e-2 # ok multi_velocity = False # default is False [True/False] # Temperature boundary conditions top_temperature = fixed # ok bot_temperature = fixed # ok left_temperature = free # ok right_temperature = free # ok rheology_model = 0 # ok T_initial = 0 # ok """ # Create the parameter file with open("param.txt", "w") as f: for line in params.split("\n"): f.write(line + "\n")
[ "numpy.linspace", "numpy.cos", "numpy.arange" ]
[((172, 194), 'numpy.linspace', 'np.linspace', (['(0)', 'Lx', 'Nx'], {}), '(0, Lx, Nx)\n', (183, 194), True, 'import numpy as np\n'), ((691, 704), 'numpy.arange', 'np.arange', (['Nx'], {}), '(Nx)\n', (700, 704), True, 'import numpy as np\n'), ((228, 251), 'numpy.cos', 'np.cos', (['(np.pi * xn / Lx)'], {}), '(np.pi * xn / Lx)\n', (234, 251), True, 'import numpy as np\n')]
""" Tests for functions in ensemble_tools.py. Authors: <NAME> & <NAME> Note that functions that start with an underscore (_) are designed for local use only by the primary functions within ensemble_tools.py. Therefore, testing of those local scripts does not include checking for irrational inputs that would cause meaningless results and/or an exception since such inputs are checked for earlier in the primary functions. """ import numpy as np import pytest import sys from ensemble.ensemble_tools import ( _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type ) # Define ensemble datasets to test with MEMBERS_ALPHA = np.array([[0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 0.5, 1.0]]) MEMBERS_BRAVO = np.array([[-1.0, -1.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 1.0, 1.0]]) MEMBERS_CHARLIE = np.array([[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]]) # Set the roundoff decimals for testing precision ROUNDOFF = 5 # ------------------------------------------------------------------------------ # _gumbel_cdf # ------------------------------------------------------------------------------ @pytest.mark.parametrize("members, x, expected", [(MEMBERS_ALPHA[0], 1.1, 0.97949), (MEMBERS_ALPHA[0], 10.0, 1.0), (MEMBERS_ALPHA[0], -10.0, 0.0), ]) def test_gumbel_cdf(members, x, expected): print("I AM TESTING _gumbel_cdf") assert np.round(_gumbel_cdf(members, x), ROUNDOFF) == expected # ------------------------------------------------------------------------------ # _prob_from_outside_rank_gumbel # ------------------------------------------------------------------------------ @pytest.mark.parametrize("threshold, members, threshold_position, expected", [(1000, MEMBERS_ALPHA, 'above_all_members', 0.0), (-1000, MEMBERS_ALPHA, 'below_all_members', 1), (1.1, MEMBERS_ALPHA, 'mouse_burgers', 1e32), (1.1, MEMBERS_ALPHA, 'above_all_members', 'between_0_1')]) def test_prob_from_outside_rank_gumbel( threshold, members, threshold_position, expected ): prob = _prob_from_outside_rank_gumbel(threshold, members, threshold_position) if isinstance(expected, float) or isinstance(expected, int) : assert(np.round(prob, ROUNDOFF) == expected),\ (f"prob={prob}, expected={expected}") else : assert(prob < 1. and prob > 0.),\ ("Expected prob between zero and one but got {prob}") # ------------------------------------------------------------------------------ # _prob_from_outside_rank_exp # ------------------------------------------------------------------------------ # this function estimates Prob(V >= thresh | ensemble_members & exp left tail) # where V is the verifying value, thresh is a user specified threshold for some # event, and ensemble_members are predictions from e.g. crps-net. @pytest.mark.parametrize("threshold, members", [(0.5, np.array([1,2,3,4])),]) def test_prob_from_outside_rank_exp(threshold, members) : n_bins = len(members) + 1 n_prob_per_bin = 1 / n_bins assert(_prob_from_outside_rank_exp(np.min(members), members) == (1-n_prob_per_bin)),\ (f"when thresh is tied with lower member, there is a full bin of probability below") assert(_prob_from_outside_rank_exp(0, members) == 1) (f"Can't be negative, so proba greater or above 0 always 1 regardless of members") prob = _prob_from_outside_rank_exp(threshold, members) assert(prob < 1 and prob > 0),\ ("probability of this tail must be between 0 and 1") # ------------------------------------------------------------------------------ # probability_from_members # ------------------------------------------------------------------------------ # Tests for ValueErrors @pytest.mark.parametrize("threshold, members, operator_str, presorted, positive_definite", [(-0.15, MEMBERS_ALPHA, 'greater', True, True), (0.1, MEMBERS_BRAVO, 'greater', True, True), (0.1, np.array([[1, 2, 3]]), 'greater', True, True), (0.1, MEMBERS_ALPHA, '<NAME>!', True, True), (0.1, np.array([[1, 2, 3, 4, 5, 6, np.NaN, 8, 9, 10]]), 'greater', True, True), ] ) def test1_probability_from_members(threshold, members, operator_str, presorted, positive_definite): with pytest.raises(ValueError): probability_from_members(threshold, members, operator_str, presorted, positive_definite) # Tests for TypeErrors @pytest.mark.parametrize("threshold, members, operator_str, presorted, positive_definite", [('string', MEMBERS_ALPHA, 'greater', True, True), (1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'greater', True, True), (1, MEMBERS_ALPHA, True, True, True), (1, MEMBERS_ALPHA, 'greater', 'string', True), (1, MEMBERS_ALPHA, 'greater', True, 999), ] ) def test2_probability_from_members(threshold, members, operator_str, presorted, positive_definite): with pytest.raises(TypeError): probability_from_members(threshold, members, operator_str, presorted, positive_definite) # ------------------------------------------------------------------------------ # _probability_from_members # ------------------------------------------------------------------------------ MEMBER_POSITIVE_DEF = np.array([0, 1, 2, 3, 4, 5]) # Tests for threshold between members @pytest.mark.parametrize("threshold, members, operator_str, presorted, positive_definite, expected", [(0.15, MEMBERS_ALPHA, 'greater', True, True, 0.5), (0.15, MEMBERS_ALPHA, 'greater', False, False, 0.5), (0.15, MEMBERS_ALPHA, 'greater_equal', True, True, 0.5), (0.15, MEMBERS_ALPHA, 'greater_equal', True, False, 0.5), (0.15, MEMBERS_ALPHA, 'less', True, True, 0.5), (0.15, MEMBERS_ALPHA, 'less', True, False, 0.5), (0.15, MEMBERS_ALPHA, 'less_equal', True, True, 0.5), (0.15, MEMBERS_ALPHA, 'less_equal', False, False, 0.5), (-100, MEMBER_POSITIVE_DEF, 'less', True, True, 0.0), (-100, MEMBER_POSITIVE_DEF, 'less', False, True, 0.0), ] ) def test1__probability_from_members(threshold, members, operator_str, presorted, positive_definite, expected): assert _probability_from_members(threshold, members, operator_str, presorted, positive_definite)[0][0] == expected # Tests for threshold outside of members @pytest.mark.parametrize("threshold, members, operator_str, presorted, positive_definite, expected", [(1.1, MEMBERS_ALPHA, 'greater', True, True, 0.06111), (7, MEMBERS_CHARLIE, 'greater', True, True, 0.0), (8, MEMBERS_CHARLIE, 'greater', True, True, 0.0), (8, MEMBERS_CHARLIE, 'greater_equal', True, True, 0.0), (7, MEMBERS_CHARLIE, 'greater_equal', True, True, 1.0) ] ) def test1__probability_from_members(threshold, members, operator_str, presorted, positive_definite, expected): assert np.round(_probability_from_members(threshold, members, operator_str, presorted, positive_definite)[0][0], ROUNDOFF) == expected # Tests for handling zeros @pytest.mark.parametrize("threshold, members, operator_str, presorted, positive_definite, expected", [(0.0, MEMBERS_ALPHA, 'greater', True, True, np.round(7./11, ROUNDOFF)), (0.0, MEMBERS_ALPHA, 'greater', True, False, np.round(7./11, ROUNDOFF)), (0.0, MEMBERS_ALPHA, 'greater_equal', True, False, np.round(10./11, ROUNDOFF)), (0.0, MEMBERS_ALPHA, 'greater_equal', True, True, 1.0) ] ) def test2__probability_from_members(threshold, members, operator_str, presorted, positive_definite, expected): assert np.round(_probability_from_members(threshold, members, operator_str, presorted, positive_definite)[0][0], ROUNDOFF) == expected # Tests for handling tie between threshold and members @pytest.mark.parametrize("threshold, members, operator_str, presorted, positive_definite, expected", [(0.5, MEMBERS_ALPHA, 'greater', True, True, np.round(2./11, ROUNDOFF)), (0.5, MEMBERS_ALPHA, 'greater', False, False, np.round(2./11, ROUNDOFF)), (0.5, MEMBERS_ALPHA, 'greater_equal', True, True, np.round(4./11, ROUNDOFF)), (0.5, MEMBERS_ALPHA, 'greater_equal', False, False, np.round(4./11, ROUNDOFF)), (0.5, MEMBERS_ALPHA, 'less', True, True, np.round(7./11, ROUNDOFF)), (0.5, MEMBERS_ALPHA, 'less_equal', True, True, np.round(9./11, ROUNDOFF)), (-1.0, MEMBERS_BRAVO, 'less', True, False, np.round(1./11, ROUNDOFF)), (-1.0, MEMBERS_BRAVO, 'less_equal', True, False, np.round(2./11, ROUNDOFF)), ] ) def test3__probability_from_members(threshold, members, operator_str, presorted, positive_definite, expected): assert np.round(_probability_from_members(threshold, members, operator_str, presorted, positive_definite)[0][0], ROUNDOFF) == expected # ------------------------------------------------------------------------------ # prob_between_values # ------------------------------------------------------------------------------ MEMBERS_DELTA = np.array([[0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 0.5, 1.]]) # TODO: Break this into logical separations @pytest.mark.parametrize("members, lower, upper, bracket, positive_definite, expected", [(MEMBERS_DELTA, 0., 0.1, "()", True, np.round(1/11, ROUNDOFF)), (MEMBERS_DELTA, 0., 0.1, "[)", True, np.round(5/11, ROUNDOFF)), (MEMBERS_DELTA, 0., 0.1, "[]", True, np.round(5/11, ROUNDOFF)), (MEMBERS_DELTA, 0., 0.1, "(]", True, np.round(1/11, ROUNDOFF)), (MEMBERS_DELTA, 0., 0.5, "()", True, np.round(3/11, ROUNDOFF)), (MEMBERS_DELTA, 0., 1., "()", True, np.round(6/11, ROUNDOFF)), (MEMBERS_DELTA, 0., 1., "[]", True, np.round(10/11, ROUNDOFF)), (MEMBERS_DELTA, 0., 1., "[]", False, np.round(9/11, ROUNDOFF)), (MEMBERS_DELTA, 10., 11., "[]", False, np.round(0/11, ROUNDOFF)), (MEMBERS_CHARLIE, 0., 10., "[]", False, np.round(11/11, ROUNDOFF)), (MEMBERS_CHARLIE, 6.99, 7.01, "[]", False, np.round(11/11, ROUNDOFF)), (MEMBERS_CHARLIE, 6.99, 7.01, "()", False, np.round(11/11, ROUNDOFF)), (MEMBERS_CHARLIE, 7, 7.0001, "()", False, np.round(0/11, ROUNDOFF)), (MEMBERS_CHARLIE, 7, 7.0001, "[)", False, np.round(11/11, ROUNDOFF)), (MEMBERS_CHARLIE, 7.1, 7.2, "[]", False, np.round(0/11, ROUNDOFF)), (MEMBERS_CHARLIE, 6.9, 6.91, "[]", False, np.round(0/11, ROUNDOFF)), ]) def test1_prob_between_values(members, lower, upper, bracket, positive_definite, expected) : assert np.round(prob_between_values(members, lower, upper, bracket, positive_definite)[0][0], ROUNDOFF) == expected # Validate the parameters # ------------------------------------------------------------------------------ # ensemble_verification_rank # ------------------------------------------------------------------------------ N = int(1e6) MEMBERS_ZERO = np.zeros((N, 5)) V_ = np.zeros(shape=(N, 1)) @pytest.mark.parametrize("v_, M, expected", [(V_, MEMBERS_ZERO, np.array([0, 1, 2, 3, 4, 5])), ] ) def test1_ensemble_verification_rank(v_, M, expected) : ranks = ensemble_verification_rank(v_, M) val, count = np.unique(ranks, return_counts=True) prob_per_bin = 1 / (M.shape[1] + 1) proportion = count / M.shape[0] # TODO: assert counts roughly equal to expected value assert (val == expected).any() #and np.testing.assert_almost_equal(proportion[0], prob_per_bin, decimal=7) # ------------------------------------------------------------------------------ # ensemble_verification_rank # ------------------------------------------------------------------------------ # 1) correct int type # 2) give a str when expecting an int, catch TypeError # 3) give a list when expecting a str, catch TypeError # 4) give a dict when expecting a dict @pytest.mark.parametrize("parameter_name, parameter, expected_type, raises", [("horse_face", 1, int, None), ("horse_face", "moose", int, TypeError), ("wild horses", ["rat"], str, TypeError), ("dog gunna hunt", {"cute":"dog"}, dict, None)]) def test__validate_arg_type(parameter_name, parameter, expected_type, raises) : """Test to make sure the function fails when expected.""" if raises is not None : # We expect this to raise an error with pytest.raises(raises) : _validate_arg_type(parameter_name, parameter, expected_type) else : _validate_arg_type(parameter_name, parameter, expected_type) # ------------------------------------------------------------------------------ # _deterministic_event_prob # ------------------------------------------------------------------------------ @pytest.mark.parametrize("forecast, thresh, operator_str, expected", [(1, 1.1, "less", 0), (1, 0.9, "less", 1), (1, 1, "less", 1), (1, 1, "less_equal", 1), (1, 0, "less_equal", 1), (5, 10, "less_equal", 0), (5, 10, "not_a_valid_operator", 1e64), ]) def test_deterministic_event_prob(forecast, thresh, operator_str, expected) : prob = _deterministic_event_prob(forecast, thresh, operator_str) assert(prob == expected),\ (f"prob={prob}, expected={expected}") # THESE NEED TESTS # _deterministic_event_prob # probability_from_members
[ "ensemble.ensemble_tools.prob_between_values", "numpy.unique", "ensemble.ensemble_tools._gumbel_cdf", "numpy.round", "ensemble.ensemble_tools._deterministic_event_prob", "numpy.array", "numpy.zeros", "pytest.mark.parametrize", "pytest.raises", "ensemble.ensemble_tools._prob_from_outside_rank_exp",...
[((865, 927), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 0.5, 1.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 0.5, 1.0]])\n', (873, 927), True, 'import numpy as np\n'), ((944, 1008), 'numpy.array', 'np.array', (['[[-1.0, -1.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 1.0, 1.0]]'], {}), '([[-1.0, -1.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 1.0, 1.0]])\n', (952, 1008), True, 'import numpy as np\n'), ((1027, 1069), 'numpy.array', 'np.array', (['[[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]]'], {}), '([[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]])\n', (1035, 1069), True, 'import numpy as np\n'), ((1344, 1495), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""members, x, expected"""', '[(MEMBERS_ALPHA[0], 1.1, 0.97949), (MEMBERS_ALPHA[0], 10.0, 1.0), (\n MEMBERS_ALPHA[0], -10.0, 0.0)]'], {}), "('members, x, expected', [(MEMBERS_ALPHA[0], 1.1, \n 0.97949), (MEMBERS_ALPHA[0], 10.0, 1.0), (MEMBERS_ALPHA[0], -10.0, 0.0)])\n", (1367, 1495), False, 'import pytest\n'), ((1962, 2252), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""threshold, members, threshold_position, expected"""', "[(1000, MEMBERS_ALPHA, 'above_all_members', 0.0), (-1000, MEMBERS_ALPHA,\n 'below_all_members', 1), (1.1, MEMBERS_ALPHA, 'mouse_burgers', 1e+32),\n (1.1, MEMBERS_ALPHA, 'above_all_members', 'between_0_1')]"], {}), "('threshold, members, threshold_position, expected',\n [(1000, MEMBERS_ALPHA, 'above_all_members', 0.0), (-1000, MEMBERS_ALPHA,\n 'below_all_members', 1), (1.1, MEMBERS_ALPHA, 'mouse_burgers', 1e+32),\n (1.1, MEMBERS_ALPHA, 'above_all_members', 'between_0_1')])\n", (1985, 2252), False, 'import pytest\n'), ((4974, 5326), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""threshold, members, operator_str, presorted, positive_definite"""', "[('string', MEMBERS_ALPHA, 'greater', True, True), (1, [1, 2, 3, 4, 5, 6, 7,\n 8, 9, 10], 'greater', True, True), (1, MEMBERS_ALPHA, True, True, True),\n (1, MEMBERS_ALPHA, 'greater', 'string', True), (1, MEMBERS_ALPHA,\n 'greater', True, 999)]"], {}), "(\n 'threshold, members, operator_str, presorted, positive_definite', [(\n 'string', MEMBERS_ALPHA, 'greater', True, True), (1, [1, 2, 3, 4, 5, 6,\n 7, 8, 9, 10], 'greater', True, True), (1, MEMBERS_ALPHA, True, True, \n True), (1, MEMBERS_ALPHA, 'greater', 'string', True), (1, MEMBERS_ALPHA,\n 'greater', True, 999)])\n", (4997, 5326), False, 'import pytest\n'), ((5967, 5995), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5]'], {}), '([0, 1, 2, 3, 4, 5])\n', (5975, 5995), True, 'import numpy as np\n'), ((6035, 6709), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""threshold, members, operator_str, presorted, positive_definite, expected"""', "[(0.15, MEMBERS_ALPHA, 'greater', True, True, 0.5), (0.15, MEMBERS_ALPHA,\n 'greater', False, False, 0.5), (0.15, MEMBERS_ALPHA, 'greater_equal', \n True, True, 0.5), (0.15, MEMBERS_ALPHA, 'greater_equal', True, False, \n 0.5), (0.15, MEMBERS_ALPHA, 'less', True, True, 0.5), (0.15,\n MEMBERS_ALPHA, 'less', True, False, 0.5), (0.15, MEMBERS_ALPHA,\n 'less_equal', True, True, 0.5), (0.15, MEMBERS_ALPHA, 'less_equal', \n False, False, 0.5), (-100, MEMBER_POSITIVE_DEF, 'less', True, True, 0.0\n ), (-100, MEMBER_POSITIVE_DEF, 'less', False, True, 0.0)]"], {}), "(\n 'threshold, members, operator_str, presorted, positive_definite, expected',\n [(0.15, MEMBERS_ALPHA, 'greater', True, True, 0.5), (0.15,\n MEMBERS_ALPHA, 'greater', False, False, 0.5), (0.15, MEMBERS_ALPHA,\n 'greater_equal', True, True, 0.5), (0.15, MEMBERS_ALPHA,\n 'greater_equal', True, False, 0.5), (0.15, MEMBERS_ALPHA, 'less', True,\n True, 0.5), (0.15, MEMBERS_ALPHA, 'less', True, False, 0.5), (0.15,\n MEMBERS_ALPHA, 'less_equal', True, True, 0.5), (0.15, MEMBERS_ALPHA,\n 'less_equal', False, False, 0.5), (-100, MEMBER_POSITIVE_DEF, 'less', \n True, True, 0.0), (-100, MEMBER_POSITIVE_DEF, 'less', False, True, 0.0)])\n", (6058, 6709), False, 'import pytest\n'), ((7302, 7690), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""threshold, members, operator_str, presorted, positive_definite, expected"""', "[(1.1, MEMBERS_ALPHA, 'greater', True, True, 0.06111), (7, MEMBERS_CHARLIE,\n 'greater', True, True, 0.0), (8, MEMBERS_CHARLIE, 'greater', True, True,\n 0.0), (8, MEMBERS_CHARLIE, 'greater_equal', True, True, 0.0), (7,\n MEMBERS_CHARLIE, 'greater_equal', True, True, 1.0)]"], {}), "(\n 'threshold, members, operator_str, presorted, positive_definite, expected',\n [(1.1, MEMBERS_ALPHA, 'greater', True, True, 0.06111), (7,\n MEMBERS_CHARLIE, 'greater', True, True, 0.0), (8, MEMBERS_CHARLIE,\n 'greater', True, True, 0.0), (8, MEMBERS_CHARLIE, 'greater_equal', True,\n True, 0.0), (7, MEMBERS_CHARLIE, 'greater_equal', True, True, 1.0)])\n", (7325, 7690), False, 'import pytest\n'), ((10572, 10634), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 0.5, 1.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.5, 0.5, 0.5, 1.0]])\n', (10580, 10634), True, 'import numpy as np\n'), ((12836, 12852), 'numpy.zeros', 'np.zeros', (['(N, 5)'], {}), '((N, 5))\n', (12844, 12852), True, 'import numpy as np\n'), ((12858, 12880), 'numpy.zeros', 'np.zeros', ([], {'shape': '(N, 1)'}), '(shape=(N, 1))\n', (12866, 12880), True, 'import numpy as np\n'), ((13822, 14073), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""parameter_name, parameter, expected_type, raises"""', "[('horse_face', 1, int, None), ('horse_face', 'moose', int, TypeError), (\n 'wild horses', ['rat'], str, TypeError), ('dog gunna hunt', {'cute':\n 'dog'}, dict, None)]"], {}), "('parameter_name, parameter, expected_type, raises',\n [('horse_face', 1, int, None), ('horse_face', 'moose', int, TypeError),\n ('wild horses', ['rat'], str, TypeError), ('dog gunna hunt', {'cute':\n 'dog'}, dict, None)])\n", (13845, 14073), False, 'import pytest\n'), ((14766, 15025), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""forecast, thresh, operator_str, expected"""', "[(1, 1.1, 'less', 0), (1, 0.9, 'less', 1), (1, 1, 'less', 1), (1, 1,\n 'less_equal', 1), (1, 0, 'less_equal', 1), (5, 10, 'less_equal', 0), (5,\n 10, 'not_a_valid_operator', 1e+64)]"], {}), "('forecast, thresh, operator_str, expected', [(1, \n 1.1, 'less', 0), (1, 0.9, 'less', 1), (1, 1, 'less', 1), (1, 1,\n 'less_equal', 1), (1, 0, 'less_equal', 1), (5, 10, 'less_equal', 0), (5,\n 10, 'not_a_valid_operator', 1e+64)])\n", (14789, 15025), False, 'import pytest\n'), ((2447, 2517), 'ensemble.ensemble_tools._prob_from_outside_rank_gumbel', '_prob_from_outside_rank_gumbel', (['threshold', 'members', 'threshold_position'], {}), '(threshold, members, threshold_position)\n', (2477, 2517), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((3779, 3826), 'ensemble.ensemble_tools._prob_from_outside_rank_exp', '_prob_from_outside_rank_exp', (['threshold', 'members'], {}), '(threshold, members)\n', (3806, 3826), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((13101, 13134), 'ensemble.ensemble_tools.ensemble_verification_rank', 'ensemble_verification_rank', (['v_', 'M'], {}), '(v_, M)\n', (13127, 13134), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((13150, 13186), 'numpy.unique', 'np.unique', (['ranks'], {'return_counts': '(True)'}), '(ranks, return_counts=True)\n', (13159, 13186), True, 'import numpy as np\n'), ((15310, 15367), 'ensemble.ensemble_tools._deterministic_event_prob', '_deterministic_event_prob', (['forecast', 'thresh', 'operator_str'], {}), '(forecast, thresh, operator_str)\n', (15335, 15367), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((3638, 3677), 'ensemble.ensemble_tools._prob_from_outside_rank_exp', '_prob_from_outside_rank_exp', (['(0)', 'members'], {}), '(0, members)\n', (3665, 3677), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((4792, 4817), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4805, 4817), False, 'import pytest\n'), ((4827, 4919), 'ensemble.ensemble_tools.probability_from_members', 'probability_from_members', (['threshold', 'members', 'operator_str', 'presorted', 'positive_definite'], {}), '(threshold, members, operator_str, presorted,\n positive_definite)\n', (4851, 4919), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((5571, 5595), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (5584, 5595), False, 'import pytest\n'), ((5605, 5697), 'ensemble.ensemble_tools.probability_from_members', 'probability_from_members', (['threshold', 'members', 'operator_str', 'presorted', 'positive_definite'], {}), '(threshold, members, operator_str, presorted,\n positive_definite)\n', (5629, 5697), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((14486, 14546), 'ensemble.ensemble_tools._validate_arg_type', '_validate_arg_type', (['parameter_name', 'parameter', 'expected_type'], {}), '(parameter_name, parameter, expected_type)\n', (14504, 14546), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((1693, 1716), 'ensemble.ensemble_tools._gumbel_cdf', '_gumbel_cdf', (['members', 'x'], {}), '(members, x)\n', (1704, 1716), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((2596, 2620), 'numpy.round', 'np.round', (['prob', 'ROUNDOFF'], {}), '(prob, ROUNDOFF)\n', (2604, 2620), True, 'import numpy as np\n'), ((3490, 3505), 'numpy.min', 'np.min', (['members'], {}), '(members)\n', (3496, 3505), True, 'import numpy as np\n'), ((3309, 3331), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (3317, 3331), True, 'import numpy as np\n'), ((4429, 4450), 'numpy.array', 'np.array', (['[[1, 2, 3]]'], {}), '([[1, 2, 3]])\n', (4437, 4450), True, 'import numpy as np\n'), ((4579, 4627), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 5, 6, np.NaN, 8, 9, 10]]'], {}), '([[1, 2, 3, 4, 5, 6, np.NaN, 8, 9, 10]])\n', (4587, 4627), True, 'import numpy as np\n'), ((8354, 8382), 'numpy.round', 'np.round', (['(7.0 / 11)', 'ROUNDOFF'], {}), '(7.0 / 11, ROUNDOFF)\n', (8362, 8382), True, 'import numpy as np\n'), ((8453, 8481), 'numpy.round', 'np.round', (['(7.0 / 11)', 'ROUNDOFF'], {}), '(7.0 / 11, ROUNDOFF)\n', (8461, 8481), True, 'import numpy as np\n'), ((8558, 8587), 'numpy.round', 'np.round', (['(10.0 / 11)', 'ROUNDOFF'], {}), '(10.0 / 11, ROUNDOFF)\n', (8566, 8587), True, 'import numpy as np\n'), ((9253, 9281), 'numpy.round', 'np.round', (['(2.0 / 11)', 'ROUNDOFF'], {}), '(2.0 / 11, ROUNDOFF)\n', (9261, 9281), True, 'import numpy as np\n'), ((9353, 9381), 'numpy.round', 'np.round', (['(2.0 / 11)', 'ROUNDOFF'], {}), '(2.0 / 11, ROUNDOFF)\n', (9361, 9381), True, 'import numpy as np\n'), ((9457, 9485), 'numpy.round', 'np.round', (['(4.0 / 11)', 'ROUNDOFF'], {}), '(4.0 / 11, ROUNDOFF)\n', (9465, 9485), True, 'import numpy as np\n'), ((9563, 9591), 'numpy.round', 'np.round', (['(4.0 / 11)', 'ROUNDOFF'], {}), '(4.0 / 11, ROUNDOFF)\n', (9571, 9591), True, 'import numpy as np\n'), ((9658, 9686), 'numpy.round', 'np.round', (['(7.0 / 11)', 'ROUNDOFF'], {}), '(7.0 / 11, ROUNDOFF)\n', (9666, 9686), True, 'import numpy as np\n'), ((9759, 9787), 'numpy.round', 'np.round', (['(9.0 / 11)', 'ROUNDOFF'], {}), '(9.0 / 11, ROUNDOFF)\n', (9767, 9787), True, 'import numpy as np\n'), ((9856, 9884), 'numpy.round', 'np.round', (['(1.0 / 11)', 'ROUNDOFF'], {}), '(1.0 / 11, ROUNDOFF)\n', (9864, 9884), True, 'import numpy as np\n'), ((9959, 9987), 'numpy.round', 'np.round', (['(2.0 / 11)', 'ROUNDOFF'], {}), '(2.0 / 11, ROUNDOFF)\n', (9967, 9987), True, 'import numpy as np\n'), ((10831, 10857), 'numpy.round', 'np.round', (['(1 / 11)', 'ROUNDOFF'], {}), '(1 / 11, ROUNDOFF)\n', (10839, 10857), True, 'import numpy as np\n'), ((10921, 10947), 'numpy.round', 'np.round', (['(5 / 11)', 'ROUNDOFF'], {}), '(5 / 11, ROUNDOFF)\n', (10929, 10947), True, 'import numpy as np\n'), ((11011, 11037), 'numpy.round', 'np.round', (['(5 / 11)', 'ROUNDOFF'], {}), '(5 / 11, ROUNDOFF)\n', (11019, 11037), True, 'import numpy as np\n'), ((11101, 11127), 'numpy.round', 'np.round', (['(1 / 11)', 'ROUNDOFF'], {}), '(1 / 11, ROUNDOFF)\n', (11109, 11127), True, 'import numpy as np\n'), ((11191, 11217), 'numpy.round', 'np.round', (['(3 / 11)', 'ROUNDOFF'], {}), '(3 / 11, ROUNDOFF)\n', (11199, 11217), True, 'import numpy as np\n'), ((11280, 11306), 'numpy.round', 'np.round', (['(6 / 11)', 'ROUNDOFF'], {}), '(6 / 11, ROUNDOFF)\n', (11288, 11306), True, 'import numpy as np\n'), ((11369, 11396), 'numpy.round', 'np.round', (['(10 / 11)', 'ROUNDOFF'], {}), '(10 / 11, ROUNDOFF)\n', (11377, 11396), True, 'import numpy as np\n'), ((11460, 11486), 'numpy.round', 'np.round', (['(9 / 11)', 'ROUNDOFF'], {}), '(9 / 11, ROUNDOFF)\n', (11468, 11486), True, 'import numpy as np\n'), ((11552, 11578), 'numpy.round', 'np.round', (['(0 / 11)', 'ROUNDOFF'], {}), '(0 / 11, ROUNDOFF)\n', (11560, 11578), True, 'import numpy as np\n'), ((11645, 11672), 'numpy.round', 'np.round', (['(11 / 11)', 'ROUNDOFF'], {}), '(11 / 11, ROUNDOFF)\n', (11653, 11672), True, 'import numpy as np\n'), ((11742, 11769), 'numpy.round', 'np.round', (['(11 / 11)', 'ROUNDOFF'], {}), '(11 / 11, ROUNDOFF)\n', (11750, 11769), True, 'import numpy as np\n'), ((11839, 11866), 'numpy.round', 'np.round', (['(11 / 11)', 'ROUNDOFF'], {}), '(11 / 11, ROUNDOFF)\n', (11847, 11866), True, 'import numpy as np\n'), ((11935, 11961), 'numpy.round', 'np.round', (['(0 / 11)', 'ROUNDOFF'], {}), '(0 / 11, ROUNDOFF)\n', (11943, 11961), True, 'import numpy as np\n'), ((12030, 12057), 'numpy.round', 'np.round', (['(11 / 11)', 'ROUNDOFF'], {}), '(11 / 11, ROUNDOFF)\n', (12038, 12057), True, 'import numpy as np\n'), ((12125, 12151), 'numpy.round', 'np.round', (['(0 / 11)', 'ROUNDOFF'], {}), '(0 / 11, ROUNDOFF)\n', (12133, 12151), True, 'import numpy as np\n'), ((12220, 12246), 'numpy.round', 'np.round', (['(0 / 11)', 'ROUNDOFF'], {}), '(0 / 11, ROUNDOFF)\n', (12228, 12246), True, 'import numpy as np\n'), ((12973, 13001), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5]'], {}), '([0, 1, 2, 3, 4, 5])\n', (12981, 13001), True, 'import numpy as np\n'), ((14382, 14403), 'pytest.raises', 'pytest.raises', (['raises'], {}), '(raises)\n', (14395, 14403), False, 'import pytest\n'), ((14412, 14472), 'ensemble.ensemble_tools._validate_arg_type', '_validate_arg_type', (['parameter_name', 'parameter', 'expected_type'], {}), '(parameter_name, parameter, expected_type)\n', (14430, 14472), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((7116, 7209), 'ensemble.ensemble_tools._probability_from_members', '_probability_from_members', (['threshold', 'members', 'operator_str', 'presorted', 'positive_definite'], {}), '(threshold, members, operator_str, presorted,\n positive_definite)\n', (7141, 7209), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((7992, 8085), 'ensemble.ensemble_tools._probability_from_members', '_probability_from_members', (['threshold', 'members', 'operator_str', 'presorted', 'positive_definite'], {}), '(threshold, members, operator_str, presorted,\n positive_definite)\n', (8017, 8085), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((8863, 8956), 'ensemble.ensemble_tools._probability_from_members', '_probability_from_members', (['threshold', 'members', 'operator_str', 'presorted', 'positive_definite'], {}), '(threshold, members, operator_str, presorted,\n positive_definite)\n', (8888, 8956), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((10182, 10275), 'ensemble.ensemble_tools._probability_from_members', '_probability_from_members', (['threshold', 'members', 'operator_str', 'presorted', 'positive_definite'], {}), '(threshold, members, operator_str, presorted,\n positive_definite)\n', (10207, 10275), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n'), ((12420, 12490), 'ensemble.ensemble_tools.prob_between_values', 'prob_between_values', (['members', 'lower', 'upper', 'bracket', 'positive_definite'], {}), '(members, lower, upper, bracket, positive_definite)\n', (12439, 12490), False, 'from ensemble.ensemble_tools import _gumbel_cdf, _probability_from_members, probability_from_members, _prob_from_outside_rank_gumbel, _prob_from_outside_rank_exp, _deterministic_event_prob, probability_from_members, prob_between_values, ensemble_verification_rank, _validate_arg_type\n')]
import argparse import numpy as np import os from keras import backend as K from keras.models import load_model import pdb import sys import traceback import matplotlib.pyplot as plt import numpy as np from keras import layers, models, optimizers from keras import backend as K from keras.utils import to_categorical import matplotlib.pyplot as plt from utils import combine_images from PIL import Image from capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask # dimensions of the generated pictures for each filter. img_width = 28 img_height = 28 def CapsNet(input_shape, n_class, routings): """ A Capsule Network on MNIST. :param input_shape: data shape, 3d, [width, height, channels] :param n_class: number of classes :param routings: number of routing iterations :return: Two Keras Models, the first one used for training, and the second one for evaluation. `eval_model` can also be used for training. """ x = layers.Input(shape=input_shape) # Layer 1: Just a conventional Conv2D layer conv1 = layers.Conv2D(filters=256, kernel_size=9, strides=1, padding='valid', activation='relu', name='conv1')(x) # Layer 2: Conv2D layer with `squash` activation, then reshape to [None, num_capsule, dim_capsule] primarycaps = PrimaryCap(conv1, dim_capsule=8, n_channels=32, kernel_size=9, strides=2, padding='valid') # Layer 3: Capsule layer. Routing algorithm works here. digitcaps = CapsuleLayer(num_capsule=n_class, dim_capsule=16, routings=routings, name='digitcaps')(primarycaps) # Layer 4: This is an auxiliary layer to replace each capsule with its length. Just to match the true label's shape. # If using tensorflow, this will not be necessary. :) out_caps = Length(name='capsnet')(digitcaps) # Decoder network. y = layers.Input(shape=(n_class,)) masked_by_y = Mask()([digitcaps, y]) # The true label is used to mask the output of capsule layer. For training masked = Mask()(digitcaps) # Mask using the capsule with maximal length. For prediction # Shared Decoder model in training and prediction decoder = models.Sequential(name='decoder') decoder.add(layers.Dense(512, activation='relu', input_dim=16*n_class)) decoder.add(layers.Dense(1024, activation='relu')) decoder.add(layers.Dense(np.prod(input_shape), activation='sigmoid')) decoder.add(layers.Reshape(target_shape=input_shape, name='out_recon')) # Models for training and evaluation (prediction) train_model = models.Model([x, y], [out_caps, decoder(masked_by_y)]) eval_model = models.Model(x, [out_caps, decoder(masked)]) # manipulate model noise = layers.Input(shape=(n_class, 16)) noised_digitcaps = layers.Add()([digitcaps, noise]) masked_noised_y = Mask()([noised_digitcaps, y]) manipulate_model = models.Model([x, y, noise], decoder(masked_noised_y)) return train_model, eval_model, manipulate_model def get_test(csv): xs = [] with open(csv) as f: f.readline() for l in f: cols = l.split(',') xs.append(list(map(int, cols[1].split()))) return {'x': np.array(xs)} def normalize(x): # utility function to normalize a tensor by its L2 norm return x / (K.sqrt(K.mean(K.square(x))) + 1e-7) def manipulate_latent(model, data, args): print('-'*30 + 'Begin: manipulate' + '-'*30) x_test, y_test = data index = np.argmax(y_test, 1) == args.digit number = np.random.randint(low=0, high=sum(index) - 1) x, y = x_test[index][number], y_test[index][number] x, y = np.expand_dims(x, 0), np.expand_dims(y, 0) noise = np.zeros([1, 10, 16]) x_recons = [] for dim in range(16): for r in [-0.25, -0.2, -0.15, -0.1, -0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25]: tmp = np.copy(noise) tmp[:,:,dim] = r x_recon = model.predict([x, y, tmp]) x_recons.append(x_recon) x_recons = np.concatenate(x_recons) img = combine_images(x_recons, height=16) image = img*255 Image.fromarray(image.astype(np.uint8)).save(args.save_dir + '/manipulate-%d.png' % args.digit) print('manipulated result saved to %s/manipulate-%d.png' % (args.save_dir, args.digit)) print('-' * 30 + 'End: manipulate' + '-' * 30) def load_mnist(): # the data, shuffled and split between train and test sets from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255. x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255. y_train = to_categorical(y_train.astype('float32')) y_test = to_categorical(y_test.astype('float32')) return (x_train, y_train), (x_test, y_test) def main(): n_iter = 100 # load data (x_train, y_train), (x_test, y_test) = load_mnist() # define model model, eval_model, manipulate_model = CapsNet(input_shape=x_train.shape[1:], n_class=len(np.unique(np.argmax(y_train, 1))), routings=3) model.summary() model.load_weights('result/trained_model.h5') layer_dict = dict([layer.name, layer] for layer in model.layers) layer = layer_dict["primarycap_squash"] """ n_filters = layer.filters print() print('layer={}'.format(layer)) print() filter_imgs = [[] for i in range(n_filters)] for ind_filter in range(n_filters): filter_imgs[ind_filter] = np.random.random((1, img_width, img_height, 1)) activation = K.mean(layer.output[:, :, :, ind_filter]) grads = normalize(K.gradients(activation, model.inputs[0])[0]) iterate = K.function([model.inputs[0], K.learning_phase()], [activation, grads]) print('processing filter %d' % ind_filter) for i in range(n_iter): act, g = iterate([filter_imgs[ind_filter], 0]) filter_imgs[ind_filter] += g """ n_filters = 32 filter_imgs = [[] for i in range(n_filters)] for ind_filter in range(n_filters): filter_imgs[ind_filter] = np.random.random((1, img_width, img_height, 1)) #activation = K.mean(layer.output[:, 36*ind_filter:36*(ind_filter+1), :]) activation = K.mean(layer.output[:, ind_filter::36, :]) grads = normalize(K.gradients(activation, model.inputs[0])[0]) iterate = K.function([model.inputs[0], K.learning_phase()], [activation, grads]) print('processing filter %d' % ind_filter) for i in range(n_iter): act, g = iterate([filter_imgs[ind_filter], 0]) filter_imgs[ind_filter] += g fig = plt.figure(figsize=(14, 2 * ind_filter / 16)) for ind_filter in range(n_filters): ax = fig.add_subplot(n_filters / 16 + 1, 16, ind_filter + 1) ax.imshow(filter_imgs[ind_filter].reshape(img_width, img_height), cmap='BuGn') plt.xticks(np.array([])) plt.yticks(np.array([])) plt.xlabel('filter %d' % ind_filter) plt.tight_layout() fig.suptitle('Filters of PrimaryCap') fig.savefig('filters.png') if __name__ == '__main__': try: main() except: type, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb)
[ "capsulelayers.PrimaryCap", "numpy.prod", "keras.layers.Conv2D", "keras.backend.learning_phase", "keras.backend.gradients", "numpy.array", "sys.exc_info", "keras.layers.Dense", "keras.datasets.mnist.load_data", "numpy.random.random", "matplotlib.pyplot.xlabel", "pdb.post_mortem", "keras.back...
[((1003, 1034), 'keras.layers.Input', 'layers.Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (1015, 1034), False, 'from keras import layers, models, optimizers\n'), ((1330, 1424), 'capsulelayers.PrimaryCap', 'PrimaryCap', (['conv1'], {'dim_capsule': '(8)', 'n_channels': '(32)', 'kernel_size': '(9)', 'strides': '(2)', 'padding': '"""valid"""'}), "(conv1, dim_capsule=8, n_channels=32, kernel_size=9, strides=2,\n padding='valid')\n", (1340, 1424), False, 'from capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\n'), ((1899, 1929), 'keras.layers.Input', 'layers.Input', ([], {'shape': '(n_class,)'}), '(shape=(n_class,))\n', (1911, 1929), False, 'from keras import layers, models, optimizers\n'), ((2214, 2247), 'keras.models.Sequential', 'models.Sequential', ([], {'name': '"""decoder"""'}), "(name='decoder')\n", (2231, 2247), False, 'from keras import layers, models, optimizers\n'), ((2766, 2799), 'keras.layers.Input', 'layers.Input', ([], {'shape': '(n_class, 16)'}), '(shape=(n_class, 16))\n', (2778, 2799), False, 'from keras import layers, models, optimizers\n'), ((3765, 3786), 'numpy.zeros', 'np.zeros', (['[1, 10, 16]'], {}), '([1, 10, 16])\n', (3773, 3786), True, 'import numpy as np\n'), ((4087, 4111), 'numpy.concatenate', 'np.concatenate', (['x_recons'], {}), '(x_recons)\n', (4101, 4111), True, 'import numpy as np\n'), ((4125, 4160), 'utils.combine_images', 'combine_images', (['x_recons'], {'height': '(16)'}), '(x_recons, height=16)\n', (4139, 4160), False, 'from utils import combine_images\n'), ((4597, 4614), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (4612, 4614), False, 'from keras.datasets import mnist\n'), ((6950, 6995), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(14, 2 * ind_filter / 16)'}), '(figsize=(14, 2 * ind_filter / 16))\n', (6960, 6995), True, 'import matplotlib.pyplot as plt\n'), ((1099, 1205), 'keras.layers.Conv2D', 'layers.Conv2D', ([], {'filters': '(256)', 'kernel_size': '(9)', 'strides': '(1)', 'padding': '"""valid"""', 'activation': '"""relu"""', 'name': '"""conv1"""'}), "(filters=256, kernel_size=9, strides=1, padding='valid',\n activation='relu', name='conv1')\n", (1112, 1205), False, 'from keras import layers, models, optimizers\n'), ((1501, 1592), 'capsulelayers.CapsuleLayer', 'CapsuleLayer', ([], {'num_capsule': 'n_class', 'dim_capsule': '(16)', 'routings': 'routings', 'name': '"""digitcaps"""'}), "(num_capsule=n_class, dim_capsule=16, routings=routings, name=\n 'digitcaps')\n", (1513, 1592), False, 'from capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\n'), ((1830, 1852), 'capsulelayers.Length', 'Length', ([], {'name': '"""capsnet"""'}), "(name='capsnet')\n", (1836, 1852), False, 'from capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\n'), ((1949, 1955), 'capsulelayers.Mask', 'Mask', ([], {}), '()\n', (1953, 1955), False, 'from capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\n'), ((2062, 2068), 'capsulelayers.Mask', 'Mask', ([], {}), '()\n', (2066, 2068), False, 'from capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\n'), ((2265, 2325), 'keras.layers.Dense', 'layers.Dense', (['(512)'], {'activation': '"""relu"""', 'input_dim': '(16 * n_class)'}), "(512, activation='relu', input_dim=16 * n_class)\n", (2277, 2325), False, 'from keras import layers, models, optimizers\n'), ((2342, 2379), 'keras.layers.Dense', 'layers.Dense', (['(1024)'], {'activation': '"""relu"""'}), "(1024, activation='relu')\n", (2354, 2379), False, 'from keras import layers, models, optimizers\n'), ((2473, 2531), 'keras.layers.Reshape', 'layers.Reshape', ([], {'target_shape': 'input_shape', 'name': '"""out_recon"""'}), "(target_shape=input_shape, name='out_recon')\n", (2487, 2531), False, 'from keras import layers, models, optimizers\n'), ((2824, 2836), 'keras.layers.Add', 'layers.Add', ([], {}), '()\n', (2834, 2836), False, 'from keras import layers, models, optimizers\n'), ((2880, 2886), 'capsulelayers.Mask', 'Mask', ([], {}), '()\n', (2884, 2886), False, 'from capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\n'), ((3259, 3271), 'numpy.array', 'np.array', (['xs'], {}), '(xs)\n', (3267, 3271), True, 'import numpy as np\n'), ((3545, 3565), 'numpy.argmax', 'np.argmax', (['y_test', '(1)'], {}), '(y_test, 1)\n', (3554, 3565), True, 'import numpy as np\n'), ((3709, 3729), 'numpy.expand_dims', 'np.expand_dims', (['x', '(0)'], {}), '(x, 0)\n', (3723, 3729), True, 'import numpy as np\n'), ((3731, 3751), 'numpy.expand_dims', 'np.expand_dims', (['y', '(0)'], {}), '(y, 0)\n', (3745, 3751), True, 'import numpy as np\n'), ((6362, 6409), 'numpy.random.random', 'np.random.random', (['(1, img_width, img_height, 1)'], {}), '((1, img_width, img_height, 1))\n', (6378, 6409), True, 'import numpy as np\n'), ((6515, 6557), 'keras.backend.mean', 'K.mean', (['layer.output[:, ind_filter::36, :]'], {}), '(layer.output[:, ind_filter::36, :])\n', (6521, 6557), True, 'from keras import backend as K\n'), ((7291, 7327), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["('filter %d' % ind_filter)"], {}), "('filter %d' % ind_filter)\n", (7301, 7327), True, 'import matplotlib.pyplot as plt\n'), ((7337, 7355), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (7353, 7355), True, 'import matplotlib.pyplot as plt\n'), ((2411, 2431), 'numpy.prod', 'np.prod', (['input_shape'], {}), '(input_shape)\n', (2418, 2431), True, 'import numpy as np\n'), ((3936, 3950), 'numpy.copy', 'np.copy', (['noise'], {}), '(noise)\n', (3943, 3950), True, 'import numpy as np\n'), ((7234, 7246), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (7242, 7246), True, 'import numpy as np\n'), ((7268, 7280), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (7276, 7280), True, 'import numpy as np\n'), ((7531, 7545), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (7543, 7545), False, 'import sys\n'), ((7555, 7576), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (7574, 7576), False, 'import traceback\n'), ((7586, 7605), 'pdb.post_mortem', 'pdb.post_mortem', (['tb'], {}), '(tb)\n', (7601, 7605), False, 'import pdb\n'), ((6585, 6625), 'keras.backend.gradients', 'K.gradients', (['activation', 'model.inputs[0]'], {}), '(activation, model.inputs[0])\n', (6596, 6625), True, 'from keras import backend as K\n'), ((6678, 6696), 'keras.backend.learning_phase', 'K.learning_phase', ([], {}), '()\n', (6694, 6696), True, 'from keras import backend as K\n'), ((3388, 3399), 'keras.backend.square', 'K.square', (['x'], {}), '(x)\n', (3396, 3399), True, 'from keras import backend as K\n'), ((5208, 5229), 'numpy.argmax', 'np.argmax', (['y_train', '(1)'], {}), '(y_train, 1)\n', (5217, 5229), True, 'import numpy as np\n')]
import numpy as np class MaskRaster(): def __init__(self): self.name = "Mask Raster Function" self.description = "Applies a raster as the NoData mask of the input raster." def getParameterInfo(self): return [ { 'name': 'r', 'dataType': 'raster', 'value': None, 'required': True, 'displayName': "Input Raster", 'description': "The primary input raster." }, { 'name': 'm', 'dataType': 'raster', 'value': None, 'required': True, 'displayName': "Mask Raster", 'description': "The input mask raster." }, ] def getConfiguration(self, **scalars): return { 'inputMask': True } def updatePixels(self, tlc, shape, props, **pixelBlocks): M = np.zeros(shape, 'u1') I = (pixelBlocks['m_pixels'] > 0) & (pixelBlocks['m_mask'] > 0) np.putmask(M, I, 1) pixelBlocks['output_mask'] = M pixelBlocks['output_pixels'] = pixelBlocks['r_pixels'].astype(props['pixelType'], copy=False) return pixelBlocks
[ "numpy.zeros", "numpy.putmask" ]
[((996, 1017), 'numpy.zeros', 'np.zeros', (['shape', '"""u1"""'], {}), "(shape, 'u1')\n", (1004, 1017), True, 'import numpy as np\n'), ((1100, 1119), 'numpy.putmask', 'np.putmask', (['M', 'I', '(1)'], {}), '(M, I, 1)\n', (1110, 1119), True, 'import numpy as np\n')]
from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from .maplabeller import map_labeller, labelfile_reader class MapDesign(object): """Class for holding map design elements.""" def __init__(self, mapcorners, standard_pm, projection='cyl', mapcolor='light', maplabels=None, area_threshold=10000, resolution='c', zborder=14, zlandfill=12, zmapbound=10, zlatlon=11, lat_labels=['left'], lon_labels=['top'], latlon_labelspacing=(10, 20), latlon_fs=20, latlon_spacing=(10, 20), drawstates=False, drawoutlines=True, draw_latlons=True, land_alpha=0.85): """ Initialize ``MapDesign`` instance. Is your map blank? Try changing zmapbound. Parameters ---------- mapcorners : list of floats Used to construct the map view for 'conic' and 'cyl' projections. Lower left longitude, latitude; upper right longitude, latitude. standard_pm : list of floats For cylindrical and conic projections, the list creates standard parallels and meridians (``lon_0``, ``lat_0``, ``lat_1``, ``lat_2``). For orthographic projection, ``lon_0`` and ``lat_0`` only are required. Sets the view from above the earth. For polar projections, ``lon_0`` indicates the longitude that will be oriented N-S. ``lat_0`` is replaced by the ``boundinglat``, the lowest latitude that should appear on the map. ``lat_1`` and ``lat_2`` not required projection : string Indicates map projection. Default 'cyl'. 'cyl' : Equidistant cylindrical 'cea' : Equal Area cylindrical 'lcc' : Lambert Conformal Conic 'aea' : Albers Equal Area Conic 'ortho' : Orthographic (globe) 'npstere' : North polar steroegraphic (conformal) 'spstere' : South polar steroegraphic (conformal) 'nplaea' : North polar azimuthal (equal area) 'splaea' : South polar azimuthal (equal area) mapcolor : string Default 'light'. The map grayscheme. ['light'|'medium'|'dark'|None] Not available for 'ortho' projections maplabels : tuple of strings Default ``None``. (Label group, label file full/relative path, optional: zorder). Label group is a list of any or all of: ['sea', 'city', 'country','ocean','place'] Label zorder defaults to 15. area_threshold : int Default 10000. The minimum surface area a feature must have to be drawn on the map. resolution : char Default 'c'. ['c'|'l'|'i'|'h'|'f']. Crude, low, intermediate, high, full. The relative resolution of map boundaries. Drops off by about 80 percent between datasets. zborder : int Default 14. The zorder of country and coastal outlines. zlandfill : int Default 12. The zorder of the continent fill color. zmapbound : int Default 16. The zorder of the map boundary in older versions of basemap (background correctly put at bottom of stack), and zorder of the ocean/background in newer versions (boundary correctly put at top of stack). Try zmapbound=10 if 16 yields a blank map. zlatlon : int Default 11. The zorder of the lines of latitutde and longitude. lat_labels : list of strings Default ['right']. The sides of the map that should have the latitudes labelled. lon_labels : list of strings Default ['top']. The sides of the map that should have the longitudes labelled. latlon_labelspacing : int or float Default (10, 20). Degrees between (latitude, longitude) labels latlon_fs : int or float Default 20. Font size of latitude, longitude labels. latlonspacing : int or float Default (10, 20). Degrees between plotted lines of latitude. drawstates : Boolean Default False. Draw state outlines on ``Basemap``. drawoutlines : Boolean Default True. Draw country and coastal outlines on ``Basemap``. draw_latlons : Boolean Default True. Draw and label lines of latitude and longitude. land_alpha : float Default 0.85. The alpha value of the continent fill. """ # Initialize self.mapcorners = mapcorners self.standard_pm = standard_pm self.mapcolor = mapcolor self.land_alpha = land_alpha self.coloropts = {'light': {'water': None, 'land': '0.95'}, 'medium': {'water': '0.625', 'land': '0.775'}, 'dark': {'water': '0.3', 'land': '0.75'}} self.area_threshold = area_threshold self.resolution = resolution self.zborder = zborder self.zlandfill = zlandfill self.zmapbound = zmapbound self.zlatlon = zlatlon # Initialize projection self._set_projection(projection) self._set_latlonlabels(lat_labels, lon_labels) self.latlon_fs = latlon_fs self.latspacing = latlon_spacing[0] self.lonspacing = latlon_spacing[1] self.latstep = latlon_labelspacing[0] self.lonstep = latlon_labelspacing[1] self.drawstates = drawstates self.drawoutlines = drawoutlines self.draw_latlons = draw_latlons # Try to set label attributes if maplabels is not None: self.labels, self.labelstyle = labelfile_reader(maplabels[1]) self.labelgroup = maplabels[0] # Label zorder optional, default 15 if none given. try: self.label_zorder = maplabels[2] except: self.label_zorder = 15 else: self.labels = None def _set_latlonlabels(self, lat_labels, lon_labels): """ Edit latitude, longitude labelling preferences. Parameters ---------- lat_labels : list of strings The sides of the map with longitude labels. lon_labels : list of strings The sides of the map with latitude labels. """ meridian_labels = [0, 0, 0, 0] parallel_labels = [0, 0, 0, 0] ind_dict = {'left': 0, 'right': 1, 'top': 2, 'bottom': 3} for la in lat_labels: parallel_labels[ind_dict[la]] = 1 self.parallel_labels = parallel_labels for lo in lon_labels: meridian_labels[ind_dict[lo]] = 1 self.meridian_labels = meridian_labels def _set_projection(self, projection): """ Set the projection. Defaults to 'cyl'. Parameters ---------- projection : string Indicates which projection to use. Default 'cyl' 'cyl' : Equidistant cylindrical 'cea' : Equal Area cylindrical 'lcc' : Lambert Conformal Conic 'aea' : Albers Equal Area Conic 'ortho' : Orthographic (globe) 'npstere' : North polar steroegraphic (conformal) 'spstere' : South polar steroegraphic (conformal) 'nplaea' : North polar azimuthal (equal area) 'splaea' : South polar azimuthal (equal area) """ available_proj = {'cyl': 'Equidistant cylindrical', 'cea': 'Equal Area cylindrical', 'lcc': 'Lambert Conformal Conic', 'aea': 'Albers Equal Area', 'ortho': 'Orthographic', 'npstere': 'North Polar Stereographic', 'spstere': 'South polar steroegraphic', 'nplaea': 'North polar azimuthal', 'splaea': 'South polar azimuthal'} if projection in available_proj: self.projection = projection else: self.projection = 'cyl' print('Projection not recognized, defaulting to `cyl`.') def make_basemap(self, ax=None, figsize=(10, 10)): """ Produce an actual map. Takes the MapDesign attributes plus a figure size and creates a map on which data can be plotted. Parameters ---------- ax : axes instance Default None, figure and axis will be created. Otherwise, basemap will be created on given axis. figsize : tuple of ints Default (10, 10). The size of the figure in inches. Only used if ``ax`` is ``None``. Returns ------- basemap : ``Basemap`` instance A map ready for data plotting. Can access axis and figure via ``basemap.ax`` and ``basemap.ax.get_figure()``, respectively. """ if ax is None: # Create figure instance fig, ax = plt.subplots(1, 1, figsize=figsize) # Labels are left, right, top, bottom meridian_labels = self.meridian_labels parallel_labels = self.parallel_labels if self.projection is 'lcc': # Lambert conformal conic basemap = Basemap(llcrnrlon=self.mapcorners[0], llcrnrlat=self.mapcorners[1], urcrnrlon=self.mapcorners[2], urcrnrlat=self.mapcorners[3], projection='lcc', lat_1=self.standard_pm[2], lat_2=self.standard_pm[3], lon_0=self.standard_pm[0], area_thresh=self.area_threshold, resolution=self.resolution, ax=ax) elif self.projection is 'aea': # Albers equal area conic basemap = Basemap(llcrnrlon=self.mapcorners[0], llcrnrlat=self.mapcorners[1], urcrnrlon=self.mapcorners[2], urcrnrlat=self.mapcorners[3], projection='aea', lat_1=self.standard_pm[2], lat_2=self.standard_pm[3], lon_0=self.standard_pm[0], lat_0=self.standard_pm[1], area_thresh=self.area_threshold, resolution=self.resolution, ax=ax) elif self.projection is 'cea': # equal area cylindrical basemap = Basemap(llcrnrlon=self.mapcorners[0], llcrnrlat=self.mapcorners[1], urcrnrlon=self.mapcorners[2], urcrnrlat=self.mapcorners[3], projection='cea', area_thresh=self.area_threshold, resolution=self.resolution, ax=ax) elif self.projection is 'ortho': # the earth basemap = Basemap(projection='ortho', lon_0=self.standard_pm[0], lat_0=self.standard_pm[1], area_thresh=self.area_threshold, resolution=self.resolution, ax=ax) meridian_labels = [0, 0, 0, 0] parallel_labels = [0, 0, 0, 0] elif self.projection[1:] == 'plaea' or self.projection[1:] == 'pstere': # Polar steroegraphic (conformal) or polar azimuthal(equal-area) basemap = Basemap(projection=self.projection, boundinglat=self.standard_pm[1], lon_0=self.standard_pm[0], area_thresh=self.area_threshold, resolution=self.resolution, ax=ax) else: # Projection is 'cyl', Basemap's default equidist. cyl projection basemap = Basemap(llcrnrlon=self.mapcorners[0], llcrnrlat=self.mapcorners[1], urcrnrlon=self.mapcorners[2], urcrnrlat=self.mapcorners[3], area_thresh=self.area_threshold, resolution=self.resolution, ax=ax) # Draw labels if self.labels is not None: map_labeller(basemap, self.labelgroup, self.labels, self.labelstyle, self.label_zorder) # Draw countries, states, coastlines, and map boundary if self.drawstates: basemap.drawstates(zorder=self.zborder) if self.drawoutlines: basemap.drawcountries(zorder=self.zborder) basemap.drawcoastlines(zorder=self.zborder) if self.draw_latlons: lat = -90 if self.latstep == 20: lat = -80 # Draw and label lines of longitude if self.lonstep > self.lonspacing: basemap.drawmeridians(np.arange(-180, 180, self.lonspacing), labels=[0, 0, 0, 0], zorder=self.zlatlon) basemap.drawmeridians(np.arange(-180, 180, self.lonstep), labels=meridian_labels, zorder=self.zlatlon, fontsize=self.latlon_fs) else: basemap.drawmeridians(np.arange(-180, 180, self.lonstep), labels=meridian_labels, zorder=self.zlatlon, fontsize=self.latlon_fs) # Draw and label lines of latitude if self.latstep > self.latspacing: basemap.drawparallels(np.arange(-90, 90, self.latspacing), labels=[0, 0, 0, 0], zorder=self.zlatlon) basemap.drawparallels(np.arange(lat, 90, self.latstep), labels=parallel_labels, zorder=self.zlatlon, fontsize=self.latlon_fs) else: basemap.drawparallels(np.arange(lat, 90, self.latstep), labels=parallel_labels, zorder=self.zlatlon, fontsize=self.latlon_fs) # Map color defaults to white for ortho projection if self.mapcolor is not None: if self.projection is not 'ortho': colors = self.coloropts[self.mapcolor] basemap.drawmapboundary(zorder=self.zmapbound, fill_color=colors['water']) basemap.fillcontinents(color=colors['land'], zorder=self.zlandfill, alpha=0.85, lake_color=colors['water']) else: basemap.fillcontinents(color='0.99', zorder=self.zlandfill, alpha=0.85) return basemap
[ "mpl_toolkits.basemap.Basemap", "matplotlib.pyplot.subplots", "numpy.arange" ]
[((9475, 9510), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (9487, 9510), True, 'import matplotlib.pyplot as plt\n'), ((9750, 10063), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'llcrnrlon': 'self.mapcorners[0]', 'llcrnrlat': 'self.mapcorners[1]', 'urcrnrlon': 'self.mapcorners[2]', 'urcrnrlat': 'self.mapcorners[3]', 'projection': '"""lcc"""', 'lat_1': 'self.standard_pm[2]', 'lat_2': 'self.standard_pm[3]', 'lon_0': 'self.standard_pm[0]', 'area_thresh': 'self.area_threshold', 'resolution': 'self.resolution', 'ax': 'ax'}), "(llcrnrlon=self.mapcorners[0], llcrnrlat=self.mapcorners[1],\n urcrnrlon=self.mapcorners[2], urcrnrlat=self.mapcorners[3], projection=\n 'lcc', lat_1=self.standard_pm[2], lat_2=self.standard_pm[3], lon_0=self\n .standard_pm[0], area_thresh=self.area_threshold, resolution=self.\n resolution, ax=ax)\n", (9757, 10063), False, 'from mpl_toolkits.basemap import Basemap\n'), ((10445, 10785), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'llcrnrlon': 'self.mapcorners[0]', 'llcrnrlat': 'self.mapcorners[1]', 'urcrnrlon': 'self.mapcorners[2]', 'urcrnrlat': 'self.mapcorners[3]', 'projection': '"""aea"""', 'lat_1': 'self.standard_pm[2]', 'lat_2': 'self.standard_pm[3]', 'lon_0': 'self.standard_pm[0]', 'lat_0': 'self.standard_pm[1]', 'area_thresh': 'self.area_threshold', 'resolution': 'self.resolution', 'ax': 'ax'}), "(llcrnrlon=self.mapcorners[0], llcrnrlat=self.mapcorners[1],\n urcrnrlon=self.mapcorners[2], urcrnrlat=self.mapcorners[3], projection=\n 'aea', lat_1=self.standard_pm[2], lat_2=self.standard_pm[3], lon_0=self\n .standard_pm[0], lat_0=self.standard_pm[1], area_thresh=self.\n area_threshold, resolution=self.resolution, ax=ax)\n", (10452, 10785), False, 'from mpl_toolkits.basemap import Basemap\n'), ((11196, 11418), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'llcrnrlon': 'self.mapcorners[0]', 'llcrnrlat': 'self.mapcorners[1]', 'urcrnrlon': 'self.mapcorners[2]', 'urcrnrlat': 'self.mapcorners[3]', 'projection': '"""cea"""', 'area_thresh': 'self.area_threshold', 'resolution': 'self.resolution', 'ax': 'ax'}), "(llcrnrlon=self.mapcorners[0], llcrnrlat=self.mapcorners[1],\n urcrnrlon=self.mapcorners[2], urcrnrlat=self.mapcorners[3], projection=\n 'cea', area_thresh=self.area_threshold, resolution=self.resolution, ax=ax)\n", (11203, 11418), False, 'from mpl_toolkits.basemap import Basemap\n'), ((13823, 13860), 'numpy.arange', 'np.arange', (['(-180)', '(180)', 'self.lonspacing'], {}), '(-180, 180, self.lonspacing)\n', (13832, 13860), True, 'import numpy as np\n'), ((13980, 14014), 'numpy.arange', 'np.arange', (['(-180)', '(180)', 'self.lonstep'], {}), '(-180, 180, self.lonstep)\n', (13989, 14014), True, 'import numpy as np\n'), ((14256, 14290), 'numpy.arange', 'np.arange', (['(-180)', '(180)', 'self.lonstep'], {}), '(-180, 180, self.lonstep)\n', (14265, 14290), True, 'import numpy as np\n'), ((14610, 14645), 'numpy.arange', 'np.arange', (['(-90)', '(90)', 'self.latspacing'], {}), '(-90, 90, self.latspacing)\n', (14619, 14645), True, 'import numpy as np\n'), ((14765, 14797), 'numpy.arange', 'np.arange', (['lat', '(90)', 'self.latstep'], {}), '(lat, 90, self.latstep)\n', (14774, 14797), True, 'import numpy as np\n'), ((15039, 15071), 'numpy.arange', 'np.arange', (['lat', '(90)', 'self.latstep'], {}), '(lat, 90, self.latstep)\n', (15048, 15071), True, 'import numpy as np\n'), ((11708, 11867), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""ortho"""', 'lon_0': 'self.standard_pm[0]', 'lat_0': 'self.standard_pm[1]', 'area_thresh': 'self.area_threshold', 'resolution': 'self.resolution', 'ax': 'ax'}), "(projection='ortho', lon_0=self.standard_pm[0], lat_0=self.\n standard_pm[1], area_thresh=self.area_threshold, resolution=self.\n resolution, ax=ax)\n", (11715, 11867), False, 'from mpl_toolkits.basemap import Basemap\n'), ((12275, 12448), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': 'self.projection', 'boundinglat': 'self.standard_pm[1]', 'lon_0': 'self.standard_pm[0]', 'area_thresh': 'self.area_threshold', 'resolution': 'self.resolution', 'ax': 'ax'}), '(projection=self.projection, boundinglat=self.standard_pm[1], lon_0=\n self.standard_pm[0], area_thresh=self.area_threshold, resolution=self.\n resolution, ax=ax)\n', (12282, 12448), False, 'from mpl_toolkits.basemap import Basemap\n'), ((12704, 12908), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'llcrnrlon': 'self.mapcorners[0]', 'llcrnrlat': 'self.mapcorners[1]', 'urcrnrlon': 'self.mapcorners[2]', 'urcrnrlat': 'self.mapcorners[3]', 'area_thresh': 'self.area_threshold', 'resolution': 'self.resolution', 'ax': 'ax'}), '(llcrnrlon=self.mapcorners[0], llcrnrlat=self.mapcorners[1],\n urcrnrlon=self.mapcorners[2], urcrnrlat=self.mapcorners[3], area_thresh\n =self.area_threshold, resolution=self.resolution, ax=ax)\n', (12711, 12908), False, 'from mpl_toolkits.basemap import Basemap\n')]
import numpy as np from numba import njit from tardis.montecarlo.montecarlo_numba import njit_dict_no_parallel from tardis.energy_input.util import ( doppler_gamma, solve_quadratic_equation, C_CGS, ) @njit(**njit_dict_no_parallel) def calculate_distance_radial(photon, r_inner, r_outer): """ Calculates 3D distance to shell from gamma ray position Parameters ---------- photon : GXPhoton object r_inner : float r_outer : float Returns ------- distance : float """ # solve the quadratic distance equation for the inner and # outer shell boundaries inner_1, inner_2 = solve_quadratic_equation( photon.location, photon.direction, r_inner ) outer_1, outer_2 = solve_quadratic_equation( photon.location, photon.direction, r_outer ) final_position_inner_1 = photon.location + photon.direction * inner_1 final_position_inner_2 = photon.location + photon.direction * inner_2 final_position_outer_1 = photon.location + photon.direction * outer_1 final_position_outer_2 = photon.location + photon.direction * outer_2 if np.dot(final_position_inner_1, photon.direction) > 0: inner_1 = -1 if np.dot(final_position_inner_2, photon.direction) > 0: inner_2 = -1 if np.dot(final_position_outer_1, photon.direction) < 0: outer_1 = -1 if np.dot(final_position_outer_2, photon.direction) < 0: outer_2 = -1 distances = np.array([inner_1, inner_2, outer_1, outer_2]) # the correct distance is the shortest positive distance distance_list = [i for i in distances if i > 0] if not distance_list: print(photon.get_location_r() - r_inner) print(photon.get_location_r() - r_outer) print(photon.get_location_r()) print(photon.location, photon.direction, r_inner, r_outer) print(distances) print(photon.shell) raise ValueError("No root found for distance calculation!") shortest = min(distance_list) shell_change = 1 if shortest == (inner_1 or inner_2): shell_change = -1 return shortest, shell_change @njit(**njit_dict_no_parallel) def distance_trace( photon, inner_velocity, outer_velocity, total_opacity, current_time, next_time, ): """ Traces distance traveled by gamma ray and finds distance to next interaction and boundary Parameters ---------- photon : GXPhoton object inner_velocity : One dimensional Numpy array, dtype float outer_velocity : One dimensional Numpy array, dtype float total_opacity : float current_time : float next_time : float Returns ------- distance_interaction : float distance_boundary : float distance_time : float shell_change : int """ distance_boundary, shell_change = calculate_distance_radial( photon, inner_velocity[photon.shell] * current_time, outer_velocity[photon.shell] * current_time, ) distance_interaction = photon.tau / total_opacity distance_time = (next_time - photon.time_current) * C_CGS return distance_interaction, distance_boundary, distance_time, shell_change @njit(**njit_dict_no_parallel) def move_packet(packet, distance): """ Moves packet a distance along its direction vector Parameters ---------- packet : GXPacket object distance : float Returns ------- packet : GXPacket object """ location_old = packet.location direction = packet.direction location_new = location_old + distance * direction packet.location = location_new doppler_factor = doppler_gamma( packet.direction, packet.location, packet.time_current ) packet.nu_cmf = packet.nu_rf * doppler_factor packet.energy_cmf = packet.energy_rf * doppler_factor return packet
[ "tardis.energy_input.util.solve_quadratic_equation", "numba.njit", "numpy.array", "numpy.dot", "tardis.energy_input.util.doppler_gamma" ]
[((216, 245), 'numba.njit', 'njit', ([], {}), '(**njit_dict_no_parallel)\n', (220, 245), False, 'from numba import njit\n'), ((2148, 2177), 'numba.njit', 'njit', ([], {}), '(**njit_dict_no_parallel)\n', (2152, 2177), False, 'from numba import njit\n'), ((3206, 3235), 'numba.njit', 'njit', ([], {}), '(**njit_dict_no_parallel)\n', (3210, 3235), False, 'from numba import njit\n'), ((641, 709), 'tardis.energy_input.util.solve_quadratic_equation', 'solve_quadratic_equation', (['photon.location', 'photon.direction', 'r_inner'], {}), '(photon.location, photon.direction, r_inner)\n', (665, 709), False, 'from tardis.energy_input.util import doppler_gamma, solve_quadratic_equation, C_CGS\n'), ((747, 815), 'tardis.energy_input.util.solve_quadratic_equation', 'solve_quadratic_equation', (['photon.location', 'photon.direction', 'r_outer'], {}), '(photon.location, photon.direction, r_outer)\n', (771, 815), False, 'from tardis.energy_input.util import doppler_gamma, solve_quadratic_equation, C_CGS\n'), ((1473, 1519), 'numpy.array', 'np.array', (['[inner_1, inner_2, outer_1, outer_2]'], {}), '([inner_1, inner_2, outer_1, outer_2])\n', (1481, 1519), True, 'import numpy as np\n'), ((3660, 3729), 'tardis.energy_input.util.doppler_gamma', 'doppler_gamma', (['packet.direction', 'packet.location', 'packet.time_current'], {}), '(packet.direction, packet.location, packet.time_current)\n', (3673, 3729), False, 'from tardis.energy_input.util import doppler_gamma, solve_quadratic_equation, C_CGS\n'), ((1135, 1183), 'numpy.dot', 'np.dot', (['final_position_inner_1', 'photon.direction'], {}), '(final_position_inner_1, photon.direction)\n', (1141, 1183), True, 'import numpy as np\n'), ((1217, 1265), 'numpy.dot', 'np.dot', (['final_position_inner_2', 'photon.direction'], {}), '(final_position_inner_2, photon.direction)\n', (1223, 1265), True, 'import numpy as np\n'), ((1299, 1347), 'numpy.dot', 'np.dot', (['final_position_outer_1', 'photon.direction'], {}), '(final_position_outer_1, photon.direction)\n', (1305, 1347), True, 'import numpy as np\n'), ((1381, 1429), 'numpy.dot', 'np.dot', (['final_position_outer_2', 'photon.direction'], {}), '(final_position_outer_2, photon.direction)\n', (1387, 1429), True, 'import numpy as np\n')]
# --------------------------- Sentiment analysis death and not death -------------------------------- import string import re import numpy as np from os import listdir from nltk.corpus import stopwords from keras.preprocessing.text import Tokenizer from keras.utils.vis_utils import plot_model from keras.models import Sequential from keras.layers import Dense # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # turn a doc into clean tokens def clean_doc(doc): # split into tokens by white space tokens = doc.split() # prepare regex for char filtering re_punc = re.compile('[%s]' % re.escape(string.punctuation)) # remove punctuation from each word tokens = [re_punc.sub('', w) for w in tokens] # remove remaining tokens that are not alphabetic tokens = [word for word in tokens if word.isalpha()] # filter out stop words stop_words = set(stopwords.words('english')) tokens = [w for w in tokens if not w in stop_words] # filter out short tokens tokens = [word for word in tokens if len(word) > 1] return tokens # load doc, clean and return line of tokens def doc_to_line(filename, vocab): # load the doc doc = load_doc(filename) # clean doc tokens = clean_doc(doc) # filter by vocab tokens = [w for w in tokens if w in vocab] return ' '.join(tokens) # load all docs in a directory def process_docs(directory, vocab): lines = list() # walk through all files in the folder for filename in listdir(directory): # create the full path of the file to open path = directory + '/' + filename # load and clean the doc line = doc_to_line(path, vocab) # add to list lines.append(line) return lines # load and clean a dataset def load_clean_dataset(vocab): # load documents pneu = process_docs('death', vocab) coro = process_docs('notdeath', vocab) docs = pneu + coro # prepare labels labels = [0 for _ in range(len(pneu))] + [1 for _ in range(len(coro))] return docs, labels # fit a tokenizer def create_tokenizer(lines): tokenizer = Tokenizer() tokenizer.fit_on_texts(lines) return tokenizer # define the model def define_model(n_words): # define network model = Sequential() model.add(Dense(50, input_shape=(n_words,), activation='relu')) model.add(Dense(64, input_shape=(n_words,), activation='relu')) model.add(Dense(1, activation='sigmoid')) # compile network model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # summarize defined model model.summary() plot_model(model, to_file='model.png', show_shapes=True) return model # classify a death or not from brief hospital course def predict_sentiment(review, vocab, tokenizer, model): # clean tokens = clean_doc(review) # filter by vocab tokens = [w for w in tokens if w in vocab] # convert to line line = ' '.join(tokens) # encode encoded = tokenizer.texts_to_matrix([line], mode='binary') # predict sentiment yhat = model.predict(encoded, verbose=0) # retrieve predicted percentage and label percent_of = yhat[0,0] if round(percent_of) == 0: return 1-(percent_of*0.8), 'Death' return percent_of*1.2, 'Not Death' # load the vocabulary vocab_filename = 'vocab.txt' vocab = load_doc(vocab_filename) vocab = set(vocab.split()) # load all data train_docs, ytrain = load_clean_dataset(vocab) test_docs, ytest = load_clean_dataset(vocab) # create the tokenizer tokenizer = create_tokenizer(train_docs) # encode data Xtrain = tokenizer.texts_to_matrix(train_docs, mode='binary') Xtest = tokenizer.texts_to_matrix(test_docs, mode='binary') # define network n_words = Xtrain.shape[1] model = define_model(n_words) # change to np array Xtrain = np.array(Xtrain) ytrain = np.array(ytrain) # fit network model.fit(Xtrain, ytrain, epochs=200, verbose=2) # test death text = 'Example text for death class.' percent, sentiment = predict_sentiment(text, vocab, tokenizer, model) print('Review: [%s]\nSentiment: %s (%.3f%%)' % (text, sentiment, percent*100)) # test not death text = 'Example text for not death class.' percent, sentiment = predict_sentiment(text, vocab, tokenizer, model) print('Review: [%s]\nSentiment: %s (%.3f%%)' % (text, sentiment, percent*100))
[ "re.escape", "os.listdir", "keras.preprocessing.text.Tokenizer", "nltk.corpus.stopwords.words", "keras.utils.vis_utils.plot_model", "keras.models.Sequential", "numpy.array", "keras.layers.Dense" ]
[((3964, 3980), 'numpy.array', 'np.array', (['Xtrain'], {}), '(Xtrain)\n', (3972, 3980), True, 'import numpy as np\n'), ((3990, 4006), 'numpy.array', 'np.array', (['ytrain'], {}), '(ytrain)\n', (3998, 4006), True, 'import numpy as np\n'), ((1643, 1661), 'os.listdir', 'listdir', (['directory'], {}), '(directory)\n', (1650, 1661), False, 'from os import listdir\n'), ((2263, 2274), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {}), '()\n', (2272, 2274), False, 'from keras.preprocessing.text import Tokenizer\n'), ((2409, 2421), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2419, 2421), False, 'from keras.models import Sequential\n'), ((2766, 2822), 'keras.utils.vis_utils.plot_model', 'plot_model', (['model'], {'to_file': '"""model.png"""', 'show_shapes': '(True)'}), "(model, to_file='model.png', show_shapes=True)\n", (2776, 2822), False, 'from keras.utils.vis_utils import plot_model\n'), ((1039, 1065), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (1054, 1065), False, 'from nltk.corpus import stopwords\n'), ((2436, 2488), 'keras.layers.Dense', 'Dense', (['(50)'], {'input_shape': '(n_words,)', 'activation': '"""relu"""'}), "(50, input_shape=(n_words,), activation='relu')\n", (2441, 2488), False, 'from keras.layers import Dense\n'), ((2504, 2556), 'keras.layers.Dense', 'Dense', (['(64)'], {'input_shape': '(n_words,)', 'activation': '"""relu"""'}), "(64, input_shape=(n_words,), activation='relu')\n", (2509, 2556), False, 'from keras.layers import Dense\n'), ((2572, 2602), 'keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""sigmoid"""'}), "(1, activation='sigmoid')\n", (2577, 2602), False, 'from keras.layers import Dense\n'), ((758, 787), 're.escape', 're.escape', (['string.punctuation'], {}), '(string.punctuation)\n', (767, 787), False, 'import re\n')]
from __future__ import print_function import keras from keras.models import Sequential, Model, load_model from keras import backend as K import tensorflow as tf import isolearn.keras as iso import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from keras.utils import plot_model import time from aparent.predictor import * ################################################## #import bioPython for working with FASTA files from Bio import SeqIO ################################################## aparent_model = load_model('./saved_models/aparent_large_lessdropout_all_libs_no_sampleweights.h5') #plot_model(aparent_model, show_shapes = True, to_file='APARENTmodel.png') aparent_encoder = get_aparent_encoder(lib_bias=4) #def openForwardReverse(stem, name): # totalNameFor = stem + name + ".npy" # print (totalNameFor) # forward = np.load(totalNameFor) # reverse = np.load(stem + name + "RC.npy") # return forward, reverse def openTrueValuesForTypeAndCount(name, pasType): #opening all the true values from PolyASite2.0 colnames = ["seqName", "start" , "end", "clusterID", "avgTPM", "strand", "percentSupporting", "protocolsSupporting", "avgTPM2", "type", "upstreamClusters"] pas_stuff =pd.read_csv('atlas.clusters.hg38.2-0.bed',delimiter='\t', names = colnames, dtype = {"seqName": str}) trueValBoolMask = pas_stuff['seqName'] == name #print (name) currentTrueVals = pas_stuff[trueValBoolMask] #filtered true vals #print (currentTrueVals) #set up true value array clustersForward = {} clustersRC = {} #key of (Start, End) will use to track clusters with no peaks for the FN totalLength = 0 if pasType == "All": for index, row in currentTrueVals.iterrows(): if row['strand'] == "+": #forward strand clustersForward[(row['start'], row['end'])] = [] totalLength += row['end']-row['start'] + 1 else: #negative strand, RC cluster clustersRC[(row['start'], row['end'])] = [] clustersForward['Unplaced'] = [] clustersRC['Unplaced'] = [] else: maskType = currentTrueVals["type"] == pasType maskedTrue = currentTrueVals[maskType] for index, row in maskedTrue.iterrows(): if row['strand'] == "+": #forward strand clustersForward[(row['start'], row['end'])] = [] else: #negative strand, RC cluster clustersRC[(row['start'], row['end'])] = [] clustersForward['Unplaced'] = [] clustersRC['Unplaced'] = [] #print (clustersForward) return clustersForward, clustersRC, totalLength, len(clustersForward.keys()) #https://stackoverflow.com/questions/1713335/peak-finding-algorithm-for-python-scipy #https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2631518/ # https://ggbaker.ca/data-science/content/filtering.html #https://ggbaker.ca/data-science/content/filtering.html #choose several filters from scipy.signal filters #find peaks off of these filtered signals #using this resource: testing smoothed vs not-smoothed for a few differnet smoothing methods, then signal prominence thresholding with different windows (size to use is waht????) #vary none, smooth method 1, smooth method 2, smooth method 3, ..... #Vary prominence adnd min height cut offs.... # #open forward and reverse predictions types = ['All'] #for each type and subtype #types = ['AU', 'AE'] tolerances = [0, 10, 20] #tolerances around clusters dists = [50] #for peak finding algorithm minHeights = np.linspace(0,1.0,20) #skip 0 because it's going to be bad runtime wise min_dist = 50 peak_prom = (0.01, None) iterations = {} largestF1 = float('-inf') bestSettings = "" fileNames = ["chr15", "chr18", "chr19", "chr21", "chr22", "chrX", "chrY"] names = ["15", "18", "19", "21", "22", "X", "Y"] minHeights = [0.01, 0.05, 0.1] tolerances = [0, 10, 20] #tolerances around clusters dists = [25, 50] #for peak finding algorithm #skip 0 because it's going to be bad runtime wise peak_prom = (0.01, None) #dictionary set up for pasType in types: iterations[pasType] = {} for tolerance in tolerances: for dist in dists: iterations[pasType][(tolerance,dist)] = [] stem = "./chromosomePredictions50/" fastaDestination = "./fastas/" name = "Y" nameStem = "chrY" min_height = 0.01 totalPAS = 0 totalPASLength = 0 totalSeqLen = 0 pasTypeTotals = {} for pasType in types: counterTypes = 0 for i, fname in enumerate(fileNames): #add overall types to iterations: #forward, reverse = openForwardReverse(stem, fname) contigSeq = SeqIO.read(fastaDestination + fname + ".fasta", "fasta") seq = contigSeq.seq #actual genomic sequence from the file rcseq = contigSeq.reverse_complement() print ("-------------------------------------------------------------") print ("Chromosome: ", names[i], " PAS Type: ", pasType) print ("length: ", len(seq)) totalSeqLen += 2 * len(seq) clustersForward, clustersRC, countLen, countSites = openTrueValuesForTypeAndCount(names[i], pasType) print ("Forward size: ", len(clustersForward.keys()) - 1) print ("Reverse size: ", len(clustersRC.keys()) -1 ) print ("All signals: ", len(clustersForward.keys()) + len(clustersRC.keys())- 2) totalPAS += len(clustersForward.keys()) + len(clustersRC.keys()) totalPASLength += countLen print ("total PAS sites: ", totalPAS) print ("total length of all sites: ", totalPASLength) print ("Length of sequence: ", totalSeqLen) print ("PAS fraction tol 0: ", totalPASLength/totalSeqLen) print ("with tolerance of 10: ", (totalPAS * 20 + totalPASLength)/totalSeqLen) print ("With tolerance of 20: ", (totalPAS * 40 + totalPASLength)/totalSeqLen)
[ "numpy.linspace", "keras.models.load_model", "Bio.SeqIO.read", "pandas.read_csv" ]
[((566, 654), 'keras.models.load_model', 'load_model', (['"""./saved_models/aparent_large_lessdropout_all_libs_no_sampleweights.h5"""'], {}), "(\n './saved_models/aparent_large_lessdropout_all_libs_no_sampleweights.h5')\n", (576, 654), False, 'from keras.models import Sequential, Model, load_model\n'), ((3399, 3422), 'numpy.linspace', 'np.linspace', (['(0)', '(1.0)', '(20)'], {}), '(0, 1.0, 20)\n', (3410, 3422), True, 'import numpy as np\n'), ((1261, 1363), 'pandas.read_csv', 'pd.read_csv', (['"""atlas.clusters.hg38.2-0.bed"""'], {'delimiter': '"""\t"""', 'names': 'colnames', 'dtype': "{'seqName': str}"}), "('atlas.clusters.hg38.2-0.bed', delimiter='\\t', names=colnames,\n dtype={'seqName': str})\n", (1272, 1363), True, 'import pandas as pd\n'), ((4432, 4488), 'Bio.SeqIO.read', 'SeqIO.read', (["(fastaDestination + fname + '.fasta')", '"""fasta"""'], {}), "(fastaDestination + fname + '.fasta', 'fasta')\n", (4442, 4488), False, 'from Bio import SeqIO\n')]
#%% import numpy as np from kdg.utils import generate_gaussian_parity, generate_ellipse, generate_spirals, generate_sinewave, generate_polynomial from kdg.utils import plot_2dsim from kdg import kdf import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from scipy.io import savemat, loadmat # %% n_samples = 1e4 X, y = {}, {} #%% X['gxor'], y['gxor'] = generate_gaussian_parity(n_samples) X['spiral'], y['spiral'] = generate_spirals(n_samples) X['circle'], y['circle'] = generate_ellipse(n_samples) X['sine'], y['sine'] = generate_sinewave(n_samples) X['poly'], y['poly'] = generate_polynomial(n_samples, a=[1,3]) #%% sns.set_context('talk') fig, ax = plt.subplots(6,5, figsize=(40,48), sharex=True) title_size = 45 ticksize = 30 plot_2dsim(X['gxor'], y['gxor'], ax=ax[0][0]) ax[0][0].set_ylabel('Simulation Data', fontsize=title_size-5) ax[0][0].set_xlim([-2,2]) ax[0][0].set_ylim([-2,2]) ax[0][0].set_xticks([]) ax[0][0].set_yticks([-2,-1,0,1,2]) ax[0][0].tick_params(labelsize=ticksize) ax[0][0].set_title('Gaussian XOR', fontsize=title_size) plot_2dsim(X['spiral'], y['spiral'], ax=ax[0][1]) ax[0][1].set_xlim([-2,2]) ax[0][1].set_ylim([-2,2]) ax[0][1].set_xticks([]) ax[0][1].set_yticks([]) ax[0][1].tick_params(labelsize=ticksize) ax[0][1].set_title('Spiral', fontsize=title_size) plot_2dsim(X['circle'], y['circle'], ax=ax[0][2]) ax[0][2].set_xlim([-2,2]) ax[0][2].set_ylim([-2,2]) ax[0][2].set_xticks([]) ax[0][2].set_yticks([]) ax[0][2].tick_params(labelsize=ticksize) ax[0][2].set_title('Circle', fontsize=title_size) plot_2dsim(X['sine'], y['sine'], ax=ax[0][3]) ax[0][3].set_xlim([-2,2]) ax[0][3].set_ylim([-2,2]) ax[0][3].set_xticks([]) ax[0][3].set_yticks([]) ax[0][3].tick_params(labelsize=ticksize) ax[0][3].set_title('Sinewave', fontsize=title_size) plot_2dsim(X['poly'], y['poly'], ax=ax[0][4]) ax[0][4].set_xlim([-2,2]) ax[0][4].set_ylim([-2,2]) ax[0][4].set_xticks([]) ax[0][4].set_yticks([]) ax[0][4].tick_params(labelsize=ticksize) ax[0][4].set_title('Polynomial', fontsize=title_size) ################################################ #define grids p = np.arange(-2, 2, step=0.01) q = np.arange(-2, 2, step=0.01) xx, yy = np.meshgrid(p, q) # get true posterior tp_df = pd.read_csv("true_posterior/Gaussian_xor_pdf.csv") proba_true = 0.5*np.ones((400, 400)) tmp = np.array([tp_df["posterior"][x] for x in range(40000)]) tmp = tmp.reshape(200, 200) proba_true[100:300, 100:300] = tmp ax0 = ax[1][0].imshow( proba_true, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) #ax[1][0].set_title("True Class Posteriors", fontsize=24) ax[1][0].set_aspect("equal") ax[1][0].tick_params(labelsize=ticksize) ax[1][0].set_yticks([-2,-1,0,1,2]) ax[1][0].set_xticks([]) ax[1][0].set_ylabel('True Posteriors',fontsize=title_size-5) tp_df = pd.read_csv("true_posterior/spiral_pdf.csv") proba_true = 0.5*np.ones((400, 400)) tmp = np.array([tp_df["posterior"][x] for x in range(40000)]) tmp = tmp.reshape(200, 200) proba_true[100:300, 100:300] = 1 - tmp ax0 = ax[1][1].imshow( np.flip(proba_true, axis=0), extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) #ax[1][1].set_title("True Class Posteriors", fontsize=24) ax[1][1].set_aspect("equal") ax[1][1].tick_params(labelsize=ticksize) ax[1][1].set_yticks([]) ax[1][1].set_xticks([]) tp_df = pd.read_csv("true_posterior/ellipse_pdf.csv") proba_true = 0.5*np.ones((400, 400)) tmp = np.array([tp_df["posterior"][x] for x in range(40000)]) tmp = tmp.reshape(200, 200) proba_true[100:300, 100:300] = tmp ax0 = ax[1][2].imshow( proba_true, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) #ax[1][2].set_title("True Class Posteriors", fontsize=24) ax[1][2].set_aspect("equal") ax[1][2].tick_params(labelsize=ticksize) ax[1][2].set_yticks([]) ax[1][2].set_xticks([]) tp_df = pd.read_csv("true_posterior/sinewave_pdf.csv") proba_true = 0.5*np.ones((400, 400)) tmp = np.array([tp_df["posterior"][x] for x in range(40000)]) tmp = np.flip(tmp.reshape(200, 200),axis=0) proba_true[100:300, 100:300] = tmp ax0 = ax[1][3].imshow( proba_true, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) #ax[1][3].set_title("True Class Posteriors", fontsize=24) ax[1][3].set_aspect("equal") ax[1][3].tick_params(labelsize=ticksize) ax[1][3].set_yticks([]) ax[1][3].set_xticks([]) tp_df = pd.read_csv("true_posterior/polynomial_pdf.csv") proba_true = 0.5*np.ones((400, 400)) tmp = np.array([tp_df["posterior"][x] for x in range(40000)]) tmp = np.flip(tmp.reshape(200, 200),axis=0) proba_true[100:300, 100:300] = tmp ax0 = ax[1][4].imshow( proba_true, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) #ax[1][4].set_title("True Class Posteriors", fontsize=24) ax[1][4].set_aspect("equal") ax[1][4].tick_params(labelsize=ticksize) ax[1][4].set_yticks([]) ax[1][4].set_xticks([]) ######################################################### df = loadmat('kdf_experiments/results/gxor_plot_data.mat') ax1 = ax[2][0].imshow( df['posterior_rf'], extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[2][0].set_ylabel("RF Posteriors", fontsize=title_size-5) ax[2][0].set_aspect("equal") ax[2][0].tick_params(labelsize=ticksize) ax[2][0].set_yticks([-2,-1,0,1,2]) ax[2][0].set_xticks([]) ax1 = ax[3][0].imshow( df['posterior_kdf'], extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[3][0].set_ylabel('KDF Posteriors', fontsize=title_size-5) ax[3][0].set_aspect("equal") ax[3][0].tick_params(labelsize=ticksize) ax[3][0].set_yticks([-2,-1,0,1,2]) ax[3][0].set_xticks([]) ############################################ df = loadmat('kdf_experiments/results/spiral_plot_data.mat') ax1 = ax[2][1].imshow( 1-np.flip(df['posterior_rf'],axis=0), extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[2][1].set_aspect("equal") ax[2][1].tick_params(labelsize=ticksize) ax[2][1].set_yticks([]) ax[2][1].set_xticks([]) ax1 = ax[3][1].imshow( 1-np.flip(df['posterior_kdf'],axis=0), extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[3][1].set_aspect("equal") ax[3][1].tick_params(labelsize=ticksize) ax[3][1].set_yticks([]) ax[3][1].set_xticks([]) ############################################# df = loadmat('kdf_experiments/results/circle_plot_data.mat') ax1 = ax[2][2].imshow( df['posterior_rf'], extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[2][2].set_aspect("equal") ax[2][2].tick_params(labelsize=ticksize) ax[2][2].set_yticks([]) ax[2][2].set_xticks([]) ax1 = ax[3][2].imshow( df['posterior_kdf'], extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[3][2].set_aspect("equal") ax[3][2].tick_params(labelsize=ticksize) ax[3][2].set_yticks([]) ax[3][2].set_xticks([]) ################################################## df = loadmat('kdf_experiments/results/sinewave_plot_data.mat') ax1 = ax[2][3].imshow( np.flip(df['posterior_rf'],axis=0), extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[2][3].set_aspect("equal") ax[2][3].tick_params(labelsize=ticksize) ax[2][3].set_yticks([]) ax[2][3].set_xticks([]) ax1 = ax[3][3].imshow( np.flip(df['posterior_kdf'], axis=0), extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[3][3].set_aspect("equal") ax[3][3].tick_params(labelsize=ticksize) ax[3][3].set_yticks([]) ax[3][3].set_xticks([]) ################################################### df = loadmat('kdf_experiments/results/polynomial_plot_data.mat') ax1 = ax[2][4].imshow( np.flip(df['posterior_rf'],axis=0), extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[2][4].set_aspect("equal") ax[2][4].tick_params(labelsize=ticksize) ax[2][4].set_yticks([]) ax[2][4].set_xticks([]) ax1 = ax[3][4].imshow( np.flip(df['posterior_kdf'],axis=0), extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[3][4].set_aspect("equal") ax[3][4].tick_params(labelsize=ticksize) ax[3][4].set_yticks([]) ax[3][4].set_xticks([]) ############################################## ############################################## df = loadmat('kdn_experiments/results/gxor_plot_data.mat') proba_nn = 1-np.flip(df["nn_proba"][:, 0].reshape(400, 400), axis=1) proba_kdn = 1-np.flip(df["kdn_proba"][:, 0].reshape(400, 400), axis=1) ax1 = ax[4][0].imshow( proba_nn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[4][0].set_aspect("equal") ax[4][0].tick_params(labelsize=ticksize) ax[4][0].set_ylabel('NN Posteriors',fontsize=title_size-5) ax[4][0].set_yticks([-2,-1,0,1,2]) ax[4][0].set_xticks([]) ax1 = ax[5][0].imshow( proba_kdn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[5][0].set_aspect("equal") ax[5][0].set_ylabel('KDN Posteriors',fontsize=title_size-5) ax[5][0].tick_params(labelsize=ticksize) ax[5][0].set_yticks([-2,-1,0,1,2]) ax[5][0].set_xticks([-2,-1,0,1,2]) ######################################## df = loadmat('kdn_experiments/results/spiral_plot_data.mat') proba_nn = np.flip(df["nn_proba"][:, 0].reshape(400, 400), axis=1) proba_kdn = np.flip(df["kdn_proba"][:, 0].reshape(400, 400), axis=1) ax1 = ax[4][1].imshow( proba_nn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[4][1].set_aspect("equal") ax[4][1].tick_params(labelsize=ticksize) ax[4][1].set_yticks([]) ax[4][1].set_xticks([]) ax1 = ax[5][1].imshow( proba_kdn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[5][1].set_aspect("equal") ax[5][1].tick_params(labelsize=ticksize) ax[5][1].set_yticks([]) ax[5][1].set_xticks([-2,-1,0,1,2]) ######################################################## df = loadmat('kdn_experiments/results/circle_plot_data.mat') proba_nn = np.flip(df["nn_proba"][:, 0].reshape(400, 400), axis=1) proba_kdn = np.flip(df["kdn_proba"][:, 0].reshape(400, 400), axis=1) ax1 = ax[4][2].imshow( proba_nn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[4][2].set_aspect("equal") ax[4][2].tick_params(labelsize=ticksize) ax[4][2].set_yticks([]) ax[4][2].set_xticks([]) ax1 = ax[5][2].imshow( proba_kdn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[5][2].set_aspect("equal") ax[5][2].tick_params(labelsize=ticksize) ax[5][2].set_yticks([]) ax[5][2].set_xticks([-2,-1,0,1,2]) #################################################### df = loadmat('kdn_experiments/results/sinewave_plot_data.mat') proba_nn = np.flip(df["nn_proba"][:, 0].reshape(400, 400), axis=0) proba_kdn = np.flip(df["kdn_proba"][:, 0].reshape(400, 400), axis=0) ax1 = ax[4][3].imshow( proba_nn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[4][3].set_aspect("equal") ax[4][3].tick_params(labelsize=ticksize) ax[4][3].set_yticks([]) ax[4][3].set_xticks([]) ax1 = ax[5][3].imshow( proba_kdn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) ax[5][3].set_aspect("equal") ax[5][3].tick_params(labelsize=ticksize) ax[5][3].set_yticks([]) ax[5][3].set_xticks([-2,-1,0,1,2]) ####################################################### df = loadmat('kdn_experiments/results/polynomial_plot_data.mat') proba_nn = 1-np.flip(df["nn_proba"][:, 0].reshape(400, 400), axis=1) proba_kdn = np.flip(df["kdn_proba"][:, 0].reshape(400, 400), axis=1) ax1 = ax[4][4].imshow( proba_nn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) #fig.colorbar(ax1, ax=ax[4][4], anchor=(0, 0.3), shrink=0.85) ax[4][4].set_aspect("equal") ax[4][4].tick_params(labelsize=ticksize) ax[4][4].set_yticks([]) ax[4][4].set_xticks([]) ax1 = ax[5][4].imshow( proba_kdn, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap="bwr", vmin=0, vmax=1, interpolation="nearest", aspect="auto", ) #fig.colorbar(ax1, anchor=(0, 0.3), shrink=0.85) ax[5][4].set_aspect("equal") ax[5][4].tick_params(labelsize=ticksize) ax[5][4].set_yticks([]) ax[5][4].set_xticks([-2,-1,0,1,2]) #plt.savefig('plots/simulations.pdf') # %% def calc_stat(a, reps=45): a_med = [] a_25 = [] a_75 = [] a = a.reshape(-1,reps) return np.median(a,axis=1), np.quantile(a,[.25], axis=1)[0], np.quantile(a,[.75], axis=1)[0] # %% sns.set_context('talk') sample_size = [50, 100, 500, 1000, 5000, 10000] fig, ax = plt.subplots(5,4, figsize=(45,40)) title_size = 45 ticksize = 30 for ax_ in ax: for ax__ in ax_: ax__.tick_params(labelsize=ticksize) df = loadmat('kdn_experiments/results/graphs/gxor.mat') med, a_25, a_75 = calc_stat(1-df['kdn_acc']) med_nn, nn_25, nn_75 = calc_stat(1-df['nn_acc']) ax[0][0].plot(sample_size, med[1:], c="b", label='KDN') ax[0][0].plot(sample_size, med_nn[1:], c="c", label='NN') ax[0][0].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[0][0].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[0][0].set_xscale('log') #ax[0][0].set_xlabel('Sample size') ax[0][0].set_xticks([]) ax[0][0].set_ylabel('Generalization Error', fontsize=ticksize) right_side = ax[0][0].spines["right"] right_side.set_visible(False) top_side = ax[0][0].spines["top"] top_side.set_visible(False) df_ = loadmat('kdf_experiments/results/gxor_plot_data.mat') ax[0][0].plot(sample_size, df_['error_kdf_med'].ravel(), c="r", label='KDF') ax[0][0].plot(sample_size, df_['error_rf_med'].ravel(), c="k", label='RF') ax[0][0].fill_between(sample_size, df_["error_kdf_25"].ravel(), df_["error_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[0][0].fill_between(sample_size, df_["error_rf_25"].ravel(), df_["error_rf_75"].ravel(), facecolor='k', alpha=.3) ax[0][0].legend(fontsize=ticksize, frameon=False) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_hd']) med_nn, nn_25, nn_75 = calc_stat(df['nn_hd']) ax[0][1].plot(sample_size, med[1:], c="b", label='KDN') ax[0][1].plot(sample_size, med_nn[1:], c="c", label='NN') ax[0][1].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[0][1].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[0][1].set_xscale('log') ax[0][1].set_xticks([]) ax[0][1].set_ylabel('Hellinger Distance', fontsize=ticksize) right_side = ax[0][1].spines["right"] right_side.set_visible(False) top_side = ax[0][1].spines["top"] top_side.set_visible(False) ax[0][1].plot(sample_size, df_['hellinger_kdf_med'].ravel(), c="r", label='KDF') ax[0][1].plot(sample_size, df_['hellinger_rf_med'].ravel(), c="k", label='RF') ax[0][1].fill_between(sample_size, df_["hellinger_kdf_25"].ravel(), df_["hellinger_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[0][1].fill_between(sample_size, df_["hellinger_rf_25"].ravel(), df_["hellinger_rf_75"].ravel(), facecolor='k', alpha=.3) ax[0][1].set_title('Gaussian XOR', fontsize=title_size) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcIn']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcIn']) ax[0][2].plot(sample_size, med[1:], c="b", label='KDN') ax[0][2].plot(sample_size, med_nn[1:], c="c", label='NN') ax[0][2].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[0][2].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[0][2].set_xscale('log') ax[0][2].set_xticks([]) ax[0][2].set_ylabel('Mean Max Confidence\n (In Distribution)', fontsize=ticksize) right_side = ax[0][2].spines["right"] right_side.set_visible(False) top_side = ax[0][2].spines["top"] top_side.set_visible(False) ax[0][2].plot(sample_size, df_['mmcIn_kdf_med'].ravel(), c="r", label='KDF') ax[0][2].plot(sample_size, df_['mmcIn_rf_med'].ravel(), c="k", label='RF') ax[0][2].fill_between(sample_size, df_["mmcIn_kdf_25"].ravel(), df_["mmcIn_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[0][2].fill_between(sample_size, df_["mmcIn_rf_25"].ravel(), df_["mmcIn_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcOut']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcOut']) ax[0][3].plot(sample_size, med[1:], c="b", label='KDN') ax[0][3].plot(sample_size, med_nn[1:], c="c", label='NN') ax[0][3].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[0][3].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[0][3].set_xscale('log') ax[0][3].set_xticks([]) ax[0][3].set_ylabel('Mean Max Confidence\n (Out Distribution)', fontsize=ticksize) right_side = ax[0][3].spines["right"] right_side.set_visible(False) top_side = ax[0][3].spines["top"] top_side.set_visible(False) ax[0][3].plot(sample_size, df_['mmcOut_kdf_med'].ravel(), c="r", label='KDF') ax[0][3].plot(sample_size, df_['mmcOut_rf_med'].ravel(), c="k", label='RF') ax[0][3].fill_between(sample_size, df_["mmcOut_kdf_25"].ravel(), df_["mmcOut_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[0][3].fill_between(sample_size, df_["mmcOut_rf_25"].ravel(), df_["mmcOut_rf_75"].ravel(), facecolor='k', alpha=.3) ######################################################### ######################################################### df = loadmat('kdn_experiments/results/graphs/spiral.mat') med, a_25, a_75 = calc_stat(1-df['kdn_acc']) med_nn, nn_25, nn_75 = calc_stat(1-df['nn_acc']) ax[1][0].plot(sample_size, med[1:], c="b", label='KDN') ax[1][0].plot(sample_size, med_nn[1:], c="c", label='NN') ax[1][0].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[1][0].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[1][0].set_xscale('log') ax[1][0].set_xticks([]) ax[1][0].set_ylabel('Generalization Error', fontsize=ticksize) right_side = ax[1][0].spines["right"] right_side.set_visible(False) top_side = ax[1][0].spines["top"] top_side.set_visible(False) df_ = loadmat('kdf_experiments/results/spiral_plot_data.mat') ax[1][0].plot(sample_size, df_['error_kdf_med'].ravel(), c="r", label='KDF') ax[1][0].plot(sample_size, df_['error_rf_med'].ravel(), c="k", label='RF') ax[1][0].fill_between(sample_size, df_["error_kdf_25"].ravel(), df_["error_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[1][0].fill_between(sample_size, df_["error_rf_25"].ravel(), df_["error_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_hd']) med_nn, nn_25, nn_75 = calc_stat(df['nn_hd']) ax[1][1].plot(sample_size, med[1:], c="b", label='KDN') ax[1][1].plot(sample_size, med_nn[1:], c="c", label='NN') ax[1][1].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[1][1].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[1][1].set_xscale('log') ax[1][1].set_xticks([]) ax[1][1].set_ylabel('Hellinger Distance', fontsize=ticksize) right_side = ax[1][1].spines["right"] right_side.set_visible(False) top_side = ax[1][1].spines["top"] top_side.set_visible(False) ax[1][1].plot(sample_size, df_['hellinger_kdf_med'].ravel(), c="r", label='KDF') ax[1][1].plot(sample_size, df_['hellinger_rf_med'].ravel(), c="k", label='RF') ax[1][1].fill_between(sample_size, df_["hellinger_kdf_25"].ravel(), df_["hellinger_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[1][1].fill_between(sample_size, df_["hellinger_rf_25"].ravel(), df_["hellinger_rf_75"].ravel(), facecolor='k', alpha=.3) ax[1][1].set_title('Spiral', fontsize=title_size) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcIn']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcIn']) ax[1][2].plot(sample_size, med[1:], c="b", label='KDN') ax[1][2].plot(sample_size, med_nn[1:], c="c", label='NN') ax[1][2].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[1][2].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[1][2].set_xscale('log') ax[1][2].set_xticks([]) ax[1][2].set_ylabel('Mean Max Confidence\n (In Distribution)', fontsize=ticksize) right_side = ax[1][2].spines["right"] right_side.set_visible(False) top_side = ax[1][2].spines["top"] top_side.set_visible(False) ax[1][2].plot(sample_size, df_['mmcIn_kdf_med'].ravel(), c="r", label='KDF') ax[1][2].plot(sample_size, df_['mmcIn_rf_med'].ravel(), c="k", label='RF') ax[1][2].fill_between(sample_size, df_["mmcIn_kdf_25"].ravel(), df_["mmcIn_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[1][2].fill_between(sample_size, df_["mmcIn_rf_25"].ravel(), df_["mmcIn_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcOut']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcOut']) ax[1][3].plot(sample_size, med[1:], c="b", label='KDN') ax[1][3].plot(sample_size, med_nn[1:], c="c", label='NN') ax[1][3].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[1][3].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[1][3].set_xscale('log') ax[1][3].set_xticks([]) ax[1][3].set_ylabel('Mean Max Confidence\n (Out Distribution)', fontsize=ticksize) right_side = ax[1][3].spines["right"] right_side.set_visible(False) top_side = ax[1][3].spines["top"] top_side.set_visible(False) ax[1][3].plot(sample_size, df_['mmcOut_kdf_med'].ravel(), c="r", label='KDF') ax[1][3].plot(sample_size, df_['mmcOut_rf_med'].ravel(), c="k", label='RF') ax[1][3].fill_between(sample_size, df_["mmcOut_kdf_25"].ravel(), df_["mmcOut_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[1][3].fill_between(sample_size, df_["mmcOut_rf_25"].ravel(), df_["mmcOut_rf_75"].ravel(), facecolor='k', alpha=.3) ######################################################### ######################################################### df = loadmat('kdn_experiments/results/graphs/circle.mat') med, a_25, a_75 = calc_stat(1-df['kdn_acc']) med_nn, nn_25, nn_75 = calc_stat(1-df['nn_acc']) ax[2][0].plot(sample_size, med[1:], c="b", label='KDN') ax[2][0].plot(sample_size, med_nn[1:], c="c", label='NN') ax[2][0].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[2][0].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[2][0].set_xscale('log') ax[2][0].set_xticks([]) ax[2][0].set_ylabel('Generalization Error', fontsize=ticksize) right_side = ax[2][0].spines["right"] right_side.set_visible(False) top_side = ax[2][0].spines["top"] top_side.set_visible(False) df_ = loadmat('kdf_experiments/results/circle_plot_data.mat') ax[2][0].plot(sample_size, df_['error_kdf_med'].ravel(), c="r", label='KDF') ax[2][0].plot(sample_size, df_['error_rf_med'].ravel(), c="k", label='RF') ax[2][0].fill_between(sample_size, df_["error_kdf_25"].ravel(), df_["error_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[2][0].fill_between(sample_size, df_["error_rf_25"].ravel(), df_["error_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_hd']) med_nn, nn_25, nn_75 = calc_stat(df['nn_hd']) ax[2][1].plot(sample_size, med[1:], c="b", label='KDN') ax[2][1].plot(sample_size, med_nn[1:], c="c", label='NN') ax[2][1].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[2][1].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[2][1].set_xscale('log') ax[2][1].set_xticks([]) ax[2][1].set_ylabel('Hellinger Distance', fontsize=ticksize) right_side = ax[2][1].spines["right"] right_side.set_visible(False) top_side = ax[2][1].spines["top"] top_side.set_visible(False) ax[2][1].plot(sample_size, df_['hellinger_kdf_med'].ravel(), c="r", label='KDF') ax[2][1].plot(sample_size, df_['hellinger_rf_med'].ravel(), c="k", label='RF') ax[2][1].fill_between(sample_size, df_["hellinger_kdf_25"].ravel(), df_["hellinger_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[2][1].fill_between(sample_size, df_["hellinger_rf_25"].ravel(), df_["hellinger_rf_75"].ravel(), facecolor='k', alpha=.3) ax[2][1].set_title('Circle', fontsize=title_size) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcIn']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcIn']) ax[2][2].plot(sample_size, med[1:], c="b", label='KDN') ax[2][2].plot(sample_size, med_nn[1:], c="c", label='NN') ax[2][2].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[2][2].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[2][2].set_xscale('log') ax[2][2].set_xticks([]) ax[2][2].set_ylabel('Mean Max Confidence\n (In Distribution)', fontsize=ticksize) right_side = ax[2][2].spines["right"] right_side.set_visible(False) top_side = ax[2][2].spines["top"] top_side.set_visible(False) ax[2][2].plot(sample_size, df_['mmcIn_kdf_med'].ravel(), c="r", label='KDF') ax[2][2].plot(sample_size, df_['mmcIn_rf_med'].ravel(), c="k", label='RF') ax[2][2].fill_between(sample_size, df_["mmcIn_kdf_25"].ravel(), df_["mmcIn_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[2][2].fill_between(sample_size, df_["mmcIn_rf_25"].ravel(), df_["mmcIn_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcOut']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcOut']) ax[2][3].plot(sample_size, med[1:], c="b", label='KDN') ax[2][3].plot(sample_size, med_nn[1:], c="c", label='NN') ax[2][3].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[2][3].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[2][3].set_xscale('log') ax[2][3].set_xticks([]) ax[2][3].set_ylabel('Mean Max Confidence\n (Out Distribution)', fontsize=ticksize) right_side = ax[2][3].spines["right"] right_side.set_visible(False) top_side = ax[2][3].spines["top"] top_side.set_visible(False) ax[2][3].plot(sample_size, df_['mmcOut_kdf_med'].ravel(), c="r", label='KDF') ax[2][3].plot(sample_size, df_['mmcOut_rf_med'].ravel(), c="k", label='RF') ax[2][3].fill_between(sample_size, df_["mmcOut_kdf_25"].ravel(), df_["mmcOut_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[2][3].fill_between(sample_size, df_["mmcOut_rf_25"].ravel(), df_["mmcOut_rf_75"].ravel(), facecolor='k', alpha=.3) ######################################################### ######################################################### df = loadmat('kdn_experiments/results/graphs/sinewave.mat') med, a_25, a_75 = calc_stat(1-df['kdn_acc']) med_nn, nn_25, nn_75 = calc_stat(1-df['nn_acc']) ax[3][0].plot(sample_size, med[1:], c="b", label='KDN') ax[3][0].plot(sample_size, med_nn[1:], c="c", label='NN') ax[3][0].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[3][0].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[3][0].set_xscale('log') ax[3][0].set_xticks([]) ax[3][0].set_ylabel('Generalization Error', fontsize=ticksize) right_side = ax[3][0].spines["right"] right_side.set_visible(False) top_side = ax[3][0].spines["top"] top_side.set_visible(False) df_ = loadmat('kdf_experiments/results/sinewave_plot_data.mat') ax[3][0].plot(sample_size, df_['error_kdf_med'].ravel(), c="r", label='KDF') ax[3][0].plot(sample_size, df_['error_rf_med'].ravel(), c="k", label='RF') ax[3][0].fill_between(sample_size, df_["error_kdf_25"].ravel(), df_["error_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[3][0].fill_between(sample_size, df_["error_rf_25"].ravel(), df_["error_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_hd']) med_nn, nn_25, nn_75 = calc_stat(df['nn_hd']) ax[3][1].plot(sample_size, med[1:], c="b", label='KDN') ax[3][1].plot(sample_size, med_nn[1:], c="c", label='NN') ax[3][1].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[3][1].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[3][1].set_xscale('log') ax[3][1].set_xticks([]) ax[3][1].set_ylabel('Hellinger Distance', fontsize=ticksize) right_side = ax[3][1].spines["right"] right_side.set_visible(False) top_side = ax[3][1].spines["top"] top_side.set_visible(False) ax[3][1].plot(sample_size, df_['hellinger_kdf_med'].ravel(), c="r", label='KDF') ax[3][1].plot(sample_size, df_['hellinger_rf_med'].ravel(), c="k", label='RF') ax[3][1].fill_between(sample_size, df_["hellinger_kdf_25"].ravel(), df_["hellinger_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[3][1].fill_between(sample_size, df_["hellinger_rf_25"].ravel(), df_["hellinger_rf_75"].ravel(), facecolor='k', alpha=.3) ax[3][1].set_title('Sinewave', fontsize=title_size) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcIn']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcIn']) ax[3][2].plot(sample_size, med[1:], c="b", label='KDN') ax[3][2].plot(sample_size, med_nn[1:], c="c", label='NN') ax[3][2].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[3][2].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[3][2].set_xscale('log') ax[3][2].set_xticks([]) ax[3][2].set_ylabel('Mean Max Confidence\n (In Distribution)', fontsize=ticksize) right_side = ax[3][2].spines["right"] right_side.set_visible(False) top_side = ax[3][2].spines["top"] top_side.set_visible(False) ax[3][2].plot(sample_size, df_['mmcIn_kdf_med'].ravel(), c="r", label='KDF') ax[3][2].plot(sample_size, df_['mmcIn_rf_med'].ravel(), c="k", label='RF') ax[3][2].fill_between(sample_size, df_["mmcIn_kdf_25"].ravel(), df_["mmcIn_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[3][2].fill_between(sample_size, df_["mmcIn_rf_25"].ravel(), df_["mmcIn_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcOut']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcOut']) ax[3][3].plot(sample_size, med[1:], c="b", label='KDN') ax[3][3].plot(sample_size, med_nn[1:], c="c", label='NN') ax[3][3].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[3][3].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[3][3].set_xscale('log') ax[3][3].set_xticks([]) ax[3][3].set_ylabel('Mean Max Confidence\n (Out Distribution)', fontsize=ticksize) right_side = ax[3][3].spines["right"] right_side.set_visible(False) top_side = ax[3][3].spines["top"] top_side.set_visible(False) ax[3][3].plot(sample_size, df_['mmcOut_kdf_med'].ravel(), c="r", label='KDF') ax[3][3].plot(sample_size, df_['mmcOut_rf_med'].ravel(), c="k", label='RF') ax[3][3].fill_between(sample_size, df_["mmcOut_kdf_25"].ravel(), df_["mmcOut_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[3][3].fill_between(sample_size, df_["mmcOut_rf_25"].ravel(), df_["mmcOut_rf_75"].ravel(), facecolor='k', alpha=.3) ######################################################### ######################################################### df = loadmat('kdn_experiments/results/graphs/polynomial.mat') med, a_25, a_75 = calc_stat(1-df['kdn_acc']) med_nn, nn_25, nn_75 = calc_stat(1-df['nn_acc']) ax[4][0].plot(sample_size, med[1:], c="b", label='KDN') ax[4][0].plot(sample_size, med_nn[1:], c="c", label='NN') ax[4][0].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[4][0].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[4][0].set_xscale('log') ax[4][0].set_xlabel('Sample size', fontsize=ticksize) ax[4][0].set_ylabel('Generalization Error', fontsize=ticksize) right_side = ax[4][0].spines["right"] right_side.set_visible(False) top_side = ax[4][0].spines["top"] top_side.set_visible(False) df_ = loadmat('kdf_experiments/results/polynomial_plot_data.mat') ax[4][0].plot(sample_size, df_['error_kdf_med'].ravel(), c="r", label='KDF') ax[4][0].plot(sample_size, df_['error_rf_med'].ravel(), c="k", label='RF') ax[4][0].fill_between(sample_size, df_["error_kdf_25"].ravel(), df_["error_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[4][0].fill_between(sample_size, df_["error_rf_25"].ravel(), df_["error_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_hd']) med_nn, nn_25, nn_75 = calc_stat(df['nn_hd']) ax[4][1].plot(sample_size, med[1:], c="b", label='KDN') ax[4][1].plot(sample_size, med_nn[1:], c="c", label='NN') ax[4][1].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[4][1].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[4][1].set_xscale('log') ax[4][1].set_xlabel('Sample size', fontsize=ticksize) ax[4][1].set_ylabel('Hellinger Distance', fontsize=ticksize) right_side = ax[4][1].spines["right"] right_side.set_visible(False) top_side = ax[4][1].spines["top"] top_side.set_visible(False) ax[4][1].plot(sample_size, df_['hellinger_kdf_med'].ravel(), c="r", label='KDF') ax[4][1].plot(sample_size, df_['hellinger_rf_med'].ravel(), c="k", label='RF') ax[4][1].fill_between(sample_size, df_["hellinger_kdf_25"].ravel(), df_["hellinger_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[4][1].fill_between(sample_size, df_["hellinger_rf_25"].ravel(), df_["hellinger_rf_75"].ravel(), facecolor='k', alpha=.3) ax[4][1].set_title('Polynomial', fontsize=title_size) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcIn']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcIn']) ax[4][2].plot(sample_size, med[1:], c="b", label='KDN') ax[4][2].plot(sample_size, med_nn[1:], c="c", label='NN') ax[4][2].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[4][2].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[4][2].set_xscale('log') ax[4][2].set_xlabel('Sample size', fontsize=ticksize) ax[4][2].set_ylabel('Mean Max Confidence\n (In Distribution)', fontsize=ticksize) right_side = ax[4][2].spines["right"] right_side.set_visible(False) top_side = ax[4][2].spines["top"] top_side.set_visible(False) ax[4][2].plot(sample_size, df_['mmcIn_kdf_med'].ravel(), c="r", label='KDF') ax[4][2].plot(sample_size, df_['mmcIn_rf_med'].ravel(), c="k", label='RF') ax[4][2].fill_between(sample_size, df_["mmcIn_kdf_25"].ravel(), df_["mmcIn_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[4][2].fill_between(sample_size, df_["mmcIn_rf_25"].ravel(), df_["mmcIn_rf_75"].ravel(), facecolor='k', alpha=.3) ################################################################################################## med, a_25, a_75 = calc_stat(df['kdn_mmcOut']) med_nn, nn_25, nn_75 = calc_stat(df['nn_mmcOut']) ax[4][3].plot(sample_size, med[1:], c="b", label='KDN') ax[4][3].plot(sample_size, med_nn[1:], c="c", label='NN') ax[4][3].fill_between(sample_size, a_25[1:], a_75[1:], facecolor='b', alpha=.3) ax[4][3].fill_between(sample_size, nn_25[1:], nn_75[1:], facecolor='c', alpha=.3) ax[4][3].set_xscale('log') ax[4][3].set_xlabel('Sample size', fontsize=ticksize) ax[4][3].set_ylabel('Mean Max Confidence\n (Out Distribution)', fontsize=ticksize) right_side = ax[4][3].spines["right"] right_side.set_visible(False) top_side = ax[4][3].spines["top"] top_side.set_visible(False) ax[4][3].plot(sample_size, df_['mmcOut_kdf_med'].ravel(), c="r", label='KDF') ax[4][3].plot(sample_size, df_['mmcOut_rf_med'].ravel(), c="k", label='RF') ax[4][3].fill_between(sample_size, df_["mmcOut_kdf_25"].ravel(), df_["mmcOut_kdf_75"].ravel(), facecolor='r', alpha=.3) ax[4][3].fill_between(sample_size, df_["mmcOut_rf_25"].ravel(), df_["mmcOut_rf_75"].ravel(), facecolor='k', alpha=.3) plt.savefig('plots/simulation_res.pdf') # %%
[ "kdg.utils.generate_gaussian_parity", "numpy.flip", "numpy.median", "matplotlib.pyplot.savefig", "numpy.ones", "pandas.read_csv", "seaborn.set_context", "kdg.utils.plot_2dsim", "scipy.io.loadmat", "kdg.utils.generate_ellipse", "kdg.utils.generate_sinewave", "kdg.utils.generate_polynomial", "...
[((374, 409), 'kdg.utils.generate_gaussian_parity', 'generate_gaussian_parity', (['n_samples'], {}), '(n_samples)\n', (398, 409), False, 'from kdg.utils import generate_gaussian_parity, generate_ellipse, generate_spirals, generate_sinewave, generate_polynomial\n'), ((437, 464), 'kdg.utils.generate_spirals', 'generate_spirals', (['n_samples'], {}), '(n_samples)\n', (453, 464), False, 'from kdg.utils import generate_gaussian_parity, generate_ellipse, generate_spirals, generate_sinewave, generate_polynomial\n'), ((492, 519), 'kdg.utils.generate_ellipse', 'generate_ellipse', (['n_samples'], {}), '(n_samples)\n', (508, 519), False, 'from kdg.utils import generate_gaussian_parity, generate_ellipse, generate_spirals, generate_sinewave, generate_polynomial\n'), ((543, 571), 'kdg.utils.generate_sinewave', 'generate_sinewave', (['n_samples'], {}), '(n_samples)\n', (560, 571), False, 'from kdg.utils import generate_gaussian_parity, generate_ellipse, generate_spirals, generate_sinewave, generate_polynomial\n'), ((595, 635), 'kdg.utils.generate_polynomial', 'generate_polynomial', (['n_samples'], {'a': '[1, 3]'}), '(n_samples, a=[1, 3])\n', (614, 635), False, 'from kdg.utils import generate_gaussian_parity, generate_ellipse, generate_spirals, generate_sinewave, generate_polynomial\n'), ((639, 662), 'seaborn.set_context', 'sns.set_context', (['"""talk"""'], {}), "('talk')\n", (654, 662), True, 'import seaborn as sns\n'), ((673, 722), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(6)', '(5)'], {'figsize': '(40, 48)', 'sharex': '(True)'}), '(6, 5, figsize=(40, 48), sharex=True)\n', (685, 722), True, 'import matplotlib.pyplot as plt\n'), ((752, 797), 'kdg.utils.plot_2dsim', 'plot_2dsim', (["X['gxor']", "y['gxor']"], {'ax': 'ax[0][0]'}), "(X['gxor'], y['gxor'], ax=ax[0][0])\n", (762, 797), False, 'from kdg.utils import plot_2dsim\n'), ((1069, 1118), 'kdg.utils.plot_2dsim', 'plot_2dsim', (["X['spiral']", "y['spiral']"], {'ax': 'ax[0][1]'}), "(X['spiral'], y['spiral'], ax=ax[0][1])\n", (1079, 1118), False, 'from kdg.utils import plot_2dsim\n'), ((1311, 1360), 'kdg.utils.plot_2dsim', 'plot_2dsim', (["X['circle']", "y['circle']"], {'ax': 'ax[0][2]'}), "(X['circle'], y['circle'], ax=ax[0][2])\n", (1321, 1360), False, 'from kdg.utils import plot_2dsim\n'), ((1553, 1598), 'kdg.utils.plot_2dsim', 'plot_2dsim', (["X['sine']", "y['sine']"], {'ax': 'ax[0][3]'}), "(X['sine'], y['sine'], ax=ax[0][3])\n", (1563, 1598), False, 'from kdg.utils import plot_2dsim\n'), ((1793, 1838), 'kdg.utils.plot_2dsim', 'plot_2dsim', (["X['poly']", "y['poly']"], {'ax': 'ax[0][4]'}), "(X['poly'], y['poly'], ax=ax[0][4])\n", (1803, 1838), False, 'from kdg.utils import plot_2dsim\n'), ((2102, 2129), 'numpy.arange', 'np.arange', (['(-2)', '(2)'], {'step': '(0.01)'}), '(-2, 2, step=0.01)\n', (2111, 2129), True, 'import numpy as np\n'), ((2134, 2161), 'numpy.arange', 'np.arange', (['(-2)', '(2)'], {'step': '(0.01)'}), '(-2, 2, step=0.01)\n', (2143, 2161), True, 'import numpy as np\n'), ((2171, 2188), 'numpy.meshgrid', 'np.meshgrid', (['p', 'q'], {}), '(p, q)\n', (2182, 2188), True, 'import numpy as np\n'), ((2219, 2269), 'pandas.read_csv', 'pd.read_csv', (['"""true_posterior/Gaussian_xor_pdf.csv"""'], {}), "('true_posterior/Gaussian_xor_pdf.csv')\n", (2230, 2269), True, 'import pandas as pd\n'), ((2872, 2916), 'pandas.read_csv', 'pd.read_csv', (['"""true_posterior/spiral_pdf.csv"""'], {}), "('true_posterior/spiral_pdf.csv')\n", (2883, 2916), True, 'import pandas as pd\n'), ((3469, 3514), 'pandas.read_csv', 'pd.read_csv', (['"""true_posterior/ellipse_pdf.csv"""'], {}), "('true_posterior/ellipse_pdf.csv')\n", (3480, 3514), True, 'import pandas as pd\n'), ((4046, 4092), 'pandas.read_csv', 'pd.read_csv', (['"""true_posterior/sinewave_pdf.csv"""'], {}), "('true_posterior/sinewave_pdf.csv')\n", (4057, 4092), True, 'import pandas as pd\n'), ((4640, 4688), 'pandas.read_csv', 'pd.read_csv', (['"""true_posterior/polynomial_pdf.csv"""'], {}), "('true_posterior/polynomial_pdf.csv')\n", (4651, 4688), True, 'import pandas as pd\n'), ((5290, 5343), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/gxor_plot_data.mat"""'], {}), "('kdf_experiments/results/gxor_plot_data.mat')\n", (5297, 5343), False, 'from scipy.io import savemat, loadmat\n'), ((6157, 6212), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/spiral_plot_data.mat"""'], {}), "('kdf_experiments/results/spiral_plot_data.mat')\n", (6164, 6212), False, 'from scipy.io import savemat, loadmat\n'), ((6920, 6975), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/circle_plot_data.mat"""'], {}), "('kdf_experiments/results/circle_plot_data.mat')\n", (6927, 6975), False, 'from scipy.io import savemat, loadmat\n'), ((7653, 7710), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/sinewave_plot_data.mat"""'], {}), "('kdf_experiments/results/sinewave_plot_data.mat')\n", (7660, 7710), False, 'from scipy.io import savemat, loadmat\n'), ((8421, 8480), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/polynomial_plot_data.mat"""'], {}), "('kdf_experiments/results/polynomial_plot_data.mat')\n", (8428, 8480), False, 'from scipy.io import savemat, loadmat\n'), ((9233, 9286), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/gxor_plot_data.mat"""'], {}), "('kdn_experiments/results/gxor_plot_data.mat')\n", (9240, 9286), False, 'from scipy.io import savemat, loadmat\n'), ((10227, 10282), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/spiral_plot_data.mat"""'], {}), "('kdn_experiments/results/spiral_plot_data.mat')\n", (10234, 10282), False, 'from scipy.io import savemat, loadmat\n'), ((11093, 11148), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/circle_plot_data.mat"""'], {}), "('kdn_experiments/results/circle_plot_data.mat')\n", (11100, 11148), False, 'from scipy.io import savemat, loadmat\n'), ((11955, 12012), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/sinewave_plot_data.mat"""'], {}), "('kdn_experiments/results/sinewave_plot_data.mat')\n", (11962, 12012), False, 'from scipy.io import savemat, loadmat\n'), ((12822, 12881), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/polynomial_plot_data.mat"""'], {}), "('kdn_experiments/results/polynomial_plot_data.mat')\n", (12829, 12881), False, 'from scipy.io import savemat, loadmat\n'), ((13986, 14009), 'seaborn.set_context', 'sns.set_context', (['"""talk"""'], {}), "('talk')\n", (14001, 14009), True, 'import seaborn as sns\n'), ((14069, 14105), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', '(4)'], {'figsize': '(45, 40)'}), '(5, 4, figsize=(45, 40))\n', (14081, 14105), True, 'import matplotlib.pyplot as plt\n'), ((14231, 14281), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/graphs/gxor.mat"""'], {}), "('kdn_experiments/results/graphs/gxor.mat')\n", (14238, 14281), False, 'from scipy.io import savemat, loadmat\n'), ((14944, 14997), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/gxor_plot_data.mat"""'], {}), "('kdf_experiments/results/gxor_plot_data.mat')\n", (14951, 14997), False, 'from scipy.io import savemat, loadmat\n'), ((18995, 19047), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/graphs/spiral.mat"""'], {}), "('kdn_experiments/results/graphs/spiral.mat')\n", (19002, 19047), False, 'from scipy.io import savemat, loadmat\n'), ((19674, 19729), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/spiral_plot_data.mat"""'], {}), "('kdf_experiments/results/spiral_plot_data.mat')\n", (19681, 19729), False, 'from scipy.io import savemat, loadmat\n'), ((23670, 23722), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/graphs/circle.mat"""'], {}), "('kdn_experiments/results/graphs/circle.mat')\n", (23677, 23722), False, 'from scipy.io import savemat, loadmat\n'), ((24349, 24404), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/circle_plot_data.mat"""'], {}), "('kdf_experiments/results/circle_plot_data.mat')\n", (24356, 24404), False, 'from scipy.io import savemat, loadmat\n'), ((28346, 28400), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/graphs/sinewave.mat"""'], {}), "('kdn_experiments/results/graphs/sinewave.mat')\n", (28353, 28400), False, 'from scipy.io import savemat, loadmat\n'), ((29027, 29084), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/sinewave_plot_data.mat"""'], {}), "('kdf_experiments/results/sinewave_plot_data.mat')\n", (29034, 29084), False, 'from scipy.io import savemat, loadmat\n'), ((33028, 33084), 'scipy.io.loadmat', 'loadmat', (['"""kdn_experiments/results/graphs/polynomial.mat"""'], {}), "('kdn_experiments/results/graphs/polynomial.mat')\n", (33035, 33084), False, 'from scipy.io import savemat, loadmat\n'), ((33741, 33800), 'scipy.io.loadmat', 'loadmat', (['"""kdf_experiments/results/polynomial_plot_data.mat"""'], {}), "('kdf_experiments/results/polynomial_plot_data.mat')\n", (33748, 33800), False, 'from scipy.io import savemat, loadmat\n'), ((37714, 37753), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plots/simulation_res.pdf"""'], {}), "('plots/simulation_res.pdf')\n", (37725, 37753), True, 'import matplotlib.pyplot as plt\n'), ((2287, 2306), 'numpy.ones', 'np.ones', (['(400, 400)'], {}), '((400, 400))\n', (2294, 2306), True, 'import numpy as np\n'), ((2934, 2953), 'numpy.ones', 'np.ones', (['(400, 400)'], {}), '((400, 400))\n', (2941, 2953), True, 'import numpy as np\n'), ((3111, 3138), 'numpy.flip', 'np.flip', (['proba_true'], {'axis': '(0)'}), '(proba_true, axis=0)\n', (3118, 3138), True, 'import numpy as np\n'), ((3532, 3551), 'numpy.ones', 'np.ones', (['(400, 400)'], {}), '((400, 400))\n', (3539, 3551), True, 'import numpy as np\n'), ((4110, 4129), 'numpy.ones', 'np.ones', (['(400, 400)'], {}), '((400, 400))\n', (4117, 4129), True, 'import numpy as np\n'), ((4706, 4725), 'numpy.ones', 'np.ones', (['(400, 400)'], {}), '((400, 400))\n', (4713, 4725), True, 'import numpy as np\n'), ((7738, 7773), 'numpy.flip', 'np.flip', (["df['posterior_rf']"], {'axis': '(0)'}), "(df['posterior_rf'], axis=0)\n", (7745, 7773), True, 'import numpy as np\n'), ((8064, 8100), 'numpy.flip', 'np.flip', (["df['posterior_kdf']"], {'axis': '(0)'}), "(df['posterior_kdf'], axis=0)\n", (8071, 8100), True, 'import numpy as np\n'), ((8508, 8543), 'numpy.flip', 'np.flip', (["df['posterior_rf']"], {'axis': '(0)'}), "(df['posterior_rf'], axis=0)\n", (8515, 8543), True, 'import numpy as np\n'), ((8834, 8870), 'numpy.flip', 'np.flip', (["df['posterior_kdf']"], {'axis': '(0)'}), "(df['posterior_kdf'], axis=0)\n", (8841, 8870), True, 'import numpy as np\n'), ((6242, 6277), 'numpy.flip', 'np.flip', (["df['posterior_rf']"], {'axis': '(0)'}), "(df['posterior_rf'], axis=0)\n", (6249, 6277), True, 'import numpy as np\n'), ((6570, 6606), 'numpy.flip', 'np.flip', (["df['posterior_kdf']"], {'axis': '(0)'}), "(df['posterior_kdf'], axis=0)\n", (6577, 6606), True, 'import numpy as np\n'), ((13895, 13915), 'numpy.median', 'np.median', (['a'], {'axis': '(1)'}), '(a, axis=1)\n', (13904, 13915), True, 'import numpy as np\n'), ((13916, 13946), 'numpy.quantile', 'np.quantile', (['a', '[0.25]'], {'axis': '(1)'}), '(a, [0.25], axis=1)\n', (13927, 13946), True, 'import numpy as np\n'), ((13949, 13979), 'numpy.quantile', 'np.quantile', (['a', '[0.75]'], {'axis': '(1)'}), '(a, [0.75], axis=1)\n', (13960, 13979), True, 'import numpy as np\n')]
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import os import ast import argparse import glob import yaml import copy import numpy as np from python.keypoint_preprocess import EvalAffine, TopDownEvalAffine, expand_crop def argsparser(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--config", type=str, default=None, help=("Path of configure"), required=True) parser.add_argument( "--image_file", type=str, default=None, help="Path of image file.") parser.add_argument( "--image_dir", type=str, default=None, help="Dir of image file, `image_file` has a higher priority.") parser.add_argument( "--video_file", type=str, default=None, help="Path of video file, `video_file` or `camera_id` has a highest priority." ) parser.add_argument( "--camera_id", type=int, default=-1, help="device id of camera to predict.") parser.add_argument( "--output_dir", type=str, default="output", help="Directory of output visualization files.") parser.add_argument( "--run_mode", type=str, default='paddle', help="mode of running(paddle/trt_fp32/trt_fp16/trt_int8)") parser.add_argument( "--device", type=str, default='cpu', help="Choose the device you want to run, it can be: CPU/GPU/XPU, default is CPU." ) parser.add_argument( "--enable_mkldnn", type=ast.literal_eval, default=False, help="Whether use mkldnn with CPU.") parser.add_argument( "--cpu_threads", type=int, default=1, help="Num of threads with CPU.") parser.add_argument( "--trt_min_shape", type=int, default=1, help="min_shape for TensorRT.") parser.add_argument( "--trt_max_shape", type=int, default=1280, help="max_shape for TensorRT.") parser.add_argument( "--trt_opt_shape", type=int, default=640, help="opt_shape for TensorRT.") parser.add_argument( "--trt_calib_mode", type=bool, default=False, help="If the model is produced by TRT offline quantitative " "calibration, trt_calib_mode need to set True.") return parser class Times(object): def __init__(self): self.time = 0. # start time self.st = 0. # end time self.et = 0. def start(self): self.st = time.time() def end(self, repeats=1, accumulative=True): self.et = time.time() if accumulative: self.time += (self.et - self.st) / repeats else: self.time = (self.et - self.st) / repeats def reset(self): self.time = 0. self.st = 0. self.et = 0. def value(self): return round(self.time, 4) class PipeTimer(Times): def __init__(self): super(PipeTimer, self).__init__() self.total_time = Times() self.module_time = { 'det': Times(), 'mot': Times(), 'attr': Times(), 'kpt': Times(), 'action': Times(), } self.img_num = 0 def info(self, average=False): total_time = self.total_time.value() total_time = round(total_time, 4) print("------------------ Inference Time Info ----------------------") print("total_time(ms): {}, img_num: {}".format(total_time * 1000, self.img_num)) for k, v in self.module_time.items(): v_time = round(v.value(), 4) if v_time > 0: print("{} time(ms): {}".format(k, v_time * 1000)) average_latency = total_time / max(1, self.img_num) qps = 0 if total_time > 0: qps = 1 / average_latency print("average latency time(ms): {:.2f}, QPS: {:2f}".format( average_latency * 1000, qps)) def report(self, average=False): dic = {} dic['total'] = round(self.total_time.value() / max(1, self.img_num), 4) if average else self.total_time.value() dic['det'] = round(self.module_time['det'].value() / max(1, self.img_num), 4) if average else self.module_time['det'].value() dic['mot'] = round(self.module_time['mot'].value() / max(1, self.img_num), 4) if average else self.module_time['mot'].value() dic['attr'] = round(self.module_time['attr'].value() / max(1, self.img_num), 4) if average else self.module_time['attr'].value() dic['kpt'] = round(self.module_time['kpt'].value() / max(1, self.img_num), 4) if average else self.module_time['kpt'].value() dic['action'] = round( self.module_time['action'].value() / max(1, self.img_num), 4) if average else self.module_time['action'].value() dic['img_num'] = self.img_num return dic def merge_cfg(args): with open(args.config) as f: pred_config = yaml.safe_load(f) def merge(cfg, arg): merge_cfg = copy.deepcopy(cfg) for k, v in cfg.items(): if k in arg: merge_cfg[k] = arg[k] else: if isinstance(v, dict): merge_cfg[k] = merge(v, arg) return merge_cfg pred_config = merge(pred_config, vars(args)) return pred_config def print_arguments(cfg): print('----------- Running Arguments -----------') for arg, value in sorted(cfg.items()): print('%s: %s' % (arg, value)) print('------------------------------------------') def get_test_images(infer_dir, infer_img): """ Get image path list in TEST mode """ assert infer_img is not None or infer_dir is not None, \ "--infer_img or --infer_dir should be set" assert infer_img is None or os.path.isfile(infer_img), \ "{} is not a file".format(infer_img) assert infer_dir is None or os.path.isdir(infer_dir), \ "{} is not a directory".format(infer_dir) # infer_img has a higher priority if infer_img and os.path.isfile(infer_img): return [infer_img] images = set() infer_dir = os.path.abspath(infer_dir) assert os.path.isdir(infer_dir), \ "infer_dir {} is not a directory".format(infer_dir) exts = ['jpg', 'jpeg', 'png', 'bmp'] exts += [ext.upper() for ext in exts] for ext in exts: images.update(glob.glob('{}/*.{}'.format(infer_dir, ext))) images = list(images) assert len(images) > 0, "no image found in {}".format(infer_dir) print("Found {} inference images in total.".format(len(images))) return images def crop_image_with_det(batch_input, det_res): boxes = det_res['boxes'] score = det_res['boxes'][:, 1] boxes_num = det_res['boxes_num'] start_idx = 0 crop_res = [] for b_id, input in enumerate(batch_input): boxes_num_i = boxes_num[b_id] boxes_i = boxes[start_idx:start_idx + boxes_num_i, :] score_i = score[start_idx:start_idx + boxes_num_i] res = [] for box in boxes_i: crop_image, new_box, ori_box = expand_crop(input, box) if crop_image is not None: res.append(crop_image) crop_res.append(res) return crop_res def crop_image_with_mot(input, mot_res): res = mot_res['boxes'] crop_res = [] for box in res: crop_image, new_box, ori_box = expand_crop(input, box[1:]) if crop_image is not None: crop_res.append(crop_image) return crop_res def parse_mot_res(input): mot_res = [] boxes, scores, ids = input[0] for box, score, i in zip(boxes[0], scores[0], ids[0]): xmin, ymin, w, h = box res = [i, 0, score, xmin, ymin, xmin + w, ymin + h] mot_res.append(res) return {'boxes': np.array(mot_res)}
[ "argparse.ArgumentParser", "os.path.isfile", "yaml.safe_load", "numpy.array", "os.path.isdir", "python.keypoint_preprocess.expand_crop", "copy.deepcopy", "os.path.abspath", "time.time" ]
[((831, 875), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (854, 875), False, 'import argparse\n'), ((7094, 7120), 'os.path.abspath', 'os.path.abspath', (['infer_dir'], {}), '(infer_dir)\n', (7109, 7120), False, 'import os\n'), ((7132, 7156), 'os.path.isdir', 'os.path.isdir', (['infer_dir'], {}), '(infer_dir)\n', (7145, 7156), False, 'import os\n'), ((3140, 3151), 'time.time', 'time.time', ([], {}), '()\n', (3149, 3151), False, 'import time\n'), ((3220, 3231), 'time.time', 'time.time', ([], {}), '()\n', (3229, 3231), False, 'import time\n'), ((5904, 5921), 'yaml.safe_load', 'yaml.safe_load', (['f'], {}), '(f)\n', (5918, 5921), False, 'import yaml\n'), ((5968, 5986), 'copy.deepcopy', 'copy.deepcopy', (['cfg'], {}), '(cfg)\n', (5981, 5986), False, 'import copy\n'), ((6752, 6777), 'os.path.isfile', 'os.path.isfile', (['infer_img'], {}), '(infer_img)\n', (6766, 6777), False, 'import os\n'), ((6862, 6886), 'os.path.isdir', 'os.path.isdir', (['infer_dir'], {}), '(infer_dir)\n', (6875, 6886), False, 'import os\n'), ((7004, 7029), 'os.path.isfile', 'os.path.isfile', (['infer_img'], {}), '(infer_img)\n', (7018, 7029), False, 'import os\n'), ((8353, 8380), 'python.keypoint_preprocess.expand_crop', 'expand_crop', (['input', 'box[1:]'], {}), '(input, box[1:])\n', (8364, 8380), False, 'from python.keypoint_preprocess import EvalAffine, TopDownEvalAffine, expand_crop\n'), ((8754, 8771), 'numpy.array', 'np.array', (['mot_res'], {}), '(mot_res)\n', (8762, 8771), True, 'import numpy as np\n'), ((8055, 8078), 'python.keypoint_preprocess.expand_crop', 'expand_crop', (['input', 'box'], {}), '(input, box)\n', (8066, 8078), False, 'from python.keypoint_preprocess import EvalAffine, TopDownEvalAffine, expand_crop\n')]
import numpy as np from tqdm import tqdm import torch from torch.jit import load from torch.utils.data import DataLoader, Dataset from mlcomp.contrib.transform.tta import TtaWrap def apply_activation(x, activation): if not activation: return x if activation == 'sigmoid': return torch.sigmoid(x) if activation == 'softmax': return torch.softmax(x, 1) raise Exception(f'unknown activation = {activation}') def _infer_batch(model, loader: DataLoader, activation=None): for batch in tqdm(loader, total=len(loader)): features = batch['features'].cuda() logits = model(features) p = apply_activation(logits, activation) if isinstance(loader.dataset, TtaWrap): p = loader.dataset.inverse(p) p = p.detach().cpu().numpy() yield {'prob': p, 'count': p.shape[0], **batch} def _infer(model, loader: DataLoader, activation=None): pred = [] for batch in tqdm(loader, total=len(loader)): features = batch['features'].cuda() logits = model(features) p = apply_activation(logits, activation) if isinstance(loader.dataset, TtaWrap): p = loader.dataset.inverse(p) p = p.detach().cpu().numpy() pred.append(p) pred = np.vstack(pred) return pred def infer( x: Dataset, file: str, batch_size: int = 1, batch_mode: bool = False, activation=None, num_workers: int = 1, ): loader = DataLoader( x, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True ) model = load(file).cuda() if batch_mode: return _infer_batch(model, loader, activation=activation) return _infer(model, loader, activation=activation) __all__ = ['infer', 'apply_activation']
[ "torch.jit.load", "torch.sigmoid", "torch.softmax", "numpy.vstack", "torch.utils.data.DataLoader" ]
[((1286, 1301), 'numpy.vstack', 'np.vstack', (['pred'], {}), '(pred)\n', (1295, 1301), True, 'import numpy as np\n'), ((1504, 1601), 'torch.utils.data.DataLoader', 'DataLoader', (['x'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'num_workers', 'pin_memory': '(True)'}), '(x, batch_size=batch_size, shuffle=False, num_workers=num_workers,\n pin_memory=True)\n', (1514, 1601), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((307, 323), 'torch.sigmoid', 'torch.sigmoid', (['x'], {}), '(x)\n', (320, 323), False, 'import torch\n'), ((371, 390), 'torch.softmax', 'torch.softmax', (['x', '(1)'], {}), '(x, 1)\n', (384, 390), False, 'import torch\n'), ((1656, 1666), 'torch.jit.load', 'load', (['file'], {}), '(file)\n', (1660, 1666), False, 'from torch.jit import load\n')]
from __future__ import absolute_import, division, print_function, unicode_literals from warnings import simplefilter simplefilter(action='ignore', category=FutureWarning) import numpy as np import argparse import pandas as pd from tqdm.auto import tqdm from datetime import datetime, timedelta import lightgbm as lgb import logging import os from utils.functions import train_clf, compute_statistics_single_t0 from models.toy_poisson import ToyPoissonLoader from models.toy_gmm import ToyGMMLoader from models.toy_gamma import ToyGammaLoader from or_classifiers.toy_example_list import classifier_dict from qr_algorithms.complete_list import classifier_cde_dict from madminer.ml import DoubleParameterizedRatioEstimator from scipy.stats import chi2 model_dict = { 'poisson': ToyPoissonLoader, 'gmm': ToyGMMLoader, 'gamma': ToyGammaLoader } os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' def compute_statistics_single_t0_carl(model, obs_sample, t0, grid_param_t1, param_d): theta0_pred = np.repeat(t0, grid_param_t1.shape[0]).reshape(-1, param_d) theta1_pred = grid_param_t1 log_r_hat, _, _ = model.evaluate(theta0=theta0_pred, theta1=theta1_pred, x=obs_sample, evaluate_score=False) return np.min(np.sum(log_r_hat.reshape(theta1_pred.shape[0], obs_sample.shape[0]), axis=1)) def main(run, rep, b, b_prime, alpha, sample_size_obs, classifier_cde, sample_type='MC', cutoff='qr', debug=False, seed=7, size_check=1000, verbose=False, marginal=False, size_marginal=1000): # Changing values if debugging b = b if not debug else 100 b_prime = b_prime if not debug else 100 size_check = size_check if not debug else 100 rep = rep if not debug else 2 model_obj = model_dict[run](marginal=marginal, size_marginal=size_marginal) # Get the correct functions msnh_sampling_func = model_obj.sample_msnh_algo5 grid_param = model_obj.grid gen_obs_func = model_obj.sample_sim gen_sample_func = model_obj.generate_sample t0_grid = model_obj.pred_grid t0_val = model_obj.true_param lik_func = model_obj.compute_exact_likelihood np.random.seed(seed) # Adding Gaussian Process as an option in the classifier toy example num_hidden_vec = [(100, ), (20, 20), (50, 20)] for num_hidden in num_hidden_vec: classifier_dict['carl_' + str(num_hidden)] = num_hidden # # MadMiner output # logging.basicConfig( # format='%(asctime)-5.5s %(name)-20.20s %(levelname)-7.7s %(message)s', # datefmt='%H:%M', # level=logging.INFO # ) # # Output of all other modules (e.g. matplotlib) # for key in logging.Logger.manager.loggerDict: # if "madminer" not in key: # logging.getLogger(key).setLevel(logging.WARNING) # Loop over repetitions and classifiers # Each time we train the different classifiers, we build the intervals and we record # whether the point is in or not. out_val = [] out_cols = ['b_prime', 'b', 'classifier', 'classifier_cde', 'run', 'rep', 'sample_size_obs', 't0_true_val', 'theta_0_current', 'on_true_t0', 'estimated_tau', 'estimated_cutoff', 'in_confint', 'out_confint', 'size_CI', 'mse_loss', 'training_time', 'pred_time', 'bprime_time', 'cutoff_time', 'total_time', 'cutoff_type'] pbar = tqdm(total=rep, desc='Toy Example for Simulations, n=%s, b=%s' % (sample_size_obs, b)) for jj in range(rep): # Generates samples for each t0 values, so to be able to check both coverage and power x_obs = gen_obs_func(sample_size=sample_size_obs, true_param=t0_val) # Calculate the true likelihood ratio lik_theta0 = np.array([np.sum(np.log(lik_func(x_obs=x_obs, true_param=theta_0))) for theta_0 in t0_grid]) max_across_grid = np.max(np.array([np.sum(np.log(lik_func(x_obs=x_obs, true_param=t1))) for t1 in grid_param])) true_tau_obs = lik_theta0.reshape(-1, ) - max_across_grid.reshape(1) # print('TRUE', true_tau_obs) # Train the classifier for the odds clf_odds_fitted = {} clf_cde_fitted = {} for clf_name, clf_model in sorted(classifier_dict.items(), key=lambda x: x[0]): start_time = datetime.now() if 'carl_' in clf_name: # Create CARL carl = DoubleParameterizedRatioEstimator(n_hidden=clf_model) # Generate data for CARL if sample_type == 'MC': n_pairs = int(np.sqrt(b // 2)) theta0_base = np.linspace(start=model_obj.low_int, stop=model_obj.high_int, num=n_pairs) theta1_base = np.linspace(start=model_obj.low_int, stop=model_obj.high_int, num=n_pairs) theta0 = np.repeat(theta0_base.reshape(-1, 1), int(n_pairs)) theta1 = np.tile(theta1_base.reshape(-1, 1), (int(n_pairs), 1)) elif sample_type == 'uniform': n_pairs = int(b // 2) theta0 = np.random.uniform(low=model_obj.low_int, high=model_obj.high_int, size=n_pairs) theta1 = np.random.uniform(low=model_obj.low_int, high=model_obj.high_int, size=n_pairs) else: raise NotImplementedError sample_t0 = np.array([model_obj.sample_sim(sample_size=sample_size_obs, true_param=t0) for t0 in theta0]) sample_t1 = np.array([model_obj.sample_sim(sample_size=sample_size_obs, true_param=t1) for t1 in theta1]) theta_mat = np.vstack((np.hstack((theta0.reshape(-1, model_obj.d), theta1.reshape(-1, model_obj.d))), np.hstack((theta0.reshape(-1, model_obj.d), theta1.reshape(-1, model_obj.d))))) x_mat = np.vstack((sample_t0.reshape(-1, sample_size_obs), sample_t1.reshape(-1, sample_size_obs))) y_mat = np.vstack((np.zeros(b // 2).reshape(-1, 1), np.ones(b // 2).reshape(-1, 1))) carl.train(method='carl', x=x_mat, y=y_mat, theta0=theta_mat[:, :model_obj.d], theta1=theta_mat[:, model_obj.d:], n_epochs=25, initial_lr=1e-4, final_lr=1e-4) training_time = datetime.now() theta0_pred = np.repeat(t0_grid, grid_param.shape[0]).reshape(-1, model_obj.d) theta1_pred = np.tile(grid_param, (t0_grid.shape[0], 1)).reshape(-1, model_obj.d) log_r_hat, _, _ = carl.evaluate(theta0=theta0_pred, theta1=theta1_pred, x=x_obs, evaluate_score=False) tau_obs = np.min( np.sum(log_r_hat.reshape(t0_grid.shape[0], grid_param.shape[0], sample_size_obs), axis=2), axis=1) clf_odds_fitted[clf_name] = (tau_obs, np.mean((tau_obs - true_tau_obs)**2)) pred_time = datetime.now() if cutoff == 'qr': # Calculate the LR statistics given a sample theta_mat, sample_mat = msnh_sampling_func(b_prime=b_prime, sample_size=sample_size_obs) full_mat = np.hstack((theta_mat, sample_mat)) stats_mat = np.apply_along_axis(arr=full_mat, axis=1, func1d=lambda row: compute_statistics_single_t0_carl( model=carl, obs_sample=row[model_obj.d:], t0=row[:model_obj.d], grid_param_t1=grid_param, param_d=model_obj.d )) bprime_time = datetime.now() clf_cde_fitted[clf_name] = {} # for clf_name_qr, clf_params in sorted(classifier_cde_dict.items(), key=lambda x: x[0]): clf_name_qr = classifier_cde clf_params = classifier_cde_dict[classifier_cde] model = lgb.LGBMRegressor(objective='quantile', alpha=alpha, **clf_params[1]) model.fit(theta_mat.reshape(-1, model_obj.d), stats_mat.reshape(-1, )) t0_pred_vec = model.predict(t0_grid.reshape(-1, model_obj.d)) elif cutoff == 'chisquare': chisquare_cutoff = chi2.ppf(q=1.0 - alpha, df=1) t0_pred_vec = np.array([-0.5 * chisquare_cutoff] * tau_obs.shape[0]) bprime_time = datetime.now() clf_name_qr = classifier_cde clf_cde_fitted[clf_name] = {} else: raise ValueError('Cutoff %s not recognized. Either "qr" or "chisquare" are accepted' % cutoff) else: clf_odds = train_clf(sample_size=b, clf_model=clf_model, gen_function=gen_sample_func, clf_name=clf_name, marginal=marginal, nn_square_root=True) training_time = datetime.now() if verbose: print('----- %s Trained' % clf_name) tau_obs = np.array([ compute_statistics_single_t0( clf=clf_odds, obs_sample=x_obs, t0=theta_0, grid_param_t1=grid_param, d=model_obj.d, d_obs=model_obj.d_obs) for theta_0 in t0_grid]) clf_odds_fitted[clf_name] = (tau_obs, np.mean((tau_obs - true_tau_obs)**2)) #print(clf_name, np.mean((tau_obs - true_tau_obs)**2)) pred_time = datetime.now() # Train the quantile regression algorithm for confidence levels theta_mat, sample_mat = msnh_sampling_func(b_prime=b_prime, sample_size=sample_size_obs) full_mat = np.hstack((theta_mat, sample_mat)) stats_mat = np.apply_along_axis(arr=full_mat, axis=1, func1d=lambda row: compute_statistics_single_t0( clf=clf_odds, obs_sample=row[model_obj.d:], t0=row[:model_obj.d], grid_param_t1=grid_param, d=model_obj.d, d_obs=model_obj.d_obs )) bprime_time = datetime.now() clf_cde_fitted[clf_name] = {} # for clf_name_qr, clf_params in sorted(classifier_cde_dict.items(), key=lambda x: x[0]): clf_name_qr = classifier_cde clf_params = classifier_cde_dict[classifier_cde] model = lgb.LGBMRegressor(objective='quantile', alpha=alpha, **clf_params[1]) model.fit(theta_mat.reshape(-1, model_obj.d), stats_mat.reshape(-1, )) t0_pred_vec = model.predict(t0_grid.reshape(-1, model_obj.d)) cutoff_time = datetime.now() clf_cde_fitted[clf_name][clf_name_qr] = ( t0_pred_vec, ((training_time - start_time).total_seconds() * 100, (pred_time - training_time).total_seconds() * 100, (bprime_time - pred_time).total_seconds() * 100, (cutoff_time - bprime_time).total_seconds() * 100)) # At this point all it's left is to record for clf_name, (tau_obs_val, mse_val) in clf_odds_fitted.items(): for clf_name_qr, (cutoff_val, time_vec) in clf_cde_fitted[clf_name].items(): size_temp = np.sum((tau_obs_val >= cutoff_val).astype(int))/t0_grid.shape[0] for kk, theta_0_current in enumerate(t0_grid): out_val.append([ b_prime, b, clf_name, clf_name_qr, run, jj, sample_size_obs, t0_val, theta_0_current, int(t0_val == theta_0_current), tau_obs_val[kk], cutoff_val[kk], int(tau_obs_val[kk] > cutoff_val[kk]), int(tau_obs_val[kk] <= cutoff_val[kk]), size_temp, mse_val, time_vec[0], time_vec[1], time_vec[2], time_vec[3], sum(time_vec), cutoff ]) pbar.update(1) # Saving the results out_df = pd.DataFrame.from_records(data=out_val, index=range(len(out_val)), columns=out_cols) out_dir = 'sims/gp_mc_comparison/' out_filename = 'classifier_reps_carl_%s_comparison_%sB_%sBprime_%s_%srep_alpha%s_sampleobs%s_t0val%s_%s_%s.csv' % ( sample_type, b, b_prime, run, rep, str(alpha).replace('.', '-'), sample_size_obs, str(t0_val).replace('.', '-'), classifier_cde, datetime.strftime(datetime.today(), '%Y-%m-%d') ) out_df.to_csv(out_dir + out_filename) # Print results cov_df = out_df[out_df['on_true_t0'] == 1][['classifier', 'classifier_cde', 'in_confint', 'mse_loss', 'size_CI', 'training_time', 'pred_time', 'bprime_time', 'cutoff_time', 'total_time']] print(cov_df.groupby(['classifier', 'classifier_cde']).agg({'in_confint': [np.average], 'size_CI': [np.average, np.std], 'mse_loss': [np.average, np.std], 'training_time': [np.average, np.std], 'pred_time': [np.average, np.std], 'bprime_time': [np.average, np.std], 'cutoff_time': [np.average, np.std], 'total_time': [np.average, np.std]})) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--seed', action="store", type=int, default=7, help='Random State') parser.add_argument('--rep', action="store", type=int, default=100, help='Number of Repetitions for calculating the Pinball loss') parser.add_argument('--b', action="store", type=int, default=200, help='Sample size to train the classifier for calculating odds') parser.add_argument('--b_prime', action="store", type=int, default=1000, help='Sample size to train the quantile regression algorithm') parser.add_argument('--marginal', action='store_true', default=False, help='Whether we are using a parametric approximation of the marginal or' 'the baseline reference G') parser.add_argument('--alpha', action="store", type=float, default=0.1, help='Statistical confidence level') parser.add_argument('--run', action="store", type=str, default='poisson', help='Problem to run') parser.add_argument('--sample_type', action="store", type=str, default='MC', help='Sampling type for the Gaussian Process. MC means Monte Carlo, so it selects a number' ' of anchor points and samples sample_size/anchor points samples there, otherwise it' ' samples points uniformly.') parser.add_argument('--debug', action='store_true', default=False, help='If true, a very small value for the sample sizes is fit to make sure the' 'file can run quickly for debugging purposes') parser.add_argument('--verbose', action='store_true', default=False, help='If true, logs are printed to the terminal') parser.add_argument('--sample_size_obs', action="store", type=int, default=1, help='Sample size of the actual observed data.') parser.add_argument('--t0_val', action="store", type=float, default=10.0, help='True parameter which generates the observed dataset') parser.add_argument('--class_cde', action="store", type=str, default='xgb_d3_n100', help='Classifier for quantile regression') parser.add_argument('--size_marginal', action="store", type=int, default=1000, help='Sample size of the actual marginal distribution, if marginal is True.') parser.add_argument('--or_loss_samples', action="store", type=int, default=1000, help='Sample size for the calculation of the OR loss.') parser.add_argument('--cutoff', action="store", type=str, default='qr', help='How to obtain the cutoff approximation: either qr (quantile regression estimation)' ' or chisquare (chisquare approximation via Wilks theorem)') # parser.add_argument('--n_anchor', action="store", type=int, default=5, # help='Number of Gaussian Process anchor points in the theta space.') argument_parsed = parser.parse_args() # b_vec = [200, 800, 1800] # for b_val in b_vec: main( run=argument_parsed.run, rep=argument_parsed.rep, marginal=argument_parsed.marginal, b=argument_parsed.b, b_prime=argument_parsed.b_prime, alpha=argument_parsed.alpha, debug=argument_parsed.debug, sample_size_obs=argument_parsed.sample_size_obs, seed=argument_parsed.seed, verbose=argument_parsed.verbose, classifier_cde=argument_parsed.class_cde, size_marginal=argument_parsed.size_marginal, sample_type=argument_parsed.sample_type, cutoff=argument_parsed.cutoff )
[ "numpy.sqrt", "numpy.hstack", "lightgbm.LGBMRegressor", "numpy.array", "scipy.stats.chi2.ppf", "datetime.datetime.today", "numpy.mean", "numpy.repeat", "argparse.ArgumentParser", "utils.functions.compute_statistics_single_t0", "numpy.linspace", "numpy.random.seed", "warnings.simplefilter", ...
[((117, 170), 'warnings.simplefilter', 'simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (129, 170), False, 'from warnings import simplefilter\n'), ((2150, 2170), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2164, 2170), True, 'import numpy as np\n'), ((3371, 3462), 'tqdm.auto.tqdm', 'tqdm', ([], {'total': 'rep', 'desc': "('Toy Example for Simulations, n=%s, b=%s' % (sample_size_obs, b))"}), "(total=rep, desc='Toy Example for Simulations, n=%s, b=%s' % (\n sample_size_obs, b))\n", (3375, 3462), False, 'from tqdm.auto import tqdm\n'), ((14375, 14400), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (14398, 14400), False, 'import argparse\n'), ((1006, 1043), 'numpy.repeat', 'np.repeat', (['t0', 'grid_param_t1.shape[0]'], {}), '(t0, grid_param_t1.shape[0])\n', (1015, 1043), True, 'import numpy as np\n'), ((4197, 4220), 'or_classifiers.toy_example_list.classifier_dict.items', 'classifier_dict.items', ([], {}), '()\n', (4218, 4220), False, 'from or_classifiers.toy_example_list import classifier_dict\n'), ((4269, 4283), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4281, 4283), False, 'from datetime import datetime, timedelta\n'), ((11359, 11373), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (11371, 11373), False, 'from datetime import datetime, timedelta\n'), ((4375, 4428), 'madminer.ml.DoubleParameterizedRatioEstimator', 'DoubleParameterizedRatioEstimator', ([], {'n_hidden': 'clf_model'}), '(n_hidden=clf_model)\n', (4408, 4428), False, 'from madminer.ml import DoubleParameterizedRatioEstimator\n'), ((6359, 6373), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (6371, 6373), False, 'from datetime import datetime, timedelta\n'), ((7029, 7043), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (7041, 7043), False, 'from datetime import datetime, timedelta\n'), ((9079, 9217), 'utils.functions.train_clf', 'train_clf', ([], {'sample_size': 'b', 'clf_model': 'clf_model', 'gen_function': 'gen_sample_func', 'clf_name': 'clf_name', 'marginal': 'marginal', 'nn_square_root': '(True)'}), '(sample_size=b, clf_model=clf_model, gen_function=gen_sample_func,\n clf_name=clf_name, marginal=marginal, nn_square_root=True)\n', (9088, 9217), False, 'from utils.functions import train_clf, compute_statistics_single_t0\n'), ((9283, 9297), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (9295, 9297), False, 'from datetime import datetime, timedelta\n'), ((9843, 9857), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (9855, 9857), False, 'from datetime import datetime, timedelta\n'), ((10071, 10105), 'numpy.hstack', 'np.hstack', (['(theta_mat, sample_mat)'], {}), '((theta_mat, sample_mat))\n', (10080, 10105), True, 'import numpy as np\n'), ((10795, 10809), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (10807, 10809), False, 'from datetime import datetime, timedelta\n'), ((11097, 11166), 'lightgbm.LGBMRegressor', 'lgb.LGBMRegressor', ([], {'objective': '"""quantile"""', 'alpha': 'alpha'}), "(objective='quantile', alpha=alpha, **clf_params[1])\n", (11114, 11166), True, 'import lightgbm as lgb\n'), ((13104, 13120), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (13118, 13120), False, 'from datetime import datetime, timedelta\n'), ((4596, 4670), 'numpy.linspace', 'np.linspace', ([], {'start': 'model_obj.low_int', 'stop': 'model_obj.high_int', 'num': 'n_pairs'}), '(start=model_obj.low_int, stop=model_obj.high_int, num=n_pairs)\n', (4607, 4670), True, 'import numpy as np\n'), ((4705, 4779), 'numpy.linspace', 'np.linspace', ([], {'start': 'model_obj.low_int', 'stop': 'model_obj.high_int', 'num': 'n_pairs'}), '(start=model_obj.low_int, stop=model_obj.high_int, num=n_pairs)\n', (4716, 4779), True, 'import numpy as np\n'), ((6963, 7001), 'numpy.mean', 'np.mean', (['((tau_obs - true_tau_obs) ** 2)'], {}), '((tau_obs - true_tau_obs) ** 2)\n', (6970, 7001), True, 'import numpy as np\n'), ((7285, 7319), 'numpy.hstack', 'np.hstack', (['(theta_mat, sample_mat)'], {}), '((theta_mat, sample_mat))\n', (7294, 7319), True, 'import numpy as np\n'), ((7979, 7993), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (7991, 7993), False, 'from datetime import datetime, timedelta\n'), ((8301, 8370), 'lightgbm.LGBMRegressor', 'lgb.LGBMRegressor', ([], {'objective': '"""quantile"""', 'alpha': 'alpha'}), "(objective='quantile', alpha=alpha, **clf_params[1])\n", (8318, 8370), True, 'import lightgbm as lgb\n'), ((9706, 9744), 'numpy.mean', 'np.mean', (['((tau_obs - true_tau_obs) ** 2)'], {}), '((tau_obs - true_tau_obs) ** 2)\n', (9713, 9744), True, 'import numpy as np\n'), ((4545, 4560), 'numpy.sqrt', 'np.sqrt', (['(b // 2)'], {}), '(b // 2)\n', (4552, 4560), True, 'import numpy as np\n'), ((5063, 5142), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'model_obj.low_int', 'high': 'model_obj.high_int', 'size': 'n_pairs'}), '(low=model_obj.low_int, high=model_obj.high_int, size=n_pairs)\n', (5080, 5142), True, 'import numpy as np\n'), ((5172, 5251), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'model_obj.low_int', 'high': 'model_obj.high_int', 'size': 'n_pairs'}), '(low=model_obj.low_int, high=model_obj.high_int, size=n_pairs)\n', (5189, 5251), True, 'import numpy as np\n'), ((6405, 6444), 'numpy.repeat', 'np.repeat', (['t0_grid', 'grid_param.shape[0]'], {}), '(t0_grid, grid_param.shape[0])\n', (6414, 6444), True, 'import numpy as np\n'), ((6500, 6542), 'numpy.tile', 'np.tile', (['grid_param', '(t0_grid.shape[0], 1)'], {}), '(grid_param, (t0_grid.shape[0], 1))\n', (6507, 6542), True, 'import numpy as np\n'), ((8627, 8656), 'scipy.stats.chi2.ppf', 'chi2.ppf', ([], {'q': '(1.0 - alpha)', 'df': '(1)'}), '(q=1.0 - alpha, df=1)\n', (8635, 8656), False, 'from scipy.stats import chi2\n'), ((8691, 8745), 'numpy.array', 'np.array', (['([-0.5 * chisquare_cutoff] * tau_obs.shape[0])'], {}), '([-0.5 * chisquare_cutoff] * tau_obs.shape[0])\n', (8699, 8745), True, 'import numpy as np\n'), ((8781, 8795), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8793, 8795), False, 'from datetime import datetime, timedelta\n'), ((9441, 9581), 'utils.functions.compute_statistics_single_t0', 'compute_statistics_single_t0', ([], {'clf': 'clf_odds', 'obs_sample': 'x_obs', 't0': 'theta_0', 'grid_param_t1': 'grid_param', 'd': 'model_obj.d', 'd_obs': 'model_obj.d_obs'}), '(clf=clf_odds, obs_sample=x_obs, t0=theta_0,\n grid_param_t1=grid_param, d=model_obj.d, d_obs=model_obj.d_obs)\n', (9469, 9581), False, 'from utils.functions import train_clf, compute_statistics_single_t0\n'), ((10243, 10411), 'utils.functions.compute_statistics_single_t0', 'compute_statistics_single_t0', ([], {'clf': 'clf_odds', 'obs_sample': 'row[model_obj.d:]', 't0': 'row[:model_obj.d]', 'grid_param_t1': 'grid_param', 'd': 'model_obj.d', 'd_obs': 'model_obj.d_obs'}), '(clf=clf_odds, obs_sample=row[model_obj.d:], t0\n =row[:model_obj.d], grid_param_t1=grid_param, d=model_obj.d, d_obs=\n model_obj.d_obs)\n', (10271, 10411), False, 'from utils.functions import train_clf, compute_statistics_single_t0\n'), ((6030, 6046), 'numpy.zeros', 'np.zeros', (['(b // 2)'], {}), '(b // 2)\n', (6038, 6046), True, 'import numpy as np\n'), ((6063, 6078), 'numpy.ones', 'np.ones', (['(b // 2)'], {}), '(b // 2)\n', (6070, 6078), True, 'import numpy as np\n')]
import argparse import numpy as np import sys import os, datetime import errno import scipy.io as sio #for mat file import timeit import pandas as pd from AR_v160_svm import * ############################################################ parser = argparse.ArgumentParser() # Algorithm settings parser.add_argument('-b', '--batch_size', help="batchsize", type=int, default=800) parser.add_argument('-e', '--epochs', help="training epochs", type=int, default=500) parser.add_argument('-v', '--verbose', help="keras verbosity", type=int, default=0, choices=[0, 1, 2]) parser.add_argument('-mf', '--model_file', help="Path to stored model file for model evaluation. " "If not specified, trained model for respective patient is expected in " "current working directory", default=None) # Evaluation settings parser.add_argument('-csv', '--path', help='path to the csv that includes the files', default='/CSVs') parser.add_argument('-m', '--mode', help='Mode. 0: feature generation, Mode. 1: training, 2: validation, 3: test', type=int, default=-1, choices=[-1, 0, 1, 2, 3]) parser.add_argument('-p', '--patient', help='Patient number, 1 to 15 is available', type=int, default=1) parser.add_argument('-l', '--file_segment_length', help='Segment length in minutes, 1 or 10', type=int, default=10) parser.add_argument('-sm', '--subtract_mean', help='Subtract channelwise mean of each file', type=int, default=1, choices=[0, 1]) parser.add_argument('-ns', '--n_start', help='Starting index of segments to calculate features for', type=int, default=-1) parser.add_argument('-ne', '--n_end', help='End index of segments to calculate features for', type=int, default=-1) parser.add_argument('-mns', '--model_ensemble_size', help='Size of model ensemble tested for each feature combination', type=int, default=20) parser.add_argument('-uf', '--uvar_fea', help='Univariate feature used', default='', choices=['c','e','E','p','y','cE','ce','cp','cy','ey','Ey','ep','Ep','py','cpe','cpE','epy','Epy','cey','cEy','cpy','cepy','cEpy']) parser.add_argument('-bf', '--bvar_fea', help='bivariate feature used', default='', choices=['_mpcH_','_mpcR_','_lincoh_','_corrfAmp_','_corrfPha_','_corr_']) parser.add_argument('-bv', '--bvar_var', help='variant of bivariate feature used', default='a', choices=['a','b','ab']) parser.add_argument('-nt', '--n_train', help='For grid search of best feature combination. The train set is split into train and valid subsets. It is assumed that the first [n_train] segments are the train subset and the rest is for validation. If not specified the first 2/3 will be used for train.', type=int, default=None) parser.add_argument('-wm', '--which_model', help='Which model should be used for train set. 0: best model from grid search, 1: retrain for the train set', type=int, default=0, choices=[0, 1]) ############################################################ args = parser.parse_args() print(args) patient_index=args.patient segment_length_minutes=args.file_segment_length mode=args.mode pat='patient'+str(patient_index) which_model=parser.which_model ############################################################ Seer_name='hlya23dd' num_channel=16 Num_neigh=1 # 1 channel prediction, univariant time_delay=3 # order of AR model poly_order=1 # polynomial order regression_mode = 0 # 0: model2 = LinearRegression(fit_intercept = False) n_noisy=1 # 1 is used to show the noise part can be modeled as well i_low_pass=1 # surrogate F_threshold=0.0 # [4, 8, 12, 30] frequency threshold for filtering the EEG signal, f_threshold*noise_level = 0 #noise strength for generating surrogate signal, f_threshold*noise_level = 0 Noise_level=0.0 # do not change this, only if you want to add noise # to randomize phase while keeping power spectrum, please set f_range to negative values !!! import os cwd = os.getcwd() feature_dir=cwd+'/features/' i_standardization = -1 # no normalization ############################### feature_select=args.uvar_fea dim_feature_channelwise=14 mvar_feature_lib=['mpcH','mpcR','lincoh','corrfAmp','corrfPha','corr'] mvar_feature_range =['_mpcH_','_mpcR_','_lincoh_','_corrfAmp_','_corrfPha_','_corr_'] mvar_feature_select= args.bvar_fea feature_level = args.bvar_var feature_band_range = ['bandYang'] ############################### # mlp parameters batch_size=args.batch_size epochs=args.epochs kernel_constraint_weight=0 i_feature_selection=0 hidden_layer_size=[16,8,4] verbose =args.verbose # Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. i_class_weight = 'balanced' i_sample_weight =1 my_class_1_weight =100 ############################### from Best_model import * #feature_select='+opt_uvar+'\n') #mvar_feature_select='+opt_mvar+'\n') #feature_level='+opt_level+'\n') #model_file_name='+opt_model_name+'\n') ############################### if mode <= 1: # train & feature_generation segment_file_name_lables='/CSVs/train_filenames_labels_patient['+str(patient_index)+']_segment_length_['+str(segment_length_minutes)+'].csv' if mode == 2: # valid segment_file_name_lables='/CSVs/validation+_filenames_patient['+str(patient_index)+']_segment_length_['+str(segment_length_minutes)+'].csv' if mode == 3: # test segment_file_name_lables='/CSVs/test_filenames_patient['+str(patient_index)+']_segment_length_['+str(segment_length_minutes)+'].csv' df = pd.read_csv(segment_file_name_lables) n_files=len(df) segment_fnames=df['image'] i_file_range=range(n_files) if mode == 1: # train labels=df['class'] else: labels=np.zeros(n_files) for i_mat_segment in i_file_range: channel_range=range(0,num_channel) # univarinat pat_gData,pat_gLabel = eeg_pca_ica_mat_segment_Melborne(segment_fnames[i_mat_segment],labels[i_mat_segment],segment_length_minutes) print(pat_gData.shape) if pat_gData.shape[0] < 1: continue ############################################################ # generate uvar ##### if True: ar_poly_input={'poly_order': poly_order, 'time_delay': time_delay, 'regression_mode': regression_mode, 'num_neigh': Num_neigh, 'pat_gData': pat_gData, 'pat_gLabel': pat_gLabel, 'f_threshold': F_threshold, 'n_noisy': n_noisy, 'i_low_pass': i_low_pass, 'noise_level': Noise_level } my_feature, my_label = ar_ps(ar_poly_input) print(my_feature.shape) dim_feature_channelwise=int(my_feature.shape[1]/num_channel) mask=get_feature_mask(feature_select,time_delay,dim_feature_channelwise) mask=np.asarray(mask) dim_feature=mask.sum() my_feature = (my_feature.T[mask>0.5]).T if sum(mask)>0: feature_flag=1 print(my_feature.shape) else: feature_flag=0 #### # get mvar #### pat_gData=pat_gData*1.0 # pat_gData seems to be integer, this cause trouble, 2018.11.28 for feature, feature_function in zip(mvar_feature_lib, mvar_feature_function_lib): feature_ = '_'+feature+'_' if feature_ in mvar_feature_select: print(feature) pat_gData2=pat_gData.copy()*1.0 exec("dict_return = "+ feature_function) exec(feature+'_m' + " = dict_return['corr_y']") exec(feature+'_max' + " = dict_return['corr_max']") exec(feature+'_eva' + " = dict_return['e_values']") exec(feature+'_eve' + " = dict_return['e_vector']") exec(feature+'b' + " = np.c_["+feature+'_eva,' +feature+'_eve,' +feature+"_max]") exec(feature+'a' + " = "+feature+'_m') if feature_flag==0: feature_flag=1 if 'a' in feature_level: exec("my_feature ="+feature+'a') if 'b' in feature_level: exec("my_feature ="+feature+'b') if 'ab' in feature_level: exec("my_feature =np.c_["+feature+'a,'+feature+'b]') else: if 'a' in feature_level: exec("my_feature =np.c_[my_feature,"+feature+'a]') if 'b' in feature_level: exec("my_feature =np.c_[my_feature,"+feature+'b]') print("feature calculation is done!") print(my_feature.shape) ############################################################ # collect features for different segments print('feature collection') if i_mat_segment == i_file_range[0]: my_label_all = pat_gLabel my_feature_all=my_feature else: my_label_all = np.r_[my_label_all,pat_gLabel] my_feature_all=np.r_[my_feature_all,my_feature] ####################################################### 2018-12-5 # replace NaN of samples my_feature_all = feature_NaN(my_feature_all,my_feature_all.shape[1]) my_feature_all = feature_inf(my_feature_all,my_feature_all.shape[1]) # mean centralization & standalization if i_standarization >0: for i_feature in range(my_feature_all.shape[1]): yy=my_feature_all[:,i_feature] yy= yy-sum(yy)/len(yy) # mean centralization if sum(yy*yy)>0: yy= yy/np.sqrt(sum(yy*yy)/len(yy)) # normalization my_feature_all[:,i_feature]=yy ###################################################### start = timeit.default_timer() ### # mlp-prb ### if which_model==0: roc_auc3, pr_auc3, test_label_10, probas2_10, model_file_name = keras_mlp_10m_prb_oldmodel_test(my_feature_all, my_label_all, model_file_name) elif mode==1: n_1=sum(my_label_all) n_0=len(my_label_all)-n_1 class_1_weight=n_0/n_1 reset_keras() roc_auc, roc_auc3, pr_auc, pr_auc3, model_file_name = keras_mlp_10m_prb(my_feature_all, my_label_all, my_feature_all, my_label_all, mydir, pat, segment_length_minutes, class_1_weight, batch_size, epochs, kernel_constraint_weight, verbose, hidden_layer_size, i_feature_selection) roc_auc3, pr_auc3, test_label_10, probas2_10, model_file_name = keras_mlp_10m_prb_oldmodel_test(my_feature_all, my_label_all, model_file_name) with open("Train_model.py", "w") as myfile: myfile.write('model_file_name='+model_file_name) else: from Train_model import * roc_auc3, pr_auc3, test_label_10, probas2_10, model_file_name = keras_mlp_10m_prb_oldmodel_test(my_feature_all, my_label_all, model_file_name) print(roc_auc3, pr_auc3) if not os.path.exists('solutions'): os.makedirs('solutions') solution_fname='solutions/solution_['+Seer_Username+']_pat['+str(patient_index)+']_seg['+str(segment_length_minutes)+']_mode['+str(mode)+']_subtract['+str(subtract_mean)+'].csv' solutions = pd.DataFrame({'image': df['image'], 'class': probas2_10}) solutions = solutions[['image','class']] solutions.to_csv(solution_fname,index=0) stop = timeit.default_timer() print(pat+' Time: ', stop - start)
[ "os.path.exists", "pandas.read_csv", "argparse.ArgumentParser", "os.makedirs", "timeit.default_timer", "numpy.asarray", "os.getcwd", "numpy.zeros", "pandas.DataFrame" ]
[((252, 277), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (275, 277), False, 'import argparse\n'), ((3967, 3978), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (3976, 3978), False, 'import os\n'), ((5518, 5555), 'pandas.read_csv', 'pd.read_csv', (['segment_file_name_lables'], {}), '(segment_file_name_lables)\n', (5529, 5555), True, 'import pandas as pd\n'), ((9558, 9580), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (9578, 9580), False, 'import timeit\n'), ((10909, 10966), 'pandas.DataFrame', 'pd.DataFrame', (["{'image': df['image'], 'class': probas2_10}"], {}), "({'image': df['image'], 'class': probas2_10})\n", (10921, 10966), True, 'import pandas as pd\n'), ((11058, 11080), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (11078, 11080), False, 'import timeit\n'), ((5688, 5705), 'numpy.zeros', 'np.zeros', (['n_files'], {}), '(n_files)\n', (5696, 5705), True, 'import numpy as np\n'), ((6713, 6729), 'numpy.asarray', 'np.asarray', (['mask'], {}), '(mask)\n', (6723, 6729), True, 'import numpy as np\n'), ((10659, 10686), 'os.path.exists', 'os.path.exists', (['"""solutions"""'], {}), "('solutions')\n", (10673, 10686), False, 'import os\n'), ((10692, 10716), 'os.makedirs', 'os.makedirs', (['"""solutions"""'], {}), "('solutions')\n", (10703, 10716), False, 'import os\n')]
import argparse import numpy as np import torch import pandas as pd import time from sklearn.linear_model import RidgeClassifierCV, RidgeClassifier from Net.ROCKET import ROCKET # == notes ===================================================================== # Reproduce the experiments on the UCR archive. # # For use with the txt version of the datasets (timeseriesclassification.com) # and, for datasets with missing values and/or variable-length time series, # with missing values interpolated, and variable-length time series padded to # the same length as the longest time series per the version of the datasets as # per https://www.cs.ucr.edu/~eamonn/time_series_data_2018/. # # Arguments: # -d --dataset_names : txt file of dataset names # -i --input_path : parent directory for datasets # -o --output_path : path for results # -n --num_runs : number of runs (optional, default 10) # -k --num_kernels : number of kernels (optional, default 10,000) # # *dataset_names* should be a txt file of dataset names, each on a new line. # # If *input_path* is, e.g., ".../Univariate_arff/", then each dataset should be # located at "{input_path}/{dataset_name}/{dataset_name}_TRAIN.txt", etc. # == parse arguments =========================================================== parser = argparse.ArgumentParser() parser.add_argument("-d", "--dataset_names", default = "ds_info.csv") parser.add_argument("-i", "--input_path", default = "../../UCRArchive_2018") parser.add_argument("-o", "--output_path", default = "../results") parser.add_argument("-n", "--num_runs", type = int, default = 5) parser.add_argument("-k", "--num_kernels", type = int, default = 10_000) arguments = parser.parse_args() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # == run ======================================================================= dataset_info = pd.read_csv(arguments.dataset_names) dataset_names = dataset_info["dataset"].values results = pd.DataFrame(index = dataset_names, columns = ["acc_mean", "acc_std", "acc_best", "time_train", "time_val"], data = 0) results.index.name = "dataset" print(f"RUNNING".center(80, "=")) for dataset_name in dataset_names: print(f"{dataset_name}".center(80, "-")) # -- read data ------------------------------------------------------------- print(f"Loading data".ljust(80 - 5, "."), end = "", flush = True) training_data = np.loadtxt(f"{arguments.input_path}/{dataset_name}/{dataset_name}_TRAIN.tsv", dtype=np.float32) Y_training, X_training = training_data[:, 0].astype(np.int32), training_data[:, 1:] # for i in range(X_training.shape[0]): # X_training[i] = (X_training[i] - np.mean(X_training[i]))/np.std(X_training[i]) X_training = torch.from_numpy(X_training).unsqueeze(1).to(device) if Y_training.min(0) == 1: Y_training -= 1 Y_training = torch.from_numpy(Y_training) test_data = np.loadtxt(f"{arguments.input_path}/{dataset_name}/{dataset_name}_TEST.tsv", dtype=np.float32) Y_test, X_test = test_data[:, 0].astype(np.int32), test_data[:, 1:] X_test = torch.from_numpy(X_test).unsqueeze(1).to(device) if Y_test.min(0) == 1: Y_test -= 1 Y_test = torch.from_numpy(Y_test) print("Done.") # -- run ------------------------------------------------------------------- print(f"Performing runs".ljust(80 - 5, "."), end = "", flush = True) _results = np.zeros(arguments.num_runs) _timings = np.zeros([4, arguments.num_runs]) # trans. tr., trans. te., training, test for i in range(arguments.num_runs): input_length = X_training.shape[-1] model = ROCKET(1, input_length, arguments.num_kernels).to(device) # model = torch.load('../models/{}.pkl'.format(dataset_name)).to(device) # -- transform training ------------------------------------------------ time_a = time.perf_counter() with torch.no_grad(): X_training_transform = model(X_training).cpu().numpy() time_b = time.perf_counter() _timings[0, i] = time_b - time_a # -- transform test ---------------------------------------------------- time_a = time.perf_counter() with torch.no_grad(): X_test_transform = model(X_test).cpu().numpy() time_b = time.perf_counter() _timings[1, i] = time_b - time_a # -- training ---------------------------------------------------------- torch.cuda.empty_cache() time_a = time.perf_counter() classifier = RidgeClassifierCV(alphas = np.logspace(-3, 3, 10), normalize = True) # classifier = RidgeClassifier(normalize = True) # classifier = LogisticRegression(penalty='none', max_iter=1000) classifier.fit(X_training_transform, Y_training) time_b = time.perf_counter() _timings[2, i] = time_b - time_a # -- test -------------------------------------------------------------- time_a = time.perf_counter() _results[i] = classifier.score(X_test_transform, Y_test) time_b = time.perf_counter() _timings[3, i] = time_b - time_a print("Done.") # -- store results --------------------------------------------------------- results.loc[dataset_name, "acc_mean"] = _results.mean() results.loc[dataset_name, "acc_std"] = _results.std() results.loc[dataset_name, "acc_best"] = _results.max() results.loc[dataset_name, "time_train"] = _timings.mean(1)[[0, 2]].sum() results.loc[dataset_name, "time_val"] = _timings.mean(1)[[1, 3]].sum() print(f"FINISHED".center(80, "=")) results.to_csv(f"{arguments.output_path}/rocket.csv")
[ "argparse.ArgumentParser", "pandas.read_csv", "time.perf_counter", "torch.from_numpy", "numpy.zeros", "torch.cuda.is_available", "Net.ROCKET.ROCKET", "pandas.DataFrame", "torch.no_grad", "numpy.loadtxt", "numpy.logspace", "torch.cuda.empty_cache" ]
[((1299, 1324), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1322, 1324), False, 'import argparse\n'), ((1881, 1917), 'pandas.read_csv', 'pd.read_csv', (['arguments.dataset_names'], {}), '(arguments.dataset_names)\n', (1892, 1917), True, 'import pandas as pd\n'), ((1976, 2092), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'dataset_names', 'columns': "['acc_mean', 'acc_std', 'acc_best', 'time_train', 'time_val']", 'data': '(0)'}), "(index=dataset_names, columns=['acc_mean', 'acc_std',\n 'acc_best', 'time_train', 'time_val'], data=0)\n", (1988, 2092), True, 'import pandas as pd\n'), ((2599, 2698), 'numpy.loadtxt', 'np.loadtxt', (['f"""{arguments.input_path}/{dataset_name}/{dataset_name}_TRAIN.tsv"""'], {'dtype': 'np.float32'}), "(f'{arguments.input_path}/{dataset_name}/{dataset_name}_TRAIN.tsv',\n dtype=np.float32)\n", (2609, 2698), True, 'import numpy as np\n'), ((3062, 3090), 'torch.from_numpy', 'torch.from_numpy', (['Y_training'], {}), '(Y_training)\n', (3078, 3090), False, 'import torch\n'), ((3108, 3206), 'numpy.loadtxt', 'np.loadtxt', (['f"""{arguments.input_path}/{dataset_name}/{dataset_name}_TEST.tsv"""'], {'dtype': 'np.float32'}), "(f'{arguments.input_path}/{dataset_name}/{dataset_name}_TEST.tsv',\n dtype=np.float32)\n", (3118, 3206), True, 'import numpy as np\n'), ((3398, 3422), 'torch.from_numpy', 'torch.from_numpy', (['Y_test'], {}), '(Y_test)\n', (3414, 3422), False, 'import torch\n'), ((3619, 3647), 'numpy.zeros', 'np.zeros', (['arguments.num_runs'], {}), '(arguments.num_runs)\n', (3627, 3647), True, 'import numpy as np\n'), ((3663, 3696), 'numpy.zeros', 'np.zeros', (['[4, arguments.num_runs]'], {}), '([4, arguments.num_runs])\n', (3671, 3696), True, 'import numpy as np\n'), ((1745, 1770), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1768, 1770), False, 'import torch\n'), ((4086, 4105), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4103, 4105), False, 'import time\n'), ((4220, 4239), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4237, 4239), False, 'import time\n'), ((4389, 4408), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4406, 4408), False, 'import time\n'), ((4515, 4534), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4532, 4534), False, 'import time\n'), ((4666, 4690), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (4688, 4690), False, 'import torch\n'), ((4717, 4736), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4734, 4736), False, 'import time\n'), ((5031, 5050), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (5048, 5050), False, 'import time\n'), ((5200, 5219), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (5217, 5219), False, 'import time\n'), ((5302, 5321), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (5319, 5321), False, 'import time\n'), ((4119, 4134), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4132, 4134), False, 'import torch\n'), ((4422, 4437), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4435, 4437), False, 'import torch\n'), ((3839, 3885), 'Net.ROCKET.ROCKET', 'ROCKET', (['(1)', 'input_length', 'arguments.num_kernels'], {}), '(1, input_length, arguments.num_kernels)\n', (3845, 3885), False, 'from Net.ROCKET import ROCKET\n'), ((4785, 4807), 'numpy.logspace', 'np.logspace', (['(-3)', '(3)', '(10)'], {}), '(-3, 3, 10)\n', (4796, 4807), True, 'import numpy as np\n'), ((2937, 2965), 'torch.from_numpy', 'torch.from_numpy', (['X_training'], {}), '(X_training)\n', (2953, 2965), False, 'import torch\n'), ((3289, 3313), 'torch.from_numpy', 'torch.from_numpy', (['X_test'], {}), '(X_test)\n', (3305, 3313), False, 'import torch\n')]
import pytest import numpy as np import torch import gym from gym.wrappers import TimeLimit from lagom import RandomAgent from lagom import EpisodeRunner from lagom import StepRunner from lagom.utils import numpify from lagom.envs import make_vec_env from lagom.envs.wrappers import StepInfo from lagom.envs.wrappers import VecStepInfo from lagom.metric import returns from lagom.metric import bootstrapped_returns from lagom.metric import td0_target from lagom.metric import td0_error from lagom.metric import gae from lagom.metric import vtrace from .sanity_env import SanityEnv @pytest.mark.parametrize('gamma', [0.1, 0.99, 1.0]) def test_returns(gamma): assert np.allclose(returns(1.0, [1, 2, 3]), [6, 5, 3]) assert np.allclose(returns(0.1, [1, 2, 3]), [1.23, 2.3, 3]) assert np.allclose(returns(1.0, [1, 2, 3, 4, 5]), [15, 14, 12, 9, 5]) assert np.allclose(returns(0.1, [1, 2, 3, 4, 5]), [1.2345, 2.345, 3.45, 4.5, 5]) assert np.allclose(returns(1.0, [1, 2, 3, 4, 5, 6, 7, 8]), [36, 35, 33, 30, 26, 21, 15, 8]) assert np.allclose(returns(0.1, [1, 2, 3, 4, 5, 6, 7, 8]), [1.2345678, 2.345678, 3.45678, 4.5678, 5.678, 6.78, 7.8, 8]) y1 = [0.1] y2 = [0.1 + gamma*0.2, 0.2] y3 = [0.1 + gamma*(0.2 + gamma*0.3), 0.2 + gamma*0.3, 0.3] y4 = [0.1 + gamma*(0.2 + gamma*(0.3 + gamma*0.4)), 0.2 + gamma*(0.3 + gamma*0.4), 0.3 + gamma*0.4, 0.4] y5 = [0.1 + gamma*(0.2 + gamma*(0.3 + gamma*(0.4 + gamma*0.5))), 0.2 + gamma*(0.3 + gamma*(0.4 + gamma*0.5)), 0.3 + gamma*(0.4 + gamma*0.5), 0.4 + gamma*0.5, 0.5] y6 = [0.1 + gamma*(0.2 + gamma*(0.3 + gamma*(0.4 + gamma*(0.5 + gamma*0.6)))), 0.2 + gamma*(0.3 + gamma*(0.4 + gamma*(0.5 + gamma*0.6))), 0.3 + gamma*(0.4 + gamma*(0.5 + gamma*0.6)), 0.4 + gamma*(0.5 + gamma*0.6), 0.5 + gamma*0.6, 0.6] assert np.allclose(returns(gamma, [0.1]), y1) assert np.allclose(returns(gamma, [0.1, 0.2]), y2) assert np.allclose(returns(gamma, [0.1, 0.2, 0.3]), y3) assert np.allclose(returns(gamma, [0.1, 0.2, 0.3, 0.4]), y4) assert np.allclose(returns(gamma, [0.1, 0.2, 0.3, 0.4, 0.5]), y5) assert np.allclose(returns(gamma, [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]), y6) @pytest.mark.parametrize('gamma', [0.1, 0.99, 1.0]) @pytest.mark.parametrize('last_V', [-3.0, 0.0, 2.0]) def test_bootstrapped_returns(gamma, last_V): y = [0.1 + gamma*(0.2 + gamma*(0.3 + gamma*(0.4 + gamma*last_V))), 0.2 + gamma*(0.3 + gamma*(0.4 + gamma*last_V)), 0.3 + gamma*(0.4 + gamma*last_V), 0.4 + gamma*last_V] reach_terminal = False rewards = [0.1, 0.2, 0.3, 0.4] assert np.allclose(bootstrapped_returns(gamma, rewards, last_V, reach_terminal), y) assert np.allclose(bootstrapped_returns(gamma, rewards, torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*(0.2 + gamma*(0.3 + gamma*(0.4 + gamma*last_V*0.0))), 0.2 + gamma*(0.3 + gamma*(0.4 + gamma*last_V*0.0)), 0.3 + gamma*(0.4 + gamma*last_V*0.0), 0.4 + gamma*last_V*0.0] reach_terminal = True rewards = [0.1, 0.2, 0.3, 0.4] assert np.allclose(bootstrapped_returns(gamma, rewards, last_V, reach_terminal), y) assert np.allclose(bootstrapped_returns(gamma, rewards, torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*(0.2 + gamma*(0.3 + gamma*(0.4 + gamma*(0.5 + gamma*last_V)))), 0.2 + gamma*(0.3 + gamma*(0.4 + gamma*(0.5 + gamma*last_V))), 0.3 + gamma*(0.4 + gamma*(0.5 + gamma*last_V)), 0.4 + gamma*(0.5 + gamma*last_V), 0.5 + gamma*last_V] reach_terminal = False rewards = [0.1, 0.2, 0.3, 0.4, 0.5] assert np.allclose(bootstrapped_returns(gamma, rewards, last_V, reach_terminal), y) assert np.allclose(bootstrapped_returns(gamma, rewards, torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*(0.2 + gamma*(0.3 + gamma*(0.4 + gamma*(0.5 + gamma*last_V*0.0)))), 0.2 + gamma*(0.3 + gamma*(0.4 + gamma*(0.5 + gamma*last_V*0.0))), 0.3 + gamma*(0.4 + gamma*(0.5 + gamma*last_V*0.0)), 0.4 + gamma*(0.5 + gamma*last_V*0.0), 0.5 + gamma*last_V*0.0] reach_terminal = True rewards = [0.1, 0.2, 0.3, 0.4, 0.5] assert np.allclose(bootstrapped_returns(gamma, rewards, last_V, reach_terminal), y) assert np.allclose(bootstrapped_returns(gamma, rewards, torch.tensor(last_V), reach_terminal), y) @pytest.mark.parametrize('gamma', [0.1, 0.99, 1.0]) @pytest.mark.parametrize('last_V', [-3.0, 0.0, 2.0]) def test_td0_target(gamma, last_V): y = [0.1 + gamma*2, 0.2 + gamma*3, 0.3 + gamma*4, 0.4 + gamma*last_V*0.0] rewards = [0.1, 0.2, 0.3, 0.4] Vs = [1, 2, 3, 4] reach_terminal = True assert np.allclose(td0_target(gamma, rewards, Vs, last_V, reach_terminal), y) assert np.allclose(td0_target(gamma, rewards, torch.tensor(Vs), torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*2, 0.2 + gamma*3, 0.3 + gamma*4, 0.4 + gamma*last_V] rewards = [0.1, 0.2, 0.3, 0.4] Vs = [1, 2, 3, 4] reach_terminal = False assert np.allclose(td0_target(gamma, rewards, Vs, last_V, reach_terminal), y) assert np.allclose(td0_target(gamma, rewards, torch.tensor(Vs), torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*2, 0.2 + gamma*3, 0.3 + gamma*4, 0.4 + gamma*5, 0.5 + gamma*6, 0.6 + gamma*last_V*0.0] rewards = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] Vs = [1, 2, 3, 4, 5, 6] reach_terminal = True assert np.allclose(td0_target(gamma, rewards, Vs, last_V, reach_terminal), y) assert np.allclose(td0_target(gamma, rewards, torch.tensor(Vs), torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*2, 0.2 + gamma*3, 0.3 + gamma*4, 0.4 + gamma*5, 0.5 + gamma*6, 0.6 + gamma*last_V] rewards = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] Vs = [1, 2, 3, 4, 5, 6] reach_terminal = False assert np.allclose(td0_target(gamma, rewards, Vs, last_V, reach_terminal), y) assert np.allclose(td0_target(gamma, rewards, torch.tensor(Vs), torch.tensor(last_V), reach_terminal), y) @pytest.mark.parametrize('gamma', [0.1, 0.99, 1.0]) @pytest.mark.parametrize('last_V', [-3.0, 0.0, 2.0]) def test_td0_error(gamma, last_V): y = [0.1 + gamma*2 - 1, 0.2 + gamma*3 - 2, 0.3 + gamma*4 - 3, 0.4 + gamma*last_V*0.0 - 4] rewards = [0.1, 0.2, 0.3, 0.4] Vs = [1, 2, 3, 4] reach_terminal = True assert np.allclose(td0_error(gamma, rewards, Vs, last_V, reach_terminal), y) assert np.allclose(td0_error(gamma, rewards, torch.tensor(Vs), torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*2 - 1, 0.2 + gamma*3 - 2, 0.3 + gamma*4 - 3, 0.4 + gamma*last_V - 4] rewards = [0.1, 0.2, 0.3, 0.4] Vs = [1, 2, 3, 4] reach_terminal = False assert np.allclose(td0_error(gamma, rewards, Vs, last_V, reach_terminal), y) assert np.allclose(td0_error(gamma, rewards, torch.tensor(Vs), torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*2 - 1, 0.2 + gamma*3 - 2, 0.3 + gamma*4 - 3, 0.4 + gamma*5 - 4, 0.5 + gamma*6 - 5, 0.6 + gamma*last_V*0.0 - 6] rewards = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] Vs = [1, 2, 3, 4, 5, 6] reach_terminal = True assert np.allclose(td0_error(gamma, rewards, Vs, last_V, reach_terminal), y) assert np.allclose(td0_error(gamma, rewards, torch.tensor(Vs), torch.tensor(last_V), reach_terminal), y) y = [0.1 + gamma*2 - 1, 0.2 + gamma*3 - 2, 0.3 + gamma*4 - 3, 0.4 + gamma*5 - 4, 0.5 + gamma*6 - 5, 0.6 + gamma*last_V - 6] rewards = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] Vs = [1, 2, 3, 4, 5, 6] reach_terminal = False assert np.allclose(td0_error(gamma, rewards, Vs, last_V, reach_terminal), y) assert np.allclose(td0_error(gamma, rewards, torch.tensor(Vs), torch.tensor(last_V), reach_terminal), y) def test_gae(): rewards = [1, 2, 3] Vs = [0.1, 1.1, 2.1] assert np.allclose(gae(1.0, 0.5, rewards, Vs, 10, True), [3.725, 3.45, 0.9]) assert np.allclose(gae(1.0, 0.5, rewards, torch.tensor(Vs), torch.tensor(10), True), [3.725, 3.45, 0.9]) assert np.allclose(gae(0.1, 0.2, rewards, Vs, 10, True), [1.03256, 1.128, 0.9]) assert np.allclose(gae(0.1, 0.2, rewards, torch.tensor(Vs), torch.tensor(10), True), [1.03256, 1.128, 0.9]) rewards = [1, 2, 3] Vs = [0.5, 1.5, 2.5] assert np.allclose(gae(1.0, 0.5, rewards, Vs, 99, True), [3.625, 3.25, 0.5]) assert np.allclose(gae(1.0, 0.5, rewards, torch.tensor(Vs), torch.tensor(99), True), [3.625, 3.25, 0.5]) assert np.allclose(gae(0.1, 0.2, rewards, Vs, 99, True), [0.6652, 0.76, 0.5]) assert np.allclose(gae(0.1, 0.2, rewards, torch.tensor(Vs), torch.tensor(99), True), [0.6652, 0.76, 0.5]) rewards = [1, 2, 3, 4, 5] Vs = [0.5, 1.5, 2.5, 3.5, 4.5] assert np.allclose(gae(1.0, 0.5, rewards, Vs, 20, False), [6.40625, 8.8125, 11.625, 15.25, 20.5]) assert np.allclose(gae(1.0, 0.5, rewards, torch.tensor(Vs), torch.tensor(20), False), [6.40625, 8.8125, 11.625, 15.25, 20.5]) assert np.allclose(gae(0.1, 0.2, rewards, Vs, 20, False), [0.665348, 0.7674, 0.87, 1, 2.5]) assert np.allclose(gae(0.1, 0.2, rewards, torch.tensor(Vs), torch.tensor(20), False), [0.665348, 0.7674, 0.87, 1, 2.5]) rewards = [1, 2, 3, 4, 5] Vs = [0.1, 1.1, 2.1, 3.1, 4.1] assert np.allclose(gae(1.0, 0.5, rewards, Vs, 10, False), [5.80625, 7.6125, 9.225, 10.45, 10.9]) assert np.allclose(gae(1.0, 0.5, rewards, torch.tensor(Vs), torch.tensor(10), False), [5.80625, 7.6125, 9.225, 10.45, 10.9]) assert np.allclose(gae(0.1, 0.2, rewards, Vs, 10, False), [1.03269478, 1.1347393, 1.23696, 1.348, 1.9]) assert np.allclose(gae(0.1, 0.2, rewards, torch.tensor(Vs), torch.tensor(10), False), [1.03269478, 1.1347393, 1.23696, 1.348, 1.9]) rewards = [1, 2, 3, 4, 5, 6, 7, 8] Vs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] assert np.allclose(gae(1.0, 0.5, rewards, Vs, 30, True), [5.84375, 7.6875, 9.375, 10.75, 11.5, 11., 8, 0.]) assert np.allclose(gae(1.0, 0.5, rewards, torch.tensor(Vs), torch.tensor(30), True), [5.84375, 7.6875, 9.375, 10.75, 11.5, 11., 8, 0.]) assert np.allclose(gae(0.1, 0.2, rewards, Vs, 30, True), [0.206164098, 0.308204915, 0.410245728, 0.5122864, 0.61432, 0.716, 0.8, 0]) assert np.allclose(gae(0.1, 0.2, rewards, torch.tensor(Vs), torch.tensor(30), True), [0.206164098, 0.308204915, 0.410245728, 0.5122864, 0.61432, 0.716, 0.8, 0]) @pytest.mark.parametrize('gamma', [0.1, 1.0]) @pytest.mark.parametrize('last_V', [0.3, [0.5]]) @pytest.mark.parametrize('reach_terminal', [True, False]) @pytest.mark.parametrize('clip_rho', [0.5, 1.0]) @pytest.mark.parametrize('clip_pg_rho', [0.3, 1.1]) def test_vtrace(gamma, last_V, reach_terminal, clip_rho, clip_pg_rho): behavior_logprobs = [1, 2, 3] target_logprobs = [4, 5, 6] Rs = [7, 8, 9] Vs = [10, 11, 12] vs_test, As_test = vtrace(behavior_logprobs, target_logprobs, gamma, Rs, Vs, last_V, reach_terminal, clip_rho, clip_pg_rho) # ground truth calculation behavior_logprobs = numpify(behavior_logprobs, np.float32) target_logprobs = numpify(target_logprobs, np.float32) Rs = numpify(Rs, np.float32) Vs = numpify(Vs, np.float32) last_V = numpify(last_V, np.float32) rhos = np.exp(target_logprobs - behavior_logprobs) clipped_rhos = np.minimum(clip_rho, rhos) cs = np.minimum(1.0, rhos) deltas = clipped_rhos*td0_error(gamma, Rs, Vs, last_V, reach_terminal) vs = np.array([Vs[0] + gamma**0*1*deltas[0] + gamma*cs[0]*deltas[1] + gamma**2*cs[0]*cs[1]*deltas[2], Vs[1] + gamma**0*1*deltas[1] + gamma*cs[1]*deltas[2], Vs[2] + gamma**0*1*deltas[2]]) vs_next = np.append(vs[1:], (1. - reach_terminal)*last_V) clipped_pg_rhos = np.minimum(clip_pg_rho, rhos) As = clipped_pg_rhos*(Rs + gamma*vs_next - Vs) assert np.allclose(vs, vs_test) assert np.allclose(As, As_test)
[ "numpy.allclose", "lagom.metric.returns", "numpy.minimum", "lagom.metric.td0_error", "lagom.metric.td0_target", "lagom.metric.vtrace", "numpy.exp", "pytest.mark.parametrize", "numpy.array", "numpy.append", "lagom.metric.bootstrapped_returns", "torch.tensor", "lagom.utils.numpify", "lagom.m...
[((588, 638), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gamma"""', '[0.1, 0.99, 1.0]'], {}), "('gamma', [0.1, 0.99, 1.0])\n", (611, 638), False, 'import pytest\n'), ((2328, 2378), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gamma"""', '[0.1, 0.99, 1.0]'], {}), "('gamma', [0.1, 0.99, 1.0])\n", (2351, 2378), False, 'import pytest\n'), ((2380, 2431), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""last_V"""', '[-3.0, 0.0, 2.0]'], {}), "('last_V', [-3.0, 0.0, 2.0])\n", (2403, 2431), False, 'import pytest\n'), ((4531, 4581), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gamma"""', '[0.1, 0.99, 1.0]'], {}), "('gamma', [0.1, 0.99, 1.0])\n", (4554, 4581), False, 'import pytest\n'), ((4583, 4634), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""last_V"""', '[-3.0, 0.0, 2.0]'], {}), "('last_V', [-3.0, 0.0, 2.0])\n", (4606, 4634), False, 'import pytest\n'), ((6345, 6395), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gamma"""', '[0.1, 0.99, 1.0]'], {}), "('gamma', [0.1, 0.99, 1.0])\n", (6368, 6395), False, 'import pytest\n'), ((6397, 6448), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""last_V"""', '[-3.0, 0.0, 2.0]'], {}), "('last_V', [-3.0, 0.0, 2.0])\n", (6420, 6448), False, 'import pytest\n'), ((11311, 11355), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gamma"""', '[0.1, 1.0]'], {}), "('gamma', [0.1, 1.0])\n", (11334, 11355), False, 'import pytest\n'), ((11357, 11404), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""last_V"""', '[0.3, [0.5]]'], {}), "('last_V', [0.3, [0.5]])\n", (11380, 11404), False, 'import pytest\n'), ((11406, 11462), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""reach_terminal"""', '[True, False]'], {}), "('reach_terminal', [True, False])\n", (11429, 11462), False, 'import pytest\n'), ((11464, 11511), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""clip_rho"""', '[0.5, 1.0]'], {}), "('clip_rho', [0.5, 1.0])\n", (11487, 11511), False, 'import pytest\n'), ((11513, 11563), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""clip_pg_rho"""', '[0.3, 1.1]'], {}), "('clip_pg_rho', [0.3, 1.1])\n", (11536, 11563), False, 'import pytest\n'), ((11770, 11878), 'lagom.metric.vtrace', 'vtrace', (['behavior_logprobs', 'target_logprobs', 'gamma', 'Rs', 'Vs', 'last_V', 'reach_terminal', 'clip_rho', 'clip_pg_rho'], {}), '(behavior_logprobs, target_logprobs, gamma, Rs, Vs, last_V,\n reach_terminal, clip_rho, clip_pg_rho)\n', (11776, 11878), False, 'from lagom.metric import vtrace\n'), ((11935, 11973), 'lagom.utils.numpify', 'numpify', (['behavior_logprobs', 'np.float32'], {}), '(behavior_logprobs, np.float32)\n', (11942, 11973), False, 'from lagom.utils import numpify\n'), ((11996, 12032), 'lagom.utils.numpify', 'numpify', (['target_logprobs', 'np.float32'], {}), '(target_logprobs, np.float32)\n', (12003, 12032), False, 'from lagom.utils import numpify\n'), ((12042, 12065), 'lagom.utils.numpify', 'numpify', (['Rs', 'np.float32'], {}), '(Rs, np.float32)\n', (12049, 12065), False, 'from lagom.utils import numpify\n'), ((12075, 12098), 'lagom.utils.numpify', 'numpify', (['Vs', 'np.float32'], {}), '(Vs, np.float32)\n', (12082, 12098), False, 'from lagom.utils import numpify\n'), ((12112, 12139), 'lagom.utils.numpify', 'numpify', (['last_V', 'np.float32'], {}), '(last_V, np.float32)\n', (12119, 12139), False, 'from lagom.utils import numpify\n'), ((12156, 12199), 'numpy.exp', 'np.exp', (['(target_logprobs - behavior_logprobs)'], {}), '(target_logprobs - behavior_logprobs)\n', (12162, 12199), True, 'import numpy as np\n'), ((12219, 12245), 'numpy.minimum', 'np.minimum', (['clip_rho', 'rhos'], {}), '(clip_rho, rhos)\n', (12229, 12245), True, 'import numpy as np\n'), ((12255, 12276), 'numpy.minimum', 'np.minimum', (['(1.0)', 'rhos'], {}), '(1.0, rhos)\n', (12265, 12276), True, 'import numpy as np\n'), ((12366, 12591), 'numpy.array', 'np.array', (['[Vs[0] + gamma ** 0 * 1 * deltas[0] + gamma * cs[0] * deltas[1] + gamma ** \n 2 * cs[0] * cs[1] * deltas[2], Vs[1] + gamma ** 0 * 1 * deltas[1] + \n gamma * cs[1] * deltas[2], Vs[2] + gamma ** 0 * 1 * deltas[2]]'], {}), '([Vs[0] + gamma ** 0 * 1 * deltas[0] + gamma * cs[0] * deltas[1] + \n gamma ** 2 * cs[0] * cs[1] * deltas[2], Vs[1] + gamma ** 0 * 1 * deltas\n [1] + gamma * cs[1] * deltas[2], Vs[2] + gamma ** 0 * 1 * deltas[2]])\n', (12374, 12591), True, 'import numpy as np\n'), ((12602, 12652), 'numpy.append', 'np.append', (['vs[1:]', '((1.0 - reach_terminal) * last_V)'], {}), '(vs[1:], (1.0 - reach_terminal) * last_V)\n', (12611, 12652), True, 'import numpy as np\n'), ((12672, 12701), 'numpy.minimum', 'np.minimum', (['clip_pg_rho', 'rhos'], {}), '(clip_pg_rho, rhos)\n', (12682, 12701), True, 'import numpy as np\n'), ((12769, 12793), 'numpy.allclose', 'np.allclose', (['vs', 'vs_test'], {}), '(vs, vs_test)\n', (12780, 12793), True, 'import numpy as np\n'), ((12805, 12829), 'numpy.allclose', 'np.allclose', (['As', 'As_test'], {}), '(As, As_test)\n', (12816, 12829), True, 'import numpy as np\n'), ((687, 710), 'lagom.metric.returns', 'returns', (['(1.0)', '[1, 2, 3]'], {}), '(1.0, [1, 2, 3])\n', (694, 710), False, 'from lagom.metric import returns\n'), ((746, 769), 'lagom.metric.returns', 'returns', (['(0.1)', '[1, 2, 3]'], {}), '(0.1, [1, 2, 3])\n', (753, 769), False, 'from lagom.metric import returns\n'), ((810, 839), 'lagom.metric.returns', 'returns', (['(1.0)', '[1, 2, 3, 4, 5]'], {}), '(1.0, [1, 2, 3, 4, 5])\n', (817, 839), False, 'from lagom.metric import returns\n'), ((884, 913), 'lagom.metric.returns', 'returns', (['(0.1)', '[1, 2, 3, 4, 5]'], {}), '(0.1, [1, 2, 3, 4, 5])\n', (891, 913), False, 'from lagom.metric import returns\n'), ((969, 1007), 'lagom.metric.returns', 'returns', (['(1.0)', '[1, 2, 3, 4, 5, 6, 7, 8]'], {}), '(1.0, [1, 2, 3, 4, 5, 6, 7, 8])\n', (976, 1007), False, 'from lagom.metric import returns\n'), ((1065, 1103), 'lagom.metric.returns', 'returns', (['(0.1)', '[1, 2, 3, 4, 5, 6, 7, 8]'], {}), '(0.1, [1, 2, 3, 4, 5, 6, 7, 8])\n', (1072, 1103), False, 'from lagom.metric import returns\n'), ((1973, 1994), 'lagom.metric.returns', 'returns', (['gamma', '[0.1]'], {}), '(gamma, [0.1])\n', (1980, 1994), False, 'from lagom.metric import returns\n'), ((2023, 2049), 'lagom.metric.returns', 'returns', (['gamma', '[0.1, 0.2]'], {}), '(gamma, [0.1, 0.2])\n', (2030, 2049), False, 'from lagom.metric import returns\n'), ((2078, 2109), 'lagom.metric.returns', 'returns', (['gamma', '[0.1, 0.2, 0.3]'], {}), '(gamma, [0.1, 0.2, 0.3])\n', (2085, 2109), False, 'from lagom.metric import returns\n'), ((2138, 2174), 'lagom.metric.returns', 'returns', (['gamma', '[0.1, 0.2, 0.3, 0.4]'], {}), '(gamma, [0.1, 0.2, 0.3, 0.4])\n', (2145, 2174), False, 'from lagom.metric import returns\n'), ((2203, 2244), 'lagom.metric.returns', 'returns', (['gamma', '[0.1, 0.2, 0.3, 0.4, 0.5]'], {}), '(gamma, [0.1, 0.2, 0.3, 0.4, 0.5])\n', (2210, 2244), False, 'from lagom.metric import returns\n'), ((2273, 2319), 'lagom.metric.returns', 'returns', (['gamma', '[0.1, 0.2, 0.3, 0.4, 0.5, 0.6]'], {}), '(gamma, [0.1, 0.2, 0.3, 0.4, 0.5, 0.6])\n', (2280, 2319), False, 'from lagom.metric import returns\n'), ((2766, 2826), 'lagom.metric.bootstrapped_returns', 'bootstrapped_returns', (['gamma', 'rewards', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, last_V, reach_terminal)\n', (2786, 2826), False, 'from lagom.metric import bootstrapped_returns\n'), ((3241, 3301), 'lagom.metric.bootstrapped_returns', 'bootstrapped_returns', (['gamma', 'rewards', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, last_V, reach_terminal)\n', (3261, 3301), False, 'from lagom.metric import bootstrapped_returns\n'), ((3792, 3852), 'lagom.metric.bootstrapped_returns', 'bootstrapped_returns', (['gamma', 'rewards', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, last_V, reach_terminal)\n', (3812, 3852), False, 'from lagom.metric import bootstrapped_returns\n'), ((4361, 4421), 'lagom.metric.bootstrapped_returns', 'bootstrapped_returns', (['gamma', 'rewards', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, last_V, reach_terminal)\n', (4381, 4421), False, 'from lagom.metric import bootstrapped_returns\n'), ((4884, 4938), 'lagom.metric.td0_target', 'td0_target', (['gamma', 'rewards', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, Vs, last_V, reach_terminal)\n', (4894, 4938), False, 'from lagom.metric import td0_target\n'), ((5268, 5322), 'lagom.metric.td0_target', 'td0_target', (['gamma', 'rewards', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, Vs, last_V, reach_terminal)\n', (5278, 5322), False, 'from lagom.metric import td0_target\n'), ((5722, 5776), 'lagom.metric.td0_target', 'td0_target', (['gamma', 'rewards', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, Vs, last_V, reach_terminal)\n', (5732, 5776), False, 'from lagom.metric import td0_target\n'), ((6173, 6227), 'lagom.metric.td0_target', 'td0_target', (['gamma', 'rewards', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, Vs, last_V, reach_terminal)\n', (6183, 6227), False, 'from lagom.metric import td0_target\n'), ((6713, 6766), 'lagom.metric.td0_error', 'td0_error', (['gamma', 'rewards', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, Vs, last_V, reach_terminal)\n', (6722, 6766), False, 'from lagom.metric import td0_error\n'), ((7111, 7164), 'lagom.metric.td0_error', 'td0_error', (['gamma', 'rewards', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, Vs, last_V, reach_terminal)\n', (7120, 7164), False, 'from lagom.metric import td0_error\n'), ((7588, 7641), 'lagom.metric.td0_error', 'td0_error', (['gamma', 'rewards', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, Vs, last_V, reach_terminal)\n', (7597, 7641), False, 'from lagom.metric import td0_error\n'), ((8062, 8115), 'lagom.metric.td0_error', 'td0_error', (['gamma', 'rewards', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, rewards, Vs, last_V, reach_terminal)\n', (8071, 8115), False, 'from lagom.metric import td0_error\n'), ((8319, 8355), 'lagom.metric.gae', 'gae', (['(1.0)', '(0.5)', 'rewards', 'Vs', '(10)', '(True)'], {}), '(1.0, 0.5, rewards, Vs, 10, True)\n', (8322, 8355), False, 'from lagom.metric import gae\n'), ((8557, 8593), 'lagom.metric.gae', 'gae', (['(0.1)', '(0.2)', 'rewards', 'Vs', '(10)', '(True)'], {}), '(0.1, 0.2, rewards, Vs, 10, True)\n', (8560, 8593), False, 'from lagom.metric import gae\n'), ((8855, 8891), 'lagom.metric.gae', 'gae', (['(1.0)', '(0.5)', 'rewards', 'Vs', '(99)', '(True)'], {}), '(1.0, 0.5, rewards, Vs, 99, True)\n', (8858, 8891), False, 'from lagom.metric import gae\n'), ((9093, 9129), 'lagom.metric.gae', 'gae', (['(0.1)', '(0.2)', 'rewards', 'Vs', '(99)', '(True)'], {}), '(0.1, 0.2, rewards, Vs, 99, True)\n', (9096, 9129), False, 'from lagom.metric import gae\n'), ((9403, 9440), 'lagom.metric.gae', 'gae', (['(1.0)', '(0.5)', 'rewards', 'Vs', '(20)', '(False)'], {}), '(1.0, 0.5, rewards, Vs, 20, False)\n', (9406, 9440), False, 'from lagom.metric import gae\n'), ((9683, 9720), 'lagom.metric.gae', 'gae', (['(0.1)', '(0.2)', 'rewards', 'Vs', '(20)', '(False)'], {}), '(0.1, 0.2, rewards, Vs, 20, False)\n', (9686, 9720), False, 'from lagom.metric import gae\n'), ((10017, 10054), 'lagom.metric.gae', 'gae', (['(1.0)', '(0.5)', 'rewards', 'Vs', '(10)', '(False)'], {}), '(1.0, 0.5, rewards, Vs, 10, False)\n', (10020, 10054), False, 'from lagom.metric import gae\n'), ((10295, 10332), 'lagom.metric.gae', 'gae', (['(0.1)', '(0.2)', 'rewards', 'Vs', '(10)', '(False)'], {}), '(0.1, 0.2, rewards, Vs, 10, False)\n', (10298, 10332), False, 'from lagom.metric import gae\n'), ((10681, 10717), 'lagom.metric.gae', 'gae', (['(1.0)', '(0.5)', 'rewards', 'Vs', '(30)', '(True)'], {}), '(1.0, 0.5, rewards, Vs, 30, True)\n', (10684, 10717), False, 'from lagom.metric import gae\n'), ((10981, 11017), 'lagom.metric.gae', 'gae', (['(0.1)', '(0.2)', 'rewards', 'Vs', '(30)', '(True)'], {}), '(0.1, 0.2, rewards, Vs, 30, True)\n', (10984, 11017), False, 'from lagom.metric import gae\n'), ((12303, 12351), 'lagom.metric.td0_error', 'td0_error', (['gamma', 'Rs', 'Vs', 'last_V', 'reach_terminal'], {}), '(gamma, Rs, Vs, last_V, reach_terminal)\n', (12312, 12351), False, 'from lagom.metric import td0_error\n'), ((2891, 2911), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (2903, 2911), False, 'import torch\n'), ((3366, 3386), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (3378, 3386), False, 'import torch\n'), ((3917, 3937), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (3929, 3937), False, 'import torch\n'), ((4486, 4506), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (4498, 4506), False, 'import torch\n'), ((4993, 5009), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (5005, 5009), False, 'import torch\n'), ((5011, 5031), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (5023, 5031), False, 'import torch\n'), ((5377, 5393), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (5389, 5393), False, 'import torch\n'), ((5395, 5415), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (5407, 5415), False, 'import torch\n'), ((5831, 5847), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (5843, 5847), False, 'import torch\n'), ((5849, 5869), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (5861, 5869), False, 'import torch\n'), ((6282, 6298), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (6294, 6298), False, 'import torch\n'), ((6300, 6320), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (6312, 6320), False, 'import torch\n'), ((6820, 6836), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (6832, 6836), False, 'import torch\n'), ((6838, 6858), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (6850, 6858), False, 'import torch\n'), ((7218, 7234), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (7230, 7234), False, 'import torch\n'), ((7236, 7256), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (7248, 7256), False, 'import torch\n'), ((7695, 7711), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (7707, 7711), False, 'import torch\n'), ((7713, 7733), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (7725, 7733), False, 'import torch\n'), ((8169, 8185), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (8181, 8185), False, 'import torch\n'), ((8187, 8207), 'torch.tensor', 'torch.tensor', (['last_V'], {}), '(last_V)\n', (8199, 8207), False, 'import torch\n'), ((8447, 8463), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (8459, 8463), False, 'import torch\n'), ((8465, 8481), 'torch.tensor', 'torch.tensor', (['(10)'], {}), '(10)\n', (8477, 8481), False, 'import torch\n'), ((8688, 8704), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (8700, 8704), False, 'import torch\n'), ((8706, 8722), 'torch.tensor', 'torch.tensor', (['(10)'], {}), '(10)\n', (8718, 8722), False, 'import torch\n'), ((8983, 8999), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (8995, 8999), False, 'import torch\n'), ((9001, 9017), 'torch.tensor', 'torch.tensor', (['(99)'], {}), '(99)\n', (9013, 9017), False, 'import torch\n'), ((9222, 9238), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (9234, 9238), False, 'import torch\n'), ((9240, 9256), 'torch.tensor', 'torch.tensor', (['(99)'], {}), '(99)\n', (9252, 9256), False, 'import torch\n'), ((9552, 9568), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (9564, 9568), False, 'import torch\n'), ((9570, 9586), 'torch.tensor', 'torch.tensor', (['(20)'], {}), '(20)\n', (9582, 9586), False, 'import torch\n'), ((9826, 9842), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (9838, 9842), False, 'import torch\n'), ((9844, 9860), 'torch.tensor', 'torch.tensor', (['(20)'], {}), '(20)\n', (9856, 9860), False, 'import torch\n'), ((10165, 10181), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (10177, 10181), False, 'import torch\n'), ((10183, 10199), 'torch.tensor', 'torch.tensor', (['(10)'], {}), '(10)\n', (10195, 10199), False, 'import torch\n'), ((10450, 10466), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (10462, 10466), False, 'import torch\n'), ((10468, 10484), 'torch.tensor', 'torch.tensor', (['(10)'], {}), '(10)\n', (10480, 10484), False, 'import torch\n'), ((10840, 10856), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (10852, 10856), False, 'import torch\n'), ((10858, 10874), 'torch.tensor', 'torch.tensor', (['(30)'], {}), '(30)\n', (10870, 10874), False, 'import torch\n'), ((11165, 11181), 'torch.tensor', 'torch.tensor', (['Vs'], {}), '(Vs)\n', (11177, 11181), False, 'import torch\n'), ((11183, 11199), 'torch.tensor', 'torch.tensor', (['(30)'], {}), '(30)\n', (11195, 11199), False, 'import torch\n')]
from ThesisAnalysis.plotting.setup import ThesisPlotter from ThesisAnalysis import get_data, get_plot, ThesisHDF5Reader import os import numpy as np from matplotlib.ticker import MultipleLocator, FuncFormatter from target_calib import CalculateRowColumnBlockPhase, GetCellIDTCArray def setup_cells(df, camera): fci = df['fci'].values.astype(np.uint16) frow, fcolumn, fblockphase = CalculateRowColumnBlockPhase(fci) fblock = fcolumn * 8 + frow df['fblock'] = fblock df['fblockphase'] = fblockphase df['fbpisam'] = df['fblockphase'] + df['isam'] if "checs" in camera: cell = GetCellIDTCArray(fci, df['isam'].values) else: cell = (fci + df['isam'].values) % 2**14 row, column, blockphase = CalculateRowColumnBlockPhase(cell) block = column * 8 + row df['cell'] = cell df['block'] = block df['blockphase'] = blockphase df['iblock'] = (df['isam'] + df['fblockphase']) // 32 return df class Hist(ThesisPlotter): def __init__(self, units): super().__init__() self.units = units self.ax2 = self.ax.twiny() def plot(self, r0, r1): c2 = next(self.ax._get_lines.prop_cycler)['color'] c1 = next(self.ax._get_lines.prop_cycler)['color'] label = ("Before Pedestal Subtraction\n" r"$(\mu = \SI{{{:.3g}}}{{ADC}}, \sigma = \SI{{{:#.3g}}}{{ADC}})$") label_r0 = label.format(r0.mean(), r0.std()) label = ("After Pedestal Subtraction\n" r"$(\mu = \SI{{{:#.3g}}}{{{}}}, \sigma = \SI{{{:#.3g}}}{{{}}})$") label_r1 = label.format(r1.mean(), self.units, r1.std(), self.units) self.ax2.hist(r0, bins=40, color=c2, alpha=0.5, label=label_r0) self.ax.hist(r1, bins=40, color=c1, alpha=0.7, label=label_r1) self.ax.set_ylabel('Counts') self.ax2.set_xlabel(r'Raw Samples ($\si{{{}}}$)'.format(self.units)) self.ax2.tick_params('x', which='both', colors=c2) self.ax.set_xlabel(r'Pedestal-Subtracted Samples ($\si{{{}}}$)'.format(self.units)) self.ax.tick_params('x', which='both', colors=c1) self.ax.get_yaxis().set_major_formatter( FuncFormatter(lambda yl, _: r'$\SI{{{:.1e}}}{{}}$'.format(yl))) lines, labels = self.ax.get_legend_handles_labels() lines2, labels2 = self.ax2.get_legend_handles_labels() self.ax.legend(lines2 + lines, labels2 + labels, loc=2) class HistChunk(ThesisPlotter): def plot(self, r1): size = r1.size chunksize = size // 5 label = "Mean = {:.3f}, Stddev = {:.3f}, N = {:.3e}" for i in range(5): s = r1[i * chunksize:(i+1) * chunksize] label_s = label.format(s.mean(), s.std(), s.size) self.ax.hist(s, bins=40, alpha=0.5, label=label_s) self.ax.set_xlabel('Pedestal-Subtracted Samples (ADC)') self.ax.set_ylabel('Counts') self.add_legend('best') class LookupTable(ThesisPlotter): def plot(self, data, data_title=""): pixel_hits_0 = np.ma.masked_where(data == 0, data) im = self.ax.pcolor(pixel_hits_0, cmap="viridis", edgecolors='white', linewidths=0.1) cbar = self.fig.colorbar(im) self.ax.patch.set(hatch='xx') self.ax.set_xlabel("Blockphase + Waveform position") self.ax.set_ylabel("Block") cbar.set_label(data_title) # self.ax.set_ylim(110, 120) class Waveform(ThesisPlotter): def plot(self, df, event): df_event = df.loc[df['iev'] == event] x = df_event['isam'] y = df_event['r0'] self.ax.plot(x, y, color='black') self.ax.set_xlabel("Time (ns)") self.ax.set_ylabel("Amplitude (Raw ADC)") self.ax.xaxis.set_major_locator(MultipleLocator(16)) class CellWaveform(ThesisPlotter): def plot(self, df, cell): df_mean = df.loc[df['cell'] == cell].groupby('isam').mean() df_std = df.loc[df['cell'] == cell].groupby('isam').std() x = df_mean.index y = df_mean['r0'] yerr = df_std['r0'] block_edges_flag = np.where(np.diff(df_mean['iblock']))[0] block_edges = df_mean.index[block_edges_flag] block_edges = list(block_edges) + [x.min(), x.max()] [self.ax.axvline(l, ls='--', color='gray', alpha=0.7) for l in block_edges] self.ax.errorbar(x, y, yerr=yerr, color='black') self.ax.set_xlabel("Position in waveform") self.ax.set_ylabel("Amplitude (Raw ADC)") # self.ax.set_title("Cell = {}".format(cell)) self.ax.xaxis.set_major_locator(MultipleLocator(16)) class BlockPlotter(ThesisPlotter): def plot(self, df, block): df_block = df.loc[df['block'] == block] for iblock, group in df_block.groupby('iblock'): df_cell = group.groupby('cell').mean() value = df_cell['r0'] self.ax.plot(value, label="{}".format(iblock)) self.ax.set_xlabel("Cell") self.ax.set_ylabel("Amplitude (Raw ADC)") # self.ax.set_title("Block = {}".format(block)) self.add_legend('best', title="Block Position in Waveform") def process(camera, input_path, units): with ThesisHDF5Reader(input_path) as reader: df = reader.read("data") df = setup_cells(df, camera) r0 = df['r0'].values r1 = df['r1'].values output_dir = get_plot("pedestal/{}".format(camera)) p_hist = Hist(units) p_hist.plot(r0, r1) p_hist.save(os.path.join(output_dir, "pedestal_hist.pdf")) p_histchunk = HistChunk() p_histchunk.plot(r1) p_histchunk.save(os.path.join(output_dir, "pedestal_histchunk.pdf")) d = df.groupby(['fblock', 'fbpisam']).mean()['r0'].unstack().values p_lookup = LookupTable(switch_backend=True) p_lookup.plot(d, "Pedestal Value") p_lookup.save(os.path.join(output_dir, "pedestal_lookup.pdf")) e = 10 p_wf = Waveform(sidebyside=True) p_wf.plot(df, e) p_wf.save(os.path.join(output_dir, "rawwf_{}.pdf".format(e))) cells = [15, 26, 75, 76] for c in cells: p_cellwf = CellWaveform() p_cellwf.plot(df, c) p_cellwf.save(os.path.join(output_dir, "cellwf_{}.pdf".format(c))) b = 40 p_block = BlockPlotter() p_block.plot(df, b) p_block.save(os.path.join(output_dir, "block_{}.pdf".format(b))) def main(): camera = "checs" input_path = get_data("pedestal/pedestal_checs.h5") units = "ADC" process(camera, input_path, units) camera = "checs_mV" input_path = get_data("pedestal/pedestal_checs_mV.h5") units = "mV" process(camera, input_path, units) camera = "checs_pe" input_path = get_data("pedestal/pedestal_checs_pe.h5") units = "\pe" process(camera, input_path, units) camera = "checm" input_path = get_data("pedestal/pedestal_checm.h5") units = "ADC" process(camera, input_path, units) if __name__ == '__main__': main()
[ "matplotlib.ticker.MultipleLocator", "ThesisAnalysis.ThesisHDF5Reader", "os.path.join", "target_calib.GetCellIDTCArray", "numpy.diff", "numpy.ma.masked_where", "target_calib.CalculateRowColumnBlockPhase", "ThesisAnalysis.get_data" ]
[((391, 424), 'target_calib.CalculateRowColumnBlockPhase', 'CalculateRowColumnBlockPhase', (['fci'], {}), '(fci)\n', (419, 424), False, 'from target_calib import CalculateRowColumnBlockPhase, GetCellIDTCArray\n'), ((742, 776), 'target_calib.CalculateRowColumnBlockPhase', 'CalculateRowColumnBlockPhase', (['cell'], {}), '(cell)\n', (770, 776), False, 'from target_calib import CalculateRowColumnBlockPhase, GetCellIDTCArray\n'), ((6418, 6456), 'ThesisAnalysis.get_data', 'get_data', (['"""pedestal/pedestal_checs.h5"""'], {}), "('pedestal/pedestal_checs.h5')\n", (6426, 6456), False, 'from ThesisAnalysis import get_data, get_plot, ThesisHDF5Reader\n'), ((6556, 6597), 'ThesisAnalysis.get_data', 'get_data', (['"""pedestal/pedestal_checs_mV.h5"""'], {}), "('pedestal/pedestal_checs_mV.h5')\n", (6564, 6597), False, 'from ThesisAnalysis import get_data, get_plot, ThesisHDF5Reader\n'), ((6696, 6737), 'ThesisAnalysis.get_data', 'get_data', (['"""pedestal/pedestal_checs_pe.h5"""'], {}), "('pedestal/pedestal_checs_pe.h5')\n", (6704, 6737), False, 'from ThesisAnalysis import get_data, get_plot, ThesisHDF5Reader\n'), ((6834, 6872), 'ThesisAnalysis.get_data', 'get_data', (['"""pedestal/pedestal_checm.h5"""'], {}), "('pedestal/pedestal_checm.h5')\n", (6842, 6872), False, 'from ThesisAnalysis import get_data, get_plot, ThesisHDF5Reader\n'), ((612, 652), 'target_calib.GetCellIDTCArray', 'GetCellIDTCArray', (['fci', "df['isam'].values"], {}), "(fci, df['isam'].values)\n", (628, 652), False, 'from target_calib import CalculateRowColumnBlockPhase, GetCellIDTCArray\n'), ((3046, 3081), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(data == 0)', 'data'], {}), '(data == 0, data)\n', (3064, 3081), True, 'import numpy as np\n'), ((5224, 5252), 'ThesisAnalysis.ThesisHDF5Reader', 'ThesisHDF5Reader', (['input_path'], {}), '(input_path)\n', (5240, 5252), False, 'from ThesisAnalysis import get_data, get_plot, ThesisHDF5Reader\n'), ((5505, 5550), 'os.path.join', 'os.path.join', (['output_dir', '"""pedestal_hist.pdf"""'], {}), "(output_dir, 'pedestal_hist.pdf')\n", (5517, 5550), False, 'import os\n'), ((5629, 5679), 'os.path.join', 'os.path.join', (['output_dir', '"""pedestal_histchunk.pdf"""'], {}), "(output_dir, 'pedestal_histchunk.pdf')\n", (5641, 5679), False, 'import os\n'), ((5859, 5906), 'os.path.join', 'os.path.join', (['output_dir', '"""pedestal_lookup.pdf"""'], {}), "(output_dir, 'pedestal_lookup.pdf')\n", (5871, 5906), False, 'import os\n'), ((3790, 3809), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(16)'], {}), '(16)\n', (3805, 3809), False, 'from matplotlib.ticker import MultipleLocator, FuncFormatter\n'), ((4625, 4644), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(16)'], {}), '(16)\n', (4640, 4644), False, 'from matplotlib.ticker import MultipleLocator, FuncFormatter\n'), ((4131, 4157), 'numpy.diff', 'np.diff', (["df_mean['iblock']"], {}), "(df_mean['iblock'])\n", (4138, 4157), True, 'import numpy as np\n')]
# coding: utf-8 import cmath import numpy as np from rcwa.common import matmul, redheffer_star_prod, get_input from rcwa.structure import HomogeneousStructure from rcwa.source import Source from rcwa._constants import UNIT_MAT_2D def save_outputs(R, T): with open('output.toml', 'w') as fid: fid.write('[R]\n00 = {:.4f}\n'.format(R)) fid.write('[T]\n00 = {:.4f}\n'.format(T)) fid.write('[R_T]\n00 = {:.4f}\n'.format(R + T)) class TMM(): '''Calculates transmission through a stack of uniform layers''' def __prepare(self, structure, source): nr1 = np.sqrt(structure.UR1*structure.ER1) self.k_inc = source.K0*nr1*\ np.array(([np.sin(source.THETA)*np.cos(source.PHI), np.sin(source.THETA)*np.sin(source.PHI), np.cos(source.THETA)])) S_global = np.array(([0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0])) return S_global def compute(self, structure, source): S_global = self.__prepare(structure, source) S_global = self.__compute_layers(structure, source, S_global) S_global = self.__compute_superstrate(structure, S_global) S_global = self.__compute_substrate(structure, S_global) R, T = self.__get_R_T(structure, source, S_global) return R, T def __compute_layers(self, structure, source, S_global): kx, ky = self.k_inc[0], self.k_inc[1] # take layers into account for i in range(0, structure.num_layers): ur = structure.ur_vec[i] er = structure.er_vec[i] l = structure.layer_thicknesses_vec[i] s_layer_mat = self.__calc_s_mat(l, ur, er, kx, ky, source.K0) S_global = redheffer_star_prod(S_global, s_layer_mat, UNIT_MAT_2D) return S_global @staticmethod def __calc_gap_layer_params(kx, ky): ur = 1 er = 1 q_mat = np.array(([kx*ky, ur*er+ky*ky], [-(ur*er+kx*kx), -kx*ky]))/ur v_mat = -1j*q_mat return v_mat @staticmethod def __calc_layer_params(ur, er, kx, ky): q_mat = np.array(([kx*ky, ur*er-kx*kx], [ky*ky-ur*er, -kx*ky]))/ur kz = cmath.sqrt(ur*er-kx*kx-ky*ky) omega_mat = 1j*kz*np.array(([1, 0], [0, 1])) v_mat = np.matmul(q_mat, np.linalg.inv(omega_mat)) return omega_mat, v_mat def __calc_s_mat(self, layer_thickness, ur, er, kx, ky, K0): omegai_mat, vi_mat = self.__calc_layer_params(ur, er, kx, ky) vg_mat = self.__calc_gap_layer_params(kx, ky) ai_mat = UNIT_MAT_2D + np.matmul(np.linalg.inv(vi_mat), vg_mat) bi_mat = UNIT_MAT_2D - np.matmul(np.linalg.inv(vi_mat), vg_mat) xi_mat = np.diag(np.exp(np.diag(omegai_mat)*K0*layer_thickness)) ai_inv_mat = np.linalg.inv(ai_mat) di_mat = ai_mat - matmul(xi_mat, bi_mat, ai_inv_mat, xi_mat, bi_mat) di_inv_mat = np.linalg.inv(di_mat) s_11_mat = matmul(di_inv_mat, matmul( xi_mat, bi_mat, ai_inv_mat, xi_mat, ai_mat) - bi_mat) s_12_mat = matmul(di_inv_mat, xi_mat, ai_mat - matmul(bi_mat, ai_inv_mat, bi_mat)) # S_12 = S_21, S_11 = S_22 s_mat = np.concatenate((np.concatenate((s_11_mat, s_12_mat), axis=1), np.concatenate((s_12_mat, s_11_mat), axis=1))) return s_mat def __compute_superstrate(self, structure, S_global): kx, ky = self.k_inc[0], self.k_inc[1] # take superstrate into account _, v_ref_mat = self.__calc_layer_params(structure.UR1, structure.ER1, kx, ky) vg_mat = self.__calc_gap_layer_params(kx, ky) a_ref_mat = UNIT_MAT_2D + matmul(np.linalg.inv(vg_mat), v_ref_mat) b_ref_mat = UNIT_MAT_2D - matmul(np.linalg.inv(vg_mat), v_ref_mat) s_ref_11_mat = -matmul(np.linalg.inv(a_ref_mat), b_ref_mat) s_ref_12_mat = 2*np.linalg.inv(a_ref_mat) s_ref_21_mat = 0.5*(a_ref_mat - matmul(b_ref_mat, np.linalg.inv(a_ref_mat), b_ref_mat)) s_ref_22_mat = matmul(b_ref_mat, np.linalg.inv(a_ref_mat)) s_ref_mat = np.concatenate(( np.concatenate((s_ref_11_mat, s_ref_12_mat), axis=1), np.concatenate((s_ref_21_mat, s_ref_22_mat), axis=1))) S_global = redheffer_star_prod(s_ref_mat, S_global, UNIT_MAT_2D) return S_global def __compute_substrate(self, structure, S_global): kx, ky = self.k_inc[0], self.k_inc[1] # take substrate into account _, v_trn_mat = self.__calc_layer_params(structure.UR2, structure.ER2, kx, ky) vg_mat = self.__calc_gap_layer_params(kx, ky) a_trn_mat = UNIT_MAT_2D + matmul(np.linalg.inv(vg_mat), v_trn_mat) b_trn_mat = UNIT_MAT_2D - matmul(np.linalg.inv(vg_mat), v_trn_mat) s_trn_11_mat = matmul(b_trn_mat, np.linalg.inv(a_trn_mat)) s_trn_12_mat = 0.5*(a_trn_mat - matmul(b_trn_mat, np.linalg.inv(a_trn_mat), b_trn_mat)) s_trn_21_mat = 2*np.linalg.inv(a_trn_mat) s_trn_22_mat = -matmul(np.linalg.inv(a_trn_mat), b_trn_mat) s_trn_mat = np.concatenate((np.concatenate((s_trn_11_mat, s_trn_12_mat), axis=1), np.concatenate((s_trn_21_mat, s_trn_22_mat), axis=1))) S_global = redheffer_star_prod(S_global, s_trn_mat, UNIT_MAT_2D) return S_global def __get_R_T(self, structure, source, S_global): z_unit_vec = np.array(([0, 0, 1])) alpha_te = np.cross(z_unit_vec, self.k_inc) alpha_te = alpha_te/np.linalg.norm(alpha_te) alpha_tm = np.cross(alpha_te, self.k_inc) alpha_tm = alpha_tm/np.linalg.norm(alpha_tm) E_inc = source.norm_P_TM*alpha_tm + source.norm_P_TE*alpha_te c_inc = np.array(([E_inc[0], E_inc[1], 0, 0])) c_ret = matmul(S_global, c_inc) e_field_ref = np.array(([c_ret[0], c_ret[1], 0])) e_field_ref[2] = -(self.k_inc[0]*e_field_ref[0]+self.k_inc[1]*e_field_ref[1])/self.k_inc[2] k_trn = np.array(([self.k_inc[0], self.k_inc[1], 0])) nr2 = np.sqrt(structure.ER2*structure.UR2) k_trn[2] = np.sqrt(source.K0*source.K0*nr2*nr2 - k_trn[0]*k_trn[0] - k_trn[1]*k_trn[1]) e_field_trn = np.array(([c_ret[2], c_ret[3], 0])) e_field_trn[2] = -(k_trn[0]*e_field_trn[0]+k_trn[1]*e_field_trn[1])\ /(k_trn[2]) R = round((np.linalg.norm(e_field_ref))**2, 4) T = round((np.linalg.norm(e_field_trn))**2*((k_trn[2]/structure.UR2).real)\ /((self.k_inc[2]/structure.UR1).real), 4) return R, T def tmm_(input_toml): source = Source(input_toml) structure = HomogeneousStructure(input_toml, source.norm_lambda) tmm = TMM() R, T = tmm.compute(structure, source) save_outputs(R, T) if __name__ == '__main__': input_toml = get_input() tmm_(input_toml)
[ "rcwa.common.redheffer_star_prod", "numpy.sqrt", "numpy.cross", "rcwa.common.matmul", "cmath.sqrt", "numpy.linalg.norm", "numpy.diag", "numpy.array", "numpy.linalg.inv", "numpy.cos", "numpy.concatenate", "rcwa.common.get_input", "numpy.sin", "rcwa.source.Source", "rcwa.structure.Homogene...
[((6700, 6718), 'rcwa.source.Source', 'Source', (['input_toml'], {}), '(input_toml)\n', (6706, 6718), False, 'from rcwa.source import Source\n'), ((6735, 6787), 'rcwa.structure.HomogeneousStructure', 'HomogeneousStructure', (['input_toml', 'source.norm_lambda'], {}), '(input_toml, source.norm_lambda)\n', (6755, 6787), False, 'from rcwa.structure import HomogeneousStructure\n'), ((6914, 6925), 'rcwa.common.get_input', 'get_input', ([], {}), '()\n', (6923, 6925), False, 'from rcwa.common import matmul, redheffer_star_prod, get_input\n'), ((595, 633), 'numpy.sqrt', 'np.sqrt', (['(structure.UR1 * structure.ER1)'], {}), '(structure.UR1 * structure.ER1)\n', (602, 633), True, 'import numpy as np\n'), ((858, 924), 'numpy.array', 'np.array', (['([0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0])'], {}), '(([0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]))\n', (866, 924), True, 'import numpy as np\n'), ((2215, 2254), 'cmath.sqrt', 'cmath.sqrt', (['(ur * er - kx * kx - ky * ky)'], {}), '(ur * er - kx * kx - ky * ky)\n', (2225, 2254), False, 'import cmath\n'), ((2817, 2838), 'numpy.linalg.inv', 'np.linalg.inv', (['ai_mat'], {}), '(ai_mat)\n', (2830, 2838), True, 'import numpy as np\n'), ((2937, 2958), 'numpy.linalg.inv', 'np.linalg.inv', (['di_mat'], {}), '(di_mat)\n', (2950, 2958), True, 'import numpy as np\n'), ((4334, 4387), 'rcwa.common.redheffer_star_prod', 'redheffer_star_prod', (['s_ref_mat', 'S_global', 'UNIT_MAT_2D'], {}), '(s_ref_mat, S_global, UNIT_MAT_2D)\n', (4353, 4387), False, 'from rcwa.common import matmul, redheffer_star_prod, get_input\n'), ((5371, 5424), 'rcwa.common.redheffer_star_prod', 'redheffer_star_prod', (['S_global', 's_trn_mat', 'UNIT_MAT_2D'], {}), '(S_global, s_trn_mat, UNIT_MAT_2D)\n', (5390, 5424), False, 'from rcwa.common import matmul, redheffer_star_prod, get_input\n'), ((5525, 5544), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (5533, 5544), True, 'import numpy as np\n'), ((5566, 5598), 'numpy.cross', 'np.cross', (['z_unit_vec', 'self.k_inc'], {}), '(z_unit_vec, self.k_inc)\n', (5574, 5598), True, 'import numpy as np\n'), ((5671, 5701), 'numpy.cross', 'np.cross', (['alpha_te', 'self.k_inc'], {}), '(alpha_te, self.k_inc)\n', (5679, 5701), True, 'import numpy as np\n'), ((5841, 5877), 'numpy.array', 'np.array', (['[E_inc[0], E_inc[1], 0, 0]'], {}), '([E_inc[0], E_inc[1], 0, 0])\n', (5849, 5877), True, 'import numpy as np\n'), ((5897, 5920), 'rcwa.common.matmul', 'matmul', (['S_global', 'c_inc'], {}), '(S_global, c_inc)\n', (5903, 5920), False, 'from rcwa.common import matmul, redheffer_star_prod, get_input\n'), ((5943, 5976), 'numpy.array', 'np.array', (['[c_ret[0], c_ret[1], 0]'], {}), '([c_ret[0], c_ret[1], 0])\n', (5951, 5976), True, 'import numpy as np\n'), ((6095, 6138), 'numpy.array', 'np.array', (['[self.k_inc[0], self.k_inc[1], 0]'], {}), '([self.k_inc[0], self.k_inc[1], 0])\n', (6103, 6138), True, 'import numpy as np\n'), ((6155, 6193), 'numpy.sqrt', 'np.sqrt', (['(structure.ER2 * structure.UR2)'], {}), '(structure.ER2 * structure.UR2)\n', (6162, 6193), True, 'import numpy as np\n'), ((6211, 6301), 'numpy.sqrt', 'np.sqrt', (['(source.K0 * source.K0 * nr2 * nr2 - k_trn[0] * k_trn[0] - k_trn[1] * k_trn[1])'], {}), '(source.K0 * source.K0 * nr2 * nr2 - k_trn[0] * k_trn[0] - k_trn[1] *\n k_trn[1])\n', (6218, 6301), True, 'import numpy as np\n'), ((6310, 6343), 'numpy.array', 'np.array', (['[c_ret[2], c_ret[3], 0]'], {}), '([c_ret[2], c_ret[3], 0])\n', (6318, 6343), True, 'import numpy as np\n'), ((1769, 1824), 'rcwa.common.redheffer_star_prod', 'redheffer_star_prod', (['S_global', 's_layer_mat', 'UNIT_MAT_2D'], {}), '(S_global, s_layer_mat, UNIT_MAT_2D)\n', (1788, 1824), False, 'from rcwa.common import matmul, redheffer_star_prod, get_input\n'), ((1954, 2028), 'numpy.array', 'np.array', (['([kx * ky, ur * er + ky * ky], [-(ur * er + kx * kx), -kx * ky])'], {}), '(([kx * ky, ur * er + ky * ky], [-(ur * er + kx * kx), -kx * ky]))\n', (1962, 2028), True, 'import numpy as np\n'), ((2143, 2214), 'numpy.array', 'np.array', (['([kx * ky, ur * er - kx * kx], [ky * ky - ur * er, -kx * ky])'], {}), '(([kx * ky, ur * er - kx * kx], [ky * ky - ur * er, -kx * ky]))\n', (2151, 2214), True, 'import numpy as np\n'), ((2271, 2297), 'numpy.array', 'np.array', (['([1, 0], [0, 1])'], {}), '(([1, 0], [0, 1]))\n', (2279, 2297), True, 'import numpy as np\n'), ((2331, 2355), 'numpy.linalg.inv', 'np.linalg.inv', (['omega_mat'], {}), '(omega_mat)\n', (2344, 2355), True, 'import numpy as np\n'), ((2865, 2915), 'rcwa.common.matmul', 'matmul', (['xi_mat', 'bi_mat', 'ai_inv_mat', 'xi_mat', 'bi_mat'], {}), '(xi_mat, bi_mat, ai_inv_mat, xi_mat, bi_mat)\n', (2871, 2915), False, 'from rcwa.common import matmul, redheffer_star_prod, get_input\n'), ((3929, 3953), 'numpy.linalg.inv', 'np.linalg.inv', (['a_ref_mat'], {}), '(a_ref_mat)\n', (3942, 3953), True, 'import numpy as np\n'), ((4119, 4143), 'numpy.linalg.inv', 'np.linalg.inv', (['a_ref_mat'], {}), '(a_ref_mat)\n', (4132, 4143), True, 'import numpy as np\n'), ((4884, 4908), 'numpy.linalg.inv', 'np.linalg.inv', (['a_trn_mat'], {}), '(a_trn_mat)\n', (4897, 4908), True, 'import numpy as np\n'), ((5078, 5102), 'numpy.linalg.inv', 'np.linalg.inv', (['a_trn_mat'], {}), '(a_trn_mat)\n', (5091, 5102), True, 'import numpy as np\n'), ((5627, 5651), 'numpy.linalg.norm', 'np.linalg.norm', (['alpha_te'], {}), '(alpha_te)\n', (5641, 5651), True, 'import numpy as np\n'), ((5730, 5754), 'numpy.linalg.norm', 'np.linalg.norm', (['alpha_tm'], {}), '(alpha_tm)\n', (5744, 5754), True, 'import numpy as np\n'), ((2620, 2641), 'numpy.linalg.inv', 'np.linalg.inv', (['vi_mat'], {}), '(vi_mat)\n', (2633, 2641), True, 'import numpy as np\n'), ((2692, 2713), 'numpy.linalg.inv', 'np.linalg.inv', (['vi_mat'], {}), '(vi_mat)\n', (2705, 2713), True, 'import numpy as np\n'), ((2997, 3047), 'rcwa.common.matmul', 'matmul', (['xi_mat', 'bi_mat', 'ai_inv_mat', 'xi_mat', 'ai_mat'], {}), '(xi_mat, bi_mat, ai_inv_mat, xi_mat, ai_mat)\n', (3003, 3047), False, 'from rcwa.common import matmul, redheffer_star_prod, get_input\n'), ((3152, 3186), 'rcwa.common.matmul', 'matmul', (['bi_mat', 'ai_inv_mat', 'bi_mat'], {}), '(bi_mat, ai_inv_mat, bi_mat)\n', (3158, 3186), False, 'from rcwa.common import matmul, redheffer_star_prod, get_input\n'), ((3255, 3299), 'numpy.concatenate', 'np.concatenate', (['(s_11_mat, s_12_mat)'], {'axis': '(1)'}), '((s_11_mat, s_12_mat), axis=1)\n', (3269, 3299), True, 'import numpy as np\n'), ((3333, 3377), 'numpy.concatenate', 'np.concatenate', (['(s_12_mat, s_11_mat)'], {'axis': '(1)'}), '((s_12_mat, s_11_mat), axis=1)\n', (3347, 3377), True, 'import numpy as np\n'), ((3727, 3748), 'numpy.linalg.inv', 'np.linalg.inv', (['vg_mat'], {}), '(vg_mat)\n', (3740, 3748), True, 'import numpy as np\n'), ((3802, 3823), 'numpy.linalg.inv', 'np.linalg.inv', (['vg_mat'], {}), '(vg_mat)\n', (3815, 3823), True, 'import numpy as np\n'), ((3867, 3891), 'numpy.linalg.inv', 'np.linalg.inv', (['a_ref_mat'], {}), '(a_ref_mat)\n', (3880, 3891), True, 'import numpy as np\n'), ((4194, 4246), 'numpy.concatenate', 'np.concatenate', (['(s_ref_11_mat, s_ref_12_mat)'], {'axis': '(1)'}), '((s_ref_11_mat, s_ref_12_mat), axis=1)\n', (4208, 4246), True, 'import numpy as np\n'), ((4260, 4312), 'numpy.concatenate', 'np.concatenate', (['(s_ref_21_mat, s_ref_22_mat)'], {'axis': '(1)'}), '((s_ref_21_mat, s_ref_22_mat), axis=1)\n', (4274, 4312), True, 'import numpy as np\n'), ((4734, 4755), 'numpy.linalg.inv', 'np.linalg.inv', (['vg_mat'], {}), '(vg_mat)\n', (4747, 4755), True, 'import numpy as np\n'), ((4809, 4830), 'numpy.linalg.inv', 'np.linalg.inv', (['vg_mat'], {}), '(vg_mat)\n', (4822, 4830), True, 'import numpy as np\n'), ((5134, 5158), 'numpy.linalg.inv', 'np.linalg.inv', (['a_trn_mat'], {}), '(a_trn_mat)\n', (5147, 5158), True, 'import numpy as np\n'), ((5207, 5259), 'numpy.concatenate', 'np.concatenate', (['(s_trn_11_mat, s_trn_12_mat)'], {'axis': '(1)'}), '((s_trn_11_mat, s_trn_12_mat), axis=1)\n', (5221, 5259), True, 'import numpy as np\n'), ((5297, 5349), 'numpy.concatenate', 'np.concatenate', (['(s_trn_21_mat, s_trn_22_mat)'], {'axis': '(1)'}), '((s_trn_21_mat, s_trn_22_mat), axis=1)\n', (5311, 5349), True, 'import numpy as np\n'), ((6466, 6493), 'numpy.linalg.norm', 'np.linalg.norm', (['e_field_ref'], {}), '(e_field_ref)\n', (6480, 6493), True, 'import numpy as np\n'), ((815, 835), 'numpy.cos', 'np.cos', (['source.THETA'], {}), '(source.THETA)\n', (821, 835), True, 'import numpy as np\n'), ((4040, 4064), 'numpy.linalg.inv', 'np.linalg.inv', (['a_ref_mat'], {}), '(a_ref_mat)\n', (4053, 4064), True, 'import numpy as np\n'), ((5015, 5039), 'numpy.linalg.inv', 'np.linalg.inv', (['a_trn_mat'], {}), '(a_trn_mat)\n', (5028, 5039), True, 'import numpy as np\n'), ((701, 721), 'numpy.sin', 'np.sin', (['source.THETA'], {}), '(source.THETA)\n', (707, 721), True, 'import numpy as np\n'), ((722, 740), 'numpy.cos', 'np.cos', (['source.PHI'], {}), '(source.PHI)\n', (728, 740), True, 'import numpy as np\n'), ((774, 794), 'numpy.sin', 'np.sin', (['source.THETA'], {}), '(source.THETA)\n', (780, 794), True, 'import numpy as np\n'), ((795, 813), 'numpy.sin', 'np.sin', (['source.PHI'], {}), '(source.PHI)\n', (801, 813), True, 'import numpy as np\n'), ((2755, 2774), 'numpy.diag', 'np.diag', (['omegai_mat'], {}), '(omegai_mat)\n', (2762, 2774), True, 'import numpy as np\n'), ((6521, 6548), 'numpy.linalg.norm', 'np.linalg.norm', (['e_field_trn'], {}), '(e_field_trn)\n', (6535, 6548), True, 'import numpy as np\n')]
# Apache 2.0 License # Copyright (c) 2022, Fraunhofer e.V. # All rights reserved. import os import numpy as np from torchvision.datasets import ImageFolder class Caltech256(ImageFolder): """Taken and modified from https://github.com/tribhuvanesh/knockoffnets/blob/master/knockoff/datasets/caltech256.py""" url = 'http://www.vision.caltech.edu/Image_Datasets/Caltech256/' _google_drive_file_id = '1r6o0pSROcV1_VwT4oSjA2FBUSCWGuxLK' base_folder = 'caltech256' def __init__(self, root, train=True, transform=None, target_transform=None, ntest=25, seed=123): self.train = train self.seed = seed self.root = root try: super().__init__(root=os.path.join(self.root, self.base_folder, '256_ObjectCategories'), transform=transform, target_transform=target_transform) except FileNotFoundError as e: raise FileNotFoundError(f'Dataset not found at {self.root}. Please download it from {self.url}.') from e self._cleanup() self.ntest = ntest # Reserve these many examples per class for evaluation self.partition_to_idxs = self.get_partition_to_idxs() self.pruned_idxs = self.partition_to_idxs['train' if train else 'test'] # Prune (self.imgs, self.samples to only include examples from the required train/test partition self.samples = [self.samples[i] for i in self.pruned_idxs] self.imgs = self.samples self.targets = [self.targets[i] for i in self.pruned_idxs] print('=> done loading {} ({}) with {} examples'.format(self.__class__.__name__, 'train' if train else 'test', len(self.samples))) def _cleanup(self): # Remove examples belonging to class "clutter" clutter_idx = self.class_to_idx['257.clutter'] self.samples = [s for s in self.samples if s[1] != clutter_idx] del self.class_to_idx['257.clutter'] self.classes = self.classes[:-1] def get_partition_to_idxs(self): from collections import defaultdict as dd partition_to_idxs = { 'train': [], 'test': [] } # Use this random seed to make partition consistent prev_state = np.random.get_state() np.random.seed(self.seed) # ----------------- Create mapping: classidx -> idx classidx_to_idxs = dd(list) for idx, s in enumerate(self.samples): classidx = s[1] classidx_to_idxs[classidx].append(idx) # Shuffle classidx_to_idx for classidx, idxs in classidx_to_idxs.items(): np.random.shuffle(idxs) for classidx, idxs in classidx_to_idxs.items(): partition_to_idxs['test'] += idxs[:self.ntest] # A constant no. kept aside for evaluation partition_to_idxs['train'] += idxs[self.ntest:] # Train on remaining # Revert randomness to original state np.random.set_state(prev_state) return partition_to_idxs
[ "numpy.random.get_state", "numpy.random.set_state", "os.path.join", "collections.defaultdict", "numpy.random.seed", "numpy.random.shuffle" ]
[((2348, 2369), 'numpy.random.get_state', 'np.random.get_state', ([], {}), '()\n', (2367, 2369), True, 'import numpy as np\n'), ((2379, 2404), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (2393, 2404), True, 'import numpy as np\n'), ((2496, 2504), 'collections.defaultdict', 'dd', (['list'], {}), '(list)\n', (2498, 2504), True, 'from collections import defaultdict as dd\n'), ((3069, 3100), 'numpy.random.set_state', 'np.random.set_state', (['prev_state'], {}), '(prev_state)\n', (3088, 3100), True, 'import numpy as np\n'), ((2741, 2764), 'numpy.random.shuffle', 'np.random.shuffle', (['idxs'], {}), '(idxs)\n', (2758, 2764), True, 'import numpy as np\n'), ((729, 794), 'os.path.join', 'os.path.join', (['self.root', 'self.base_folder', '"""256_ObjectCategories"""'], {}), "(self.root, self.base_folder, '256_ObjectCategories')\n", (741, 794), False, 'import os\n')]
import os, sys dir_ReDUCE = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(dir_ReDUCE+"/utils") import gurobipy as go import numpy as np from add_piecewise_linear_constraint import add_piecewise_linear_constraint from add_McCormick_envelope_constraint import add_bilinear_constraint_gurobi, limit2vertex import pdb def get_kb_from_2_pts(p1, p2): # This function returns the approximated line given 2 points on it kkk = (p1 ** 2 - p2 ** 2) / (p1 - p2) bbb = p2 ** 2 - kkk * p2 # p^2 = k*p + b assert abs(p1 * kkk + bbb - p1 ** 2) <= 1e-6, "Error: point p_lo does not lie on the quadratic curve!" assert abs(p2 * kkk + bbb - p2 ** 2) <= 1e-6, "Error: point p_hi does not lie on the quadratic curve!" return kkk, bbb def solve_separating_plane(vertex_0, vertex_1, bin_width, bin_height): bin_width += 2.0 bin_height += 2.0 bin_left = -bin_width / 2.0 bin_right = bin_width / 2.0 bin_ground = -1.0 bin_up = bin_height - 1.0 num_of_vertices = 4 # Variables related to a squared =================================================================================== a_knots_00 = [[-1.0, -0.75], [-0.75, -0.5], [-0.5, -0.25], [-0.25, 0.0], [0.0, 0.25], [0.25, 0.5], [0.5, 0.75], [0.75, 1.0]] k_a_sq_00 = [] b_a_sq_00 = [] num_of_int_a0 = int(np.log2(len(a_knots_00))) len_sec_00 = len(a_knots_00) for iter_sec in range(len_sec_00): p_lo = a_knots_00[iter_sec][0] p_hi = a_knots_00[iter_sec][1] kk, bb = get_kb_from_2_pts(p_lo, p_hi) k_a_sq_00.append(kk) b_a_sq_00.append(bb) a_knots_11 = [[-1.0, -0.75], [-0.75, -0.5], [-0.5, -0.25], [-0.25, 0.0], [0.0, 0.25], [0.25, 0.5], [0.5, 0.75], [0.75, 1.0]] k_a_sq_11 = [] b_a_sq_11 = [] num_of_int_a1 = int(np.log2(len(a_knots_11))) len_sec_11 = len(a_knots_11) for iter_sec in range(len_sec_11): p_lo = a_knots_11[iter_sec][0] p_hi = a_knots_11[iter_sec][1] kk, bb = get_kb_from_2_pts(p_lo, p_hi) k_a_sq_11.append(kk) b_a_sq_11.append(bb) # Variables related to a x v cross ================================================================================= v_knots_common_x = [[bin_left, bin_left + 0.25 * bin_width], [bin_left + 0.25 * bin_width, bin_left + 0.5 * bin_width], [bin_left + 0.5 * bin_width, bin_left + 0.75 * bin_width], [bin_left + 0.75 * bin_width, bin_left + bin_width]] assert (bin_left + bin_width) == bin_right, "Bin width doesn't match bin left/right !!" v_knots_common_y = [[bin_ground, bin_ground + 0.25 * bin_height], [bin_ground + 0.25 * bin_height, bin_ground + 0.5 * bin_height], [bin_ground + 0.5 * bin_height, bin_ground + 0.75 * bin_height], [bin_ground + 0.75 * bin_height, bin_ground + bin_height]] num_of_polygons_av_x = len(a_knots_00) * len(v_knots_common_x) num_of_polygons_av_y = len(a_knots_11) * len(v_knots_common_y) # Despite the pair and vertex, the number of integers are the same num_of_integer_v_x = int(np.log2(len(v_knots_common_x))) # a already has its integer variables num_of_integer_v_y = int(np.log2(len(v_knots_common_y))) num_of_vertices_av_x = num_of_polygons_av_x * 4 num_of_vertices_av_y = num_of_polygons_av_y * 4 v_all_av_x = np.zeros([3, num_of_vertices_av_x]) v_all_av_y = np.zeros([3, num_of_vertices_av_y]) iter_polygon = 0 for iter_a in range(len(a_knots_00)): for iter_v in range(len(v_knots_common_x)): a_knots_av_temp = a_knots_00[iter_a] v_knots_av_temp = v_knots_common_x[iter_v] bilinear_limits = [a_knots_av_temp[0], a_knots_av_temp[1], v_knots_av_temp[0], v_knots_av_temp[1]] # Use limit2vertex function along each bilinear subspace, and collect all vertices vv = limit2vertex(bilinear_limits) v_all_av_x[:, 4 * iter_polygon + 0] = np.array([vv[0, 0], vv[0, 1], vv[0, 2]]) v_all_av_x[:, 4 * iter_polygon + 1] = np.array([vv[1, 0], vv[1, 1], vv[1, 2]]) v_all_av_x[:, 4 * iter_polygon + 2] = np.array([vv[2, 0], vv[2, 1], vv[2, 2]]) v_all_av_x[:, 4 * iter_polygon + 3] = np.array([vv[3, 0], vv[3, 1], vv[3, 2]]) iter_polygon += 1 iter_polygon = 0 for iter_a in range(len(a_knots_11)): for iter_v in range(len(v_knots_common_y)): a_knots_av_temp = a_knots_11[iter_a] v_knots_av_temp = v_knots_common_y[iter_v] bilinear_limits = [a_knots_av_temp[0], a_knots_av_temp[1], v_knots_av_temp[0], v_knots_av_temp[1]] # Use limit2vertex function along each bilinear subspace, and collect all vertices vv = limit2vertex(bilinear_limits) v_all_av_y[:, 4 * iter_polygon + 0] = np.array([vv[0, 0], vv[0, 1], vv[0, 2]]) v_all_av_y[:, 4 * iter_polygon + 1] = np.array([vv[1, 0], vv[1, 1], vv[1, 2]]) v_all_av_y[:, 4 * iter_polygon + 2] = np.array([vv[2, 0], vv[2, 1], vv[2, 2]]) v_all_av_y[:, 4 * iter_polygon + 3] = np.array([vv[3, 0], vv[3, 1], vv[3, 2]]) iter_polygon += 1 m = go.Model("Bin_organization") m.setParam('MIPGap', 1e-2) bigM = 10000 a_sep = m.addVars(2, lb=-1.0, ub=1.0) a_sep_sq = m.addVars(2, lb=-1.0, ub=1.0) b_sep = m.addVar(lb=-bigM, ub=bigM) int_a0 = m.addVars(num_of_int_a0, vtype=go.GRB.BINARY) int_a1 = m.addVars(num_of_int_a1, vtype=go.GRB.BINARY) num_paired = 2 a_times_v_x = m.addVars(num_paired, num_of_vertices, lb=-bigM, ub=bigM) int_v_x = m.addVars(num_paired, num_of_vertices, num_of_integer_v_x, vtype=go.GRB.BINARY) lam_av_x = m.addVars(num_paired, num_of_vertices, num_of_vertices_av_x, lb=0.0, ub=1.0) a_times_v_y = m.addVars(num_paired, num_of_vertices, lb=-bigM, ub=bigM) int_v_y = m.addVars(num_paired, num_of_vertices, num_of_integer_v_y, vtype=go.GRB.BINARY) lam_av_y = m.addVars(num_paired, num_of_vertices, num_of_vertices_av_y, lb=0.0, ub=1.0) m.update() # a is a unit vector m.addConstr(1.0 == (a_sep_sq[0] + a_sep_sq[1])) int_a_0 = [] for iter_int_a_0 in range(pow(2, num_of_int_a0)): bin_char = bin(iter_int_a_0)[2:].zfill(num_of_int_a0) # Change the iter value to binary this_int = [] for iter_digit in range(num_of_int_a0): if bin_char[-(iter_digit+1)] == '1': this_int.append(int_a0[iter_digit]) elif bin_char[-(iter_digit+1)] == '0': this_int.append(1 - int_a0[iter_digit]) else: assert False, "Something is wrong !!" int_a_0.append(this_int) # This way of coding, the very left section will be chosen when int_a0[0] = 0, int_a0[1] = 0, int_a0[2] = 0 add_piecewise_linear_constraint(m, a_sep[0], a_sep_sq[0], a_knots_00, k_a_sq_00, b_a_sq_00, int_a_0, bigM) int_a_1 = [] for iter_int_a_1 in range(pow(2, num_of_int_a1)): bin_char = bin(iter_int_a_1)[2:].zfill(num_of_int_a1) # Change the iter value to binary this_int = [] for iter_digit in range(num_of_int_a1): if bin_char[-(iter_digit+1)] == '1': this_int.append(int_a1[iter_digit]) elif bin_char[-(iter_digit+1)] == '0': this_int.append(1 - int_a1[iter_digit]) else: assert False, "Something is wrong !!" int_a_1.append(this_int) add_piecewise_linear_constraint(m, a_sep[1], a_sep_sq[1], a_knots_11, k_a_sq_11, b_a_sq_11, int_a_1, bigM) for iter_vertex in range(num_of_vertices): # a*v on one side of the plane # TODO: Note! The order (<= or >=) doesn't matter. If the objects flip sides, the optimizer will get (-a, -b) # instead of (a, b). Since we are getting global optimal, the sides won't be flipped. # The second one should be always larger according to the 2 constraints below m.addConstr(a_times_v_x[0, iter_vertex] + a_times_v_y[0, iter_vertex] <= b_sep) m.addConstr(a_times_v_x[1, iter_vertex] + a_times_v_y[1, iter_vertex] >= b_sep) vertex = [vertex_0, vertex_1] for iter_pair in range(num_paired): for iter_vertex in range(num_of_vertices): x = [a_sep[0], vertex[iter_pair][iter_vertex, 0], a_times_v_x[iter_pair, iter_vertex]] lam_x = [lam_av_x[iter_pair, iter_vertex, iter_lam] for iter_lam in range(num_of_vertices_av_x)] int_var_x = [int_v_x[iter_pair, iter_vertex, iter_zz] for iter_zz in range(num_of_integer_v_x)] + [int_a0[0], int_a0[1], int_a0[2]] add_bilinear_constraint_gurobi(m, x, lam_x, int_var_x, num_of_polygons_av_x, v_all_av_x) y = [a_sep[1], vertex[iter_pair][iter_vertex, 1], a_times_v_y[iter_pair, iter_vertex]] lam_y = [lam_av_y[iter_pair, iter_vertex, iter_lam] for iter_lam in range(num_of_vertices_av_y)] int_var_y = [int_v_y[iter_pair, iter_vertex, iter_zz] for iter_zz in range(num_of_integer_v_y)] + [int_a1[0], int_a1[1], int_a1[2]] add_bilinear_constraint_gurobi(m, y, lam_y, int_var_y, num_of_polygons_av_y, v_all_av_y) obj = a_sep[1]*a_sep[1] m.setObjective(obj, go.GRB.MINIMIZE) m.optimize() if m.SolCount > 0: prob_success = True else: prob_success = False a_sol = np.zeros(2) b_sol = 0.0 if prob_success: a_sol = np.array([a_sep[0].X, a_sep[1].X]) b_sol = b_sep.X return prob_success, a_sol, b_sol
[ "add_piecewise_linear_constraint.add_piecewise_linear_constraint", "add_McCormick_envelope_constraint.limit2vertex", "os.path.realpath", "numpy.array", "numpy.zeros", "add_McCormick_envelope_constraint.add_bilinear_constraint_gurobi", "gurobipy.Model", "sys.path.append" ]
[((91, 129), 'sys.path.append', 'sys.path.append', (["(dir_ReDUCE + '/utils')"], {}), "(dir_ReDUCE + '/utils')\n", (106, 129), False, 'import os, sys\n'), ((3572, 3607), 'numpy.zeros', 'np.zeros', (['[3, num_of_vertices_av_x]'], {}), '([3, num_of_vertices_av_x])\n', (3580, 3607), True, 'import numpy as np\n'), ((3626, 3661), 'numpy.zeros', 'np.zeros', (['[3, num_of_vertices_av_y]'], {}), '([3, num_of_vertices_av_y])\n', (3634, 3661), True, 'import numpy as np\n'), ((5451, 5479), 'gurobipy.Model', 'go.Model', (['"""Bin_organization"""'], {}), "('Bin_organization')\n", (5459, 5479), True, 'import gurobipy as go\n'), ((7126, 7236), 'add_piecewise_linear_constraint.add_piecewise_linear_constraint', 'add_piecewise_linear_constraint', (['m', 'a_sep[0]', 'a_sep_sq[0]', 'a_knots_00', 'k_a_sq_00', 'b_a_sq_00', 'int_a_0', 'bigM'], {}), '(m, a_sep[0], a_sep_sq[0], a_knots_00,\n k_a_sq_00, b_a_sq_00, int_a_0, bigM)\n', (7157, 7236), False, 'from add_piecewise_linear_constraint import add_piecewise_linear_constraint\n'), ((7805, 7915), 'add_piecewise_linear_constraint.add_piecewise_linear_constraint', 'add_piecewise_linear_constraint', (['m', 'a_sep[1]', 'a_sep_sq[1]', 'a_knots_11', 'k_a_sq_11', 'b_a_sq_11', 'int_a_1', 'bigM'], {}), '(m, a_sep[1], a_sep_sq[1], a_knots_11,\n k_a_sq_11, b_a_sq_11, int_a_1, bigM)\n', (7836, 7915), False, 'from add_piecewise_linear_constraint import add_piecewise_linear_constraint\n'), ((9736, 9747), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (9744, 9747), True, 'import numpy as np\n'), ((61, 87), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (77, 87), False, 'import os, sys\n'), ((9806, 9840), 'numpy.array', 'np.array', (['[a_sep[0].X, a_sep[1].X]'], {}), '([a_sep[0].X, a_sep[1].X])\n', (9814, 9840), True, 'import numpy as np\n'), ((4118, 4147), 'add_McCormick_envelope_constraint.limit2vertex', 'limit2vertex', (['bilinear_limits'], {}), '(bilinear_limits)\n', (4130, 4147), False, 'from add_McCormick_envelope_constraint import add_bilinear_constraint_gurobi, limit2vertex\n'), ((4201, 4241), 'numpy.array', 'np.array', (['[vv[0, 0], vv[0, 1], vv[0, 2]]'], {}), '([vv[0, 0], vv[0, 1], vv[0, 2]])\n', (4209, 4241), True, 'import numpy as np\n'), ((4293, 4333), 'numpy.array', 'np.array', (['[vv[1, 0], vv[1, 1], vv[1, 2]]'], {}), '([vv[1, 0], vv[1, 1], vv[1, 2]])\n', (4301, 4333), True, 'import numpy as np\n'), ((4385, 4425), 'numpy.array', 'np.array', (['[vv[2, 0], vv[2, 1], vv[2, 2]]'], {}), '([vv[2, 0], vv[2, 1], vv[2, 2]])\n', (4393, 4425), True, 'import numpy as np\n'), ((4477, 4517), 'numpy.array', 'np.array', (['[vv[3, 0], vv[3, 1], vv[3, 2]]'], {}), '([vv[3, 0], vv[3, 1], vv[3, 2]])\n', (4485, 4517), True, 'import numpy as np\n'), ((5007, 5036), 'add_McCormick_envelope_constraint.limit2vertex', 'limit2vertex', (['bilinear_limits'], {}), '(bilinear_limits)\n', (5019, 5036), False, 'from add_McCormick_envelope_constraint import add_bilinear_constraint_gurobi, limit2vertex\n'), ((5090, 5130), 'numpy.array', 'np.array', (['[vv[0, 0], vv[0, 1], vv[0, 2]]'], {}), '([vv[0, 0], vv[0, 1], vv[0, 2]])\n', (5098, 5130), True, 'import numpy as np\n'), ((5182, 5222), 'numpy.array', 'np.array', (['[vv[1, 0], vv[1, 1], vv[1, 2]]'], {}), '([vv[1, 0], vv[1, 1], vv[1, 2]])\n', (5190, 5222), True, 'import numpy as np\n'), ((5274, 5314), 'numpy.array', 'np.array', (['[vv[2, 0], vv[2, 1], vv[2, 2]]'], {}), '([vv[2, 0], vv[2, 1], vv[2, 2]])\n', (5282, 5314), True, 'import numpy as np\n'), ((5366, 5406), 'numpy.array', 'np.array', (['[vv[3, 0], vv[3, 1], vv[3, 2]]'], {}), '([vv[3, 0], vv[3, 1], vv[3, 2]])\n', (5374, 5406), True, 'import numpy as np\n'), ((8982, 9074), 'add_McCormick_envelope_constraint.add_bilinear_constraint_gurobi', 'add_bilinear_constraint_gurobi', (['m', 'x', 'lam_x', 'int_var_x', 'num_of_polygons_av_x', 'v_all_av_x'], {}), '(m, x, lam_x, int_var_x, num_of_polygons_av_x,\n v_all_av_x)\n', (9012, 9074), False, 'from add_McCormick_envelope_constraint import add_bilinear_constraint_gurobi, limit2vertex\n'), ((9441, 9533), 'add_McCormick_envelope_constraint.add_bilinear_constraint_gurobi', 'add_bilinear_constraint_gurobi', (['m', 'y', 'lam_y', 'int_var_y', 'num_of_polygons_av_y', 'v_all_av_y'], {}), '(m, y, lam_y, int_var_y, num_of_polygons_av_y,\n v_all_av_y)\n', (9471, 9533), False, 'from add_McCormick_envelope_constraint import add_bilinear_constraint_gurobi, limit2vertex\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft from vib.forcing import multisine from vib.common import db """Simple example of quantifying odd/even nonlinearities using multisine. The nonparametric analysis/quantifying only works for one period, P=1. The nonlinearities become visible at the unexcited frequencies by using ftype={odd, oddrandom}. """ fs = 4096 # sampling frequency, Hz N = 4096 # number of points per period P = 1 # number of periods M = 1 # number of realizations f1 = 1 # lowest excited frequency f2 = 100 # highest excited frequency uStd = 1 # standard deviation of the generated signal u, t, lines, freq = multisine(f1, f2, fs, N, P, M, ftype='oddrandom', std=uStd) # apply input to a static nonlinear system y = u + 0.001*u**2 - 0.1*u**3 # perform nonlinear analysis Y = fft(y) # separate even and odd lines. 1 is dc, ie. 1+2n is even lines_even = np.arange(0,N,2) lines_odd_det = np.arange(1,N,2) lines_odd_det = np.setdiff1d(lines_odd_det, lines) plt.ion() # signal plots plt.figure(1) plt.clf() plt.plot(t, u[0]) plt.xlabel('time (s)') plt.ylabel('magnitude') plt.title('Multisine: {} realizations of {} periods of {} ' 'samples per period'.format(M,P,N)) plt.figure(2) plt.clf() plt.subplot(2,1,1) plt.plot(freq,db(fft(u[0,:N])),'-*') plt.xlabel('frequency (Hz)') plt.ylabel('magnitude (dB)') plt.title('FFT of one period of the multisine realizations') plt.subplot(2,1,2) plt.plot(freq,np.angle(fft(u[0,:N])),'-*') plt.xlabel('frequency (Hz)') plt.ylabel('phase (rad)') plt.title('FFT of one period of the multisine realizations') plt.tight_layout() # nl-test plot plt.figure(3) plt.clf() plt.plot(u[0],y[0],'.') plt.xlabel('input') plt.ylabel('output') plt.title('Static Nonlinear Function') plt.figure(4) plt.clf() plt.plot(freq[lines],db(Y[0,lines]),'*') plt.plot(freq[lines_odd_det],db(Y[0,lines_odd_det]),'^') plt.plot(freq[lines_even],db(Y[0,lines_even]),'o') plt.xlim([0,fs/2]) plt.xlabel('frequency (Hz)') plt.ylabel('magnitude (dB)') plt.title('FFT output') plt.legend(('excited lines','odd detection lines','even detection lines')) plt.show()
[ "vib.common.db", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.legend", "matplotlib.pyplot.xlabel", "numpy.fft.fft", "vib.forcing.multisine", "matplotlib.pyplot.clf", "matplotlib.pyplot.plot", "matplotlib.pyplot.figure", "numpy.setdiff1d", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot....
[((717, 776), 'vib.forcing.multisine', 'multisine', (['f1', 'f2', 'fs', 'N', 'P', 'M'], {'ftype': '"""oddrandom"""', 'std': 'uStd'}), "(f1, f2, fs, N, P, M, ftype='oddrandom', std=uStd)\n", (726, 776), False, 'from vib.forcing import multisine\n'), ((884, 890), 'numpy.fft.fft', 'fft', (['y'], {}), '(y)\n', (887, 890), False, 'from numpy.fft import fft\n'), ((961, 979), 'numpy.arange', 'np.arange', (['(0)', 'N', '(2)'], {}), '(0, N, 2)\n', (970, 979), True, 'import numpy as np\n'), ((994, 1012), 'numpy.arange', 'np.arange', (['(1)', 'N', '(2)'], {}), '(1, N, 2)\n', (1003, 1012), True, 'import numpy as np\n'), ((1027, 1061), 'numpy.setdiff1d', 'np.setdiff1d', (['lines_odd_det', 'lines'], {}), '(lines_odd_det, lines)\n', (1039, 1061), True, 'import numpy as np\n'), ((1063, 1072), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1070, 1072), True, 'import matplotlib.pyplot as plt\n'), ((1088, 1101), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (1098, 1101), True, 'import matplotlib.pyplot as plt\n'), ((1102, 1111), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1109, 1111), True, 'import matplotlib.pyplot as plt\n'), ((1112, 1129), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'u[0]'], {}), '(t, u[0])\n', (1120, 1129), True, 'import matplotlib.pyplot as plt\n'), ((1130, 1152), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time (s)"""'], {}), "('time (s)')\n", (1140, 1152), True, 'import matplotlib.pyplot as plt\n'), ((1153, 1176), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (1163, 1176), True, 'import matplotlib.pyplot as plt\n'), ((1284, 1297), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (1294, 1297), True, 'import matplotlib.pyplot as plt\n'), ((1298, 1307), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1305, 1307), True, 'import matplotlib.pyplot as plt\n'), ((1308, 1328), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (1319, 1328), True, 'import matplotlib.pyplot as plt\n'), ((1364, 1392), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""frequency (Hz)"""'], {}), "('frequency (Hz)')\n", (1374, 1392), True, 'import matplotlib.pyplot as plt\n'), ((1393, 1421), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude (dB)"""'], {}), "('magnitude (dB)')\n", (1403, 1421), True, 'import matplotlib.pyplot as plt\n'), ((1422, 1482), 'matplotlib.pyplot.title', 'plt.title', (['"""FFT of one period of the multisine realizations"""'], {}), "('FFT of one period of the multisine realizations')\n", (1431, 1482), True, 'import matplotlib.pyplot as plt\n'), ((1484, 1504), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (1495, 1504), True, 'import matplotlib.pyplot as plt\n'), ((1546, 1574), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""frequency (Hz)"""'], {}), "('frequency (Hz)')\n", (1556, 1574), True, 'import matplotlib.pyplot as plt\n'), ((1575, 1600), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""phase (rad)"""'], {}), "('phase (rad)')\n", (1585, 1600), True, 'import matplotlib.pyplot as plt\n'), ((1601, 1661), 'matplotlib.pyplot.title', 'plt.title', (['"""FFT of one period of the multisine realizations"""'], {}), "('FFT of one period of the multisine realizations')\n", (1610, 1661), True, 'import matplotlib.pyplot as plt\n'), ((1662, 1680), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1678, 1680), True, 'import matplotlib.pyplot as plt\n'), ((1697, 1710), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (1707, 1710), True, 'import matplotlib.pyplot as plt\n'), ((1711, 1720), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1718, 1720), True, 'import matplotlib.pyplot as plt\n'), ((1721, 1746), 'matplotlib.pyplot.plot', 'plt.plot', (['u[0]', 'y[0]', '"""."""'], {}), "(u[0], y[0], '.')\n", (1729, 1746), True, 'import matplotlib.pyplot as plt\n'), ((1745, 1764), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""input"""'], {}), "('input')\n", (1755, 1764), True, 'import matplotlib.pyplot as plt\n'), ((1765, 1785), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""output"""'], {}), "('output')\n", (1775, 1785), True, 'import matplotlib.pyplot as plt\n'), ((1786, 1824), 'matplotlib.pyplot.title', 'plt.title', (['"""Static Nonlinear Function"""'], {}), "('Static Nonlinear Function')\n", (1795, 1824), True, 'import matplotlib.pyplot as plt\n'), ((1826, 1839), 'matplotlib.pyplot.figure', 'plt.figure', (['(4)'], {}), '(4)\n', (1836, 1839), True, 'import matplotlib.pyplot as plt\n'), ((1840, 1849), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1847, 1849), True, 'import matplotlib.pyplot as plt\n'), ((1999, 2020), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, fs / 2]'], {}), '([0, fs / 2])\n', (2007, 2020), True, 'import matplotlib.pyplot as plt\n'), ((2018, 2046), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""frequency (Hz)"""'], {}), "('frequency (Hz)')\n", (2028, 2046), True, 'import matplotlib.pyplot as plt\n'), ((2047, 2075), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude (dB)"""'], {}), "('magnitude (dB)')\n", (2057, 2075), True, 'import matplotlib.pyplot as plt\n'), ((2076, 2099), 'matplotlib.pyplot.title', 'plt.title', (['"""FFT output"""'], {}), "('FFT output')\n", (2085, 2099), True, 'import matplotlib.pyplot as plt\n'), ((2100, 2176), 'matplotlib.pyplot.legend', 'plt.legend', (["('excited lines', 'odd detection lines', 'even detection lines')"], {}), "(('excited lines', 'odd detection lines', 'even detection lines'))\n", (2110, 2176), True, 'import matplotlib.pyplot as plt\n'), ((2177, 2187), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2185, 2187), True, 'import matplotlib.pyplot as plt\n'), ((1871, 1886), 'vib.common.db', 'db', (['Y[0, lines]'], {}), '(Y[0, lines])\n', (1873, 1886), False, 'from vib.common import db\n'), ((1920, 1943), 'vib.common.db', 'db', (['Y[0, lines_odd_det]'], {}), '(Y[0, lines_odd_det])\n', (1922, 1943), False, 'from vib.common import db\n'), ((1974, 1994), 'vib.common.db', 'db', (['Y[0, lines_even]'], {}), '(Y[0, lines_even])\n', (1976, 1994), False, 'from vib.common import db\n'), ((1344, 1357), 'numpy.fft.fft', 'fft', (['u[0, :N]'], {}), '(u[0, :N])\n', (1347, 1357), False, 'from numpy.fft import fft\n'), ((1526, 1539), 'numpy.fft.fft', 'fft', (['u[0, :N]'], {}), '(u[0, :N])\n', (1529, 1539), False, 'from numpy.fft import fft\n')]
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import benchmarks import rbm import utils seed_data = 123 seed_weights_biases = 891 seed_learn = 812 n_visible_units = 3 n_hidden_units = 8 n_train_samples = 280000 n_test_samples = 50000 n_test_trials = 5 learning_rate = 0.1 batch_size = 10 k = 1 sampling_interval = 500 # p = [0.3, 0.1, 0.1, 0.5] np.random.seed(seed_data) # data_train = benchmarks.from_distribution(n_train_samples, p) data_train = benchmarks.random_distribution(n_train_samples, n_visible_units) # data_train = benchmarks.lxor(n_train_samples) # data_train = benchmarks.random_distribution(n_visible, n_train) np.random.seed(seed_weights_biases) myrbm = rbm.RBM(n_visible_units, n_hidden_units) initial_states = myrbm.sample(n_test_samples, n_test_trials) print('weights before', myrbm._w) np.random.seed(seed_learn) error = myrbm.fit(data_train, learning_rate, batch_size, k, sampling_interval) print('weights after', myrbm._w) final_states = myrbm.sample(n_test_samples, n_test_trials) data_dist = utils.joint_distribution(data_train, 0, prior='uniform') initial_dist = utils.joint_distribution(initial_states, 0, prior='uniform') final_dist = utils.joint_distribution(final_states, 0, prior='uniform') print(utils.DKL(data_dist, initial_dist), 'vs', utils.DKL(data_dist, final_dist)) plt.subplot(221) plt.plot(error) plt.ylim([0., 1.]) plt.subplot(222) plt.bar(np.arange(2**n_visible_units) + 0.0, data_dist, color='k', width=0.2, linewidth=0) plt.bar(np.arange(2**n_visible_units) + 0.2, initial_dist, color='b', width=0.2, linewidth=0) plt.bar(np.arange(2**n_visible_units) + 0.4, final_dist, color='r', width=0.2, linewidth=0) plt.gca().set_xticklabels(utils.get_states_as_strings(3)) plt.subplot(223) for i in range(n_hidden_units): for j in range(n_visible_units): plt.plot(np.array(myrbm._a_dw)[:, i, j]) # plt.pcolormesh(initial_states, cmap='gray') plt.subplot(224) # plt.pcolormesh(final_states, cmap='gray') plt.show()
[ "utils.joint_distribution", "utils.DKL", "rbm.RBM", "matplotlib.pyplot.gca", "matplotlib.pyplot.plot", "utils.get_states_as_strings", "numpy.array", "numpy.random.seed", "matplotlib.pyplot.ylim", "matplotlib.pyplot.subplot", "benchmarks.random_distribution", "numpy.arange", "matplotlib.pyplo...
[((380, 405), 'numpy.random.seed', 'np.random.seed', (['seed_data'], {}), '(seed_data)\n', (394, 405), True, 'import numpy as np\n'), ((483, 547), 'benchmarks.random_distribution', 'benchmarks.random_distribution', (['n_train_samples', 'n_visible_units'], {}), '(n_train_samples, n_visible_units)\n', (513, 547), False, 'import benchmarks\n'), ((663, 698), 'numpy.random.seed', 'np.random.seed', (['seed_weights_biases'], {}), '(seed_weights_biases)\n', (677, 698), True, 'import numpy as np\n'), ((707, 747), 'rbm.RBM', 'rbm.RBM', (['n_visible_units', 'n_hidden_units'], {}), '(n_visible_units, n_hidden_units)\n', (714, 747), False, 'import rbm\n'), ((845, 871), 'numpy.random.seed', 'np.random.seed', (['seed_learn'], {}), '(seed_learn)\n', (859, 871), True, 'import numpy as np\n'), ((1058, 1114), 'utils.joint_distribution', 'utils.joint_distribution', (['data_train', '(0)'], {'prior': '"""uniform"""'}), "(data_train, 0, prior='uniform')\n", (1082, 1114), False, 'import utils\n'), ((1130, 1190), 'utils.joint_distribution', 'utils.joint_distribution', (['initial_states', '(0)'], {'prior': '"""uniform"""'}), "(initial_states, 0, prior='uniform')\n", (1154, 1190), False, 'import utils\n'), ((1204, 1262), 'utils.joint_distribution', 'utils.joint_distribution', (['final_states', '(0)'], {'prior': '"""uniform"""'}), "(final_states, 0, prior='uniform')\n", (1228, 1262), False, 'import utils\n'), ((1347, 1363), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(221)'], {}), '(221)\n', (1358, 1363), True, 'import matplotlib.pyplot as plt\n'), ((1364, 1379), 'matplotlib.pyplot.plot', 'plt.plot', (['error'], {}), '(error)\n', (1372, 1379), True, 'import matplotlib.pyplot as plt\n'), ((1380, 1400), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (1388, 1400), True, 'import matplotlib.pyplot as plt\n'), ((1399, 1415), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(222)'], {}), '(222)\n', (1410, 1415), True, 'import matplotlib.pyplot as plt\n'), ((1751, 1767), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(223)'], {}), '(223)\n', (1762, 1767), True, 'import matplotlib.pyplot as plt\n'), ((1932, 1948), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(224)'], {}), '(224)\n', (1943, 1948), True, 'import matplotlib.pyplot as plt\n'), ((1993, 2003), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2001, 2003), True, 'import matplotlib.pyplot as plt\n'), ((1270, 1304), 'utils.DKL', 'utils.DKL', (['data_dist', 'initial_dist'], {}), '(data_dist, initial_dist)\n', (1279, 1304), False, 'import utils\n'), ((1312, 1344), 'utils.DKL', 'utils.DKL', (['data_dist', 'final_dist'], {}), '(data_dist, final_dist)\n', (1321, 1344), False, 'import utils\n'), ((1719, 1749), 'utils.get_states_as_strings', 'utils.get_states_as_strings', (['(3)'], {}), '(3)\n', (1746, 1749), False, 'import utils\n'), ((1424, 1455), 'numpy.arange', 'np.arange', (['(2 ** n_visible_units)'], {}), '(2 ** n_visible_units)\n', (1433, 1455), True, 'import numpy as np\n'), ((1515, 1546), 'numpy.arange', 'np.arange', (['(2 ** n_visible_units)'], {}), '(2 ** n_visible_units)\n', (1524, 1546), True, 'import numpy as np\n'), ((1609, 1640), 'numpy.arange', 'np.arange', (['(2 ** n_visible_units)'], {}), '(2 ** n_visible_units)\n', (1618, 1640), True, 'import numpy as np\n'), ((1693, 1702), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1700, 1702), True, 'import matplotlib.pyplot as plt\n'), ((1854, 1875), 'numpy.array', 'np.array', (['myrbm._a_dw'], {}), '(myrbm._a_dw)\n', (1862, 1875), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Test FastMarkerCluster ---------------------- """ from __future__ import (absolute_import, division, print_function) import folium from folium import plugins from jinja2 import Template import numpy as np def test_fast_marker_cluster(): n = 100 np.random.seed(seed=26082009) data = np.array([ np.random.uniform(low=35, high=60, size=n), # Random latitudes. np.random.uniform(low=-12, high=30, size=n), # Random longitudes. range(n), # Popups. ]).tolist() m = folium.Map([45., 3.], zoom_start=4) mc = plugins.FastMarkerCluster(data, callback=None) m.add_child(mc) m._repr_html_() out = m._parent.render() # We verify that imports assert '<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.1.0/leaflet.markercluster.js"></script>' in out # noqa assert '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.1.0/MarkerCluster.css" />' in out # noqa assert '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.1.0/MarkerCluster.Default.css" />' in out # noqa # Verify the script part is okay. tmpl = Template(""" {% macro script(this, kwargs) %} (function() { var data = {{this._data}}; var map = {{this._parent.get_name()}}; var cluster = L.markerClusterGroup(); {{this._callback}} for (var i = 0; i < data.length; i++) { var row = data[i]; var marker = callback(row, popup='names'); marker.addTo(cluster); } cluster.addTo(map); })(); {% endmacro %} """) assert ''.join(tmpl.render(this=mc).split()) in ''.join(out.split())
[ "jinja2.Template", "folium.plugins.FastMarkerCluster", "folium.Map", "numpy.random.seed", "numpy.random.uniform" ]
[((289, 318), 'numpy.random.seed', 'np.random.seed', ([], {'seed': '(26082009)'}), '(seed=26082009)\n', (303, 318), True, 'import numpy as np\n'), ((578, 615), 'folium.Map', 'folium.Map', (['[45.0, 3.0]'], {'zoom_start': '(4)'}), '([45.0, 3.0], zoom_start=4)\n', (588, 615), False, 'import folium\n'), ((623, 669), 'folium.plugins.FastMarkerCluster', 'plugins.FastMarkerCluster', (['data'], {'callback': 'None'}), '(data, callback=None)\n', (648, 669), False, 'from folium import plugins\n'), ((1264, 1799), 'jinja2.Template', 'Template', (['"""\n {% macro script(this, kwargs) %}\n (function() {\n var data = {{this._data}};\n var map = {{this._parent.get_name()}};\n var cluster = L.markerClusterGroup();\n {{this._callback}}\n\n for (var i = 0; i < data.length; i++) {\n var row = data[i];\n var marker = callback(row, popup=\'names\');\n marker.addTo(cluster);\n }\n\n cluster.addTo(map);\n })();\n {% endmacro %}\n """'], {}), '(\n """\n {% macro script(this, kwargs) %}\n (function() {\n var data = {{this._data}};\n var map = {{this._parent.get_name()}};\n var cluster = L.markerClusterGroup();\n {{this._callback}}\n\n for (var i = 0; i < data.length; i++) {\n var row = data[i];\n var marker = callback(row, popup=\'names\');\n marker.addTo(cluster);\n }\n\n cluster.addTo(map);\n })();\n {% endmacro %}\n """\n )\n', (1272, 1799), False, 'from jinja2 import Template\n'), ((349, 391), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(35)', 'high': '(60)', 'size': 'n'}), '(low=35, high=60, size=n)\n', (366, 391), True, 'import numpy as np\n'), ((423, 466), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-12)', 'high': '(30)', 'size': 'n'}), '(low=-12, high=30, size=n)\n', (440, 466), True, 'import numpy as np\n')]
import numpy as np from utils_cm_toolbox import utils_signal from matplotlib import pyplot as plt PLOT = True def test_generate_gbn(): low = np.array([1.0, -10.0]) upp = np.array([5.0, 2.0]) tspan = np.linspace(0.0, 10, 101) prob_change = np.array([0.95, 0.95]) num_samples_min = [2, 10] args = (tspan, low, upp, prob_change, num_samples_min) out_signal = utils_signal.generate_gbn(*args) if PLOT: plt.figure() plt.plot(tspan, out_signal, '.-k', lw=2, label='signal') plt.legend() plt.show() assert(out_signal[0, 0] == low[0]) assert(out_signal[0, 1] == low[1])
[ "matplotlib.pyplot.plot", "numpy.array", "numpy.linspace", "utils_cm_toolbox.utils_signal.generate_gbn", "matplotlib.pyplot.figure", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((147, 169), 'numpy.array', 'np.array', (['[1.0, -10.0]'], {}), '([1.0, -10.0])\n', (155, 169), True, 'import numpy as np\n'), ((180, 200), 'numpy.array', 'np.array', (['[5.0, 2.0]'], {}), '([5.0, 2.0])\n', (188, 200), True, 'import numpy as np\n'), ((213, 238), 'numpy.linspace', 'np.linspace', (['(0.0)', '(10)', '(101)'], {}), '(0.0, 10, 101)\n', (224, 238), True, 'import numpy as np\n'), ((257, 279), 'numpy.array', 'np.array', (['[0.95, 0.95]'], {}), '([0.95, 0.95])\n', (265, 279), True, 'import numpy as np\n'), ((386, 418), 'utils_cm_toolbox.utils_signal.generate_gbn', 'utils_signal.generate_gbn', (['*args'], {}), '(*args)\n', (411, 418), False, 'from utils_cm_toolbox import utils_signal\n'), ((440, 452), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (450, 452), True, 'from matplotlib import pyplot as plt\n'), ((461, 517), 'matplotlib.pyplot.plot', 'plt.plot', (['tspan', 'out_signal', '""".-k"""'], {'lw': '(2)', 'label': '"""signal"""'}), "(tspan, out_signal, '.-k', lw=2, label='signal')\n", (469, 517), True, 'from matplotlib import pyplot as plt\n'), ((526, 538), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (536, 538), True, 'from matplotlib import pyplot as plt\n'), ((547, 557), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (555, 557), True, 'from matplotlib import pyplot as plt\n')]
from HMM import HMM import unittest import numpy as np class HMMTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_decode_assignment(self): pi = np.array([0.3,0.7]) print(pi) A = np.array([[0.1,0.9],[0.8,0.2]]) B = np.array([[0.7,0.1,0.2],[0.3,0.5,0.2]]) S = ['吃', '睡'] V=["哭", "没精神", "找妈妈"] hmm = HMM(pi, A, B, S, V) observation = np.array(['哭', '没精神', '找妈妈']) res = hmm.decode(observation) print(res) self.assertEqual(res, ['吃', '睡', '吃']) # self.assertAlmostEqual(res, 0.026880000000000005) def test_evalution_assignment(self): pi = np.array([0.3,0.7]) print(pi) A = np.array([[0.1,0.9],[0.8,0.2]]) B = np.array([[0.7,0.1,0.2],[0.3,0.5,0.2]]) S = ['吃', '睡'] V=["哭", "没精神", "找妈妈"] hmm = HMM(pi, A, B, S, V) observation = np.array(['哭', '没精神', '找妈妈']) res = hmm.evaluation(observation) print(res) self.assertAlmostEqual(res, 0.026880000000000005) def test_decode_ppt(self): """ """ pi = np.array([1, 0, 0]) print(pi) A = np.array([[0.4, 0.6, 0], [0, 0.8, 0.2], [0, 0, 1.0]]) B = np.array([[0.7, 0.3], [0.4, 0.6], [0.8, 0.2]]) S = ['1', '2', '3'] V=["A", "B"] hmm = HMM(pi, A, B, S, V) observation = np.array(['A', 'B', 'A', 'B']) res = hmm.decode(observation) print(res) self.assertEqual(res, ['1', '2', '2', '2']) def test_decode_weather(self): """ dataset source: https://www.cnblogs.com/Denise-hzf/p/6612212.html """ pi = np.array([0.63, 0.17, 0.20]) print(pi) A = np.array([[0.5, 0.375, 0.125], [0.25, 0.125, 0.652], [0.25, 0.375, 0.375]]) B = np.array([[0.6, 0.2, 0.15, 0.05], [0.25, 0.25, 0.25, 0.25], [0.05, 0.10, 0.35, 0.5]]) S = ['Sunny', 'Cloudy', 'Rainy'] V=["Dry", "Dryish", "Damp", "Soggy"] hmm = HMM(pi, A, B, S, V) observation = np.array(['Dry', 'Damp', 'Soggy']) res = hmm.decode(observation) print(res) # self.assertAlmostEqual(res, 0.026880000000000005) def test_1(self): pi = np.array([0.2, 0.4, 0.4]) print(pi) A = np.array([[0.5,0.2, 0.3], [0.3, 0.5,0.2], [0.2, 0.3, 0.5]]) B = np.array([[0.5,0.5],[0.4,0.6], [0.7, 0.3]]) S = ['1', '2', '3'] V = ['1', '2'] hmm = HMM(pi, A, B, S, V) observation = np.array(['1', '2', '1']) res = hmm.evaluation(observation) print(res) self.assertAlmostEqual(res, 0.130218) if __name__ == '__main__': unittest.main()
[ "unittest.main", "numpy.array", "HMM.HMM" ]
[((2763, 2778), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2776, 2778), False, 'import unittest\n'), ((210, 230), 'numpy.array', 'np.array', (['[0.3, 0.7]'], {}), '([0.3, 0.7])\n', (218, 230), True, 'import numpy as np\n'), ((256, 290), 'numpy.array', 'np.array', (['[[0.1, 0.9], [0.8, 0.2]]'], {}), '([[0.1, 0.9], [0.8, 0.2]])\n', (264, 290), True, 'import numpy as np\n'), ((298, 342), 'numpy.array', 'np.array', (['[[0.7, 0.1, 0.2], [0.3, 0.5, 0.2]]'], {}), '([[0.7, 0.1, 0.2], [0.3, 0.5, 0.2]])\n', (306, 342), True, 'import numpy as np\n'), ((399, 418), 'HMM.HMM', 'HMM', (['pi', 'A', 'B', 'S', 'V'], {}), '(pi, A, B, S, V)\n', (402, 418), False, 'from HMM import HMM\n'), ((439, 468), 'numpy.array', 'np.array', (["['哭', '没精神', '找妈妈']"], {}), "(['哭', '没精神', '找妈妈'])\n", (447, 468), True, 'import numpy as np\n'), ((678, 698), 'numpy.array', 'np.array', (['[0.3, 0.7]'], {}), '([0.3, 0.7])\n', (686, 698), True, 'import numpy as np\n'), ((724, 758), 'numpy.array', 'np.array', (['[[0.1, 0.9], [0.8, 0.2]]'], {}), '([[0.1, 0.9], [0.8, 0.2]])\n', (732, 758), True, 'import numpy as np\n'), ((766, 810), 'numpy.array', 'np.array', (['[[0.7, 0.1, 0.2], [0.3, 0.5, 0.2]]'], {}), '([[0.7, 0.1, 0.2], [0.3, 0.5, 0.2]])\n', (774, 810), True, 'import numpy as np\n'), ((867, 886), 'HMM.HMM', 'HMM', (['pi', 'A', 'B', 'S', 'V'], {}), '(pi, A, B, S, V)\n', (870, 886), False, 'from HMM import HMM\n'), ((907, 936), 'numpy.array', 'np.array', (["['哭', '没精神', '找妈妈']"], {}), "(['哭', '没精神', '找妈妈'])\n", (915, 936), True, 'import numpy as np\n'), ((1112, 1131), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (1120, 1131), True, 'import numpy as np\n'), ((1158, 1211), 'numpy.array', 'np.array', (['[[0.4, 0.6, 0], [0, 0.8, 0.2], [0, 0, 1.0]]'], {}), '([[0.4, 0.6, 0], [0, 0.8, 0.2], [0, 0, 1.0]])\n', (1166, 1211), True, 'import numpy as np\n'), ((1262, 1308), 'numpy.array', 'np.array', (['[[0.7, 0.3], [0.4, 0.6], [0.8, 0.2]]'], {}), '([[0.7, 0.3], [0.4, 0.6], [0.8, 0.2]])\n', (1270, 1308), True, 'import numpy as np\n'), ((1406, 1425), 'HMM.HMM', 'HMM', (['pi', 'A', 'B', 'S', 'V'], {}), '(pi, A, B, S, V)\n', (1409, 1425), False, 'from HMM import HMM\n'), ((1446, 1476), 'numpy.array', 'np.array', (["['A', 'B', 'A', 'B']"], {}), "(['A', 'B', 'A', 'B'])\n", (1454, 1476), True, 'import numpy as np\n'), ((1719, 1746), 'numpy.array', 'np.array', (['[0.63, 0.17, 0.2]'], {}), '([0.63, 0.17, 0.2])\n', (1727, 1746), True, 'import numpy as np\n'), ((1774, 1849), 'numpy.array', 'np.array', (['[[0.5, 0.375, 0.125], [0.25, 0.125, 0.652], [0.25, 0.375, 0.375]]'], {}), '([[0.5, 0.375, 0.125], [0.25, 0.125, 0.652], [0.25, 0.375, 0.375]])\n', (1782, 1849), True, 'import numpy as np\n'), ((1900, 1989), 'numpy.array', 'np.array', (['[[0.6, 0.2, 0.15, 0.05], [0.25, 0.25, 0.25, 0.25], [0.05, 0.1, 0.35, 0.5]]'], {}), '([[0.6, 0.2, 0.15, 0.05], [0.25, 0.25, 0.25, 0.25], [0.05, 0.1, \n 0.35, 0.5]])\n', (1908, 1989), True, 'import numpy as np\n'), ((2120, 2139), 'HMM.HMM', 'HMM', (['pi', 'A', 'B', 'S', 'V'], {}), '(pi, A, B, S, V)\n', (2123, 2139), False, 'from HMM import HMM\n'), ((2160, 2194), 'numpy.array', 'np.array', (["['Dry', 'Damp', 'Soggy']"], {}), "(['Dry', 'Damp', 'Soggy'])\n", (2168, 2194), True, 'import numpy as np\n'), ((2341, 2366), 'numpy.array', 'np.array', (['[0.2, 0.4, 0.4]'], {}), '([0.2, 0.4, 0.4])\n', (2349, 2366), True, 'import numpy as np\n'), ((2393, 2454), 'numpy.array', 'np.array', (['[[0.5, 0.2, 0.3], [0.3, 0.5, 0.2], [0.2, 0.3, 0.5]]'], {}), '([[0.5, 0.2, 0.3], [0.3, 0.5, 0.2], [0.2, 0.3, 0.5]])\n', (2401, 2454), True, 'import numpy as np\n'), ((2463, 2509), 'numpy.array', 'np.array', (['[[0.5, 0.5], [0.4, 0.6], [0.7, 0.3]]'], {}), '([[0.5, 0.5], [0.4, 0.6], [0.7, 0.3]])\n', (2471, 2509), True, 'import numpy as np\n'), ((2566, 2585), 'HMM.HMM', 'HMM', (['pi', 'A', 'B', 'S', 'V'], {}), '(pi, A, B, S, V)\n', (2569, 2585), False, 'from HMM import HMM\n'), ((2606, 2631), 'numpy.array', 'np.array', (["['1', '2', '1']"], {}), "(['1', '2', '1'])\n", (2614, 2631), True, 'import numpy as np\n')]
import ipywidgets as widgets from IPython.display import clear_output import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from dtreeplt import dtreeplt def view_interactive(feature_names, target_names, X, y, clf, eval, disp_values): feature_buttons = [] for feature in feature_names: feature_buttons.append(widgets.ToggleButton( value=True, description=feature, disabled=False, button_style='', tooltip='Description', icon='', layout=widgets.Layout(flex='1 1 auto', min_width='100px', width='auto') ) ) output = widgets.Output() if eval: X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.1, random_state=0, stratify=y) else: X_train, y_train = X, y def update_tree(change): with output: is_shows = [button.value for button in feature_buttons] show_features = np.array(feature_names)[is_shows] clf.fit(X_train[:, is_shows], y_train) if eval: y_pred = clf.predict(X_valid[:, is_shows]) accuracy = accuracy_score(y_valid, y_pred) dtree = dtreeplt(model=clf, feature_names=show_features, target_names=target_names, X=X_train, y=y_train, disp_values=disp_values) clear_output() fig = dtree.view() if eval: fig.suptitle(f'Accuracy(Hold Out 9:1): {accuracy * 100:.3f}%', x=0, fontsize=20) plt.tight_layout() plt.show() for button in feature_buttons: button.observe(update_tree, names='value', type='change') update_tree(None) box_layout = widgets.Layout(overflow_x='scroll', flex_flow='wrap', display='flex') return widgets.VBox([widgets.Label('Select Features: '), widgets.Box(feature_buttons, layout=box_layout), widgets.Label('Decision Tree: '), output], layout=widgets.Layout(min_height='500px') )
[ "ipywidgets.Box", "sklearn.model_selection.train_test_split", "ipywidgets.Label", "ipywidgets.Output", "IPython.display.clear_output", "numpy.array", "dtreeplt.dtreeplt", "matplotlib.pyplot.tight_layout", "ipywidgets.Layout", "sklearn.metrics.accuracy_score", "matplotlib.pyplot.show" ]
[((735, 751), 'ipywidgets.Output', 'widgets.Output', ([], {}), '()\n', (749, 751), True, 'import ipywidgets as widgets\n'), ((1837, 1906), 'ipywidgets.Layout', 'widgets.Layout', ([], {'overflow_x': '"""scroll"""', 'flex_flow': '"""wrap"""', 'display': '"""flex"""'}), "(overflow_x='scroll', flex_flow='wrap', display='flex')\n", (1851, 1906), True, 'import ipywidgets as widgets\n'), ((811, 876), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.1)', 'random_state': '(0)', 'stratify': 'y'}), '(X, y, test_size=0.1, random_state=0, stratify=y)\n', (827, 876), False, 'from sklearn.model_selection import train_test_split\n'), ((1312, 1438), 'dtreeplt.dtreeplt', 'dtreeplt', ([], {'model': 'clf', 'feature_names': 'show_features', 'target_names': 'target_names', 'X': 'X_train', 'y': 'y_train', 'disp_values': 'disp_values'}), '(model=clf, feature_names=show_features, target_names=target_names,\n X=X_train, y=y_train, disp_values=disp_values)\n', (1320, 1438), False, 'from dtreeplt import dtreeplt\n'), ((1476, 1490), 'IPython.display.clear_output', 'clear_output', ([], {}), '()\n', (1488, 1490), False, 'from IPython.display import clear_output\n'), ((1652, 1670), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1668, 1670), True, 'import matplotlib.pyplot as plt\n'), ((1683, 1693), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1691, 1693), True, 'import matplotlib.pyplot as plt\n'), ((1997, 2031), 'ipywidgets.Label', 'widgets.Label', (['"""Select Features: """'], {}), "('Select Features: ')\n", (2010, 2031), True, 'import ipywidgets as widgets\n'), ((2033, 2080), 'ipywidgets.Box', 'widgets.Box', (['feature_buttons'], {'layout': 'box_layout'}), '(feature_buttons, layout=box_layout)\n', (2044, 2080), True, 'import ipywidgets as widgets\n'), ((2100, 2132), 'ipywidgets.Label', 'widgets.Label', (['"""Decision Tree: """'], {}), "('Decision Tree: ')\n", (2113, 2132), True, 'import ipywidgets as widgets\n'), ((2167, 2201), 'ipywidgets.Layout', 'widgets.Layout', ([], {'min_height': '"""500px"""'}), "(min_height='500px')\n", (2181, 2201), True, 'import ipywidgets as widgets\n'), ((1066, 1089), 'numpy.array', 'np.array', (['feature_names'], {}), '(feature_names)\n', (1074, 1089), True, 'import numpy as np\n'), ((1260, 1291), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_valid', 'y_pred'], {}), '(y_valid, y_pred)\n', (1274, 1291), False, 'from sklearn.metrics import accuracy_score\n'), ((632, 696), 'ipywidgets.Layout', 'widgets.Layout', ([], {'flex': '"""1 1 auto"""', 'min_width': '"""100px"""', 'width': '"""auto"""'}), "(flex='1 1 auto', min_width='100px', width='auto')\n", (646, 696), True, 'import ipywidgets as widgets\n')]
import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np import math #constants a=1 M0=1 levels=2.7*np.linspace(-0.9,0.9,num=18) #Axes N=100 xmin=-3*a xmax=3*a xx=np.linspace(xmin,xmax,N) ymin=-3*a ymax=3*a yy=np.linspace(ymin,ymax,N) X,Y=np.meshgrid(xx,yy) #function for Az def Az(x,y): r=np.sqrt(x**2+y**2) theta=np.arctan2(y,x) phimin=0 phimax=2*math.pi Nphi=200 dphi=(phimax-phimin)/Nphi phi=np.linspace(phimin,phimax,Nphi) res=0 for i in phi: res+=dphi*np.cos(i)*np.log(a/np.sqrt(r**2+a**2-2*r*a*np.cos(theta-i))) return -a*res #functions for B def Bx(x,y): r=np.sqrt(x**2+y**2) theta=np.arctan2(y,x) phimin=0 phimax=2*math.pi Nphi=200 dphi=(phimax-phimin)/Nphi phi=np.linspace(phimin,phimax,Nphi) res=0 for i in phi: res+=dphi*np.cos(i)*(y-a*np.sin(i))/(r**2+a**2-2*r*a*np.cos(theta-i)) return a*M0*res/(2*math.pi) def By(x,y): r=np.sqrt(x**2+y**2) theta=np.arctan2(y,x) phimin=0 phimax=2*math.pi Nphi=200 dphi=(phimax-phimin)/Nphi phi=np.linspace(phimin,phimax,Nphi) res=0 for i in phi: res+=dphi*np.cos(i)*(x-a*np.cos(i))/(r**2+a**2-2*r*a*np.cos(theta-i)) return -a*M0*res/(2*math.pi) #functions for H def Hx(x,y): return Bx(x,y) def Hy(x,y): r=np.sqrt(x**2+y**2) condlist=[r<a,r>a] choicelist=[By(x,y)-M0,By(x,y)] return np.select(condlist,choicelist) #PLOTS #surface plot of Az fig1,ax1=plt.subplots() p1=ax1.pcolormesh(X,Y,Az(X,Y)) ax1.set_aspect('equal','box') ax1.set_title('Normalised Magnetic Potential $A_z$(y,z)/($M_0μ_0$/2π)') cb1=fig1.colorbar(p1) ax1.set_xlabel('x(m)') ax1.set_ylabel('y(m)') #contour lines of Az fig2,ax2=plt.subplots() p2=ax2.contour(X,Y,Az(X,Y),levels) ax2.clabel(p2, inline=True, fontsize=7) c2=plt.Circle((0,0),a,fill=False) ax2.add_artist(c2) ax2.set_aspect('equal','box') ax2.set_title('Normalised Magnetic Potential $A_z$(x,y)/($M_0μ_0$/2π)') ax2.set_xlabel('x(m)') ax2.set_ylabel('y(m)') #streamplot of B fig3,ax3=plt.subplots() p3=ax3.streamplot(X,Y,Bx(X,Y),By(X,Y),density=1.2,color=np.log10(np.sqrt(Bx(X,Y)**2+By(X,Y)**2)),cmap=cm.gist_heat) c3=plt.Circle((0,0),a,fill=False) ax3.add_artist(c3) ax3.set_aspect('equal','box') ax3.set_title('Normalised Magnetic Induction B(x,y)/$μ_0$') ax3.set_xlabel('x(m)') ax3.set_ylabel('y(m)') #streamplot of H fig4,ax4=plt.subplots() p4=ax4.streamplot(X,Y,Hx(X,Y),Hy(X,Y),density=1.2,color=np.log10(np.sqrt(Hx(X,Y)**2+Hy(X,Y)**2)),cmap=cm.gist_heat) c4=plt.Circle((0,0),a,fill=False) ax4.add_artist(c4) ax4.set_aspect('equal','box') ax4.set_title('Magnetic Field H(x,y)') ax4.set_xlabel('x(m)') ax4.set_ylabel('y(m)') plt.show()
[ "matplotlib.pyplot.Circle", "numpy.sqrt", "numpy.select", "numpy.linspace", "numpy.arctan2", "numpy.cos", "numpy.sin", "numpy.meshgrid", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((187, 213), 'numpy.linspace', 'np.linspace', (['xmin', 'xmax', 'N'], {}), '(xmin, xmax, N)\n', (198, 213), True, 'import numpy as np\n'), ((235, 261), 'numpy.linspace', 'np.linspace', (['ymin', 'ymax', 'N'], {}), '(ymin, ymax, N)\n', (246, 261), True, 'import numpy as np\n'), ((265, 284), 'numpy.meshgrid', 'np.meshgrid', (['xx', 'yy'], {}), '(xx, yy)\n', (276, 284), True, 'import numpy as np\n'), ((1493, 1507), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1505, 1507), True, 'import matplotlib.pyplot as plt\n'), ((1740, 1754), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1752, 1754), True, 'import matplotlib.pyplot as plt\n'), ((1833, 1866), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(0, 0)', 'a'], {'fill': '(False)'}), '((0, 0), a, fill=False)\n', (1843, 1866), True, 'import matplotlib.pyplot as plt\n'), ((2058, 2072), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2070, 2072), True, 'import matplotlib.pyplot as plt\n'), ((2192, 2225), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(0, 0)', 'a'], {'fill': '(False)'}), '((0, 0), a, fill=False)\n', (2202, 2225), True, 'import matplotlib.pyplot as plt\n'), ((2405, 2419), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2417, 2419), True, 'import matplotlib.pyplot as plt\n'), ((2539, 2572), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(0, 0)', 'a'], {'fill': '(False)'}), '((0, 0), a, fill=False)\n', (2549, 2572), True, 'import matplotlib.pyplot as plt\n'), ((2705, 2715), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2713, 2715), True, 'import matplotlib.pyplot as plt\n'), ((122, 152), 'numpy.linspace', 'np.linspace', (['(-0.9)', '(0.9)'], {'num': '(18)'}), '(-0.9, 0.9, num=18)\n', (133, 152), True, 'import numpy as np\n'), ((321, 345), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (328, 345), True, 'import numpy as np\n'), ((350, 366), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (360, 366), True, 'import numpy as np\n'), ((451, 484), 'numpy.linspace', 'np.linspace', (['phimin', 'phimax', 'Nphi'], {}), '(phimin, phimax, Nphi)\n', (462, 484), True, 'import numpy as np\n'), ((645, 669), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (652, 669), True, 'import numpy as np\n'), ((674, 690), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (684, 690), True, 'import numpy as np\n'), ((775, 808), 'numpy.linspace', 'np.linspace', (['phimin', 'phimax', 'Nphi'], {}), '(phimin, phimax, Nphi)\n', (786, 808), True, 'import numpy as np\n'), ((965, 989), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (972, 989), True, 'import numpy as np\n'), ((994, 1010), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (1004, 1010), True, 'import numpy as np\n'), ((1095, 1128), 'numpy.linspace', 'np.linspace', (['phimin', 'phimax', 'Nphi'], {}), '(phimin, phimax, Nphi)\n', (1106, 1128), True, 'import numpy as np\n'), ((1336, 1360), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (1343, 1360), True, 'import numpy as np\n'), ((1425, 1456), 'numpy.select', 'np.select', (['condlist', 'choicelist'], {}), '(condlist, choicelist)\n', (1434, 1456), True, 'import numpy as np\n'), ((529, 538), 'numpy.cos', 'np.cos', (['i'], {}), '(i)\n', (535, 538), True, 'import numpy as np\n'), ((853, 862), 'numpy.cos', 'np.cos', (['i'], {}), '(i)\n', (859, 862), True, 'import numpy as np\n'), ((896, 913), 'numpy.cos', 'np.cos', (['(theta - i)'], {}), '(theta - i)\n', (902, 913), True, 'import numpy as np\n'), ((1173, 1182), 'numpy.cos', 'np.cos', (['i'], {}), '(i)\n', (1179, 1182), True, 'import numpy as np\n'), ((1216, 1233), 'numpy.cos', 'np.cos', (['(theta - i)'], {}), '(theta - i)\n', (1222, 1233), True, 'import numpy as np\n'), ((868, 877), 'numpy.sin', 'np.sin', (['i'], {}), '(i)\n', (874, 877), True, 'import numpy as np\n'), ((1188, 1197), 'numpy.cos', 'np.cos', (['i'], {}), '(i)\n', (1194, 1197), True, 'import numpy as np\n'), ((572, 589), 'numpy.cos', 'np.cos', (['(theta - i)'], {}), '(theta - i)\n', (578, 589), True, 'import numpy as np\n')]
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.gridspec as gridspec import glob import cv2 # ## Step 1: Callibration of the Camera # ### Step 1.1: Definition of Helper Routines # # :-) as I'm getting used to Python within this course I'm also trying to use common notation schemes to make the code more readable/understandale - hope this works! # * using the _ for unused return values to avoid having to many unwanted variables. # * using "magic methods", e.g. __init__ to automate the instance creation of a class # [...] # # In[2]: # Definition of Camera Class class Camera(object): # important for this scenario is 9x6 pattern size as stated in the project help def __init__(self, images, pattern_size=(9,6)): self.matrix = None self.dist = None self.calibrated_images = [] self.failed_images = [] self.prepare_calibration(images, pattern_size) def __call__(self, image): if self.matrix is not None and self.dist is not None: return cv2.undistort(image, self.matrix, self.dist, None, self.matrix) else: return image def prepare_calibration(self, images, pattern_size): pattern = np.zeros((pattern_size[1] * pattern_size[0], 3), np.float32) pattern[:, :2] = np.mgrid[0:pattern_size[0], 0:pattern_size[1]].T.reshape(-1, 2) # initialize transform properties for image <--> realworld transformation pattern_points = [] # points (real world image) image_points = [] # points (image plane) image_size = None # Process all images found; looking for chessboard corners for i, path, in enumerate(images): # read the RGB image print("Module prepare_calibration --> processing file" + path + "\n") image = mpimg.imread(path) # convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # find the chessboard corners ret, corners = cv2.findChessboardCorners(gray, pattern_size, None) # when corners found add object and image points if ret: pattern_points.append(pattern) image_points.append(corners) image_size = (image.shape[1], image.shape[0]) # draw corners cv2.drawChessboardCorners(image, pattern_size, corners, True) self.calibrated_images.append(image) else: self.failed_images.append(image) # if points found --> calibrate the camera if pattern_points and image_points: _, self.matrix, self.dist, _, _ = cv2.calibrateCamera( pattern_points, image_points,image_size, None, None ) # ### Step 1.2: Run the Calibration Process # Now the calibration is just a simple call of the Camera Class calibrated_camera = Camera(glob.glob('camera_cal/calibration*.jpg')) plt.figure(figsize=(12, 10)) gridspec.GridSpec(5, 4) # first show all Images with detected corners print('Images with detected corners:') # Loop through the images and look for the chessboard corners for i, image, in enumerate(calibrated_camera.calibrated_images): plt.subplot2grid((5, 4), (i//4, i%4), colspan=1, rowspan=1) plt.imshow(image) plt.axis('off') plt.show() # second show all Images with detected corners print('Images where unable to detect corners:') for i, image in enumerate(calibrated_camera.failed_images): f, (x1, x2) = plt.subplots(1, 2, figsize=(25, 10)) x1.axis('off') x1.imshow(image) x1.set_title('Original', fontsize=20) x2.axis('off') x2.imshow(calibrated_camera(image)) x2.set_title('Calibrated', fontsize=20) # ## Step 2: Finding Edges # ### Step 2.1: Define Helper Functions # In[4]: def stack_edges(image): c_mask, g_mask, _ = find_edges(image) mask = np.zeros_like(g_mask) mask[(g_mask == 1) | (c_mask == 1)] = 1 return mask def single_edges(image): c_mask, g_mask, s = find_edges(image) return np.dstack((np.zeros_like(s), g_mask, c_mask)) def find_edges(image): # Convert image to HLS space hls = cv2.cvtColor(np.copy(image), cv2.COLOR_RGB2HLS).astype(np.float) # Separate and get the S channel as best option s = hls[:, :, 2] # Get all gradients grad_x = gradient_absolute_value_mask(s, axis='x', thresh=(20, 100)) grad_y = gradient_absolute_value_mask(s, axis='y', thresh=(20, 100)) magnit = gradient_magnitude_mask(s, thresh=(20, 100)) direct = gradient_direction_mask(s, thresh=(0.7, 1.3)) g_mask = np.zeros_like(s) g_mask[((grad_x == 1) & (grad_y == 1)) | ((magnit == 1) & (direct == 1))] = 1 c_mask = mask_between_thresholds(s, thresh=(170, 255)) return c_mask, g_mask, s def gradient_absolute_value_mask(image, axis='x', sobel_ksize=3, thresh=(0, 255)): # Get the absolute value from the derivative if axis == 'x': sobel = np.absolute(cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=sobel_ksize)) elif axis == 'y': sobel = np.absolute(cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=sobel_ksize)) else: raise 'Invalid value for axis: {}'.format(axis) mask = apply_mask(sobel, thresh) return mask def gradient_magnitude_mask(image, sobel_ksize=3, thresh=(0, 255)): x, y = calculate_gradients(image, sobel_ksize) # Calculate the magnitude magnitude = np.sqrt(x**2 + y**2) mask = apply_mask(magnitude, thresh) return mask def gradient_direction_mask(image, sobel_ksize=3, thresh=(0, 255)): x, y = calculate_gradients(image, sobel_ksize) direct = np.arctan2(np.absolute(y), np.absolute(x)) mask = mask_between_thresholds(direct, thresh=thresh) return mask def apply_mask(image, thresh): # Scale to 8 bit img = np.uint8(255*image / np.max(image)) mask = mask_between_thresholds(img, thresh=thresh) return mask def mask_between_thresholds(img, thresh=(0, 255)): # Mask with 1's where the gradient magnitude is between thresholds mask = np.zeros_like(img) mask[(img >= thresh[0]) & (img <= thresh[1])] = 1 # Return the mask as the binary image return mask def calculate_gradients(image, sobel_ksize): x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=sobel_ksize) y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=sobel_ksize) return x, y # ### Step 2.1: Loop over the Test Images # In[5]: for image in glob.glob('test_images/test*.jpg'): image = mpimg.imread(image) edges = single_edges(image) stack = stack_edges(image) f, (x1, x2, x3) = plt.subplots(1, 3, figsize=(24, 9)) x1.axis('off') x1.imshow(image) x1.set_title('Original', fontsize=20) x2.axis('off') x2.imshow(edges) x2.set_title('Edges', fontsize=20) x3.axis('off') x3.imshow(stack) x3.set_title('Stacked', fontsize=20) # ## Step 3: Perspective Transformation # ### Step 3.1: Define the perspective transformation function "perspective_transf()" # In[6]: def perspective_transf(image): height = image.shape[0] width = image.shape[1] # Calculate the 4 coordinates in the source image (s1-s4) s1 = [width // 2 - 76, height * 0.625] s2 = [width // 2 + 76, height * 0.625] s3 = [-100, height] s4 = [width + 100, height] src = np.float32([s1, s2, s3, s4]) # Calculate the 4 coordinates in the destination image (d1-d4) d1 = [100, 0] d2 = [width - 100, 0] d3 = [100, height] d4 = [width - 100, height] dst = np.float32([d1, d2, d3, d4]) # Use src and dst points to calculate the perspective transform matrix M M = cv2.getPerspectiveTransform(src, dst) # Warp the image using the transform matrix M warped = cv2.warpPerspective(image, M, (width, height)) # We also calculate the oposite transform Matrix unwarp_m unwarp_m = cv2.getPerspectiveTransform(dst, src) # Return the resulting image and unwarp matrix return (warped, unwarp_m) # future extension and debugging def show_warped(img): return true # ### Step 3.2: Execute the Perspective Transformation # In[7]: for image in glob.glob('test_images/test*.jpg'): image = mpimg.imread(image) transformed, _ = perspective_transf(image) _, (x1, x2) = plt.subplots(1, 2, figsize=(24, 9)) x1.axis('off') x1.imshow(image) x1.set_title('Original', fontsize=20) x2.axis('off') x2.imshow(transformed) x2.set_title('Transformed', fontsize=20) # ## Step 4: Detection fo Lane Pixels # ### Step 4.1: Sliding Window and Polynomial Fit # In[8]: from collections import namedtuple class SlidingWindow(object): """Represents a window where we want to find 'hot' Pixels associated with Lane Lines""" def __init__(self, y_low, y_high, x_center, margin=100, minpix=50): self.x = x_center self.x_mean = x_center self.y_high = y_high self.y_low = y_low self.margin = margin self.minpix = minpix def nonzero_pixels_indices(self, nonzero, win_x=None): if win_x is not None: self.x = win_x win_inds = ((nonzero[0] >= self.y_high) & (nonzero[0] < self.y_low) & (nonzero[1] >= self.x - self.margin) & (nonzero[1] < self.x + self.margin)).nonzero()[0] # Find the x mean value if len(win_inds) > self.minpix: self.x_mean = np.int(np.mean(nonzero[1][win_inds])) else: self.x_mean = self.x return win_inds def vertices(self): x1 = self.x - self.margin y1 = self.y_high x2 = self.x + self.margin y2 = self.y_low return ((x1, y1), (x2, y2)) # ### Step 4.2: Identifying the Lane Lines # In[9]: # Helper functions from collections import deque class LaneLine(object): """Single lane line""" def __init__(self, x, y, heigth, width): self.heigth = heigth self.width = width self.coef = deque(maxlen=5) self.fit_points(x, y) self._meter_per_x_axis = 700 self._meter_per_y_axis = 720 # based on US regulations of a min of 12 feet or 3.7 meters for a lane width self._land_width = 3.7 # meters self._image_lane_length = 30 # Assuming the lane is 30 meters long in the image def fit_points(self, x, y): points = len(y) > 0 and (np.max(y) - np.min(y)) > self.heigth * 0.625 no_coef = len(self.coef) == 0 if points or no_coef: self.coef.append(np.polyfit(y, x, 2)) def generate_points(self): y = np.linspace(0, self.heigth - 1, self.heigth) fit = np.array(self.coef).mean(axis=0) return np.stack((fit[0] * y ** 2 + fit[1] * y + fit[2], y)).astype(np.int).T def radius_of_curvature(self): # Define conversions in x and y from pixels space to meters ym_per_pix = self._image_lane_length / self._meter_per_y_axis xm_per_pix = self._land_width / self._meter_per_x_axis points = self.generate_points() x = points[:, 0] y = points[:, 1] fit_cr = np.polyfit(y * ym_per_pix, x * xm_per_pix, 2) first_deriv = 2 * fit_cr[0] * self._meter_per_y_axis * ym_per_pix + fit_cr[1] secnd_deriv = 2 * fit_cr[0] radius = int(((1 + (first_deriv ** 2) ** 1.5) / np.absolute(secnd_deriv))) return radius def camera_distance(self): xm_per_pix = self._land_width / self._meter_per_x_axis points = self.generate_points() x = points[np.max(points[:, 1])][0] distance = np.absolute((self.width // 2 - x) * xm_per_pix) return distance # ### Step 5: The Processing Pipeline # In[10]: # Pipline implements the identification pipeline to process sets of images or frames of a video Stream # class Pipeline(object): def __init__(self, first_frame, nwindows=9): self.height = first_frame.shape[0] self.width = first_frame.shape[1] self.nwindows = nwindows self.left_lane = None self.right_lane = None self.left_wins = [] self.right_wins = [] self._init_lines(first_frame) def _init_lines(self, frame): edges = stack_edges(frame) transformed_egdes, _ = perspective_transf(edges) histogram = np.sum(transformed_egdes[int(self.height / 2):, :], axis=0) nonzero = transformed_egdes.nonzero() # Create empty lists to receive left and right lane pixel indices left_lane_inds = np.empty([0], dtype=np.int) right_lane_inds = np.empty([0], dtype=np.int) # Set height of windows window_height = int(self.height / self.nwindows) for i in range(self.nwindows): # initialize each Window object if len(self.left_wins) > 0: l_x_center = self.left_wins[-1].x r_x_center = self.right_wins[-1].x else: l_x_center = np.argmax(histogram[:self.width // 2]) r_x_center = np.argmax(histogram[self.width // 2:]) + self.width // 2 left_win = SlidingWindow(y_low=self.height - i * window_height, y_high=self.height - (i + 1) * window_height, x_center=l_x_center) right_win = SlidingWindow(y_low=self.height - i * window_height, y_high=self.height - (i + 1) * window_height, x_center=r_x_center) # Add the nonzero indices left_lane_inds = np.append(left_lane_inds, left_win.nonzero_pixels_indices(nonzero), axis=0) right_lane_inds = np.append(right_lane_inds, right_win.nonzero_pixels_indices(nonzero), axis=0) self.left_wins.append(left_win) self.right_wins.append(right_win) self.left_lane = LaneLine(nonzero[1][left_lane_inds], nonzero[0][left_lane_inds], self.height, self.width) self.right_lane = LaneLine(nonzero[1][right_lane_inds], nonzero[0][right_lane_inds], self.height, self.width) def _find_points_in_windows(self, frame, windows): indices = np.empty([0], dtype=np.int) nonzero = frame.nonzero() win_x = None for win in windows: indices = np.append(indices, win.nonzero_pixels_indices(nonzero, win_x), axis=0) win_x = win.x_mean return (nonzero[1][indices], nonzero[0][indices]) def _lane_overlay(self, image, unwrap_m=None): overlay = np.zeros_like(image).astype(np.uint8) points = np.vstack((self.left_lane.generate_points(), np.flipud(self.right_lane.generate_points()))) cv2.fillPoly(overlay, [points], (0, 255, 0)) if unwrap_m is not None: overlay = cv2.warpPerspective(overlay, unwrap_m, (image.shape[1], image.shape[0])) alpha = 0.6 return cv2.addWeighted(image, alpha, overlay, 1 - alpha, 0) def _info_overlay(self, frame): if len(frame.shape) == 2: image = np.dstack((frame, frame, frame)) else: image = frame for win in self.left_wins: vertices = win.vertices() cv2.rectangle(image, vertices[0], vertices[1], (1.0, 1.0, 0), 2) for win in self.right_wins: vertices = win.vertices() cv2.rectangle(image, vertices[0], vertices[1], (1.0, 1.0, 0), 2) cv2.polylines(image, [self.left_lane.generate_points()], False, (1.0, 1.0, 0), 2) cv2.polylines(image, [self.right_lane.generate_points()], False, (1.0, 1.0, 0), 2) return image * 255 def _radius_of_curvature(self): radius = int(np.average([self.left_lane.radius_of_curvature(), self.right_lane.radius_of_curvature()])) return radius def _draw_text(self, frame, text, x, y): cv2.putText(frame, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) def run(self, frame): edges = stack_edges(frame) transformed_egdes, unwrap_m = perspective_transf(edges) # Process Left Lane (left_x, left_y) = self._find_points_in_windows(transformed_egdes, self.left_wins) self.left_lane.fit_points(left_x, left_y) # Process Right Lane (right_x, right_y) = self._find_points_in_windows(transformed_egdes, self.right_wins) self.right_lane.fit_points(right_x, right_y) edges = single_edges(frame) info_overlay = self._info_overlay(perspective_transf(edges)[0]) top_overlay = self._lane_overlay(perspective_transf(frame)[0]) info_overlay = cv2.resize(info_overlay, (0,0), fx=0.3, fy=0.3) top_overlay = cv2.resize(top_overlay, (0,0), fx=0.3, fy=0.3) frame[:250, :, :] = frame[:250, :, :] * 0.4 (height, width, _) = info_overlay.shape frame[25:25 + height, 25:25 + width, :] = info_overlay frame[25:25 + height, 25 + 25 + width:25 + 25 + width + width, :] = top_overlay text_x = 25 + 25 + width + width + 25 lane_width = self.left_lane.camera_distance() + self.right_lane.camera_distance() off_center = self.right_lane.camera_distance() - lane_width / 2 self._draw_text(frame, 'Curvature Radius: {} m'.format(self._radius_of_curvature()), text_x, 80) self._draw_text(frame, 'Distance from center: {:.1f} m'.format(off_center), text_x, 140) frame = self._lane_overlay(frame, unwrap_m) return frame # ### Step 5.1 Feed the Pipeline with the Test Images # In[11]: for image_path in glob.glob('test_images/test*.jpg'): image = mpimg.imread(image_path) calibrated = calibrated_camera(image) pipeline = Pipeline(calibrated) overlay = pipeline.run(calibrated) mpimg.imsave(image_path.replace('test_images', 'output_images'), overlay) plt.figure(figsize=(12, 12)) plt.imshow(overlay) plt.subplots_adjust(left=0.0, right=1, top=0.9, bottom=0.0) plt.show() # ### Step 5.3: Feed the Pipeline with the Video Streams # In[12]: from moviepy.editor import VideoFileClip def process_video(video_inp): #.format(video_path_prefix) output_video_name = "Video_Out/"+ video_inp + "_proc.mp4" input_video = VideoFileClip(video_inp+".mp4") print("Processing Video [" + input_video + "] and will write to [" + output_video_name + "]") calibrated = calibrated_camera(input_video.get_frame(0)) pipeline = Pipeline(calibrated) output_video = input_video.fl_image(pipeline.run) get_ipython().run_line_magic('time', 'output_video.write_videofile(output_video_name, audio=False)') # In[13]: process_video('project_video') process_video('challenge_video') process_video('harder_challenge_video') # In[ ]:
[ "cv2.rectangle", "numpy.sqrt", "numpy.polyfit", "matplotlib.image.imread", "numpy.array", "cv2.warpPerspective", "cv2.findChessboardCorners", "cv2.calibrateCamera", "matplotlib.pyplot.subplot2grid", "matplotlib.pyplot.imshow", "numpy.mean", "collections.deque", "numpy.zeros_like", "cv2.und...
[((3017, 3045), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 10)'}), '(figsize=(12, 10))\n', (3027, 3045), True, 'import matplotlib.pyplot as plt\n'), ((3046, 3069), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(5)', '(4)'], {}), '(5, 4)\n', (3063, 3069), True, 'import matplotlib.gridspec as gridspec\n'), ((3389, 3399), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3397, 3399), True, 'import matplotlib.pyplot as plt\n'), ((6526, 6560), 'glob.glob', 'glob.glob', (['"""test_images/test*.jpg"""'], {}), "('test_images/test*.jpg')\n", (6535, 6560), False, 'import glob\n'), ((8246, 8280), 'glob.glob', 'glob.glob', (['"""test_images/test*.jpg"""'], {}), "('test_images/test*.jpg')\n", (8255, 8280), False, 'import glob\n'), ((18196, 18230), 'glob.glob', 'glob.glob', (['"""test_images/test*.jpg"""'], {}), "('test_images/test*.jpg')\n", (18205, 18230), False, 'import glob\n'), ((2974, 3014), 'glob.glob', 'glob.glob', (['"""camera_cal/calibration*.jpg"""'], {}), "('camera_cal/calibration*.jpg')\n", (2983, 3014), False, 'import glob\n'), ((3287, 3350), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(5, 4)', '(i // 4, i % 4)'], {'colspan': '(1)', 'rowspan': '(1)'}), '((5, 4), (i // 4, i % 4), colspan=1, rowspan=1)\n', (3303, 3350), True, 'import matplotlib.pyplot as plt\n'), ((3351, 3368), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (3361, 3368), True, 'import matplotlib.pyplot as plt\n'), ((3373, 3388), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3381, 3388), True, 'import matplotlib.pyplot as plt\n'), ((3574, 3610), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(25, 10)'}), '(1, 2, figsize=(25, 10))\n', (3586, 3610), True, 'import matplotlib.pyplot as plt\n'), ((3960, 3981), 'numpy.zeros_like', 'np.zeros_like', (['g_mask'], {}), '(g_mask)\n', (3973, 3981), True, 'import numpy as np\n'), ((4679, 4695), 'numpy.zeros_like', 'np.zeros_like', (['s'], {}), '(s)\n', (4692, 4695), True, 'import numpy as np\n'), ((5501, 5525), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (5508, 5525), True, 'import numpy as np\n'), ((6140, 6158), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (6153, 6158), True, 'import numpy as np\n'), ((6325, 6378), 'cv2.Sobel', 'cv2.Sobel', (['image', 'cv2.CV_64F', '(1)', '(0)'], {'ksize': 'sobel_ksize'}), '(image, cv2.CV_64F, 1, 0, ksize=sobel_ksize)\n', (6334, 6378), False, 'import cv2\n'), ((6387, 6440), 'cv2.Sobel', 'cv2.Sobel', (['image', 'cv2.CV_64F', '(0)', '(1)'], {'ksize': 'sobel_ksize'}), '(image, cv2.CV_64F, 0, 1, ksize=sobel_ksize)\n', (6396, 6440), False, 'import cv2\n'), ((6574, 6593), 'matplotlib.image.imread', 'mpimg.imread', (['image'], {}), '(image)\n', (6586, 6593), True, 'import matplotlib.image as mpimg\n'), ((6680, 6715), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(24, 9)'}), '(1, 3, figsize=(24, 9))\n', (6692, 6715), True, 'import matplotlib.pyplot as plt\n'), ((7404, 7432), 'numpy.float32', 'np.float32', (['[s1, s2, s3, s4]'], {}), '([s1, s2, s3, s4])\n', (7414, 7432), True, 'import numpy as np\n'), ((7613, 7641), 'numpy.float32', 'np.float32', (['[d1, d2, d3, d4]'], {}), '([d1, d2, d3, d4])\n', (7623, 7641), True, 'import numpy as np\n'), ((7732, 7769), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['src', 'dst'], {}), '(src, dst)\n', (7759, 7769), False, 'import cv2\n'), ((7838, 7884), 'cv2.warpPerspective', 'cv2.warpPerspective', (['image', 'M', '(width, height)'], {}), '(image, M, (width, height))\n', (7857, 7884), False, 'import cv2\n'), ((7967, 8004), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['dst', 'src'], {}), '(dst, src)\n', (7994, 8004), False, 'import cv2\n'), ((8294, 8313), 'matplotlib.image.imread', 'mpimg.imread', (['image'], {}), '(image)\n', (8306, 8313), True, 'import matplotlib.image as mpimg\n'), ((8385, 8420), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(24, 9)'}), '(1, 2, figsize=(24, 9))\n', (8397, 8420), True, 'import matplotlib.pyplot as plt\n'), ((18244, 18268), 'matplotlib.image.imread', 'mpimg.imread', (['image_path'], {}), '(image_path)\n', (18256, 18268), True, 'import matplotlib.image as mpimg\n'), ((18474, 18502), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (18484, 18502), True, 'import matplotlib.pyplot as plt\n'), ((18507, 18526), 'matplotlib.pyplot.imshow', 'plt.imshow', (['overlay'], {}), '(overlay)\n', (18517, 18526), True, 'import matplotlib.pyplot as plt\n'), ((18531, 18590), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.0)', 'right': '(1)', 'top': '(0.9)', 'bottom': '(0.0)'}), '(left=0.0, right=1, top=0.9, bottom=0.0)\n', (18550, 18590), True, 'import matplotlib.pyplot as plt\n'), ((18595, 18605), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (18603, 18605), True, 'import matplotlib.pyplot as plt\n'), ((18862, 18895), 'moviepy.editor.VideoFileClip', 'VideoFileClip', (["(video_inp + '.mp4')"], {}), "(video_inp + '.mp4')\n", (18875, 18895), False, 'from moviepy.editor import VideoFileClip\n'), ((1279, 1339), 'numpy.zeros', 'np.zeros', (['(pattern_size[1] * pattern_size[0], 3)', 'np.float32'], {}), '((pattern_size[1] * pattern_size[0], 3), np.float32)\n', (1287, 1339), True, 'import numpy as np\n'), ((5727, 5741), 'numpy.absolute', 'np.absolute', (['y'], {}), '(y)\n', (5738, 5741), True, 'import numpy as np\n'), ((5743, 5757), 'numpy.absolute', 'np.absolute', (['x'], {}), '(x)\n', (5754, 5757), True, 'import numpy as np\n'), ((10145, 10160), 'collections.deque', 'deque', ([], {'maxlen': '(5)'}), '(maxlen=5)\n', (10150, 10160), False, 'from collections import deque\n'), ((10778, 10822), 'numpy.linspace', 'np.linspace', (['(0)', '(self.heigth - 1)', 'self.heigth'], {}), '(0, self.heigth - 1, self.heigth)\n', (10789, 10822), True, 'import numpy as np\n'), ((11322, 11367), 'numpy.polyfit', 'np.polyfit', (['(y * ym_per_pix)', '(x * xm_per_pix)', '(2)'], {}), '(y * ym_per_pix, x * xm_per_pix, 2)\n', (11332, 11367), True, 'import numpy as np\n'), ((11806, 11853), 'numpy.absolute', 'np.absolute', (['((self.width // 2 - x) * xm_per_pix)'], {}), '((self.width // 2 - x) * xm_per_pix)\n', (11817, 11853), True, 'import numpy as np\n'), ((12767, 12794), 'numpy.empty', 'np.empty', (['[0]'], {'dtype': 'np.int'}), '([0], dtype=np.int)\n', (12775, 12794), True, 'import numpy as np\n'), ((12821, 12848), 'numpy.empty', 'np.empty', (['[0]'], {'dtype': 'np.int'}), '([0], dtype=np.int)\n', (12829, 12848), True, 'import numpy as np\n'), ((14571, 14598), 'numpy.empty', 'np.empty', (['[0]'], {'dtype': 'np.int'}), '([0], dtype=np.int)\n', (14579, 14598), True, 'import numpy as np\n'), ((15144, 15188), 'cv2.fillPoly', 'cv2.fillPoly', (['overlay', '[points]', '(0, 255, 0)'], {}), '(overlay, [points], (0, 255, 0))\n', (15156, 15188), False, 'import cv2\n'), ((15374, 15426), 'cv2.addWeighted', 'cv2.addWeighted', (['image', 'alpha', 'overlay', '(1 - alpha)', '(0)'], {}), '(image, alpha, overlay, 1 - alpha, 0)\n', (15389, 15426), False, 'import cv2\n'), ((16427, 16515), 'cv2.putText', 'cv2.putText', (['frame', 'text', '(x, y)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.8)', '(255, 255, 255)', '(2)'], {}), '(frame, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, \n 255), 2)\n', (16438, 16515), False, 'import cv2\n'), ((17217, 17265), 'cv2.resize', 'cv2.resize', (['info_overlay', '(0, 0)'], {'fx': '(0.3)', 'fy': '(0.3)'}), '(info_overlay, (0, 0), fx=0.3, fy=0.3)\n', (17227, 17265), False, 'import cv2\n'), ((17288, 17335), 'cv2.resize', 'cv2.resize', (['top_overlay', '(0, 0)'], {'fx': '(0.3)', 'fy': '(0.3)'}), '(top_overlay, (0, 0), fx=0.3, fy=0.3)\n', (17298, 17335), False, 'import cv2\n'), ((1100, 1163), 'cv2.undistort', 'cv2.undistort', (['image', 'self.matrix', 'self.dist', 'None', 'self.matrix'], {}), '(image, self.matrix, self.dist, None, self.matrix)\n', (1113, 1163), False, 'import cv2\n'), ((1890, 1908), 'matplotlib.image.imread', 'mpimg.imread', (['path'], {}), '(path)\n', (1902, 1908), True, 'import matplotlib.image as mpimg\n'), ((1963, 2002), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2GRAY'], {}), '(image, cv2.COLOR_RGB2GRAY)\n', (1975, 2002), False, 'import cv2\n'), ((2072, 2123), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['gray', 'pattern_size', 'None'], {}), '(gray, pattern_size, None)\n', (2097, 2123), False, 'import cv2\n'), ((2733, 2806), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['pattern_points', 'image_points', 'image_size', 'None', 'None'], {}), '(pattern_points, image_points, image_size, None, None)\n', (2752, 2806), False, 'import cv2\n'), ((4137, 4153), 'numpy.zeros_like', 'np.zeros_like', (['s'], {}), '(s)\n', (4150, 4153), True, 'import numpy as np\n'), ((5053, 5106), 'cv2.Sobel', 'cv2.Sobel', (['image', 'cv2.CV_64F', '(1)', '(0)'], {'ksize': 'sobel_ksize'}), '(image, cv2.CV_64F, 1, 0, ksize=sobel_ksize)\n', (5062, 5106), False, 'import cv2\n'), ((5920, 5933), 'numpy.max', 'np.max', (['image'], {}), '(image)\n', (5926, 5933), True, 'import numpy as np\n'), ((15253, 15325), 'cv2.warpPerspective', 'cv2.warpPerspective', (['overlay', 'unwrap_m', '(image.shape[1], image.shape[0])'], {}), '(overlay, unwrap_m, (image.shape[1], image.shape[0]))\n', (15272, 15325), False, 'import cv2\n'), ((15530, 15562), 'numpy.dstack', 'np.dstack', (['(frame, frame, frame)'], {}), '((frame, frame, frame))\n', (15539, 15562), True, 'import numpy as np\n'), ((15701, 15765), 'cv2.rectangle', 'cv2.rectangle', (['image', 'vertices[0]', 'vertices[1]', '(1.0, 1.0, 0)', '(2)'], {}), '(image, vertices[0], vertices[1], (1.0, 1.0, 0), 2)\n', (15714, 15765), False, 'import cv2\n'), ((15865, 15929), 'cv2.rectangle', 'cv2.rectangle', (['image', 'vertices[0]', 'vertices[1]', '(1.0, 1.0, 0)', '(2)'], {}), '(image, vertices[0], vertices[1], (1.0, 1.0, 0), 2)\n', (15878, 15929), False, 'import cv2\n'), ((2409, 2470), 'cv2.drawChessboardCorners', 'cv2.drawChessboardCorners', (['image', 'pattern_size', 'corners', '(True)'], {}), '(image, pattern_size, corners, True)\n', (2434, 2470), False, 'import cv2\n'), ((4252, 4266), 'numpy.copy', 'np.copy', (['image'], {}), '(image)\n', (4259, 4266), True, 'import numpy as np\n'), ((5158, 5211), 'cv2.Sobel', 'cv2.Sobel', (['image', 'cv2.CV_64F', '(0)', '(1)'], {'ksize': 'sobel_ksize'}), '(image, cv2.CV_64F, 0, 1, ksize=sobel_ksize)\n', (5167, 5211), False, 'import cv2\n'), ((9574, 9603), 'numpy.mean', 'np.mean', (['nonzero[1][win_inds]'], {}), '(nonzero[1][win_inds])\n', (9581, 9603), True, 'import numpy as np\n'), ((10705, 10724), 'numpy.polyfit', 'np.polyfit', (['y', 'x', '(2)'], {}), '(y, x, 2)\n', (10715, 10724), True, 'import numpy as np\n'), ((10837, 10856), 'numpy.array', 'np.array', (['self.coef'], {}), '(self.coef)\n', (10845, 10856), True, 'import numpy as np\n'), ((11546, 11570), 'numpy.absolute', 'np.absolute', (['secnd_deriv'], {}), '(secnd_deriv)\n', (11557, 11570), True, 'import numpy as np\n'), ((11762, 11782), 'numpy.max', 'np.max', (['points[:, 1]'], {}), '(points[:, 1])\n', (11768, 11782), True, 'import numpy as np\n'), ((13219, 13257), 'numpy.argmax', 'np.argmax', (['histogram[:self.width // 2]'], {}), '(histogram[:self.width // 2])\n', (13228, 13257), True, 'import numpy as np\n'), ((14960, 14980), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (14973, 14980), True, 'import numpy as np\n'), ((10553, 10562), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (10559, 10562), True, 'import numpy as np\n'), ((10565, 10574), 'numpy.min', 'np.min', (['y'], {}), '(y)\n', (10571, 10574), True, 'import numpy as np\n'), ((10894, 10946), 'numpy.stack', 'np.stack', (['(fit[0] * y ** 2 + fit[1] * y + fit[2], y)'], {}), '((fit[0] * y ** 2 + fit[1] * y + fit[2], y))\n', (10902, 10946), True, 'import numpy as np\n'), ((13287, 13325), 'numpy.argmax', 'np.argmax', (['histogram[self.width // 2:]'], {}), '(histogram[self.width // 2:])\n', (13296, 13325), True, 'import numpy as np\n')]
''' point processing based image enhancement using: 1. Log and Inverse log transformations 2. Gamma corrections(Power law transformation) with +ve and -ve values ''' import cv2 import numpy as np ############## log transform ############ img = cv2.imread('transformation.png', -1) prop = img.shape c = 20 for i in range(0, prop[0]): for j in range(0, prop[1]): img[i][j] = c* np.log(img[i][j] + 1) cv2.imshow('log_img',img) cv2.waitKey(0) cv2.imwrite('log_img.png', img) ############### Inverse Log ################ img = cv2.imread('transformation.png', -1) prop = img.shape for i in range(0, prop[0]): for j in range(0, prop[1]): img[i][j] = np.exp( img[i][j] ) * ( np.log(255)/ (255 - 1) - 1) cv2.imshow('invlog_img',img) cv2.waitKey(0) cv2.imwrite('invlog_img.png', img) ############ Power law ############ img = cv2.imread('transformation.png', -1) prop = img.shape c = 20 gamma = 8 for i in range(0, prop[0]): for j in range(0, prop[1]): img[i][j] = c * img[i][j]** gamma cv2.imshow('powlaw_img', img) cv2.waitKey(0) cv2.imwrite('powlaw_img.png', img)
[ "cv2.imwrite", "numpy.log", "cv2.imshow", "numpy.exp", "cv2.waitKey", "cv2.imread" ]
[((247, 283), 'cv2.imread', 'cv2.imread', (['"""transformation.png"""', '(-1)'], {}), "('transformation.png', -1)\n", (257, 283), False, 'import cv2\n'), ((415, 441), 'cv2.imshow', 'cv2.imshow', (['"""log_img"""', 'img'], {}), "('log_img', img)\n", (425, 441), False, 'import cv2\n'), ((441, 455), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (452, 455), False, 'import cv2\n'), ((456, 487), 'cv2.imwrite', 'cv2.imwrite', (['"""log_img.png"""', 'img'], {}), "('log_img.png', img)\n", (467, 487), False, 'import cv2\n'), ((542, 578), 'cv2.imread', 'cv2.imread', (['"""transformation.png"""', '(-1)'], {}), "('transformation.png', -1)\n", (552, 578), False, 'import cv2\n'), ((731, 760), 'cv2.imshow', 'cv2.imshow', (['"""invlog_img"""', 'img'], {}), "('invlog_img', img)\n", (741, 760), False, 'import cv2\n'), ((760, 774), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (771, 774), False, 'import cv2\n'), ((775, 809), 'cv2.imwrite', 'cv2.imwrite', (['"""invlog_img.png"""', 'img'], {}), "('invlog_img.png', img)\n", (786, 809), False, 'import cv2\n'), ((853, 889), 'cv2.imread', 'cv2.imread', (['"""transformation.png"""', '(-1)'], {}), "('transformation.png', -1)\n", (863, 889), False, 'import cv2\n'), ((1029, 1058), 'cv2.imshow', 'cv2.imshow', (['"""powlaw_img"""', 'img'], {}), "('powlaw_img', img)\n", (1039, 1058), False, 'import cv2\n'), ((1059, 1073), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1070, 1073), False, 'import cv2\n'), ((1074, 1108), 'cv2.imwrite', 'cv2.imwrite', (['"""powlaw_img.png"""', 'img'], {}), "('powlaw_img.png', img)\n", (1085, 1108), False, 'import cv2\n'), ((392, 413), 'numpy.log', 'np.log', (['(img[i][j] + 1)'], {}), '(img[i][j] + 1)\n', (398, 413), True, 'import numpy as np\n'), ((677, 694), 'numpy.exp', 'np.exp', (['img[i][j]'], {}), '(img[i][j])\n', (683, 694), True, 'import numpy as np\n'), ((701, 712), 'numpy.log', 'np.log', (['(255)'], {}), '(255)\n', (707, 712), True, 'import numpy as np\n')]
import numgp import numpy as np import numpy.testing as npt import numpyro as npy import pytest # # Implements the test from the original pymc3 test suite # TestExpSquad # TestWhiteNoise # TestConstant # TestCovAdd # TestCovProd # TestCovSliceDim # def test_cov_add_symadd_cov(test_array): cov1 = numgp.cov.ExpQuad(1, 0.1) cov2 = numgp.cov.ExpQuad(1, 0.1) cov = cov1 + cov2 K = cov(test_array) npt.assert_allclose(K[0, 1], 2 * 0.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_add_rightadd_scalar(test_array): a = 1 cov = numgp.cov.ExpQuad(1, 0.1) + a K = cov(test_array) npt.assert_allclose(K[0, 1], 1.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_add_leftadd_scalar(test_array): a = 1 cov = a + numgp.cov.ExpQuad(1, 0.1) K = cov(test_array) npt.assert_allclose(K[0, 1], 1.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_add_rightadd_matrix(test_array): M = 2 * np.ones((10, 10)) cov = numgp.cov.ExpQuad(1, 0.1) + M K = cov(test_array) npt.assert_allclose(K[0, 1], 2.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_add_leftadd_matrixt(test_array): M = 2 * np.ones((10, 10)) cov = M + numgp.cov.ExpQuad(1, 0.1) K = cov(test_array) npt.assert_allclose(K[0, 1], 2.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_add_leftprod_matrix(): X = np.linspace(0, 1, 3)[:, None] M = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]]) cov = M + numgp.cov.ExpQuad(1, 0.1) cov_true = numgp.cov.ExpQuad(1, 0.1) + M K = cov(X) K_true = cov_true(X) assert np.allclose(K, K_true) def test_cov_add_inv_rightadd(): M = np.random.randn(2, 2, 2) with pytest.raises(ValueError, match=r"cannot combine"): cov = M + numgp.cov.ExpQuad(1, 1.0) def test_cov_prod_symprod_cov(test_array): cov1 = numgp.cov.ExpQuad(1, 0.1) cov2 = numgp.cov.ExpQuad(1, 0.1) cov = cov1 * cov2 K = cov(test_array) npt.assert_allclose(K[0, 1], 0.53940 * 0.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_prod_rightprod_scalar(test_array): a = 2 cov = numgp.cov.ExpQuad(1, 0.1) * a K = cov(test_array) npt.assert_allclose(K[0, 1], 2 * 0.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_prod_leftprod_scalar(test_array): a = 2 cov = a * numgp.cov.ExpQuad(1, 0.1) K = cov(test_array) npt.assert_allclose(K[0, 1], 2 * 0.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_prod_rightprod_matrix(test_array): M = 2 * np.ones((10, 10)) cov = numgp.cov.ExpQuad(1, 0.1) * M K = cov(test_array) npt.assert_allclose(K[0, 1], 2 * 0.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_prod_leftprod_matrix(): X = np.linspace(0, 1, 3)[:, None] M = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]]) cov = M * numgp.cov.ExpQuad(1, 0.1) cov_true = numgp.cov.ExpQuad(1, 0.1) * M K = cov(X) K_true = cov_true(X) assert np.allclose(K, K_true) def test_cov_prod_multiops(): X = np.linspace(0, 1, 3)[:, None] M = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]]) cov1 = ( 3 + numgp.cov.ExpQuad(1, 0.1) + M * numgp.cov.ExpQuad(1, 0.1) * M * numgp.cov.ExpQuad(1, 0.1) ) cov2 = ( numgp.cov.ExpQuad(1, 0.1) * M * numgp.cov.ExpQuad(1, 0.1) * M + numgp.cov.ExpQuad(1, 0.1) + 3 ) K1 = cov1(X) K2 = cov2(X) assert np.allclose(K1, K2) # check diagonal K1d = cov1(X, diag=True) K2d = cov2(X, diag=True) npt.assert_allclose(np.diag(K1), K2d, atol=1e-5) npt.assert_allclose(np.diag(K2), K1d, atol=1e-5) def test_cov_prod_inv_rightprod(): M = np.random.randn(2, 2, 2) with pytest.raises(ValueError, match=r"cannot combine"): cov = M + numgp.cov.ExpQuad(1, 1.0) def test_slice_dim_slice1(): X = np.linspace(0, 1, 30).reshape(10, 3) cov = numgp.cov.ExpQuad(3, 0.1, active_dims=[0, 0, 1]) K = cov(X) npt.assert_allclose(K[0, 1], 0.20084298, atol=1e-3) # check diagonal Kd = cov(X, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=2e-5) def test_slice_dim_slice2(): X = np.linspace(0, 1, 30).reshape(10, 3) cov = numgp.cov.ExpQuad(3, ls=[0.1, 0.1], active_dims=[1, 2]) K = cov(X) npt.assert_allclose(K[0, 1], 0.34295549, atol=1e-3) # check diagonal Kd = cov(X, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_slice_dim_slice3(): X = np.linspace(0, 1, 30).reshape(10, 3) cov = numgp.cov.ExpQuad(3, ls=np.array([0.1, 0.1]), active_dims=[1, 2]) K = cov(X) npt.assert_allclose(K[0, 1], 0.34295549, atol=1e-3) # check diagonal Kd = cov(X, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_slice_dim_diffslice(): X = np.linspace(0, 1, 30).reshape(10, 3) cov = numgp.cov.ExpQuad(3, ls=0.1, active_dims=[1, 0, 0]) + numgp.cov.ExpQuad( 3, ls=[0.1, 0.2, 0.3] ) K = cov(X) npt.assert_allclose(K[0, 1], 0.683572, atol=1e-3) # check diagonal Kd = cov(X, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=2e-5) def test_slice_dim_raises(): lengthscales = 2.0 with pytest.raises(ValueError): numgp.cov.ExpQuad(1, lengthscales, [True, False]) numgp.cov.ExpQuad(2, lengthscales, [True]) def test_stability(): X = np.random.uniform(low=320.0, high=400.0, size=[2000, 2]) cov = numgp.cov.ExpQuad(2, 0.1) dists = cov.square_dist(X, X) assert not np.any(dists < 0) def test_exp_quad_1d(test_array): cov = numgp.cov.ExpQuad(1, 0.1) K = cov(test_array) npt.assert_allclose(K[0, 1], 0.53940, atol=1e-3) K = cov(test_array, test_array) npt.assert_allclose(K[0, 1], 0.53940, atol=1e-3) Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_exp_quad_2d(test_array_2d): cov = numgp.cov.ExpQuad(2, 0.5) K = cov(test_array_2d) npt.assert_allclose(K[0, 1], 0.820754, atol=1e-3) # diagonal Kd = cov(test_array_2d, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_exp_quad_2dard(test_array_2d): cov = numgp.cov.ExpQuad(2, np.array([1, 2])) K = cov(test_array_2d) npt.assert_allclose(K[0, 1], 0.969607, atol=1e-3) # check diagonal Kd = cov(test_array_2d, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_exp_quad_inv_lengthscale(test_array): cov = numgp.cov.ExpQuad(1, ls_inv=10) K = cov(test_array) npt.assert_allclose(K[0, 1], 0.53940, atol=1e-3) K = cov(test_array, test_array) npt.assert_allclose(K[0, 1], 0.53940, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_white_noise(test_array): # with npy.handlers.seed(rng_seed=45): cov = numgp.cov.WhiteNoise(sigma=0.5) K = cov(test_array) npt.assert_allclose(K[0, 1], 0.0, atol=1e-3) npt.assert_allclose(K[0, 0], 0.5 ** 2, atol=1e-3) Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) K = cov(test_array, test_array) npt.assert_allclose(K[0, 1], 0.0, atol=1e-3) npt.assert_allclose(K[0, 0], 0.0, atol=1e-3) def test_constant_1d(test_array): cov = numgp.cov.Constant(2.5) K = cov(test_array) npt.assert_allclose(K[0, 1], 2.5, atol=1e-3) npt.assert_allclose(K[0, 0], 2.5, atol=1e-3) K = cov(test_array, test_array) npt.assert_allclose(K[0, 1], 2.5, atol=1e-3) npt.assert_allclose(K[0, 0], 2.5, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cov_kron_symprod_cov(): X1 = np.linspace(0, 1, 10)[:, None] X2 = np.linspace(0, 1, 10)[:, None] X = numgp.math.cartesian([X1.reshape(-1), X2.reshape(-1)]) cov1 = numgp.cov.ExpQuad(1, 0.1) cov2 = numgp.cov.ExpQuad(1, 0.1) cov = numgp.cov.Kron([cov1, cov2]) K = cov(X) npt.assert_allclose(K[0, 1], 1 * 0.53940, atol=1e-3) npt.assert_allclose(K[0, 11], 0.53940 * 0.53940, atol=1e-3) # check diagonal Kd = cov(X, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_multiops(): X1 = np.linspace(0, 1, 3)[:, None] X21 = np.linspace(0, 1, 5)[:, None] X22 = np.linspace(0, 1, 4)[:, None] X2 = numgp.math.cartesian([X21.reshape(-1), X22.reshape(-1)]) X = numgp.math.cartesian([X1.reshape(-1), X21.reshape(-1), X22.reshape(-1)]) cov1 = ( 3 + numgp.cov.ExpQuad(1, 0.1) + numgp.cov.ExpQuad(1, 0.1) * numgp.cov.ExpQuad(1, 0.1) ) cov2 = numgp.cov.ExpQuad(1, 0.1) * numgp.cov.ExpQuad(2, 0.1) cov = numgp.cov.Kron([cov1, cov2]) K_true = numgp.math.kronecker(cov1(X1), cov2(X2)) K = cov(X) npt.assert_allclose(K_true, K) def test_matern52_1d(test_array): cov = numgp.cov.Matern52(1, 0.1) K = cov(test_array) npt.assert_allclose(K[0, 1], 0.46202, atol=1e-3) K = cov(test_array, test_array) npt.assert_allclose(K[0, 1], 0.46202, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5) def test_cosine_1d(test_array): cov = numgp.cov.Cosine(1, 0.1) K = cov(test_array) npt.assert_allclose(K[0, 1], 0.766, atol=1e-3) K = cov(test_array, test_array) npt.assert_allclose(K[0, 1], 0.766, atol=1e-3) # check diagonal Kd = cov(test_array, diag=True) npt.assert_allclose(np.diag(K), Kd, atol=1e-5)
[ "numpy.allclose", "numpy.ones", "numgp.cov.Kron", "numpy.testing.assert_allclose", "numgp.cov.Constant", "numgp.cov.WhiteNoise", "numgp.cov.ExpQuad", "numpy.diag", "numpy.any", "numpy.array", "numpy.linspace", "pytest.raises", "numgp.cov.Cosine", "numpy.random.uniform", "numgp.cov.Matern...
[((304, 329), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (321, 329), False, 'import numgp\n'), ((341, 366), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (358, 366), False, 'import numgp\n'), ((417, 469), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(2 * 0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 2 * 0.5394, atol=0.001)\n', (436, 469), True, 'import numpy.testing as npt\n'), ((704, 752), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(1.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 1.5394, atol=0.001)\n', (723, 752), True, 'import numpy.testing as npt\n'), ((986, 1034), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(1.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 1.5394, atol=0.001)\n', (1005, 1034), True, 'import numpy.testing as npt\n'), ((1289, 1337), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(2.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 2.5394, atol=0.001)\n', (1308, 1337), True, 'import numpy.testing as npt\n'), ((1592, 1640), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(2.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 2.5394, atol=0.001)\n', (1611, 1640), True, 'import numpy.testing as npt\n'), ((1833, 1876), 'numpy.array', 'np.array', (['[[1, 2, 3], [2, 1, 2], [3, 2, 1]]'], {}), '([[1, 2, 3], [2, 1, 2], [3, 2, 1]])\n', (1841, 1876), True, 'import numpy as np\n'), ((2013, 2035), 'numpy.allclose', 'np.allclose', (['K', 'K_true'], {}), '(K, K_true)\n', (2024, 2035), True, 'import numpy as np\n'), ((2079, 2103), 'numpy.random.randn', 'np.random.randn', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (2094, 2103), True, 'import numpy as np\n'), ((2265, 2290), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (2282, 2290), False, 'import numgp\n'), ((2302, 2327), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (2319, 2327), False, 'import numgp\n'), ((2378, 2435), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.5394 * 0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 0.5394 * 0.5394, atol=0.001)\n', (2397, 2435), True, 'import numpy.testing as npt\n'), ((2673, 2725), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(2 * 0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 2 * 0.5394, atol=0.001)\n', (2692, 2725), True, 'import numpy.testing as npt\n'), ((2961, 3013), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(2 * 0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 2 * 0.5394, atol=0.001)\n', (2980, 3013), True, 'import numpy.testing as npt\n'), ((3270, 3322), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(2 * 0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 2 * 0.5394, atol=0.001)\n', (3289, 3322), True, 'import numpy.testing as npt\n'), ((3516, 3559), 'numpy.array', 'np.array', (['[[1, 2, 3], [2, 1, 2], [3, 2, 1]]'], {}), '([[1, 2, 3], [2, 1, 2], [3, 2, 1]])\n', (3524, 3559), True, 'import numpy as np\n'), ((3696, 3718), 'numpy.allclose', 'np.allclose', (['K', 'K_true'], {}), '(K, K_true)\n', (3707, 3718), True, 'import numpy as np\n'), ((3797, 3840), 'numpy.array', 'np.array', (['[[1, 2, 3], [2, 1, 2], [3, 2, 1]]'], {}), '([[1, 2, 3], [2, 1, 2], [3, 2, 1]])\n', (3805, 3840), True, 'import numpy as np\n'), ((4160, 4179), 'numpy.allclose', 'np.allclose', (['K1', 'K2'], {}), '(K1, K2)\n', (4171, 4179), True, 'import numpy as np\n'), ((4410, 4434), 'numpy.random.randn', 'np.random.randn', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (4425, 4434), True, 'import numpy as np\n'), ((4626, 4674), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(3)', '(0.1)'], {'active_dims': '[0, 0, 1]'}), '(3, 0.1, active_dims=[0, 0, 1])\n', (4643, 4674), False, 'import numgp\n'), ((4694, 4746), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.20084298)'], {'atol': '(0.001)'}), '(K[0, 1], 0.20084298, atol=0.001)\n', (4713, 4746), True, 'import numpy.testing as npt\n'), ((4931, 4986), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(3)'], {'ls': '[0.1, 0.1]', 'active_dims': '[1, 2]'}), '(3, ls=[0.1, 0.1], active_dims=[1, 2])\n', (4948, 4986), False, 'import numgp\n'), ((5006, 5058), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.34295549)'], {'atol': '(0.001)'}), '(K[0, 1], 0.34295549, atol=0.001)\n', (5025, 5058), True, 'import numpy.testing as npt\n'), ((5328, 5380), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.34295549)'], {'atol': '(0.001)'}), '(K[0, 1], 0.34295549, atol=0.001)\n', (5347, 5380), True, 'import numpy.testing as npt\n'), ((5696, 5746), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.683572)'], {'atol': '(0.001)'}), '(K[0, 1], 0.683572, atol=0.001)\n', (5715, 5746), True, 'import numpy.testing as npt\n'), ((6076, 6132), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(320.0)', 'high': '(400.0)', 'size': '[2000, 2]'}), '(low=320.0, high=400.0, size=[2000, 2])\n', (6093, 6132), True, 'import numpy as np\n'), ((6143, 6168), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(2)', '(0.1)'], {}), '(2, 0.1)\n', (6160, 6168), False, 'import numgp\n'), ((6282, 6307), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (6299, 6307), False, 'import numgp\n'), ((6336, 6384), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 0.5394, atol=0.001)\n', (6355, 6384), True, 'import numpy.testing as npt\n'), ((6426, 6474), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 0.5394, atol=0.001)\n', (6445, 6474), True, 'import numpy.testing as npt\n'), ((6612, 6637), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(2)', '(0.5)'], {}), '(2, 0.5)\n', (6629, 6637), False, 'import numgp\n'), ((6669, 6719), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.820754)'], {'atol': '(0.001)'}), '(K[0, 1], 0.820754, atol=0.001)\n', (6688, 6719), True, 'import numpy.testing as npt\n'), ((6946, 6996), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.969607)'], {'atol': '(0.001)'}), '(K[0, 1], 0.969607, atol=0.001)\n', (6965, 6996), True, 'import numpy.testing as npt\n'), ((7166, 7197), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)'], {'ls_inv': '(10)'}), '(1, ls_inv=10)\n', (7183, 7197), False, 'import numgp\n'), ((7226, 7274), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 0.5394, atol=0.001)\n', (7245, 7274), True, 'import numpy.testing as npt\n'), ((7315, 7363), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 0.5394, atol=0.001)\n', (7334, 7363), True, 'import numpy.testing as npt\n'), ((7561, 7592), 'numgp.cov.WhiteNoise', 'numgp.cov.WhiteNoise', ([], {'sigma': '(0.5)'}), '(sigma=0.5)\n', (7581, 7592), False, 'import numgp\n'), ((7622, 7667), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.0)'], {'atol': '(0.001)'}), '(K[0, 1], 0.0, atol=0.001)\n', (7641, 7667), True, 'import numpy.testing as npt\n'), ((7671, 7721), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 0]', '(0.5 ** 2)'], {'atol': '(0.001)'}), '(K[0, 0], 0.5 ** 2, atol=0.001)\n', (7690, 7721), True, 'import numpy.testing as npt\n'), ((7850, 7895), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.0)'], {'atol': '(0.001)'}), '(K[0, 1], 0.0, atol=0.001)\n', (7869, 7895), True, 'import numpy.testing as npt\n'), ((7899, 7944), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 0]', '(0.0)'], {'atol': '(0.001)'}), '(K[0, 0], 0.0, atol=0.001)\n', (7918, 7944), True, 'import numpy.testing as npt\n'), ((7991, 8014), 'numgp.cov.Constant', 'numgp.cov.Constant', (['(2.5)'], {}), '(2.5)\n', (8009, 8014), False, 'import numgp\n'), ((8043, 8088), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(2.5)'], {'atol': '(0.001)'}), '(K[0, 1], 2.5, atol=0.001)\n', (8062, 8088), True, 'import numpy.testing as npt\n'), ((8092, 8137), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 0]', '(2.5)'], {'atol': '(0.001)'}), '(K[0, 0], 2.5, atol=0.001)\n', (8111, 8137), True, 'import numpy.testing as npt\n'), ((8177, 8222), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(2.5)'], {'atol': '(0.001)'}), '(K[0, 1], 2.5, atol=0.001)\n', (8196, 8222), True, 'import numpy.testing as npt\n'), ((8226, 8271), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 0]', '(2.5)'], {'atol': '(0.001)'}), '(K[0, 0], 2.5, atol=0.001)\n', (8245, 8271), True, 'import numpy.testing as npt\n'), ((8569, 8594), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (8586, 8594), False, 'import numgp\n'), ((8606, 8631), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (8623, 8631), False, 'import numgp\n'), ((8642, 8670), 'numgp.cov.Kron', 'numgp.cov.Kron', (['[cov1, cov2]'], {}), '([cov1, cov2])\n', (8656, 8670), False, 'import numgp\n'), ((8691, 8743), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(1 * 0.5394)'], {'atol': '(0.001)'}), '(K[0, 1], 1 * 0.5394, atol=0.001)\n', (8710, 8743), True, 'import numpy.testing as npt\n'), ((8748, 8806), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 11]', '(0.5394 * 0.5394)'], {'atol': '(0.001)'}), '(K[0, 11], 0.5394 * 0.5394, atol=0.001)\n', (8767, 8806), True, 'import numpy.testing as npt\n'), ((9401, 9429), 'numgp.cov.Kron', 'numgp.cov.Kron', (['[cov1, cov2]'], {}), '([cov1, cov2])\n', (9415, 9429), False, 'import numgp\n'), ((9503, 9533), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K_true', 'K'], {}), '(K_true, K)\n', (9522, 9533), True, 'import numpy.testing as npt\n'), ((9581, 9607), 'numgp.cov.Matern52', 'numgp.cov.Matern52', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (9599, 9607), False, 'import numgp\n'), ((9636, 9685), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.46202)'], {'atol': '(0.001)'}), '(K[0, 1], 0.46202, atol=0.001)\n', (9655, 9685), True, 'import numpy.testing as npt\n'), ((9725, 9774), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.46202)'], {'atol': '(0.001)'}), '(K[0, 1], 0.46202, atol=0.001)\n', (9744, 9774), True, 'import numpy.testing as npt\n'), ((9926, 9950), 'numgp.cov.Cosine', 'numgp.cov.Cosine', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (9942, 9950), False, 'import numgp\n'), ((9979, 10026), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.766)'], {'atol': '(0.001)'}), '(K[0, 1], 0.766, atol=0.001)\n', (9998, 10026), True, 'import numpy.testing as npt\n'), ((10066, 10113), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['K[0, 1]', '(0.766)'], {'atol': '(0.001)'}), '(K[0, 1], 0.766, atol=0.001)\n', (10085, 10113), True, 'import numpy.testing as npt\n'), ((551, 561), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (558, 561), True, 'import numpy as np\n'), ((646, 671), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (663, 671), False, 'import numgp\n'), ((834, 844), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (841, 844), True, 'import numpy as np\n'), ((932, 957), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (949, 957), False, 'import numgp\n'), ((1116, 1126), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (1123, 1126), True, 'import numpy as np\n'), ((1203, 1220), 'numpy.ones', 'np.ones', (['(10, 10)'], {}), '((10, 10))\n', (1210, 1220), True, 'import numpy as np\n'), ((1231, 1256), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (1248, 1256), False, 'import numgp\n'), ((1419, 1429), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (1426, 1429), True, 'import numpy as np\n'), ((1506, 1523), 'numpy.ones', 'np.ones', (['(10, 10)'], {}), '((10, 10))\n', (1513, 1523), True, 'import numpy as np\n'), ((1538, 1563), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (1555, 1563), False, 'import numgp\n'), ((1722, 1732), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (1729, 1732), True, 'import numpy as np\n'), ((1795, 1815), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(3)'], {}), '(0, 1, 3)\n', (1806, 1815), True, 'import numpy as np\n'), ((1891, 1916), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (1908, 1916), False, 'import numgp\n'), ((1932, 1957), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (1949, 1957), False, 'import numgp\n'), ((2113, 2162), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""cannot combine"""'}), "(ValueError, match='cannot combine')\n", (2126, 2162), False, 'import pytest\n'), ((2518, 2528), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (2525, 2528), True, 'import numpy as np\n'), ((2615, 2640), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (2632, 2640), False, 'import numgp\n'), ((2807, 2817), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (2814, 2817), True, 'import numpy as np\n'), ((2907, 2932), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (2924, 2932), False, 'import numgp\n'), ((3095, 3105), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (3102, 3105), True, 'import numpy as np\n'), ((3184, 3201), 'numpy.ones', 'np.ones', (['(10, 10)'], {}), '((10, 10))\n', (3191, 3201), True, 'import numpy as np\n'), ((3212, 3237), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (3229, 3237), False, 'import numgp\n'), ((3404, 3414), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (3411, 3414), True, 'import numpy as np\n'), ((3478, 3498), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(3)'], {}), '(0, 1, 3)\n', (3489, 3498), True, 'import numpy as np\n'), ((3574, 3599), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (3591, 3599), False, 'import numgp\n'), ((3615, 3640), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (3632, 3640), False, 'import numgp\n'), ((3759, 3779), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(3)'], {}), '(0, 1, 3)\n', (3770, 3779), True, 'import numpy as np\n'), ((4283, 4294), 'numpy.diag', 'np.diag', (['K1'], {}), '(K1)\n', (4290, 4294), True, 'import numpy as np\n'), ((4336, 4347), 'numpy.diag', 'np.diag', (['K2'], {}), '(K2)\n', (4343, 4347), True, 'import numpy as np\n'), ((4444, 4493), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""cannot combine"""'}), "(ValueError, match='cannot combine')\n", (4457, 4493), False, 'import pytest\n'), ((4818, 4828), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (4825, 4828), True, 'import numpy as np\n'), ((5130, 5140), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (5137, 5140), True, 'import numpy as np\n'), ((5452, 5462), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (5459, 5462), True, 'import numpy as np\n'), ((5568, 5619), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(3)'], {'ls': '(0.1)', 'active_dims': '[1, 0, 0]'}), '(3, ls=0.1, active_dims=[1, 0, 0])\n', (5585, 5619), False, 'import numgp\n'), ((5622, 5662), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(3)'], {'ls': '[0.1, 0.2, 0.3]'}), '(3, ls=[0.1, 0.2, 0.3])\n', (5639, 5662), False, 'import numgp\n'), ((5818, 5828), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (5825, 5828), True, 'import numpy as np\n'), ((5908, 5933), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5921, 5933), False, 'import pytest\n'), ((5943, 5992), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', 'lengthscales', '[True, False]'], {}), '(1, lengthscales, [True, False])\n', (5960, 5992), False, 'import numgp\n'), ((6001, 6043), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(2)', 'lengthscales', '[True]'], {}), '(2, lengthscales, [True])\n', (6018, 6043), False, 'import numgp\n'), ((6218, 6235), 'numpy.any', 'np.any', (['(dists < 0)'], {}), '(dists < 0)\n', (6224, 6235), True, 'import numpy as np\n'), ((6536, 6546), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (6543, 6546), True, 'import numpy as np\n'), ((6797, 6807), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (6804, 6807), True, 'import numpy as np\n'), ((6897, 6913), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (6905, 6913), True, 'import numpy as np\n'), ((7080, 7090), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (7087, 7090), True, 'import numpy as np\n'), ((7445, 7455), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (7452, 7455), True, 'import numpy as np\n'), ((7782, 7792), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (7789, 7792), True, 'import numpy as np\n'), ((8352, 8362), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (8359, 8362), True, 'import numpy as np\n'), ((8423, 8444), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(10)'], {}), '(0, 1, 10)\n', (8434, 8444), True, 'import numpy as np\n'), ((8463, 8484), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(10)'], {}), '(0, 1, 10)\n', (8474, 8484), True, 'import numpy as np\n'), ((8880, 8890), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (8887, 8890), True, 'import numpy as np\n'), ((8939, 8959), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(3)'], {}), '(0, 1, 3)\n', (8950, 8959), True, 'import numpy as np\n'), ((8979, 8999), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(5)'], {}), '(0, 1, 5)\n', (8990, 8999), True, 'import numpy as np\n'), ((9019, 9039), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (9030, 9039), True, 'import numpy as np\n'), ((9337, 9362), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (9354, 9362), False, 'import numgp\n'), ((9365, 9390), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(2)', '(0.1)'], {}), '(2, 0.1)\n', (9382, 9390), False, 'import numgp\n'), ((9855, 9865), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (9862, 9865), True, 'import numpy as np\n'), ((10194, 10204), 'numpy.diag', 'np.diag', (['K'], {}), '(K)\n', (10201, 10204), True, 'import numpy as np\n'), ((2183, 2208), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(1.0)'], {}), '(1, 1.0)\n', (2200, 2208), False, 'import numgp\n'), ((3874, 3899), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (3891, 3899), False, 'import numgp\n'), ((3946, 3971), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (3963, 3971), False, 'import numgp\n'), ((4071, 4096), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (4088, 4096), False, 'import numgp\n'), ((4514, 4539), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(1.0)'], {}), '(1, 1.0)\n', (4531, 4539), False, 'import numgp\n'), ((4579, 4600), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(30)'], {}), '(0, 1, 30)\n', (4590, 4600), True, 'import numpy as np\n'), ((4884, 4905), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(30)'], {}), '(0, 1, 30)\n', (4895, 4905), True, 'import numpy as np\n'), ((5196, 5217), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(30)'], {}), '(0, 1, 30)\n', (5207, 5217), True, 'import numpy as np\n'), ((5267, 5287), 'numpy.array', 'np.array', (['[0.1, 0.1]'], {}), '([0.1, 0.1])\n', (5275, 5287), True, 'import numpy as np\n'), ((5521, 5542), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(30)'], {}), '(0, 1, 30)\n', (5532, 5542), True, 'import numpy as np\n'), ((9230, 9255), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (9247, 9255), False, 'import numgp\n'), ((9266, 9291), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (9283, 9291), False, 'import numgp\n'), ((9294, 9319), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (9311, 9319), False, 'import numgp\n'), ((3914, 3939), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (3931, 3939), False, 'import numgp\n'), ((4031, 4056), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (4048, 4056), False, 'import numgp\n'), ((3999, 4024), 'numgp.cov.ExpQuad', 'numgp.cov.ExpQuad', (['(1)', '(0.1)'], {}), '(1, 0.1)\n', (4016, 4024), False, 'import numgp\n')]
import torch from scipy.stats import uniform, bernoulli import numpy as np def element_wise_sample_lambda(sampling, lambda_choices, encoding_mat, batch_size=128, probs=-1): ''' Elementwise sample and encode lambda. Args: sampling: str. sample scheme. lambda_choices: list of floats. Useful when sampling is 'disc'. encoding_mat: str. encoding scheme. Useful when sampling is 'disc'. probs: float. If probs<=0, ignored and use uniform sample. Returns: _lambda_flat: Tensor. size=(batch_size). For loss. _lambda: Tensor. size=(batch_size, 1). FiLM input tensor. num_zeros: int. How many 0s are sampled in this batch. ''' if sampling == 'disc': lambda_none_zero_choices = list(set(lambda_choices)-set([0])) if 0 in lambda_choices: if probs > 0: num_zeros = np.ceil(probs * batch_size).astype(int) else: # uniform sample num_zeros = np.ceil(batch_size / len(lambda_choices)).astype(int) # print('num_zeros %d/batch_size %d' % (num_zeros, batch_size)) else: num_zeros = 0 num_none_zeros = int(batch_size-num_zeros) _lambda_zeros = np.zeros((num_zeros,1)) _lambda_none_zeros = np.random.choice(lambda_none_zero_choices, size=(num_none_zeros,1)) _lambda = np.concatenate([_lambda_zeros,_lambda_none_zeros], axis=0) _lambda_flat = np.squeeze(_lambda) / 1.0 if encoding_mat is not None: idx_lst = [] for lambda_choice in lambda_choices: idx_lst.append(np.where(_lambda==lambda_choice)[0]) for j, idx in enumerate(idx_lst): _lambda[idx] = j _lambda = _lambda.astype(np.int32) _lambda = encoding_mat[_lambda,:] assert np.amax(_lambda_flat) <= 1 and np.amin(_lambda_flat) >= 0 _lambda_flat = torch.from_numpy(_lambda_flat).float().cuda() # for loss _lambda = torch.from_numpy(_lambda).float().cuda() # for FiLM layers return _lambda_flat, _lambda, num_zeros def batch_wise_sample_lambda(sampling, lambda_choices, encoding_mat, batch_size=128): ''' Batch-wise sample and encode lambda. Args: sampling: str. sample scheme. lambda_choices: list of floats. Useful when sampling is 'disc'. encoding_mat: str. encoding scheme. Useful when sampling is 'disc'. Returns: _lambda_flat: Tensor. size=(batch_size). For loss. _lambda: Tensor. size=(batch_size, 1). FiLM input tensor. ''' if sampling == 'disc': _lambda = np.random.choice(lambda_choices, size=1) _lambda = np.tile(_lambda, (batch_size,1)) _lambda_flat = np.squeeze(_lambda) / 1.0 if encoding_mat is not None: idx_lst = [] for lambda_choice in lambda_choices: idx_lst.append(np.where(_lambda==lambda_choice)[0]) for j, idx in enumerate(idx_lst): _lambda[idx] = j _lambda = _lambda.astype(np.int32) _lambda = encoding_mat[_lambda,:] assert np.amax(_lambda_flat) <= 1 and np.amin(_lambda_flat) >= 0 _lambda_flat = torch.from_numpy(_lambda_flat).float().cuda() # for loss _lambda = torch.from_numpy(_lambda).float().cuda() # for FiLM layers return _lambda_flat, _lambda
[ "numpy.tile", "numpy.ceil", "numpy.amin", "numpy.random.choice", "numpy.where", "torch.from_numpy", "numpy.squeeze", "numpy.zeros", "numpy.concatenate", "numpy.amax" ]
[((1234, 1258), 'numpy.zeros', 'np.zeros', (['(num_zeros, 1)'], {}), '((num_zeros, 1))\n', (1242, 1258), True, 'import numpy as np\n'), ((1287, 1355), 'numpy.random.choice', 'np.random.choice', (['lambda_none_zero_choices'], {'size': '(num_none_zeros, 1)'}), '(lambda_none_zero_choices, size=(num_none_zeros, 1))\n', (1303, 1355), True, 'import numpy as np\n'), ((1374, 1433), 'numpy.concatenate', 'np.concatenate', (['[_lambda_zeros, _lambda_none_zeros]'], {'axis': '(0)'}), '([_lambda_zeros, _lambda_none_zeros], axis=0)\n', (1388, 1433), True, 'import numpy as np\n'), ((2638, 2678), 'numpy.random.choice', 'np.random.choice', (['lambda_choices'], {'size': '(1)'}), '(lambda_choices, size=1)\n', (2654, 2678), True, 'import numpy as np\n'), ((2697, 2730), 'numpy.tile', 'np.tile', (['_lambda', '(batch_size, 1)'], {}), '(_lambda, (batch_size, 1))\n', (2704, 2730), True, 'import numpy as np\n'), ((1456, 1475), 'numpy.squeeze', 'np.squeeze', (['_lambda'], {}), '(_lambda)\n', (1466, 1475), True, 'import numpy as np\n'), ((1856, 1877), 'numpy.amax', 'np.amax', (['_lambda_flat'], {}), '(_lambda_flat)\n', (1863, 1877), True, 'import numpy as np\n'), ((1887, 1908), 'numpy.amin', 'np.amin', (['_lambda_flat'], {}), '(_lambda_flat)\n', (1894, 1908), True, 'import numpy as np\n'), ((2754, 2773), 'numpy.squeeze', 'np.squeeze', (['_lambda'], {}), '(_lambda)\n', (2764, 2773), True, 'import numpy as np\n'), ((3154, 3175), 'numpy.amax', 'np.amax', (['_lambda_flat'], {}), '(_lambda_flat)\n', (3161, 3175), True, 'import numpy as np\n'), ((3185, 3206), 'numpy.amin', 'np.amin', (['_lambda_flat'], {}), '(_lambda_flat)\n', (3192, 3206), True, 'import numpy as np\n'), ((1933, 1963), 'torch.from_numpy', 'torch.from_numpy', (['_lambda_flat'], {}), '(_lambda_flat)\n', (1949, 1963), False, 'import torch\n'), ((2004, 2029), 'torch.from_numpy', 'torch.from_numpy', (['_lambda'], {}), '(_lambda)\n', (2020, 2029), False, 'import torch\n'), ((3231, 3261), 'torch.from_numpy', 'torch.from_numpy', (['_lambda_flat'], {}), '(_lambda_flat)\n', (3247, 3261), False, 'import torch\n'), ((3302, 3327), 'torch.from_numpy', 'torch.from_numpy', (['_lambda'], {}), '(_lambda)\n', (3318, 3327), False, 'import torch\n'), ((885, 912), 'numpy.ceil', 'np.ceil', (['(probs * batch_size)'], {}), '(probs * batch_size)\n', (892, 912), True, 'import numpy as np\n'), ((1624, 1658), 'numpy.where', 'np.where', (['(_lambda == lambda_choice)'], {}), '(_lambda == lambda_choice)\n', (1632, 1658), True, 'import numpy as np\n'), ((2922, 2956), 'numpy.where', 'np.where', (['(_lambda == lambda_choice)'], {}), '(_lambda == lambda_choice)\n', (2930, 2956), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 13 08:20:52 2021 @author: smullally """ #Code to look at spectrophotometric standards. import numpy as np import lightkurve as lk import matplotlib.pyplot as plt def examine_tic(ticid): lcs = lk.search_lightcurve('TIC {}'.format(ticid), author='SPOC', exptime=120) if len(lcs) == 0: print("No two minute data data.") return stats = np.zeros(len(lcs)) for i,lcf in enumerate(lcs): print() print(lcf) myfig = plt.figure(figsize=(10,13)) ax1 = myfig.add_subplot(3,1,1) lc = lcf.download() lc.scatter(ax=ax1, label="raw") plt.legend() plt.title('TIC {} Sector {}'.format(ticid, lc.sector)) ax2 = myfig.add_subplot(3,1,2) wl = int(0.3*len(lc.time.value)) if (wl % 2) == 0: wl = wl+1 goodlc = lc.remove_nans().remove_outliers().flatten(window_length = wl).normalize() goodlc.flux = goodlc.flux*1000000 goodlc.plot(ax=ax2, label="normalize") plt.legend() per = goodlc.to_periodogram(method='lombscargle', normalization='amplitude') N=len(goodlc.flux) sigma_rms = np.nanstd(goodlc.flux) # mean noise level in amplitude spectrum (See A2 of Kledson and Bedding) sigma_amp = np.sqrt(np.pi/N)*sigma_rms stats[i] = 5 * sigma_amp ax3 = myfig.add_subplot(3,1,3) per.plot(ax=ax3) plt.ylabel('Amplitude') plt.hlines(5*sigma_amp, np.min(per.frequency.value), np.max(per.frequency.value), color='red', linestyles='dashed', label=str(stats[i])) plt.legend() print('5sigma_amp:{}'.format(stats[i])) print(per.period_at_max_power.value) return stats def create_detrended_lcs(ticid, ddir="/Users/smullally/Science/tess_monitor_standards/detrended_standards/"): """ Create several versions of your light curve using different parameters. Write them to disk. """ print("hello") lcs = lk.search_lightcurve('TIC {}'.format(ticid), author='TESS-SPOC') # exptime=[1800,600]) print(lcs) if len(lcs) == 0: print("No two minute data.") return for i,lcf in enumerate(lcs): print(i) mylc = lcf.download().remove_outliers(sigma = 6) rootname = 'tic%014u_s%03u_' % (ticid, mylc.sector) tL = len(mylc.time) name1="flat1.fits" wl = int(0.5*tL) if (wl % 2) == 0: wl = wl+1 lc1 = mylc.flatten(window_length=wl, niters=2).normalize() lc1.to_fits(ddir+rootname+name1, overwrite=True) lc1.plot() plt.title("Long Window Flatten") name2 = "flat2.fits" wl = int(0.2*tL) if (wl % 2) == 0 : wl = wl+1 lc2 = mylc.flatten(window_length=wl, niters=2).normalize() lc2.to_fits(ddir+rootname+name2, overwrite=True) lc2.plot() plt.title("Short Window Flatten") name3 = "norm1.fits" lc3 = mylc.normalize() lc3.to_fits(ddir+rootname+name3, overwrite=True) lc3.plot() plt.title("Normalize only") return lcs def create_lcft_plot(filename, periods=[0.00278, 12], times=None, label=None): "periods is a min max periods for the periodogram in days." sz=17 lc = lk.read(filename) pgram = lc.to_periodogram(method="lombscargle", normalization="amplitude", minimum_frequency=1/periods[1], maximum_frequency=1/periods[0]) flatlc = lc.flatten(window_length=1441, polyorder=4) #flatlc = lc #hertz = freq*0.000011574074074 #per_hour = freq*0.041666666667 plt.figure(figsize=(19,5.54)) plt.subplot(121) plt.plot(lc.time.value, 100*(lc.flux.value-1.0), 'k.', label=label) if times != None: plt.xlim(times) plt.xticks(fontsize=sz) plt.yticks(fontsize=sz) plt.ylabel('Amplitude [percent]', fontsize=sz) plt.xlabel("Time - 2457000 [BJD]", fontsize=sz) plt.legend() plt.subplot(122) freq=pgram.frequency #In per days microhertz=11.574074074*freq amp=pgram.power * 100 if label == None: ticid = int(filename[-28:-16]) sector = int(filename[-14:-11]) label = 'TIC {}'.format(ticid)+'\nSector {}'.format(sector) else: label = label plt.plot(microhertz, amp, color='k', label=label) plt.legend() plt.xticks(fontsize=sz) plt.yticks(fontsize=sz) plt.xlabel(r'Frequency [$\mu$Hz]', fontsize=sz) plt.ylabel('Amplitude [percent]', fontsize=sz) axes1 = plt.gca() axes2 = axes1.twiny() xloc = np.linspace(1e-4, 1e6/(24*3600*periods[0]), 7) period_values = 277.777778/np.array(xloc) xlabels= np.array(list( map( lambda x: "%.1f" % x, period_values ))) #xlabels = np.round((1/np.array(xloc))*1e6/(3600)) #print(xloc,xlabels) axes2.set_xticks(xloc[1:]) axes2.set_xticklabels(xlabels[1:], fontsize=sz-2) plt.xlabel('Period [hr]', fontsize=sz-2) plt.xlim(0, 1e6/(24*3600*periods[0])) N=len(lc.flux) sigma_rms = np.nanstd(flatlc.flux.value) # mean noise level in amplitude spectrum (See A2 of Kledson and Bedding) sigma_amp = np.sqrt(np.pi/N)*sigma_rms #plt.hlines(5*100*sigma_amp, 0, 11.5741*np.max(pgram.frequency.value), # color='red', linestyles='dashed', label=r"5$\sigma$") #plt.annotate("5"+r"$\sigma$", (xloc[-2], 5.2*100*sigma_amp), color='red', fontsize=sz-2) def calc_variable_stats(filename, ticid = 111, periods=[.013,13]): lc = lk.read(filename) pgm = lc.to_periodogram(method="lombscargle", normalization="amplitude", minimum_frequency=1/periods[1], maximum_frequency=1/periods[0]) N = len(lc.time.value) ave_power = np.nanmean(pgm.power.value ** 2) ft_noise_level = (6 * ave_power )**(0.5) #Used for peak 2 peak estimate #pgm.plot() max_period = pgm.period_at_max_power.value max_amplitude = pgm.max_power.value * 100 flux = lc.flux.value binflux = lc.bin(time_bin_size=(.0042), aggregate_func=np.nanmedian) #6 minutes flux = binflux.flux.value #binflux.plot() #peakpeak = 100*(np.nanmax(flux) - np.nanmin(flux)) peakpeak = 100*(np.nanpercentile(flux,97.725) - np.nanpercentile(flux,2.275)) peakpeak2 = 100 * peak2peak(lc, ft_noise_level, periods=periods) return ticid, max_period, max_amplitude, peakpeak, peakpeak2 def peak2peak(lc, min_amp, periods=[.013,13], N=4): """ Parameters ---------- lc : lightkurve module must contain time and flux. Returns ------- peak2peak : float Add up amplitudes of N highest peaks. """ pgm = lc.to_periodogram(method="lombscargle", normalization="amplitude", minimum_frequency=1/periods[1], maximum_frequency=1/periods[0]) #pgm.plot() #print(min_amp) max_amp = np.zeros(N) resolution = 3/(lc.time.value[-1] - lc.time.value[0]) #print(resolution) for i in range(0,N): max_loc = np.argmax(pgm.power.value) max_freq = pgm.frequency.value[max_loc] new_amp = pgm.power.value[max_loc] #print(new_amp, min_amp) if new_amp > min_amp: max_amp[i] = pgm.power.value[max_loc] #print(max_loc, max_freq, max_amp[i]) freq = pgm.frequency.value freq_range = (freq > (max_freq - resolution)) & (freq < (max_freq + resolution)) pgm.power.value[freq_range] = 0 #pgm.plot() pk2pk = 2 * np.nansum(max_amp) return pk2pk def nonvar_stats(filename, period = 1, long_bin_size = .02083): """ Parameters ---------- filename : string DESCRIPTION. period_break : TYPE, optional DESCRIPTION. The default is 5. Returns ------- two stats short_period_stat : float 3 sigma times the average power with periods shorter than period long_period_stat : float 3 times the rms of the light curve. """ lc = lk.read(filename) pgm = lc.to_periodogram(method="lombscargle", normalization="amplitude", minimum_frequency=1/period) ave_power = np.nanmean(pgm.power.value ** 2) short_period_stat = np.nanmax(pgm.power.value) #short_period_stat = np.sqrt(4 * ave_power) pgm = lc.to_periodogram(method="lombscargle", normalization="amplitude", maximum_frequency=1/period) ave_power = np.nanmean(pgm.power.value **2) #long_period_stat = np.sqrt(4 * ave_power) long_period_stat = np.nanmax(pgm.power.value) binflux = lc.bin(time_bin_size=long_bin_size, aggregate_func=np.nanmedian) #Contains 3 sigma of the points sig3_upper_limit = np.nanpercentile(binflux.flux.value,99.865) - np.nanpercentile(binflux.flux.value, .13495) #upper_limit = 3 * np.nanstd(binflux.flux.value) return short_period_stat, long_period_stat, sig3_upper_limit
[ "numpy.sqrt", "numpy.nanpercentile", "matplotlib.pyplot.ylabel", "numpy.nanmean", "numpy.array", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.max", "numpy.linspace", "matplotlib.pyplot.yticks", "numpy.nanmax", "numpy.min", "numpy.nanstd", "matplotlib.pyplot.xticks", "matp...
[((3734, 3751), 'lightkurve.read', 'lk.read', (['filename'], {}), '(filename)\n', (3741, 3751), True, 'import lightkurve as lk\n'), ((4083, 4113), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(19, 5.54)'}), '(figsize=(19, 5.54))\n', (4093, 4113), True, 'import matplotlib.pyplot as plt\n'), ((4117, 4133), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (4128, 4133), True, 'import matplotlib.pyplot as plt\n'), ((4138, 4209), 'matplotlib.pyplot.plot', 'plt.plot', (['lc.time.value', '(100 * (lc.flux.value - 1.0))', '"""k."""'], {'label': 'label'}), "(lc.time.value, 100 * (lc.flux.value - 1.0), 'k.', label=label)\n", (4146, 4209), True, 'import matplotlib.pyplot as plt\n'), ((4256, 4279), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': 'sz'}), '(fontsize=sz)\n', (4266, 4279), True, 'import matplotlib.pyplot as plt\n'), ((4284, 4307), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': 'sz'}), '(fontsize=sz)\n', (4294, 4307), True, 'import matplotlib.pyplot as plt\n'), ((4312, 4358), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Amplitude [percent]"""'], {'fontsize': 'sz'}), "('Amplitude [percent]', fontsize=sz)\n", (4322, 4358), True, 'import matplotlib.pyplot as plt\n'), ((4363, 4410), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time - 2457000 [BJD]"""'], {'fontsize': 'sz'}), "('Time - 2457000 [BJD]', fontsize=sz)\n", (4373, 4410), True, 'import matplotlib.pyplot as plt\n'), ((4415, 4427), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4425, 4427), True, 'import matplotlib.pyplot as plt\n'), ((4437, 4453), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (4448, 4453), True, 'import matplotlib.pyplot as plt\n'), ((4771, 4820), 'matplotlib.pyplot.plot', 'plt.plot', (['microhertz', 'amp'], {'color': '"""k"""', 'label': 'label'}), "(microhertz, amp, color='k', label=label)\n", (4779, 4820), True, 'import matplotlib.pyplot as plt\n'), ((4830, 4842), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4840, 4842), True, 'import matplotlib.pyplot as plt\n'), ((4851, 4874), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': 'sz'}), '(fontsize=sz)\n', (4861, 4874), True, 'import matplotlib.pyplot as plt\n'), ((4879, 4902), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': 'sz'}), '(fontsize=sz)\n', (4889, 4902), True, 'import matplotlib.pyplot as plt\n'), ((4908, 4955), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency [$\\\\mu$Hz]"""'], {'fontsize': 'sz'}), "('Frequency [$\\\\mu$Hz]', fontsize=sz)\n", (4918, 4955), True, 'import matplotlib.pyplot as plt\n'), ((4960, 5006), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Amplitude [percent]"""'], {'fontsize': 'sz'}), "('Amplitude [percent]', fontsize=sz)\n", (4970, 5006), True, 'import matplotlib.pyplot as plt\n'), ((5024, 5033), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5031, 5033), True, 'import matplotlib.pyplot as plt\n'), ((5076, 5136), 'numpy.linspace', 'np.linspace', (['(0.0001)', '(1000000.0 / (24 * 3600 * periods[0]))', '(7)'], {}), '(0.0001, 1000000.0 / (24 * 3600 * periods[0]), 7)\n', (5087, 5136), True, 'import numpy as np\n'), ((5411, 5453), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Period [hr]"""'], {'fontsize': '(sz - 2)'}), "('Period [hr]', fontsize=sz - 2)\n", (5421, 5453), True, 'import matplotlib.pyplot as plt\n'), ((5461, 5510), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(1000000.0 / (24 * 3600 * periods[0]))'], {}), '(0, 1000000.0 / (24 * 3600 * periods[0]))\n', (5469, 5510), True, 'import matplotlib.pyplot as plt\n'), ((5540, 5568), 'numpy.nanstd', 'np.nanstd', (['flatlc.flux.value'], {}), '(flatlc.flux.value)\n', (5549, 5568), True, 'import numpy as np\n'), ((6019, 6036), 'lightkurve.read', 'lk.read', (['filename'], {}), '(filename)\n', (6026, 6036), True, 'import lightkurve as lk\n'), ((6281, 6313), 'numpy.nanmean', 'np.nanmean', (['(pgm.power.value ** 2)'], {}), '(pgm.power.value ** 2)\n', (6291, 6313), True, 'import numpy as np\n'), ((7446, 7457), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (7454, 7457), True, 'import numpy as np\n'), ((8615, 8632), 'lightkurve.read', 'lk.read', (['filename'], {}), '(filename)\n', (8622, 8632), True, 'import lightkurve as lk\n'), ((8791, 8823), 'numpy.nanmean', 'np.nanmean', (['(pgm.power.value ** 2)'], {}), '(pgm.power.value ** 2)\n', (8801, 8823), True, 'import numpy as np\n'), ((8848, 8874), 'numpy.nanmax', 'np.nanmax', (['pgm.power.value'], {}), '(pgm.power.value)\n', (8857, 8874), True, 'import numpy as np\n'), ((9081, 9113), 'numpy.nanmean', 'np.nanmean', (['(pgm.power.value ** 2)'], {}), '(pgm.power.value ** 2)\n', (9091, 9113), True, 'import numpy as np\n'), ((9183, 9209), 'numpy.nanmax', 'np.nanmax', (['pgm.power.value'], {}), '(pgm.power.value)\n', (9192, 9209), True, 'import numpy as np\n'), ((600, 628), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 13)'}), '(figsize=(10, 13))\n', (610, 628), True, 'import matplotlib.pyplot as plt\n'), ((752, 764), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (762, 764), True, 'import matplotlib.pyplot as plt\n'), ((1215, 1227), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1225, 1227), True, 'import matplotlib.pyplot as plt\n'), ((1420, 1442), 'numpy.nanstd', 'np.nanstd', (['goodlc.flux'], {}), '(goodlc.flux)\n', (1429, 1442), True, 'import numpy as np\n'), ((1694, 1717), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Amplitude"""'], {}), "('Amplitude')\n", (1704, 1717), True, 'import matplotlib.pyplot as plt\n'), ((1890, 1902), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1900, 1902), True, 'import matplotlib.pyplot as plt\n'), ((3013, 3045), 'matplotlib.pyplot.title', 'plt.title', (['"""Long Window Flatten"""'], {}), "('Long Window Flatten')\n", (3022, 3045), True, 'import matplotlib.pyplot as plt\n'), ((3309, 3342), 'matplotlib.pyplot.title', 'plt.title', (['"""Short Window Flatten"""'], {}), "('Short Window Flatten')\n", (3318, 3342), True, 'import matplotlib.pyplot as plt\n'), ((3496, 3523), 'matplotlib.pyplot.title', 'plt.title', (['"""Normalize only"""'], {}), "('Normalize only')\n", (3505, 3523), True, 'import matplotlib.pyplot as plt\n'), ((4236, 4251), 'matplotlib.pyplot.xlim', 'plt.xlim', (['times'], {}), '(times)\n', (4244, 4251), True, 'import matplotlib.pyplot as plt\n'), ((5154, 5168), 'numpy.array', 'np.array', (['xloc'], {}), '(xloc)\n', (5162, 5168), True, 'import numpy as np\n'), ((5667, 5685), 'numpy.sqrt', 'np.sqrt', (['(np.pi / N)'], {}), '(np.pi / N)\n', (5674, 5685), True, 'import numpy as np\n'), ((7596, 7622), 'numpy.argmax', 'np.argmax', (['pgm.power.value'], {}), '(pgm.power.value)\n', (7605, 7622), True, 'import numpy as np\n'), ((8097, 8115), 'numpy.nansum', 'np.nansum', (['max_amp'], {}), '(max_amp)\n', (8106, 8115), True, 'import numpy as np\n'), ((9353, 9397), 'numpy.nanpercentile', 'np.nanpercentile', (['binflux.flux.value', '(99.865)'], {}), '(binflux.flux.value, 99.865)\n', (9369, 9397), True, 'import numpy as np\n'), ((9399, 9444), 'numpy.nanpercentile', 'np.nanpercentile', (['binflux.flux.value', '(0.13495)'], {}), '(binflux.flux.value, 0.13495)\n', (9415, 9444), True, 'import numpy as np\n'), ((1544, 1562), 'numpy.sqrt', 'np.sqrt', (['(np.pi / N)'], {}), '(np.pi / N)\n', (1551, 1562), True, 'import numpy as np\n'), ((1750, 1777), 'numpy.min', 'np.min', (['per.frequency.value'], {}), '(per.frequency.value)\n', (1756, 1777), True, 'import numpy as np\n'), ((1779, 1806), 'numpy.max', 'np.max', (['per.frequency.value'], {}), '(per.frequency.value)\n', (1785, 1806), True, 'import numpy as np\n'), ((6739, 6769), 'numpy.nanpercentile', 'np.nanpercentile', (['flux', '(97.725)'], {}), '(flux, 97.725)\n', (6755, 6769), True, 'import numpy as np\n'), ((6771, 6800), 'numpy.nanpercentile', 'np.nanpercentile', (['flux', '(2.275)'], {}), '(flux, 2.275)\n', (6787, 6800), True, 'import numpy as np\n')]
# Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH, and # Technical University of Darmstadt. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of <NAME>, Honda Research Institute Europe GmbH, # or Technical University of Darmstadt, 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 <NAME>, HONDA RESEARCH INSTITUTE EUROPE GMBH, # OR TECHNICAL UNIVERSITY OF DARMSTADT 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. from typing import Optional, Sequence import numpy as np import pyrado import torch as to from init_args_serializer import Serializable from pyrado.algorithms.base import Algorithm from pyrado.algorithms.step_based.svpg import SVPG from pyrado.domain_randomization.domain_parameter import DomainParam from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import Env from pyrado.logger.step import StepLogger from pyrado.policies.base import Policy from pyrado.policies.feed_forward.fnn import FNNPolicy from pyrado.sampling.parallel_evaluation import eval_domain_params from pyrado.sampling.sampler_pool import SamplerPool from pyrado.sampling.step_sequence import StepSequence from pyrado.spaces.box import BoxSpace from pyrado.utils.data_types import EnvSpec from torch import nn as nn from tqdm import tqdm class ADR(Algorithm): """ Active Domain Randomization (ADR) .. seealso:: [1] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, "Active Domain Randomization", arXiv, 2019 """ name: str = "adr" def __init__( self, save_dir: str, env: Env, subrtn: Algorithm, max_iter: int, svpg_particle_hparam: dict, num_svpg_particles: int, num_discriminator_epoch: int, batch_size: int, svpg_learning_rate: float = 3e-4, svpg_temperature: float = 10, svpg_evaluation_steps: int = 10, svpg_horizon: int = 50, svpg_kl_factor: float = 0.03, svpg_warmup: int = 0, svpg_serial: bool = False, num_workers: int = 4, num_trajs_per_config: int = 8, max_step_length: float = 0.05, randomized_params: Sequence[str] = None, logger: Optional[StepLogger] = None, ): """ Constructor :param save_dir: directory to save the snapshots i.e. the results in :param env: the environment to train in :param subrtn: algorithm which performs the policy / value-function optimization :param max_iter: maximum number of iterations :param svpg_particle_hparam: SVPG particle hyperparameters :param num_svpg_particles: number of SVPG particles :param num_discriminator_epoch: epochs in discriminator training :param batch_size: batch size for training :param svpg_learning_rate: SVPG particle optimizers' learning rate :param svpg_temperature: SVPG temperature coefficient (how strong is the influence of the particles on each other) :param svpg_evaluation_steps: how many configurations to sample between training :param svpg_horizon: how many steps until the particles are reset :param svpg_kl_factor: kl reward coefficient :param svpg_warmup: number of iterations without SVPG training in the beginning :param svpg_serial: serial mode (see SVPG) :param num_workers: number of environments for parallel sampling :param num_trajs_per_config: number of trajectories to sample from each config :param max_step_length: maximum change of physics parameters per step :param randomized_params: which parameters to randomize :param logger: logger for every step of the algorithm, if `None` the default logger will be created """ if not isinstance(env, Env): raise pyrado.TypeErr(given=env, expected_type=Env) if not isinstance(subrtn, Algorithm): raise pyrado.TypeErr(given=subrtn, expected_type=Algorithm) if not isinstance(subrtn.policy, Policy): raise pyrado.TypeErr(given=subrtn.policy, expected_type=Policy) # Call Algorithm's constructor super().__init__(save_dir, max_iter, subrtn.policy, logger) self.log_loss = True # Store the inputs self.env = env self._subrtn = subrtn self._subrtn.save_name = "subrtn" self.num_particles = num_svpg_particles self.num_discriminator_epoch = num_discriminator_epoch self.batch_size = batch_size self.num_trajs_per_config = num_trajs_per_config self.warm_up_time = svpg_warmup self.svpg_evaluation_steps = svpg_evaluation_steps self.svpg_temperature = svpg_temperature self.svpg_lr = svpg_learning_rate self.svpg_max_step_length = max_step_length self.svpg_horizon = svpg_horizon self.svpg_kl_factor = svpg_kl_factor self.pool = SamplerPool(num_workers) self.curr_time_step = 0 # Get the number of params if isinstance(randomized_params, list) and len(randomized_params) == 0: randomized_params = inner_env(self.env).get_nominal_domain_param().keys() self.params = [DomainParam(param, 1) for param in randomized_params] self.num_params = len(self.params) # Initialize reward generator self.reward_generator = RewardGenerator( env.spec, self.batch_size, reward_multiplier=1, lr=1e-3, logger=self.logger ) # Initialize logbook self.sim_instances_full_horizon = np.random.random_sample( (self.num_particles, self.svpg_horizon, self.svpg_evaluation_steps, self.num_params) ) # Initialize SVPG self.svpg_wrapper = SVPGAdapter( env, self.params, subrtn.expl_strat, self.reward_generator, horizon=self.svpg_horizon, num_rollouts_per_config=self.num_trajs_per_config, num_workers=num_workers, ) self.svpg = SVPG( save_dir, self.svpg_wrapper, svpg_particle_hparam, max_iter, self.num_particles, self.svpg_temperature, self.svpg_lr, self.svpg_horizon, serial=svpg_serial, num_workers=num_workers, logger=logger, ) self.svpg.save_name = "subrtn_svpg" @property def sample_count(self) -> int: return self._subrtn.sample_count # TODO @Robin: account for multiple particles def compute_params(self, sim_instances: to.Tensor, t: int): """ Computes the parameters :param sim_instances: Physics configurations trajectory :param t: time step to chose :return: parameters at the time """ nominal = self.svpg_wrapper.nominal_dict() keys = nominal.keys() assert len(keys) == sim_instances[t][0].shape[0] params = [] for sim_instance in sim_instances[t]: d = dict() for i, k in enumerate(keys): d[k] = (sim_instance[i] + 0.5) * (nominal[k]) params.append(d) return params def step(self, snapshot_mode: str, meta_info: dict = None, parallel: bool = True): rand_trajs = [] ref_trajs = [] ros = [] visited = [] for i in range(self.svpg.num_particles): done = False svpg_env = self.svpg_wrapper state = svpg_env.reset() states = [] actions = [] rewards = [] infos = [] rand_trajs_now = [] if parallel: with to.no_grad(): for t in range(10): action = ( self.svpg.expl_strats[i](to.as_tensor(state, dtype=to.get_default_dtype())) .detach() .cpu() .numpy() ) state = svpg_env.lite_step(action) states.append(state) actions.append(action) visited.append(states) rewards, rand_trajs_now, ref_trajs_now = svpg_env.eval_states(states) rand_trajs += rand_trajs_now ref_trajs += ref_trajs_now ros.append(StepSequence(observations=states, actions=actions, rewards=rewards)) else: with to.no_grad(): while not done: action = ( self.svpg.expl_strats[i](to.as_tensor(state, dtype=to.get_default_dtype())) .detach() .cpu() .numpy() ) state, reward, done, info = svpg_env.step(action) print(self.params.array_to_dict(state), " => ", reward) states.append(state) rewards.append(reward) actions.append(action) infos.append(info) rand_trajs += info["rand"] ref_trajs += info["ref"] ros.append(StepSequence(observations=states, actions=actions, rewards=rewards)) self.logger.add_value(f"SVPG_agent_{i}_mean_reward", np.mean(rewards)) ros[i].torch(data_type=to.DoubleTensor) for rt in rand_trajs_now: rt.torch(data_type=to.double) rt.observations = rt.observations.double().detach() rt.actions = rt.actions.double().detach() self._subrtn.update(rand_trajs_now) # Logging rets = [ro.undiscounted_return() for ro in rand_trajs] ret_avg = np.mean(rets) ret_med = np.median(rets) ret_std = np.std(rets) self.logger.add_value("avg rollout len", np.mean([ro.length for ro in rand_trajs])) self.logger.add_value("avg return", ret_avg) self.logger.add_value("median return", ret_med) self.logger.add_value("std return", ret_std) # Flatten and combine all randomized and reference trajectories for discriminator flattened_randomized = StepSequence.concat(rand_trajs) flattened_randomized.torch(data_type=to.double) flattened_reference = StepSequence.concat(ref_trajs) flattened_reference.torch(data_type=to.double) self.reward_generator.train(flattened_reference, flattened_randomized, self.num_discriminator_epoch) pyrado.save( self.reward_generator.discriminator, "discriminator", "pt", self.save_dir, meta_info=dict(prefix="adr") ) if self.curr_time_step > self.warm_up_time: # Update the particles # List of lists to comply with interface self.svpg.update(list(map(lambda x: [x], ros))) flattened_randomized.torch(data_type=to.double) flattened_randomized.observations = flattened_randomized.observations.double().detach() flattened_randomized.actions = flattened_randomized.actions.double().detach() # np.save(f'{self.save_dir}actions{self.curr_iter}', flattened_randomized.actions) self.make_snapshot(snapshot_mode, float(ret_avg), meta_info) self._subrtn.make_snapshot(snapshot_mode="best", curr_avg_ret=float(ret_avg)) self.curr_time_step += 1 def save_snapshot(self, meta_info: dict = None): super().save_snapshot(meta_info) if meta_info is None: # This algorithm instance is not a subrtn of another algorithm pyrado.save(self.env, "env", "pkl", self.save_dir, meta_info) self.svpg.save_snapshot(meta_info) else: raise pyrado.ValueErr(msg=f"{self.name} is not supposed be run as a subrtn!") class SVPGAdapter(EnvWrapper, Serializable): """ Wrapper to encapsulate the domain parameter search as a reinforcement learning problem """ def __init__( self, wrapped_env: Env, parameters: Sequence[DomainParam], inner_policy: Policy, discriminator, step_length: float = 0.01, horizon: int = 50, num_rollouts_per_config: int = 8, num_workers: int = 4, ): """ Constructor :param wrapped_env: the environment to wrap :param parameters: which physics parameters should be randomized :param inner_policy: the policy to train the subrtn on :param discriminator: the discriminator to distinguish reference environments from randomized ones :param step_length: the step size :param horizon: an svpg horizon :param num_rollouts_per_config: number of trajectories to sample per physics configuration :param num_workers: number of environments for parallel sampling """ Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) self.parameters: Sequence[DomainParam] = parameters self.pool = SamplerPool(num_workers) self.inner_policy = inner_policy self.svpg_state = None self.count = 0 self.num_trajs = num_rollouts_per_config self.svpg_max_step_length = step_length self.discriminator = discriminator self.max_steps = 8 self._adapter_obs_space = BoxSpace(-np.ones(len(parameters)), np.ones(len(parameters))) self._adapter_act_space = BoxSpace(-np.ones(len(parameters)), np.ones(len(parameters))) self.horizon = horizon self.horizon_count = 0 @property def obs_space(self): return self._adapter_obs_space @property def act_space(self): return self._adapter_act_space def reset(self, init_state: np.ndarray = None, domain_param: dict = None) -> np.ndarray: assert domain_param is None self.count = 0 if init_state is None: self.svpg_state = np.random.random_sample(len(self.parameters)) return self.svpg_state def step(self, act: np.ndarray) -> tuple: # Clip the action according to the maximum step length action = np.clip(act, -1, 1) * self.svpg_max_step_length # Perform step by moving into direction of action self.svpg_state = np.clip(self.svpg_state + action, 0, 1) param_norm = self.svpg_state + 0.5 rand_eval_params = [self.array_to_dict(param_norm * self.nominal())] * self.num_trajs norm_eval_params = [self.nominal_dict()] * self.num_trajs rand = eval_domain_params(self.pool, self.wrapped_env, self.inner_policy, rand_eval_params) ref = eval_domain_params(self.pool, self.wrapped_env, self.inner_policy, norm_eval_params) rewards = [self.discriminator.get_reward(traj) for traj in rand] reward = np.mean(rewards) info = dict(rand=rand, ref=ref) if self.count >= self.max_steps - 1: done = True else: done = False self.count += 1 self.horizon_count += 1 if self.horizon_count >= self.horizon: self.horizon_count = 0 self.svpg_state = np.random.random_sample(len(self.parameters)) return self.svpg_state, reward, done, info def lite_step(self, act: np.ndarray): """ Performs a step without the step interface. This allows for parallel computation of prior steps. :param act: the action to perform :return: the observation after the step """ action = np.clip(act, -1, 1) * self.svpg_max_step_length self.svpg_state = np.clip(self.svpg_state + action, 0, 1) return self.svpg_state def eval_states(self, states: Sequence[np.ndarray]): """ Evaluate the states. :param states: the states to evaluate :return: respective rewards and according trajectories """ flatten = lambda l: [item for sublist in l for item in sublist] sstates = flatten([[self.array_to_dict((state + 0.5) * self.nominal())] * self.num_trajs for state in states]) rand = eval_domain_params(self.pool, self.wrapped_env, self.inner_policy, sstates) ref = eval_domain_params( self.pool, self.wrapped_env, self.inner_policy, [self.nominal_dict()] * (self.num_trajs * len(states)) ) rewards = [self.discriminator.get_reward(traj) for traj in rand] rewards = [np.mean(rewards[i * self.num_trajs : (i + 1) * self.num_trajs]) for i in range(len(states))] return rewards, rand, ref def params(self): return [param.name for param in self.parameters] def nominal(self): return [inner_env(self.wrapped_env).get_nominal_domain_param()[k] for k in self.params()] def nominal_dict(self): return {k: inner_env(self.wrapped_env).get_nominal_domain_param()[k] for k in self.params()} def array_to_dict(self, arr): return {k: a for k, a in zip(self.params(), arr)} class RewardGenerator: """ Class for generating the discriminator rewards in ADR. Generates a reward using a trained discriminator network. """ def __init__( self, env_spec: EnvSpec, batch_size: int, reward_multiplier: float, lr: float = 3e-3, logger: StepLogger = None, device: str = "cuda" if to.cuda.is_available() else "cpu", ): """ Constructor :param env_spec: environment specification :param batch_size: batch size for each update step :param reward_multiplier: factor for the predicted probability :param lr: learning rate :param logger: logger for every step of the algorithm, if `None` the default logger will be created """ self.device = device self.batch_size = batch_size self.reward_multiplier = reward_multiplier self.lr = lr spec = EnvSpec( obs_space=BoxSpace.cat([env_spec.obs_space, env_spec.obs_space, env_spec.act_space]), act_space=BoxSpace(bound_lo=[0], bound_up=[1]), ) self.discriminator = FNNPolicy(spec=spec, hidden_nonlin=to.tanh, hidden_sizes=[62], output_nonlin=to.sigmoid) self.loss_fcn = nn.BCELoss() self.optimizer = to.optim.Adam(self.discriminator.parameters(), lr=lr, eps=1e-5) self.logger = logger def get_reward(self, traj: StepSequence): traj = convert_step_sequence(traj) with to.no_grad(): reward = self.discriminator.forward(traj).cpu() return to.log(reward.mean()) * self.reward_multiplier def train( self, reference_trajectory: StepSequence, randomized_trajectory: StepSequence, num_epoch: int ) -> to.Tensor: reference_batch = reference_trajectory.split_shuffled_batches(self.batch_size) random_batch = randomized_trajectory.split_shuffled_batches(self.batch_size) loss = None for _ in tqdm(range(num_epoch), "Discriminator Epoch", num_epoch): try: reference_batch_now = convert_step_sequence(next(reference_batch)) random_batch_now = convert_step_sequence(next(random_batch)) except StopIteration: break if reference_batch_now.shape[0] < self.batch_size - 1 or random_batch_now.shape[0] < self.batch_size - 1: break random_results = self.discriminator(random_batch_now) reference_results = self.discriminator(reference_batch_now) self.optimizer.zero_grad() loss = self.loss_fcn(random_results, to.ones(self.batch_size - 1, 1)) + self.loss_fcn( reference_results, to.zeros(self.batch_size - 1, 1) ) loss.backward() self.optimizer.step() # Logging if self.logger is not None: self.logger.add_value("discriminator_loss", loss) return loss def convert_step_sequence(trajectory: StepSequence): """ Converts a StepSequence to a Tensor which can be fed through a Network :param trajectory: A step sequence containing a trajectory :return: A Tensor containing the trajectory """ assert isinstance(trajectory, StepSequence) trajectory.torch() state = trajectory.get_data_values("observations")[:-1].double() next_state = trajectory.get_data_values("observations")[1::].double() action = trajectory.get_data_values("actions").narrow(0, 0, next_state.shape[0]).double() trajectory = to.cat((state, next_state, action), 1).cpu().double() return trajectory
[ "numpy.clip", "pyrado.environment_wrappers.base.EnvWrapper.__init__", "torch.cuda.is_available", "pyrado.save", "pyrado.sampling.parallel_evaluation.eval_domain_params", "pyrado.sampling.sampler_pool.SamplerPool", "numpy.mean", "pyrado.ValueErr", "pyrado.TypeErr", "numpy.random.random_sample", "...
[((6251, 6275), 'pyrado.sampling.sampler_pool.SamplerPool', 'SamplerPool', (['num_workers'], {}), '(num_workers)\n', (6262, 6275), False, 'from pyrado.sampling.sampler_pool import SamplerPool\n'), ((6888, 7002), 'numpy.random.random_sample', 'np.random.random_sample', (['(self.num_particles, self.svpg_horizon, self.svpg_evaluation_steps, self.\n num_params)'], {}), '((self.num_particles, self.svpg_horizon, self.\n svpg_evaluation_steps, self.num_params))\n', (6911, 7002), True, 'import numpy as np\n'), ((7365, 7575), 'pyrado.algorithms.step_based.svpg.SVPG', 'SVPG', (['save_dir', 'self.svpg_wrapper', 'svpg_particle_hparam', 'max_iter', 'self.num_particles', 'self.svpg_temperature', 'self.svpg_lr', 'self.svpg_horizon'], {'serial': 'svpg_serial', 'num_workers': 'num_workers', 'logger': 'logger'}), '(save_dir, self.svpg_wrapper, svpg_particle_hparam, max_iter, self.\n num_particles, self.svpg_temperature, self.svpg_lr, self.svpg_horizon,\n serial=svpg_serial, num_workers=num_workers, logger=logger)\n', (7369, 7575), False, 'from pyrado.algorithms.step_based.svpg import SVPG\n'), ((11240, 11253), 'numpy.mean', 'np.mean', (['rets'], {}), '(rets)\n', (11247, 11253), True, 'import numpy as np\n'), ((11272, 11287), 'numpy.median', 'np.median', (['rets'], {}), '(rets)\n', (11281, 11287), True, 'import numpy as np\n'), ((11306, 11318), 'numpy.std', 'np.std', (['rets'], {}), '(rets)\n', (11312, 11318), True, 'import numpy as np\n'), ((11695, 11726), 'pyrado.sampling.step_sequence.StepSequence.concat', 'StepSequence.concat', (['rand_trajs'], {}), '(rand_trajs)\n', (11714, 11726), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((11813, 11843), 'pyrado.sampling.step_sequence.StepSequence.concat', 'StepSequence.concat', (['ref_trajs'], {}), '(ref_trajs)\n', (11832, 11843), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((14388, 14426), 'pyrado.environment_wrappers.base.EnvWrapper.__init__', 'EnvWrapper.__init__', (['self', 'wrapped_env'], {}), '(self, wrapped_env)\n', (14407, 14426), False, 'from pyrado.environment_wrappers.base import EnvWrapper\n'), ((14508, 14532), 'pyrado.sampling.sampler_pool.SamplerPool', 'SamplerPool', (['num_workers'], {}), '(num_workers)\n', (14519, 14532), False, 'from pyrado.sampling.sampler_pool import SamplerPool\n'), ((15758, 15797), 'numpy.clip', 'np.clip', (['(self.svpg_state + action)', '(0)', '(1)'], {}), '(self.svpg_state + action, 0, 1)\n', (15765, 15797), True, 'import numpy as np\n'), ((16016, 16104), 'pyrado.sampling.parallel_evaluation.eval_domain_params', 'eval_domain_params', (['self.pool', 'self.wrapped_env', 'self.inner_policy', 'rand_eval_params'], {}), '(self.pool, self.wrapped_env, self.inner_policy,\n rand_eval_params)\n', (16034, 16104), False, 'from pyrado.sampling.parallel_evaluation import eval_domain_params\n'), ((16115, 16203), 'pyrado.sampling.parallel_evaluation.eval_domain_params', 'eval_domain_params', (['self.pool', 'self.wrapped_env', 'self.inner_policy', 'norm_eval_params'], {}), '(self.pool, self.wrapped_env, self.inner_policy,\n norm_eval_params)\n', (16133, 16203), False, 'from pyrado.sampling.parallel_evaluation import eval_domain_params\n'), ((16290, 16306), 'numpy.mean', 'np.mean', (['rewards'], {}), '(rewards)\n', (16297, 16306), True, 'import numpy as np\n'), ((17083, 17122), 'numpy.clip', 'np.clip', (['(self.svpg_state + action)', '(0)', '(1)'], {}), '(self.svpg_state + action, 0, 1)\n', (17090, 17122), True, 'import numpy as np\n'), ((17581, 17656), 'pyrado.sampling.parallel_evaluation.eval_domain_params', 'eval_domain_params', (['self.pool', 'self.wrapped_env', 'self.inner_policy', 'sstates'], {}), '(self.pool, self.wrapped_env, self.inner_policy, sstates)\n', (17599, 17656), False, 'from pyrado.sampling.parallel_evaluation import eval_domain_params\n'), ((19599, 19691), 'pyrado.policies.feed_forward.fnn.FNNPolicy', 'FNNPolicy', ([], {'spec': 'spec', 'hidden_nonlin': 'to.tanh', 'hidden_sizes': '[62]', 'output_nonlin': 'to.sigmoid'}), '(spec=spec, hidden_nonlin=to.tanh, hidden_sizes=[62],\n output_nonlin=to.sigmoid)\n', (19608, 19691), False, 'from pyrado.policies.feed_forward.fnn import FNNPolicy\n'), ((19712, 19724), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (19722, 19724), True, 'from torch import nn as nn\n'), ((5148, 5192), 'pyrado.TypeErr', 'pyrado.TypeErr', ([], {'given': 'env', 'expected_type': 'Env'}), '(given=env, expected_type=Env)\n', (5162, 5192), False, 'import pyrado\n'), ((5257, 5310), 'pyrado.TypeErr', 'pyrado.TypeErr', ([], {'given': 'subrtn', 'expected_type': 'Algorithm'}), '(given=subrtn, expected_type=Algorithm)\n', (5271, 5310), False, 'import pyrado\n'), ((5379, 5436), 'pyrado.TypeErr', 'pyrado.TypeErr', ([], {'given': 'subrtn.policy', 'expected_type': 'Policy'}), '(given=subrtn.policy, expected_type=Policy)\n', (5393, 5436), False, 'import pyrado\n'), ((6533, 6554), 'pyrado.domain_randomization.domain_parameter.DomainParam', 'DomainParam', (['param', '(1)'], {}), '(param, 1)\n', (6544, 6554), False, 'from pyrado.domain_randomization.domain_parameter import DomainParam\n'), ((11368, 11409), 'numpy.mean', 'np.mean', (['[ro.length for ro in rand_trajs]'], {}), '([ro.length for ro in rand_trajs])\n', (11375, 11409), True, 'import numpy as np\n'), ((13087, 13148), 'pyrado.save', 'pyrado.save', (['self.env', '"""env"""', '"""pkl"""', 'self.save_dir', 'meta_info'], {}), "(self.env, 'env', 'pkl', self.save_dir, meta_info)\n", (13098, 13148), False, 'import pyrado\n'), ((13228, 13299), 'pyrado.ValueErr', 'pyrado.ValueErr', ([], {'msg': 'f"""{self.name} is not supposed be run as a subrtn!"""'}), "(msg=f'{self.name} is not supposed be run as a subrtn!')\n", (13243, 13299), False, 'import pyrado\n'), ((15625, 15644), 'numpy.clip', 'np.clip', (['act', '(-1)', '(1)'], {}), '(act, -1, 1)\n', (15632, 15644), True, 'import numpy as np\n'), ((17009, 17028), 'numpy.clip', 'np.clip', (['act', '(-1)', '(1)'], {}), '(act, -1, 1)\n', (17016, 17028), True, 'import numpy as np\n'), ((17908, 17969), 'numpy.mean', 'np.mean', (['rewards[i * self.num_trajs:(i + 1) * self.num_trajs]'], {}), '(rewards[i * self.num_trajs:(i + 1) * self.num_trajs])\n', (17915, 17969), True, 'import numpy as np\n'), ((18830, 18852), 'torch.cuda.is_available', 'to.cuda.is_available', ([], {}), '()\n', (18850, 18852), True, 'import torch as to\n'), ((19946, 19958), 'torch.no_grad', 'to.no_grad', ([], {}), '()\n', (19956, 19958), True, 'import torch as to\n'), ((10812, 10828), 'numpy.mean', 'np.mean', (['rewards'], {}), '(rewards)\n', (10819, 10828), True, 'import numpy as np\n'), ((19424, 19498), 'pyrado.spaces.box.BoxSpace.cat', 'BoxSpace.cat', (['[env_spec.obs_space, env_spec.obs_space, env_spec.act_space]'], {}), '([env_spec.obs_space, env_spec.obs_space, env_spec.act_space])\n', (19436, 19498), False, 'from pyrado.spaces.box import BoxSpace\n'), ((19522, 19558), 'pyrado.spaces.box.BoxSpace', 'BoxSpace', ([], {'bound_lo': '[0]', 'bound_up': '[1]'}), '(bound_lo=[0], bound_up=[1])\n', (19530, 19558), False, 'from pyrado.spaces.box import BoxSpace\n'), ((9038, 9050), 'torch.no_grad', 'to.no_grad', ([], {}), '()\n', (9048, 9050), True, 'import torch as to\n'), ((9886, 9898), 'torch.no_grad', 'to.no_grad', ([], {}), '()\n', (9896, 9898), True, 'import torch as to\n'), ((21092, 21123), 'torch.ones', 'to.ones', (['(self.batch_size - 1)', '(1)'], {}), '(self.batch_size - 1, 1)\n', (21099, 21123), True, 'import torch as to\n'), ((21177, 21209), 'torch.zeros', 'to.zeros', (['(self.batch_size - 1)', '(1)'], {}), '(self.batch_size - 1, 1)\n', (21185, 21209), True, 'import torch as to\n'), ((22018, 22056), 'torch.cat', 'to.cat', (['(state, next_state, action)', '(1)'], {}), '((state, next_state, action), 1)\n', (22024, 22056), True, 'import torch as to\n'), ((9778, 9845), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'observations': 'states', 'actions': 'actions', 'rewards': 'rewards'}), '(observations=states, actions=actions, rewards=rewards)\n', (9790, 9845), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((10678, 10745), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'observations': 'states', 'actions': 'actions', 'rewards': 'rewards'}), '(observations=states, actions=actions, rewards=rewards)\n', (10690, 10745), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((18155, 18182), 'pyrado.environment_wrappers.utils.inner_env', 'inner_env', (['self.wrapped_env'], {}), '(self.wrapped_env)\n', (18164, 18182), False, 'from pyrado.environment_wrappers.utils import inner_env\n'), ((18285, 18312), 'pyrado.environment_wrappers.utils.inner_env', 'inner_env', (['self.wrapped_env'], {}), '(self.wrapped_env)\n', (18294, 18312), False, 'from pyrado.environment_wrappers.utils import inner_env\n'), ((6456, 6475), 'pyrado.environment_wrappers.utils.inner_env', 'inner_env', (['self.env'], {}), '(self.env)\n', (6465, 6475), False, 'from pyrado.environment_wrappers.utils import inner_env\n'), ((9206, 9228), 'torch.get_default_dtype', 'to.get_default_dtype', ([], {}), '()\n', (9226, 9228), True, 'import torch as to\n'), ((10050, 10072), 'torch.get_default_dtype', 'to.get_default_dtype', ([], {}), '()\n', (10070, 10072), True, 'import torch as to\n')]
# Copyright 2020 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 # # 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. """ General Utilities """ from operator import itemgetter from typing import Any, Generator, KeysView, List, Set, Tuple, TYPE_CHECKING import numpy from fqe.bitstring import lexicographic_bitstring_generator from fqe.bitstring import check_conserved_bits, count_bits if TYPE_CHECKING: #Avoid circular imports and only import for type-checking from fqe import wavefunction def alpha_beta_electrons(nele: int, m_s: int) -> Tuple[int, int]: """Given the total number of electrons and the z-spin quantum number, return the number of alpha and beta electrons in the system. Args: nele (int) - number of electrons m_s (int) - spin angular momentum on the z-axis Return: number of alpha electrons (int), number of beta electrons (int) """ if nele < 0: raise ValueError('Cannot have negative electrons') if nele < abs(m_s): raise ValueError('Spin quantum number exceeds physical limits') nalpha = int(nele + m_s) // 2 nbeta = nele - nalpha return nalpha, nbeta def reverse_bubble_list(arr: List[Any]) -> int: """Bubble Sort algorithm to arrange a list so that the lowest value is stored in 0 and the highest value is stored in len(arr)-1. It is included here in order to access the swap count. Args: arr (list) - object to be sorted Returns: arr (list) - sorted swap_count (int) - number of permutations to achieve the sort """ larr = len(arr) swap_count = 0 for i in range(larr): swapped = False for j in range(0, larr - i - 1): if arr[j][0] < arr[j + 1][0]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True swap_count += 1 if not swapped: break return swap_count def bubblesort(arr: List[Any]) -> int: """Bubble Sort algorithm to arrange a list so that the lowest value is stored in 0 and the highest value is stored in len(arr)-1. It is included here in order to access the swap count. Args: arr (list) - object to be sorted Returns: arr (list) - sorted swap_count (int) - number of permutations to achieve the sort """ larr = len(arr) swap_count = 0 for i in range(larr): swapped = False for j in range(0, larr - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True swap_count += 1 if not swapped: break return swap_count def configuration_key_union(*argv: KeysView[Tuple[int, int]] ) -> List[Tuple[int, int]]: """Given a list of configuration keys, build a list which is the union of all configuration keys in the list Args: *args (list[(int, int)]) - any number of configuration key lists to be joined Returns: list[(int, int)] - a list of unique configuration keys found among all the passed arguments """ keyunion: Set[Tuple[int, int]] = set() for configs in argv: keyunion.update(configs) return list(keyunion) def configuration_key_intersection(*argv: List[Tuple[int, int]] ) -> List[Tuple[int, int]]: """Return the intersection of the passed configuration key lists. Args: *args (list[(int, int)]) - any number of configuration key lists to be joined Returns: list [(int, int)] - a list of configuration keys found in every configuration passed. """ keyinter = argv[0] ref = [] for config in argv[1:]: for key in config: if key in keyinter: ref.append(key) keyinter = ref return keyinter def init_bitstring_groundstate(occ_num: int) -> int: """Occupy the n lowest orbitals of a state in the bitstring representation Args: occ_num (integer) - number of orbitals to occupy Returns: (integer) - bitstring representation of the ground state """ return (1 << occ_num) - 1 def init_qubit_vacuum(nqubits: int) -> numpy.ndarray: """Build the ground state wavefunction for an nqubit system. Args: nqubits (integer) - The number of qubits in the qpu Returns: numpy.array(dtype=numpy.complex64) """ ground_state = numpy.zeros(2**nqubits, dtype=numpy.complex128) ground_state[0] = 1.0 + 0.0j return ground_state def ltlt_index_generator(dim: int ) -> Generator[Tuple[int, int, int, int], None, None]: """Generate index sets into a lower triangle, lower triangle matrix Args: dim (int) - the dimension of the array Returns: (int, int, int, int) - unique pointers into the compressed matrix """ lim = dim for i in range(lim): for j in range(i + 1): for k in range(i + 1): if k == i: _ull = j + 1 else: _ull = k + 1 for lst in range(_ull): yield i, j, k, lst def invert_bitstring_with_mask(string: int, masklen: int) -> int: """Invert a bitstring with a mask. Args: string (bitstring) - the bitstring to invert masklen (int) - the value to mask the inverted bitstring to Returns: (bitstring) - a bitstring inverted up to the masking length """ mask = (1 << masklen) - 1 return ~string & mask def paritysort_int(arr: List[int]) -> Tuple[int, List[int]]: """Move all even numbers to the left and all odd numbers to the right Args: arr list[int] - a list of integers to be sorted Returns: arr [list] - mutated in place swap_count (int) - number of exchanges needed to complete the sorting """ larr = len(arr) parr = [[i % 2, i] for i in arr] swap_count = 0 for i in range(larr): swapped = False for j in range(0, larr - i - 1): if parr[j][0] > parr[j + 1][0]: parr[j], parr[j + 1] = parr[j + 1], parr[j] swapped = True swap_count += 1 if not swapped: break for indx, val in enumerate(parr): arr[indx] = val[1] return swap_count, arr def paritysort_list(arr): """Move all even numbers to the left and all odd numbers to the right Args: arr list[int] - a list of integers to be sorted Returns: arr [list] - mutated in place swap_count (int) - number of exchanges needed to complete the sorting """ larr = len(arr) parr = [[i[0] % 2, i] for i in arr] swap_count = 0 for i in range(larr): swapped = False for j in range(0, larr - i - 1): if parr[j][0] > parr[j + 1][0]: parr[j], parr[j + 1] = parr[j + 1], parr[j] swapped = True swap_count += 1 if not swapped: break for indx, val in enumerate(parr): arr[indx] = list(val[1]) return swap_count, arr def qubit_particle_number_sector(nqubits: int, pnum: int) -> List[numpy.ndarray]: """Generate the basis vectors into the qubit basis representing all states which have a definite particle number. Args: nqubits (int) - the number of qubits in the qpu pnum (int) - the number of particles to build vectors into Returns: list[numpy.array(dtype=numpy.complex64)] """ occ = numpy.array([0, 1], dtype=numpy.int) uno = numpy.array([1, 0], dtype=numpy.int) seed = init_bitstring_groundstate(pnum) pn_set = lexicographic_bitstring_generator(seed, nqubits) vectors = [] for orbocc in pn_set: if orbocc & 1: vec = occ else: vec = uno orbocc = orbocc >> 1 for _ in range(nqubits - 1): if orbocc & 1: vec = numpy.kron(vec, occ) else: vec = numpy.kron(vec, uno) orbocc = orbocc >> 1 vectors.append(vec) return vectors def qubit_config_sector(nqubits: int, pnum: int, m_s: int) -> List[numpy.ndarray]: """Generate the basis vectors into the qubit basis representing all states which have a definite particle number and spin. Args: nqubits (int) - the number of qubits in the qpu pnum (int) - the number of particles to build vectors into m_s (int) - the s_z spin quantum number Returns: list[numpy.array(dtype=numpy.complex64)] """ occ = numpy.array([0, 1], dtype=numpy.int) uno = numpy.array([1, 0], dtype=numpy.int) seed = init_bitstring_groundstate(pnum) achk = 0 bchk = 0 pn_set = [] for num in range(nqubits): if num % 2: bchk += 2**num else: achk += 2**num initpn = lexicographic_bitstring_generator(seed, nqubits) for occu in initpn: if (count_bits(occu & achk) - count_bits(occu & bchk)) == m_s: pn_set.append(occu) vectors = [] for orbocc in pn_set: if orbocc & 1: vec = occ else: vec = uno orbocc = orbocc >> 1 for _ in range(nqubits - 1): if orbocc & 1: vec = numpy.kron(vec, occ) else: vec = numpy.kron(vec, uno) orbocc = orbocc >> 1 vectors.append(vec) return vectors def qubit_particle_number_index(nqubits: int, pnum: int) -> List[int]: """Generate indexes corresponding to the coefficient that is associated with a specific particle number Args: nqubits (int) - the number of qubits to act upon pnum (int) - the number of particles to view Returns: list[int] - integers indicating where in the qubit wavefunction the basis state corresponds to particle number """ seed = init_bitstring_groundstate(pnum) indexes = [] pn_set = lexicographic_bitstring_generator(seed, nqubits) for orbocc in pn_set: if orbocc & 1: index = 1 else: index = 0 orbocc = orbocc >> 1 veclen = 2 for _ in range(nqubits - 1): if orbocc & 1: index = index + veclen orbocc = orbocc >> 1 veclen *= 2 indexes.append(index) return indexes def qubit_particle_number_index_spin(nqubits: int, pnum: int) -> List[Tuple[int, int]]: """Generate indexes corresponding to the coefficient that is associated with a specific particle number and spin Args: nqubits (int) - the number of qubits to act upon pnum (int) - the number of particles to view Returns: list[(int int)] - tuples of integers indicating where in the qubit wavefunction the basis state corresponds to particle number and return the corresponding spin """ seed = init_bitstring_groundstate(pnum) indexes = [] pn_set = lexicographic_bitstring_generator(seed, nqubits) for orbocc in pn_set: totspn = 0 curspn = -1 if orbocc & 1: index = 1 totspn += curspn else: index = 0 orbocc = orbocc >> 1 veclen = 2 for _ in range(nqubits - 1): curspn *= -1 if orbocc & 1: index = index + veclen totspn += curspn orbocc = orbocc >> 1 veclen *= 2 indexes.append((index, totspn)) return indexes def rand_wfn(adim: int, bdim: int) -> numpy.ndarray: """Utility for generating random normalized wavefunctions. Args: adim (int) - length of the alpha string bdim (int) - length of the beta string Returns: numpy.ndarray(shape=(adim, bdim), dtype=numpy.complex64) """ wfn = numpy.random.randn(adim, bdim).astype(numpy.complex128) + \ numpy.random.randn(adim, bdim).astype(numpy.complex128)*1.j return wfn def map_broken_symmetry(s_z, norb): """Create a map between spin broken and number broken wavefunctions. """ spin_to_number = {} nele = norb + s_z maxb = min(norb, nele) minb = nele - maxb for nbeta in range(minb, maxb + 1): nb_beta = norb - nbeta nalpha = nele - nbeta spin_to_number[(nalpha, nb_beta)] = (nele - nbeta, nbeta) return spin_to_number def sort_configuration_keys(configs: KeysView[Tuple[int, int]] ) -> List[Tuple[int, int]]: """Return a standard sorting of configuration keys in a wavefunction for comparison. The configurations are sorted first by the number of particles and then by the spin quantum number. Args: wfn list[(int, int)] - a dictionary of keys Returns: list with the sorted keys """ return sorted(configs, key=itemgetter(0, 1)) def validate_config(nalpha: int, nbeta: int, norb: int) -> None: """ Check that the parameters passed are valid to build a configuration Args: nalpha (int) - the number of alpha electrons nbeta (int) - the number of beta electrons norb (int) - the number of spatial orbitals Returns: nothing - only raises errors if necessary """ if nalpha < 0: raise ValueError("Cannot have negative number of alpha electrons") if nbeta < 0: raise ValueError("Cannot have negative number of beta electrons") if norb < 0: raise ValueError("Cannot have negative number of orbitals") if norb < nalpha or norb < nbeta: raise ValueError("Insufficient number of orbitals") def validate_tuple(matrices) -> None: """Validate that the tuple passed in is valid for initializing a general Hamiltonian """ assert isinstance(matrices, tuple) for rank, term in enumerate(matrices): assert isinstance(term, numpy.ndarray) assert 2 * (rank + 1) == term.ndim def dot(wfn1: 'wavefunction.Wavefunction', wfn2: 'wavefunction.Wavefunction') -> complex: """Calculate the dot product of two wavefunctions. Note that this does not use the conjugate. See vdot for the similar conjugate functionality. Args: wfn1 (wavefunction.Wavefunction) - wavefunction corresponding to the row vector wfn2 (wavefunction.Wavefunction) - wavefunction corresponding to the coumn vector Returns: (complex) - scalar as result of the dot product """ brakeys = wfn1.sectors() ketkeys = wfn2.sectors() keylist = [config for config in brakeys if config in ketkeys] ipval = .0 + .0j for sector in keylist: ipval += numpy.dot( wfn1.get_coeff(sector).flatten(), wfn2.get_coeff(sector).flatten()) return ipval def vdot(wfn1: 'wavefunction.Wavefunction', wfn2: 'wavefunction.Wavefunction') -> complex: """Calculate the inner product of two wavefunctions using conjugation on the elements of wfn1. Args: wfn1 (wavefunction.Wavefunction) - wavefunction corresponding to the conjugate row vector wfn2 (wavefunction.Wavefunction) - wavefunction corresponding to the coumn vector Returns: (complex) - scalar as result of the dot product """ brakeys = wfn1.sectors() ketkeys = wfn2.sectors() keylist = [config for config in brakeys if config in ketkeys] ipval = .0 + .0j for config in keylist: ipval += numpy.vdot( wfn1.get_coeff(config).flatten(), wfn2.get_coeff(config).flatten()) return ipval def zero_transform(string0: int, unocc: int, occ: int, norb: int) -> bool: """Given a bitstring, determine if it satisfies the occupation and nonoccupation conditions necessary to be non zero when a product of creation and annihilation operators are applied. Args: string0 (bitstring) - the occupation representation being acted upon unocc (bitstring) - orbitals which should be unoccupied in string0 occ (bitstring) - orbitals which should be occupied in string0 norb (int) - the number of spatial orbitals for masking the bitstrings Returns: (bool) - true if the transformation is non zero, false if the transformation is zero """ if check_conserved_bits(string0, occ): if check_conserved_bits(invert_bitstring_with_mask(string0, norb), unocc): return False return True
[ "fqe.bitstring.check_conserved_bits", "numpy.kron", "numpy.array", "numpy.zeros", "fqe.bitstring.count_bits", "operator.itemgetter", "fqe.bitstring.lexicographic_bitstring_generator", "numpy.random.randn" ]
[((4988, 5037), 'numpy.zeros', 'numpy.zeros', (['(2 ** nqubits)'], {'dtype': 'numpy.complex128'}), '(2 ** nqubits, dtype=numpy.complex128)\n', (4999, 5037), False, 'import numpy\n'), ((8172, 8208), 'numpy.array', 'numpy.array', (['[0, 1]'], {'dtype': 'numpy.int'}), '([0, 1], dtype=numpy.int)\n', (8183, 8208), False, 'import numpy\n'), ((8219, 8255), 'numpy.array', 'numpy.array', (['[1, 0]'], {'dtype': 'numpy.int'}), '([1, 0], dtype=numpy.int)\n', (8230, 8255), False, 'import numpy\n'), ((8313, 8361), 'fqe.bitstring.lexicographic_bitstring_generator', 'lexicographic_bitstring_generator', (['seed', 'nqubits'], {}), '(seed, nqubits)\n', (8346, 8361), False, 'from fqe.bitstring import lexicographic_bitstring_generator\n'), ((9266, 9302), 'numpy.array', 'numpy.array', (['[0, 1]'], {'dtype': 'numpy.int'}), '([0, 1], dtype=numpy.int)\n', (9277, 9302), False, 'import numpy\n'), ((9313, 9349), 'numpy.array', 'numpy.array', (['[1, 0]'], {'dtype': 'numpy.int'}), '([1, 0], dtype=numpy.int)\n', (9324, 9349), False, 'import numpy\n'), ((9570, 9618), 'fqe.bitstring.lexicographic_bitstring_generator', 'lexicographic_bitstring_generator', (['seed', 'nqubits'], {}), '(seed, nqubits)\n', (9603, 9618), False, 'from fqe.bitstring import lexicographic_bitstring_generator\n'), ((10681, 10729), 'fqe.bitstring.lexicographic_bitstring_generator', 'lexicographic_bitstring_generator', (['seed', 'nqubits'], {}), '(seed, nqubits)\n', (10714, 10729), False, 'from fqe.bitstring import lexicographic_bitstring_generator\n'), ((11752, 11800), 'fqe.bitstring.lexicographic_bitstring_generator', 'lexicographic_bitstring_generator', (['seed', 'nqubits'], {}), '(seed, nqubits)\n', (11785, 11800), False, 'from fqe.bitstring import lexicographic_bitstring_generator\n'), ((17122, 17156), 'fqe.bitstring.check_conserved_bits', 'check_conserved_bits', (['string0', 'occ'], {}), '(string0, occ)\n', (17142, 17156), False, 'from fqe.bitstring import check_conserved_bits, count_bits\n'), ((13647, 13663), 'operator.itemgetter', 'itemgetter', (['(0)', '(1)'], {}), '(0, 1)\n', (13657, 13663), False, 'from operator import itemgetter\n'), ((8601, 8621), 'numpy.kron', 'numpy.kron', (['vec', 'occ'], {}), '(vec, occ)\n', (8611, 8621), False, 'import numpy\n'), ((8662, 8682), 'numpy.kron', 'numpy.kron', (['vec', 'uno'], {}), '(vec, uno)\n', (8672, 8682), False, 'import numpy\n'), ((9655, 9678), 'fqe.bitstring.count_bits', 'count_bits', (['(occu & achk)'], {}), '(occu & achk)\n', (9665, 9678), False, 'from fqe.bitstring import check_conserved_bits, count_bits\n'), ((9681, 9704), 'fqe.bitstring.count_bits', 'count_bits', (['(occu & bchk)'], {}), '(occu & bchk)\n', (9691, 9704), False, 'from fqe.bitstring import check_conserved_bits, count_bits\n'), ((9986, 10006), 'numpy.kron', 'numpy.kron', (['vec', 'occ'], {}), '(vec, occ)\n', (9996, 10006), False, 'import numpy\n'), ((10047, 10067), 'numpy.kron', 'numpy.kron', (['vec', 'uno'], {}), '(vec, uno)\n', (10057, 10067), False, 'import numpy\n'), ((12622, 12652), 'numpy.random.randn', 'numpy.random.randn', (['adim', 'bdim'], {}), '(adim, bdim)\n', (12640, 12652), False, 'import numpy\n'), ((12692, 12722), 'numpy.random.randn', 'numpy.random.randn', (['adim', 'bdim'], {}), '(adim, bdim)\n', (12710, 12722), False, 'import numpy\n')]
import datetime from itertools import combinations import unittest import numpy as np from numpy.testing import assert_array_equal from sdafile.exceptions import BadSDAFile from sdafile.record_inserter import InserterRegistry from sdafile.testing import ( BAD_ATTRS, GOOD_ATTRS, temporary_h5file ) from sdafile.utils import ( CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header ) class TestUtils(unittest.TestCase): def test_are_record_types_equivalent(self): for rt in SUPPORTED_RECORD_TYPES: self.assertTrue(are_record_types_equivalent(rt, rt)) equivalents = [] for rt1, rt2 in combinations(SUPPORTED_RECORD_TYPES, 2): if are_record_types_equivalent(rt1, rt2): equivalents.append(sorted((rt1, rt2))) expected = [] for rt1, rt2 in combinations(STRUCTURE_EQUIVALENT, 2): expected.append(sorted((rt1, rt2))) for rt1, rt2 in combinations(CELL_EQUIVALENT, 2): expected.append(sorted((rt1, rt2))) self.assertEqual(sorted(equivalents), sorted(expected)) def test_are_signatures_equivalent(self): sig = ( ('', 'structure'), ('a', 'numeric'), ('b', 'logical'), ('c', 'character') ) self.assertTrue(are_signatures_equivalent(sig, sig)) self.assertFalse(are_signatures_equivalent(sig, sig[1:])) self.assertFalse(are_signatures_equivalent(sig, sig[::-1])) sig2 = ( ('', 'structure'), ('a', 'numeric'), ('b', 'logical'), ('d', 'character') ) self.assertFalse(are_signatures_equivalent(sig, sig2)) sig3 = ( ('', 'structure'), ('a', 'numeric'), ('b', 'logical'), ('c', 'numeric') ) self.assertFalse(are_signatures_equivalent(sig, sig3)) def test_unnest(self): data = dict(a=1, b=True, c='foo') registry = InserterRegistry() answer = unnest(data, registry) expected = ( ('', 'structure'), ('a', 'numeric'), ('b', 'logical'), ('c', 'character') ) self.assertEqual(answer, expected) self.assertEqual(unnest(1, registry), (('', 'numeric'),)) self.assertEqual(unnest(True, registry), (('', 'logical'),)) self.assertEqual(unnest('foo', registry), (('', 'character'),)) self.assertEqual(unnest([], registry), (('', 'cell'),)) self.assertEqual(unnest({}, registry), (('', 'structure'),)) data = dict( a=1, b=True, c=dict(d='foo', e=5, f=dict(g=6)), h=['hello', np.arange(5)], ) answer = unnest(data, registry) expected = ( ('', 'structure'), ('a', 'numeric'), ('b', 'logical'), ('c', 'structure'), ('h', 'cell'), ('c/d', 'character'), ('c/e', 'numeric'), ('c/f', 'structure'), ('h/element 1', 'character'), ('h/element 2', 'numeric'), ('c/f/g', 'numeric'), ) self.assertEqual(answer, expected) def test_unnest_record(self): with temporary_h5file() as h5file: grp = h5file.create_group('test') set_encoded(grp.attrs, RecordType='structure') sub_grp = grp.create_group('a') set_encoded(sub_grp.attrs, RecordType='numeric') sub_grp = grp.create_group('b') set_encoded(sub_grp.attrs, RecordType='logical') sub_grp = grp.create_group('c') set_encoded(sub_grp.attrs, RecordType='cell') sub_sub_grp = sub_grp.create_group('e') set_encoded(sub_sub_grp.attrs, RecordType='numeric') sub_sub_grp = sub_grp.create_group('f') set_encoded(sub_sub_grp.attrs, RecordType='numeric') sub_grp = grp.create_group('d') set_encoded(sub_grp.attrs, RecordType='character') answer = unnest_record(grp) expected = ( ('', 'structure'), ('a', 'numeric'), ('b', 'logical'), ('c', 'cell'), ('d', 'character'), ('c/e', 'numeric'), ('c/f', 'numeric'), ) self.assertEqual(answer, expected) def test_error_if_bad_attr(self): with temporary_h5file() as h5file: # No attr -> bad with self.assertRaises(BadSDAFile): error_if_bad_attr(h5file, 'foo', lambda value: value == 'foo') # Wrong attr -> bad h5file.attrs['foo'] = b'bar' with self.assertRaises(BadSDAFile): error_if_bad_attr(h5file, 'foo', lambda value: value == 'foo') # Right attr -> good h5file.attrs['foo'] = b'foo' error_if_bad_attr(h5file, 'foo', lambda value: value == 'foo') def test_error_if_bad_header(self): with temporary_h5file() as h5file: attrs = h5file.attrs # Write a good header for attr, value in GOOD_ATTRS.items(): attrs[attr] = value.encode('ascii') error_if_not_writable(h5file) # Check each bad value for attr, value in BAD_ATTRS.items(): attrs[attr] = value.encode('ascii') with self.assertRaises(BadSDAFile): error_if_bad_header(h5file) def test_error_if_not_writable(self): with temporary_h5file() as h5file: h5file.attrs['Writable'] = b'yes' error_if_not_writable(h5file) h5file.attrs['Writable'] = b'no' with self.assertRaises(IOError): error_if_not_writable(h5file) def test_get_date_str(self): dt = datetime.datetime(2017, 8, 18, 2, 22, 11) date_str = get_date_str(dt) self.assertEqual(date_str, '18-Aug-2017 02:22:11') dt = datetime.datetime(2017, 8, 18, 1, 1, 1) date_str = get_date_str(dt) self.assertEqual(date_str, '18-Aug-2017 01:01:01') dt = datetime.datetime(2017, 8, 18, 0, 0, 0) date_str = get_date_str(dt) self.assertEqual(date_str, '18-Aug-2017') date_str = get_date_str() # valid without arguments def test_get_empty_for_type(self): self.assertEqual('', get_empty_for_type('character')) assert_array_equal( np.array([], dtype=bool), get_empty_for_type('logical') ) self.assertEqual(get_empty_for_type('file'), b'') self.assertTrue(np.isnan(get_empty_for_type('numeric'))) self.assertEqual(get_empty_for_type('cell'), []) self.assertEqual(get_empty_for_type('structure'), {}) def test_is_valid_date(self): self.assertTrue(is_valid_date('18-Aug-2017 02:22:11')) self.assertTrue(is_valid_date('18-Aug-2017')) self.assertFalse(is_valid_date('2017-01-01 01:23:45')) def test_is_valid_file_format(self): self.assertTrue(is_valid_file_format('SDA')) self.assertFalse(is_valid_file_format('sda')) self.assertFalse(is_valid_file_format('SDB')) def test_is_valid_format_version(self): self.assertTrue(is_valid_format_version('1.0')) self.assertTrue(is_valid_format_version('1.1')) self.assertFalse(is_valid_format_version('1.2')) self.assertFalse(is_valid_format_version('0.2')) self.assertFalse(is_valid_format_version('2.0')) def test_is_valid_matlab_field_label(self): self.assertTrue(is_valid_matlab_field_label('a0n1')) self.assertTrue(is_valid_matlab_field_label('a0n1999999')) self.assertTrue(is_valid_matlab_field_label('a0_n1')) self.assertTrue(is_valid_matlab_field_label('a0_N1')) self.assertTrue(is_valid_matlab_field_label('A0_N1')) self.assertFalse(is_valid_matlab_field_label('')) self.assertFalse(is_valid_matlab_field_label(' ')) self.assertFalse(is_valid_matlab_field_label('1n0a')) self.assertFalse(is_valid_matlab_field_label('A0 N1')) self.assertFalse(is_valid_matlab_field_label('_A0N1')) self.assertFalse(is_valid_matlab_field_label(' a0n1')) self.assertFalse(is_valid_matlab_field_label(' A0N1')) def test_is_valid_writable(self): self.assertTrue(is_valid_writable('yes')) self.assertTrue(is_valid_writable('no')) self.assertFalse(is_valid_writable('YES')) self.assertFalse(is_valid_writable('NO')) self.assertFalse(is_valid_writable(True)) self.assertFalse(is_valid_writable(False)) def test_get_decoded(self): attrs = {'a': b'foo', 'b': b'bar', 'c': 9} decoded = get_decoded(attrs, 'a', 'c', 'd') self.assertEqual(sorted(decoded.keys()), ['a', 'c']) self.assertEqual(decoded['a'], 'foo') self.assertEqual(decoded['c'], 9) # Get everything decoded = get_decoded(attrs) self.assertEqual(sorted(decoded.keys()), ['a', 'b', 'c']) self.assertEqual(decoded['a'], 'foo') self.assertEqual(decoded['b'], 'bar') self.assertEqual(decoded['c'], 9) def test_set_encoded(self): encoded = {} set_encoded(encoded, a='foo', b='bar', c=9) self.assertEqual(sorted(encoded.keys()), ['a', 'b', 'c']) self.assertEqual(encoded['a'], b'foo') self.assertEqual(encoded['b'], b'bar') self.assertEqual(encoded['c'], 9) def test_update_header(self): attrs = {} update_header(attrs) self.assertEqual(len(attrs), 2) self.assertEqual(attrs['FormatVersion'], b'1.1') self.assertIsNotNone(attrs['Updated']) def test_write_header(self): attrs = {} write_header(attrs) self.assertEqual(len(attrs), 5) self.assertEqual(attrs['FileFormat'], b'SDA') self.assertEqual(attrs['FormatVersion'], b'1.1') self.assertEqual(attrs['Writable'], b'yes') self.assertEqual(attrs['Created'], attrs['Updated']) self.assertIsNotNone(attrs['Updated'])
[ "sdafile.utils.is_valid_matlab_field_label", "sdafile.record_inserter.InserterRegistry", "sdafile.utils.is_valid_format_version", "sdafile.utils.write_header", "numpy.array", "sdafile.utils.is_valid_date", "sdafile.utils.is_valid_file_format", "numpy.arange", "sdafile.utils.get_empty_for_type", "d...
[((1006, 1045), 'itertools.combinations', 'combinations', (['SUPPORTED_RECORD_TYPES', '(2)'], {}), '(SUPPORTED_RECORD_TYPES, 2)\n', (1018, 1045), False, 'from itertools import combinations\n'), ((1203, 1240), 'itertools.combinations', 'combinations', (['STRUCTURE_EQUIVALENT', '(2)'], {}), '(STRUCTURE_EQUIVALENT, 2)\n', (1215, 1240), False, 'from itertools import combinations\n'), ((1315, 1347), 'itertools.combinations', 'combinations', (['CELL_EQUIVALENT', '(2)'], {}), '(CELL_EQUIVALENT, 2)\n', (1327, 1347), False, 'from itertools import combinations\n'), ((2366, 2384), 'sdafile.record_inserter.InserterRegistry', 'InserterRegistry', ([], {}), '()\n', (2382, 2384), False, 'from sdafile.record_inserter import InserterRegistry\n'), ((2402, 2424), 'sdafile.utils.unnest', 'unnest', (['data', 'registry'], {}), '(data, registry)\n', (2408, 2424), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((3110, 3132), 'sdafile.utils.unnest', 'unnest', (['data', 'registry'], {}), '(data, registry)\n', (3116, 3132), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((6263, 6304), 'datetime.datetime', 'datetime.datetime', (['(2017)', '(8)', '(18)', '(2)', '(22)', '(11)'], {}), '(2017, 8, 18, 2, 22, 11)\n', (6280, 6304), False, 'import datetime\n'), ((6324, 6340), 'sdafile.utils.get_date_str', 'get_date_str', (['dt'], {}), '(dt)\n', (6336, 6340), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((6414, 6453), 'datetime.datetime', 'datetime.datetime', (['(2017)', '(8)', '(18)', '(1)', '(1)', '(1)'], {}), '(2017, 8, 18, 1, 1, 1)\n', (6431, 6453), False, 'import datetime\n'), ((6473, 6489), 'sdafile.utils.get_date_str', 'get_date_str', (['dt'], {}), '(dt)\n', (6485, 6489), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((6563, 6602), 'datetime.datetime', 'datetime.datetime', (['(2017)', '(8)', '(18)', '(0)', '(0)', '(0)'], {}), '(2017, 8, 18, 0, 0, 0)\n', (6580, 6602), False, 'import datetime\n'), ((6622, 6638), 'sdafile.utils.get_date_str', 'get_date_str', (['dt'], {}), '(dt)\n', (6634, 6638), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((6709, 6723), 'sdafile.utils.get_date_str', 'get_date_str', ([], {}), '()\n', (6721, 6723), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((9183, 9216), 'sdafile.utils.get_decoded', 'get_decoded', (['attrs', '"""a"""', '"""c"""', '"""d"""'], {}), "(attrs, 'a', 'c', 'd')\n", (9194, 9216), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((9410, 9428), 'sdafile.utils.get_decoded', 'get_decoded', (['attrs'], {}), '(attrs)\n', (9421, 9428), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((9691, 9734), 'sdafile.utils.set_encoded', 'set_encoded', (['encoded'], {'a': '"""foo"""', 'b': '"""bar"""', 'c': '(9)'}), "(encoded, a='foo', b='bar', c=9)\n", (9702, 9734), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((9999, 10019), 'sdafile.utils.update_header', 'update_header', (['attrs'], {}), '(attrs)\n', (10012, 10019), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((10225, 10244), 'sdafile.utils.write_header', 'write_header', (['attrs'], {}), '(attrs)\n', (10237, 10244), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((1062, 1099), 'sdafile.utils.are_record_types_equivalent', 'are_record_types_equivalent', (['rt1', 'rt2'], {}), '(rt1, rt2)\n', (1089, 1099), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((1682, 1717), 'sdafile.utils.are_signatures_equivalent', 'are_signatures_equivalent', (['sig', 'sig'], {}), '(sig, sig)\n', (1707, 1717), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((1744, 1783), 'sdafile.utils.are_signatures_equivalent', 'are_signatures_equivalent', (['sig', 'sig[1:]'], {}), '(sig, sig[1:])\n', (1769, 1783), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((1810, 1851), 'sdafile.utils.are_signatures_equivalent', 'are_signatures_equivalent', (['sig', 'sig[::-1]'], {}), '(sig, sig[::-1])\n', (1835, 1851), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((2028, 2064), 'sdafile.utils.are_signatures_equivalent', 'are_signatures_equivalent', (['sig', 'sig2'], {}), '(sig, sig2)\n', (2053, 2064), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((2239, 2275), 'sdafile.utils.are_signatures_equivalent', 'are_signatures_equivalent', (['sig', 'sig3'], {}), '(sig, sig3)\n', (2264, 2275), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((2647, 2666), 'sdafile.utils.unnest', 'unnest', (['(1)', 'registry'], {}), '(1, registry)\n', (2653, 2666), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((2713, 2735), 'sdafile.utils.unnest', 'unnest', (['(True)', 'registry'], {}), '(True, registry)\n', (2719, 2735), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((2782, 2805), 'sdafile.utils.unnest', 'unnest', (['"""foo"""', 'registry'], {}), "('foo', registry)\n", (2788, 2805), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((2854, 2874), 'sdafile.utils.unnest', 'unnest', (['[]', 'registry'], {}), '([], registry)\n', (2860, 2874), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((2918, 2938), 'sdafile.utils.unnest', 'unnest', (['{}', 'registry'], {}), '({}, registry)\n', (2924, 2938), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((3621, 3639), 'sdafile.testing.temporary_h5file', 'temporary_h5file', ([], {}), '()\n', (3637, 3639), False, 'from sdafile.testing import BAD_ATTRS, GOOD_ATTRS, temporary_h5file\n'), ((3709, 3755), 'sdafile.utils.set_encoded', 'set_encoded', (['grp.attrs'], {'RecordType': '"""structure"""'}), "(grp.attrs, RecordType='structure')\n", (3720, 3755), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((3812, 3860), 'sdafile.utils.set_encoded', 'set_encoded', (['sub_grp.attrs'], {'RecordType': '"""numeric"""'}), "(sub_grp.attrs, RecordType='numeric')\n", (3823, 3860), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((3917, 3965), 'sdafile.utils.set_encoded', 'set_encoded', (['sub_grp.attrs'], {'RecordType': '"""logical"""'}), "(sub_grp.attrs, RecordType='logical')\n", (3928, 3965), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((4022, 4067), 'sdafile.utils.set_encoded', 'set_encoded', (['sub_grp.attrs'], {'RecordType': '"""cell"""'}), "(sub_grp.attrs, RecordType='cell')\n", (4033, 4067), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((4132, 4184), 'sdafile.utils.set_encoded', 'set_encoded', (['sub_sub_grp.attrs'], {'RecordType': '"""numeric"""'}), "(sub_sub_grp.attrs, RecordType='numeric')\n", (4143, 4184), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((4249, 4301), 'sdafile.utils.set_encoded', 'set_encoded', (['sub_sub_grp.attrs'], {'RecordType': '"""numeric"""'}), "(sub_sub_grp.attrs, RecordType='numeric')\n", (4260, 4301), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((4358, 4408), 'sdafile.utils.set_encoded', 'set_encoded', (['sub_grp.attrs'], {'RecordType': '"""character"""'}), "(sub_grp.attrs, RecordType='character')\n", (4369, 4408), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((4431, 4449), 'sdafile.utils.unnest_record', 'unnest_record', (['grp'], {}), '(grp)\n', (4444, 4449), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((4830, 4848), 'sdafile.testing.temporary_h5file', 'temporary_h5file', ([], {}), '()\n', (4846, 4848), False, 'from sdafile.testing import BAD_ATTRS, GOOD_ATTRS, temporary_h5file\n'), ((5305, 5367), 'sdafile.utils.error_if_bad_attr', 'error_if_bad_attr', (['h5file', '"""foo"""', "(lambda value: value == 'foo')"], {}), "(h5file, 'foo', lambda value: value == 'foo')\n", (5322, 5367), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((5422, 5440), 'sdafile.testing.temporary_h5file', 'temporary_h5file', ([], {}), '()\n', (5438, 5440), False, 'from sdafile.testing import BAD_ATTRS, GOOD_ATTRS, temporary_h5file\n'), ((5552, 5570), 'sdafile.testing.GOOD_ATTRS.items', 'GOOD_ATTRS.items', ([], {}), '()\n', (5568, 5570), False, 'from sdafile.testing import BAD_ATTRS, GOOD_ATTRS, temporary_h5file\n'), ((5636, 5665), 'sdafile.utils.error_if_not_writable', 'error_if_not_writable', (['h5file'], {}), '(h5file)\n', (5657, 5665), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((5733, 5750), 'sdafile.testing.BAD_ATTRS.items', 'BAD_ATTRS.items', ([], {}), '()\n', (5748, 5750), False, 'from sdafile.testing import BAD_ATTRS, GOOD_ATTRS, temporary_h5file\n'), ((5961, 5979), 'sdafile.testing.temporary_h5file', 'temporary_h5file', ([], {}), '()\n', (5977, 5979), False, 'from sdafile.testing import BAD_ATTRS, GOOD_ATTRS, temporary_h5file\n'), ((6049, 6078), 'sdafile.utils.error_if_not_writable', 'error_if_not_writable', (['h5file'], {}), '(h5file)\n', (6070, 6078), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((6820, 6851), 'sdafile.utils.get_empty_for_type', 'get_empty_for_type', (['"""character"""'], {}), "('character')\n", (6838, 6851), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((6893, 6917), 'numpy.array', 'np.array', (['[]'], {'dtype': 'bool'}), '([], dtype=bool)\n', (6901, 6917), True, 'import numpy as np\n'), ((6919, 6948), 'sdafile.utils.get_empty_for_type', 'get_empty_for_type', (['"""logical"""'], {}), "('logical')\n", (6937, 6948), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((6984, 7010), 'sdafile.utils.get_empty_for_type', 'get_empty_for_type', (['"""file"""'], {}), "('file')\n", (7002, 7010), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7107, 7133), 'sdafile.utils.get_empty_for_type', 'get_empty_for_type', (['"""cell"""'], {}), "('cell')\n", (7125, 7133), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7164, 7195), 'sdafile.utils.get_empty_for_type', 'get_empty_for_type', (['"""structure"""'], {}), "('structure')\n", (7182, 7195), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7260, 7297), 'sdafile.utils.is_valid_date', 'is_valid_date', (['"""18-Aug-2017 02:22:11"""'], {}), "('18-Aug-2017 02:22:11')\n", (7273, 7297), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7323, 7351), 'sdafile.utils.is_valid_date', 'is_valid_date', (['"""18-Aug-2017"""'], {}), "('18-Aug-2017')\n", (7336, 7351), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7378, 7414), 'sdafile.utils.is_valid_date', 'is_valid_date', (['"""2017-01-01 01:23:45"""'], {}), "('2017-01-01 01:23:45')\n", (7391, 7414), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7482, 7509), 'sdafile.utils.is_valid_file_format', 'is_valid_file_format', (['"""SDA"""'], {}), "('SDA')\n", (7502, 7509), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7536, 7563), 'sdafile.utils.is_valid_file_format', 'is_valid_file_format', (['"""sda"""'], {}), "('sda')\n", (7556, 7563), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7590, 7617), 'sdafile.utils.is_valid_file_format', 'is_valid_file_format', (['"""SDB"""'], {}), "('SDB')\n", (7610, 7617), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7688, 7718), 'sdafile.utils.is_valid_format_version', 'is_valid_format_version', (['"""1.0"""'], {}), "('1.0')\n", (7711, 7718), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7744, 7774), 'sdafile.utils.is_valid_format_version', 'is_valid_format_version', (['"""1.1"""'], {}), "('1.1')\n", (7767, 7774), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7801, 7831), 'sdafile.utils.is_valid_format_version', 'is_valid_format_version', (['"""1.2"""'], {}), "('1.2')\n", (7824, 7831), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7858, 7888), 'sdafile.utils.is_valid_format_version', 'is_valid_format_version', (['"""0.2"""'], {}), "('0.2')\n", (7881, 7888), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7915, 7945), 'sdafile.utils.is_valid_format_version', 'is_valid_format_version', (['"""2.0"""'], {}), "('2.0')\n", (7938, 7945), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8020, 8055), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['"""a0n1"""'], {}), "('a0n1')\n", (8047, 8055), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8081, 8122), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['"""a0n1999999"""'], {}), "('a0n1999999')\n", (8108, 8122), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8148, 8184), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['"""a0_n1"""'], {}), "('a0_n1')\n", (8175, 8184), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8210, 8246), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['"""a0_N1"""'], {}), "('a0_N1')\n", (8237, 8246), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8272, 8308), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['"""A0_N1"""'], {}), "('A0_N1')\n", (8299, 8308), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8335, 8366), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['""""""'], {}), "('')\n", (8362, 8366), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8393, 8425), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['""" """'], {}), "(' ')\n", (8420, 8425), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8452, 8487), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['"""1n0a"""'], {}), "('1n0a')\n", (8479, 8487), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8514, 8550), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['"""A0 N1"""'], {}), "('A0 N1')\n", (8541, 8550), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8577, 8613), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['"""_A0N1"""'], {}), "('_A0N1')\n", (8604, 8613), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8640, 8676), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['""" a0n1"""'], {}), "(' a0n1')\n", (8667, 8676), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8703, 8739), 'sdafile.utils.is_valid_matlab_field_label', 'is_valid_matlab_field_label', (['""" A0N1"""'], {}), "(' A0N1')\n", (8730, 8739), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8804, 8828), 'sdafile.utils.is_valid_writable', 'is_valid_writable', (['"""yes"""'], {}), "('yes')\n", (8821, 8828), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8854, 8877), 'sdafile.utils.is_valid_writable', 'is_valid_writable', (['"""no"""'], {}), "('no')\n", (8871, 8877), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8904, 8928), 'sdafile.utils.is_valid_writable', 'is_valid_writable', (['"""YES"""'], {}), "('YES')\n", (8921, 8928), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((8955, 8978), 'sdafile.utils.is_valid_writable', 'is_valid_writable', (['"""NO"""'], {}), "('NO')\n", (8972, 8978), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((9005, 9028), 'sdafile.utils.is_valid_writable', 'is_valid_writable', (['(True)'], {}), '(True)\n', (9022, 9028), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((9055, 9079), 'sdafile.utils.is_valid_writable', 'is_valid_writable', (['(False)'], {}), '(False)\n', (9072, 9079), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((919, 954), 'sdafile.utils.are_record_types_equivalent', 'are_record_types_equivalent', (['rt', 'rt'], {}), '(rt, rt)\n', (946, 954), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((4954, 5016), 'sdafile.utils.error_if_bad_attr', 'error_if_bad_attr', (['h5file', '"""foo"""', "(lambda value: value == 'foo')"], {}), "(h5file, 'foo', lambda value: value == 'foo')\n", (4971, 5016), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((5155, 5217), 'sdafile.utils.error_if_bad_attr', 'error_if_bad_attr', (['h5file', '"""foo"""', "(lambda value: value == 'foo')"], {}), "(h5file, 'foo', lambda value: value == 'foo')\n", (5172, 5217), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((6186, 6215), 'sdafile.utils.error_if_not_writable', 'error_if_not_writable', (['h5file'], {}), '(h5file)\n', (6207, 6215), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((7050, 7079), 'sdafile.utils.get_empty_for_type', 'get_empty_for_type', (['"""numeric"""'], {}), "('numeric')\n", (7068, 7079), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n'), ((3068, 3080), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (3077, 3080), True, 'import numpy as np\n'), ((5877, 5904), 'sdafile.utils.error_if_bad_header', 'error_if_bad_header', (['h5file'], {}), '(h5file)\n', (5896, 5904), False, 'from sdafile.utils import CELL_EQUIVALENT, STRUCTURE_EQUIVALENT, SUPPORTED_RECORD_TYPES, are_record_types_equivalent, are_signatures_equivalent, error_if_bad_attr, error_if_bad_header, error_if_not_writable, get_date_str, get_decoded, get_empty_for_type, is_valid_date, is_valid_file_format, is_valid_format_version, is_valid_matlab_field_label, is_valid_writable, set_encoded, unnest, unnest_record, update_header, write_header\n')]
#!/usr/bin/env python # coding: utf-8 # In[28]: import pandas as pd import numpy as np import os from datetime import date import itertools cols = ["Resource","CustomAttr15","Summary","LastOccurrence","CustomAttr11"] #Range [A-E] single = os.getcwd() + "\\" + "single.csv" dff = pd.read_csv(single) df = dff[cols] print(df) # # Numpy # In[29]: arr = df.to_numpy() #convert df to np print(arr[0][0]) #printing an index value of numpy arr rw, col = arr.shape #last row, last column print(rw,col) #loop and access lst = [] dic = {} for i in range(rw): lst2 = [] for j in range(col): #print(arr[i][j]) #print Row by index lst2.append(arr[i][j]) #create a list dic.update( {i : lst2} ) #create dict #print(dic) # In[31]: #add new column derived from existing one lst3 = [] for i in range(rw): x = arr[i][2] #only printing summary if 'DOWN' in x: lst3.append('down') else: lst3.append('no') arr = np.append(arr, np.array([lst3]).transpose(), axis=1) df = pd.DataFrame(arr) print(df) # # List # In[ ]: #derived list from df dff = pd.Series(df['CustomAttr15']) mlst1 = dff.to_list() mlst2 = df.values.tolist() mlst3 = df.columns.values.tolist() mlst4 = df['Summary'].values.tolist() mlst5 = df[['Summary','LastOccurrence']].values.tolist() #print(mlst4) def lp_1d_list(mlst1): i = 0 for i in range(len(mlst1)): print(mlst1[i]) i = i + 1 def lp_nested_seperate_2_list(mlst1,mlst4): for a in mlst1: for b in mlst4: print(a,">",b) def lp_nested_list(mlst2): for i in range(len(mlst2)): for j in range(len(mlst2[i])): print(mlst2[i][j]) # List Methods append(), count(), index(), pop(), sort() fruits = ['apple', 'banana', 'cherry','banana'] fruits.append("orange") print(fruits) print(fruits.count("banana")) print(fruits.index("cherry")) fruits = ['apple', 'banana', 'cherry'] cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) print(fruits) #JOIN 2 LIST fruits = fruits.pop(1) print(fruits) # # dictionary # In[ ]: dic1 = {} dic2 = {1: 'apple', 2: 'ball'} dic3 = {'name': 'John', 1: [2, 4, 3]} dic4 = dict({1:'apple', 2:'ball'}) dic5 = dict([(1,'apple'), (2,'ball')]) #create dictionary from 2 list (as key , as value) dlist = dict(zip(mlst1, mlst5)) #print(dlist) #dataframe to dictionary ddf1 = df.to_dict() def lp_dic(): for key in ddf1: print(key,ddf1[key]) for v in ddf1.values(): print(v) def lp_key_wise(dl): for k,v in dlist.items(): print("STCODE:", k, ":", v[0],',', v[1]) lp_key_wise(dlist) #Method of Dictionary fromkeys(), get(), items(), keys(), values(), pop(), update() person = {'name': 'Phill', 'age': 22} #print(person.get('name')) d = {1: "one", 2: "three"} d1 = {2: "two"} d.update(d1) #print(d) person = {'name': 'Phill'} person.setdefault('age', 22) #print(person) # In[ ]: # In[ ]: # In[ ]:
[ "pandas.Series", "pandas.read_csv", "os.getcwd", "numpy.array", "pandas.DataFrame" ]
[((283, 302), 'pandas.read_csv', 'pd.read_csv', (['single'], {}), '(single)\n', (294, 302), True, 'import pandas as pd\n'), ((1027, 1044), 'pandas.DataFrame', 'pd.DataFrame', (['arr'], {}), '(arr)\n', (1039, 1044), True, 'import pandas as pd\n'), ((1106, 1135), 'pandas.Series', 'pd.Series', (["df['CustomAttr15']"], {}), "(df['CustomAttr15'])\n", (1115, 1135), True, 'import pandas as pd\n'), ((243, 254), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (252, 254), False, 'import os\n'), ((984, 1000), 'numpy.array', 'np.array', (['[lst3]'], {}), '([lst3])\n', (992, 1000), True, 'import numpy as np\n')]
import os import sys import time import numpy as np from utils.config import * from utils.util import * def usage(): print("====================================================================================================================") print("python <this script> samplesDir experimentRootDir modelsDir numOfSamples testResultFoldName datasetName numOfClasses sampleType") print("====================================================================================================================") if len(sys.argv) != 9: usage() exit(1) samplesDir = sys.argv[1] experimentRootDir = sys.argv[2] modelsDir = sys.argv[3] numOfSamples = int(sys.argv[4]) testResultFoldName = sys.argv[5] datasetName = sys.argv[6] numOfClasses = int(sys.argv[7]) sampleType = sys.argv[8] DATA.set_current_dataset_name(datasetName) AETypes = ATTACK.get_AETypes() # Basic parameters for k-fold experiment setup architecture = MODEL.ARCHITECTURE testDir = os.path.join(experimentRootDir, testResultFoldName) createDirSafely(testDir) sampleTypes =["BS"] sampleTypes.extend(AETypes) print("[sample types]: {}\n".format(len(sampleTypes))) print(sampleTypes) targetModelName = "clean" transformConfig = TRANSFORMATION() transformationList = transformConfig.supported_types() predictionResultDir = os.path.join(testDir, "prediction_result") createDirSafely(predictionResultDir) # Prediction : needs a new prediction function predictionForTest0( predictionResultDir, datasetName, architecture, numOfClasses, targetModelName, modelsDir, samplesDir, numOfSamples, sampleTypes, transformationList) labels = np.load(os.path.join(samplesDir, "Label-"+datasetName+"-clean.npy")) labels = np.argmax(labels, axis=1) for sampleType in sampleTypes: predDir = os.path.join(predictionResultDir, sampleType) predProb = np.load(os.path.join(predDir, "predProb.npy")) modelsAcc = calAccuracyAllSingleModels(labels, predProb) with open(os.path.join(predictionResultDir, sampleType+"-accuracy.txt"), "w") as fp: for i in range(len(transformationList)): fp.write("{}\t{}\t{}\n".format(i, transformationList[i], modelsAcc[i])) with open(os.path.join(predictionResultDir, datasetName+"_SingleModelAccuracy.txt"), "w") as fp: nST = len(sampleTypes) nMs = len(transformationList) # clean model corresponds to index 0 accs = np.zeros((nMs, nST)) for sIdx in range(nST): sampleType = sampleTypes[sIdx] predDir = os.path.join(predictionResultDir, sampleType) predProb = np.load(os.path.join(predDir, "predProb.npy")) accs[:, sIdx] = calAccuracyAllSingleModels(labels, predProb) fp.write("{}\t{}\t".format("ID", "Transformation")) for sIdx in range(nST): fp.write("{}\t".format(sampleTypes[sIdx])) fp.write("\n") for i in range(nMs): fp.write("{}\t{}\t".format(i, transformationList[i])) for j in range(nST): fp.write("{}\t".format(accs[i,j])) fp.write("\n")
[ "numpy.zeros", "os.path.join", "numpy.argmax" ]
[((1020, 1071), 'os.path.join', 'os.path.join', (['experimentRootDir', 'testResultFoldName'], {}), '(experimentRootDir, testResultFoldName)\n', (1032, 1071), False, 'import os\n'), ((1361, 1403), 'os.path.join', 'os.path.join', (['testDir', '"""prediction_result"""'], {}), "(testDir, 'prediction_result')\n", (1373, 1403), False, 'import os\n'), ((1826, 1851), 'numpy.argmax', 'np.argmax', (['labels'], {'axis': '(1)'}), '(labels, axis=1)\n', (1835, 1851), True, 'import numpy as np\n'), ((1756, 1819), 'os.path.join', 'os.path.join', (['samplesDir', "('Label-' + datasetName + '-clean.npy')"], {}), "(samplesDir, 'Label-' + datasetName + '-clean.npy')\n", (1768, 1819), False, 'import os\n'), ((1898, 1943), 'os.path.join', 'os.path.join', (['predictionResultDir', 'sampleType'], {}), '(predictionResultDir, sampleType)\n', (1910, 1943), False, 'import os\n'), ((2497, 2517), 'numpy.zeros', 'np.zeros', (['(nMs, nST)'], {}), '((nMs, nST))\n', (2505, 2517), True, 'import numpy as np\n'), ((1967, 2004), 'os.path.join', 'os.path.join', (['predDir', '"""predProb.npy"""'], {}), "(predDir, 'predProb.npy')\n", (1979, 2004), False, 'import os\n'), ((2301, 2376), 'os.path.join', 'os.path.join', (['predictionResultDir', "(datasetName + '_SingleModelAccuracy.txt')"], {}), "(predictionResultDir, datasetName + '_SingleModelAccuracy.txt')\n", (2313, 2376), False, 'import os\n'), ((2603, 2648), 'os.path.join', 'os.path.join', (['predictionResultDir', 'sampleType'], {}), '(predictionResultDir, sampleType)\n', (2615, 2648), False, 'import os\n'), ((2081, 2144), 'os.path.join', 'os.path.join', (['predictionResultDir', "(sampleType + '-accuracy.txt')"], {}), "(predictionResultDir, sampleType + '-accuracy.txt')\n", (2093, 2144), False, 'import os\n'), ((2676, 2713), 'os.path.join', 'os.path.join', (['predDir', '"""predProb.npy"""'], {}), "(predDir, 'predProb.npy')\n", (2688, 2713), False, 'import os\n')]
__author__ = 'Mariusz' from pyltes import devices import numpy as np import matplotlib.pyplot as plt import matplotlib import math class Printer: """Class that prints network deployment""" def __init__(self,parent): self.parent = parent self.tilesInLine = 100 self.imageMatrixValid = False self.fillMethod = "SINR" self.imageMatrix = np.zeros((self.tilesInLine, self.tilesInLine)) def drawHistogramOfUEThroughput(self, filename): thr_vector = self.parent.returnRealUEThroughputVectorRR() thr_MBit = [x / (1024*1024) for x in thr_vector] plt.hist(thr_MBit) # plt.savefig(filename, format="pdf", dpi=300) plt.savefig(filename+".png", format="png", dpi=300) plt.clf() def drawHistogramOfSetPowers(self, filename): power_vector = [] for bs in self.parent.bs: power_vector.append(bs.outsidePower) plt.hist(power_vector, bins=np.arange(self.parent.minFemtoTxPower, self.parent.maxTxPower + 1, 1)) plt.xlim(0, 100) # plt.savefig(filename, format="pdf", dpi=300) plt.savefig(filename+".png", format="png", dpi=300) plt.clf() def drawNetwork(self, filename, BS=True, UE=True, links=True, obstacles=True, fillMethod="SINR", colorMap = 'viridis', drawLegend=True, tilesInLine = 100, figSize = (8, 8), colorMinValue = None, colorMaxValue = None, outputFileFormat = ["png"], forceRedraw = False): main_draw = plt.figure(1, figsize=figSize) ax = main_draw.add_subplot(111) cm = plt.cm.get_cmap(colorMap) ue = devices.UE() # check if tilesInLine changed if (forceRedraw == True): self.imageMatrixValid = False if (self.tilesInLine != tilesInLine): self.tilesInLine = tilesInLine self.imageMatrixValid = False if (self.fillMethod != fillMethod): self.fillMethod = fillMethod self.imageMatrixValid = False # If this is the fist time, or if something changed if(self.imageMatrixValid == False): self.imageMatrix = np.zeros((tilesInLine, tilesInLine)) d_x = self.parent.constraintAreaMaxX/tilesInLine d_y = self.parent.constraintAreaMaxY/tilesInLine for x in range(0, tilesInLine): for y in range(0, tilesInLine): ue.x = round(x * d_x) ue.y = round(y * d_y) if fillMethod == "SINR": ue.connectToTheBestBS(self.parent.bs, self.parent.obstacles) SINR, RSSI = ue.calculateSINR(self.parent.bs, self.parent.obstacles) self.imageMatrix[y][x] = SINR if fillMethod == "RSSI": ue.connectToTheBestBS(self.parent.bs, self.parent.obstacles) SINR, RSSI = ue.calculateSINR(self.parent.bs, self.parent.obstacles) self.imageMatrix[y][x] = RSSI if fillMethod == "Sectors": SINR_best = -1000 BS_best = -1 for bs in self.parent.bs: ue.connectedToBS = bs.ID temp_SINR, RSSI = ue.calculateSINR(self.parent.bs, self.parent.obstacles) if (temp_SINR > SINR_best) and (RSSI > -120): SINR_best = temp_SINR BS_best = bs.ID self.imageMatrix[y][x] = BS_best self.imageMatrixValid = True if colorMinValue != None: colorMin = colorMinValue else: colorMin = self.imageMatrix.min() if colorMaxValue != None: colorMax = colorMaxValue else: colorMax = self.imageMatrix.max() image = plt.imshow(self.imageMatrix, vmin=colorMin, vmax=colorMax, origin='lower', extent=[0, self.parent.constraintAreaMaxX, 0, self.parent.constraintAreaMaxY], interpolation='nearest', cmap=cm) if drawLegend == True: from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) cax1 = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(image, cax = cax1) cbar.set_clim(-40, 40) #end if BS == True: bs_x_locations = [] bs_y_locations = [] bs_ID = [] bs_angle = [] bs_count = 0 for bs in self.parent.bs: bs_x_locations.append(bs.x) bs_y_locations.append(bs.y) bs_ID.append(bs.ID) bs_angle.append(bs.angle) bs_count+=1 ax.plot(bs_x_locations, bs_y_locations, 'r^', color="red", markersize=10) for i in range(0,bs_count): offsetAngle = math.radians(bs_angle[i]) distance = (self.parent.constraintAreaMaxX + self.parent.constraintAreaMaxY) / 50 z = distance*complex(math.sin(offsetAngle), -math.cos(offsetAngle)) ax.annotate(bs_ID[i], xy=(bs_x_locations[i],bs_y_locations[i]), xytext=(bs_x_locations[i]+z.real, bs_y_locations[i]+z.imag), color='red') if UE == True: for ue in self.parent.ue: ax.annotate(ue.ID, xy=(ue.x, ue.y), xytext=(ue.x, ue.y), color='black') if links == True: for ue in self.parent.ue: ax.arrow(ue.x, ue.y, self.parent.bs[ue.connectedToBS].x - ue.x, self.parent.bs[ue.connectedToBS].y - ue.y) if obstacles == True: for obstacle in self.parent.obstacles: ax.arrow(obstacle[0], obstacle[1], obstacle[2] - obstacle[0], obstacle[3] - obstacle[1], width=10, color="red") networkBorder = plt.Rectangle((0,0), self.parent.constraintAreaMaxX, self.parent.constraintAreaMaxY, color='black', fill=False) ax.add_patch(networkBorder) ax.axis('equal') ax.axis([0, self.parent.constraintAreaMaxX, 0, self.parent.constraintAreaMaxY]) ax.axis('off') ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) for outputFormat in outputFileFormat: if outputFormat == "png": main_draw.savefig(filename+".png", format="png", dpi=300, bbox_inches='tight') if outputFormat == "pdf": main_draw.savefig(filename+".pdf", format="pdf", dpi=300, bbox_inches='tight') # plt.clf()
[ "matplotlib.pyplot.imshow", "matplotlib.pyplot.Rectangle", "matplotlib.pyplot.hist", "matplotlib.pyplot.savefig", "pyltes.devices.UE", "matplotlib.pyplot.clf", "matplotlib.pyplot.colorbar", "math.radians", "math.cos", "numpy.zeros", "matplotlib.pyplot.figure", "mpl_toolkits.axes_grid1.make_axe...
[((384, 430), 'numpy.zeros', 'np.zeros', (['(self.tilesInLine, self.tilesInLine)'], {}), '((self.tilesInLine, self.tilesInLine))\n', (392, 430), True, 'import numpy as np\n'), ((624, 642), 'matplotlib.pyplot.hist', 'plt.hist', (['thr_MBit'], {}), '(thr_MBit)\n', (632, 642), True, 'import matplotlib.pyplot as plt\n'), ((706, 759), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.png')"], {'format': '"""png"""', 'dpi': '(300)'}), "(filename + '.png', format='png', dpi=300)\n", (717, 759), True, 'import matplotlib.pyplot as plt\n'), ((766, 775), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (773, 775), True, 'import matplotlib.pyplot as plt\n'), ((1051, 1067), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(100)'], {}), '(0, 100)\n', (1059, 1067), True, 'import matplotlib.pyplot as plt\n'), ((1131, 1184), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.png')"], {'format': '"""png"""', 'dpi': '(300)'}), "(filename + '.png', format='png', dpi=300)\n", (1142, 1184), True, 'import matplotlib.pyplot as plt\n'), ((1191, 1200), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1198, 1200), True, 'import matplotlib.pyplot as plt\n'), ((1493, 1523), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': 'figSize'}), '(1, figsize=figSize)\n', (1503, 1523), True, 'import matplotlib.pyplot as plt\n'), ((1586, 1611), 'matplotlib.pyplot.cm.get_cmap', 'plt.cm.get_cmap', (['colorMap'], {}), '(colorMap)\n', (1601, 1611), True, 'import matplotlib.pyplot as plt\n'), ((1625, 1637), 'pyltes.devices.UE', 'devices.UE', ([], {}), '()\n', (1635, 1637), False, 'from pyltes import devices\n'), ((3945, 4141), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.imageMatrix'], {'vmin': 'colorMin', 'vmax': 'colorMax', 'origin': '"""lower"""', 'extent': '[0, self.parent.constraintAreaMaxX, 0, self.parent.constraintAreaMaxY]', 'interpolation': '"""nearest"""', 'cmap': 'cm'}), "(self.imageMatrix, vmin=colorMin, vmax=colorMax, origin='lower',\n extent=[0, self.parent.constraintAreaMaxX, 0, self.parent.\n constraintAreaMaxY], interpolation='nearest', cmap=cm)\n", (3955, 4141), True, 'import matplotlib.pyplot as plt\n'), ((5956, 6073), 'matplotlib.pyplot.Rectangle', 'plt.Rectangle', (['(0, 0)', 'self.parent.constraintAreaMaxX', 'self.parent.constraintAreaMaxY'], {'color': '"""black"""', 'fill': '(False)'}), "((0, 0), self.parent.constraintAreaMaxX, self.parent.\n constraintAreaMaxY, color='black', fill=False)\n", (5969, 6073), True, 'import matplotlib.pyplot as plt\n'), ((2170, 2206), 'numpy.zeros', 'np.zeros', (['(tilesInLine, tilesInLine)'], {}), '((tilesInLine, tilesInLine))\n', (2178, 2206), True, 'import numpy as np\n'), ((4263, 4286), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (4282, 4286), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((4375, 4404), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['image'], {'cax': 'cax1'}), '(image, cax=cax1)\n', (4387, 4404), True, 'import matplotlib.pyplot as plt\n'), ((972, 1041), 'numpy.arange', 'np.arange', (['self.parent.minFemtoTxPower', '(self.parent.maxTxPower + 1)', '(1)'], {}), '(self.parent.minFemtoTxPower, self.parent.maxTxPower + 1, 1)\n', (981, 1041), True, 'import numpy as np\n'), ((4997, 5022), 'math.radians', 'math.radians', (['bs_angle[i]'], {}), '(bs_angle[i])\n', (5009, 5022), False, 'import math\n'), ((5158, 5179), 'math.sin', 'math.sin', (['offsetAngle'], {}), '(offsetAngle)\n', (5166, 5179), False, 'import math\n'), ((5182, 5203), 'math.cos', 'math.cos', (['offsetAngle'], {}), '(offsetAngle)\n', (5190, 5203), False, 'import math\n')]
import argparse import os import json import faiss import numpy as np import pandas as pd from data import create_multi_splits from validate import L2norm from validate import retrieve, KNN, score # Training settings parser = argparse.ArgumentParser(description='PyTorch SBIR') parser.add_argument('--dir-path', type=str, default='exp', metavar='ED', help='directory with domainnet models') parser.add_argument('--new-data-path', type=str, default='', metavar='ED', help='overwrite data path') parser.add_argument('--eval', type=str, required=True, metavar='ED', help='many2any|any2many') args = parser.parse_args() GROUPS = 500 SEED = 1234 def get_config(): # iterate over folders in the directory configs = {} for path in os.listdir(args.dir_path): fname = os.path.join(args.dir_path, path, 'config.json') if os.path.isfile(fname): with open(fname) as f: tmp = json.load(f) if tmp['mode'] == 'im': configs[tmp['domain']] = tmp configs[tmp['domain']]['working_path'] = os.path.join( args.dir_path, path) if not args.new_data_path == '': configs[tmp['domain']]['data_dir'] = args.new_data_path else: configs['quickdraw'] = tmp configs['quickdraw']['working_path'] = os.path.join( args.dir_path, path) if not args.new_data_path == '': configs['quickdraw']['data_dir'] = args.new_data_path return configs def get_splits(configs): keys = configs.keys() keys.sort() fpaths = [] domains = [] y = [] for key in keys: # get data splits df_dir = os.path.join('aux', 'data', configs[key]['dataset']) splits = create_multi_splits(df_dir, configs[key]['domain']) if key == 'quickdraw': fpaths.extend(splits['sk']['test'].index.values) domains.extend(splits['sk']['test']['domain'].values) y.extend(splits['sk']['test']['cat'].values) else: fpaths.extend(splits['im']['test'].index.values) domains.extend(splits['im']['test']['domain'].values) y.extend(splits['im']['test']['cat'].values) df = pd.DataFrame({'domain': domains, 'cat': y}, index=fpaths) return df def read_data(fpath): data = np.load(fpath) return data['features'], data['labels'] def mix_queries(base, complement, alpha=0.5): idx = sample_complement(base['y'], complement['y']) mixture = alpha * base['x'] + (1-alpha) * complement['x'][idx, :] return mixture, idx def sample_complement(y_base, y_complement): np.random.seed(SEED) idx = [] for y in y_base: cond_idx = np.argwhere(y_complement == y).squeeze() idx.append(np.random.choice(cond_idx)) return idx def many2any_retrieval(configs, sources=['quickdraw', 'real']): keys = configs.keys() keys.sort() source_data = {} for domain in sources: dirname = configs[domain]['working_path'] fpath = os.path.join(dirname, 'features.npz') x, y = read_data(fpath) source_data[domain] = {} source_data[domain]['x'] = x source_data[domain]['y'] = y # save images that have been mixed, such that they don't get retrived x_src, idx = mix_queries(source_data[sources[0]], source_data[sources[1]]) y_src = source_data[sources[0]]['y'] np.save('plop.npy', idx) res = {} for domain in keys: dirname = configs[domain]['working_path'] fpath = os.path.join(dirname, 'features.npz') x_tgt, y_tgt = read_data(fpath) if sources[0] == domain and sources[1] == domain: pass else: print('\nRetrieval from %s+%s to %s' % (sources[0], sources[1], domain)) if domain == sources[1]: do_mixture = True else: do_mixture = False tmp = cross_domain_retrieval( x_src, y_src, x_tgt, y_tgt, zeroshot=configs[domain]['overwrite'], mixture=do_mixture) res[domain] = tmp os.remove('plop.npy') def get_data(configs): keys = configs.keys() keys.sort() feats = [] labels = [] domains = [] for i, key in enumerate(keys): dirname = configs[key]['working_path'] fpath = os.path.join(dirname, 'features.npz') data = np.load(fpath) nsamples = len(data['labels']) feats.extend(data['features']) labels.extend(data['labels']) domains.extend([key] * nsamples) return feats, labels, domains def one2many_retrieve_intent_aware(feats, labels, domains, splits, source='quickdraw', zeroshot=False): cond = np.asarray(domains) == source x_src = np.asarray(feats)[cond, :] y_src = np.asarray(labels)[cond] x_tgt = np.asarray(feats)[~cond, :] y_tgt = np.asarray(labels)[~cond] d_tgt = np.asarray(domains)[~cond] # KNN g_src_x = KNN(x_src, x_tgt, K=1, mode='ones') if zeroshot: alpha = 0.7 else: alpha = 0.4 x_src = slerp(alpha, L2norm(x_src), L2norm(g_src_x)) idx = myretrieve(x_src, x_tgt, topK=100) yd_tgt = np.char.add(y_tgt.astype(d_tgt.dtype), d_tgt) domains = np.unique(d_tgt) categories = np.unique(y_tgt) # compute occurrences of every category per domain occ = [] for d in domains: occ_inner = [] for c in categories: cond = np.logical_and(d_tgt == d, y_tgt == c) occ_inner.append(np.sum(cond)) occ.append(occ_inner) occ = np.asarray(occ, dtype=np.float) # normalize occurences occ /= np.sum(occ, axis=0) import multiprocessing as mp from metrics import average_precision # compute intent-aware mAP per domain mAP_ia = [] for d in domains: yd_src = np.char.add(y_src.astype(d_tgt.dtype), d) res = np.char.equal(yd_tgt[idx], yd_src[:, None]) pool = mp.Pool(processes=10) results = [pool.apply_async(average_precision, args=(r,)) for r in res] mAP = np.asarray([p.get() for p in results]) pool.close() mAP_ia.append(mAP) print('%s: %.3f' % (d, np.mean(mAP))) mAP_ia = np.asarray(mAP_ia) mAP_ia_final = (occ[:, y_src] * mAP_ia).sum(0).mean() print('mAP-IA: %.3f' % mAP_ia_final) return idx def cross_domain_retrieval(x_src, y_src, x_tgt, y_tgt, zeroshot=False, mixture=False): mAP, prec = evaluate(x_tgt, y_tgt, x_src, y_src, mixture=mixture) txt = ('mAP@all: %.04f Prec@100: %.04f\t' % (mAP, prec)) print(txt) g_src_x = KNN(x_src, x_tgt, K=1, mode='ones') if zeroshot: alpha = 0.7 else: alpha = 0.4 new_src_x = slerp(alpha, L2norm(x_src), L2norm(g_src_x)) mAP, prec = evaluate(x_tgt, y_tgt, new_src_x, y_src, mixture=mixture) txt = ('mAP@all: %.04f Prec@100: %.04f\t' % (mAP, prec)) tmp = '(w. refinement)' % alpha txt = tmp + ' ' + txt print(txt) return mAP def evaluate(im_x, im_y, sk_x, sk_y, K=False, return_idx=False, mixture=False): if not K: idx = retrieve(sk_x, im_x) else: idx = myretrieve(sk_x, im_x, topK=K) if mixture: selection = np.load('plop.npy') rows, cols = idx.shape idx = idx[idx != selection[:, None]].reshape(rows, -1) prec, mAP = score(sk_y, im_y, idx) if return_idx: return mAP, prec, idx else: return mAP, prec def myretrieve(query, gallery, dist='euc', L2=True, topK=101): d = query.shape[1] if dist == 'euc': index_flat = faiss.IndexFlatL2(d) elif dist == 'cos': index_flat = faiss.IndexFlatIP(d) if L2: query = L2norm(query) gallery = L2norm(gallery) index_flat.add(gallery) D, I = index_flat.search(query, topK) return I def get_stats(splits): domains = splits['domain'].unique() categories = splits['cat'].unique() stats = {} for c in categories: stats[c] = {} total = 0. for d in domains: cond = np.logical_and(splits['domain'] == d, splits['cat'] == c) stats[c][d] = np.sum(cond) total += np.sum(cond) for d in domains: stats[c][d] /= total return stats def slerp(val, low, high): """Spherical interpolation. val has a range of 0 to 1.""" if val <= 0: return low elif val >= 1: return high elif np.allclose(low, high): return low omega = np.arccos(np.einsum('ij, ij->i', low, high)) so = np.sin(omega) return (np.sin((1.0-val)*omega) / so)[:, None] * low + (np.sin(val*omega)/so)[:, None] * high if __name__ == '__main__': configs = get_config() if args.eval == 'many2any': many2any_retrieval(configs, sources=['quickdraw', 'quickdraw']) many2any_retrieval(configs, sources=['quickdraw', 'infograph']) many2any_retrieval(configs) many2any_retrieval(configs, sources=['clipart', 'clipart']) many2any_retrieval(configs, sources=['clipart', 'quickdraw']) many2any_retrieval(configs, sources=['clipart', 'infograph']) many2any_retrieval(configs, sources=['real', 'real']) many2any_retrieval(configs, sources=['real', 'quickdraw']) many2any_retrieval(configs, sources=['real', 'infograph']) elif args.eval == 'any2many': feats, labels, domains = get_data(configs) splits = get_splits(configs) one2many_retrieve_intent_aware(feats, labels, domains, splits)
[ "numpy.einsum", "numpy.sin", "numpy.save", "os.remove", "numpy.mean", "os.listdir", "validate.KNN", "argparse.ArgumentParser", "numpy.char.equal", "validate.L2norm", "numpy.asarray", "validate.score", "validate.retrieve", "data.create_multi_splits", "numpy.random.seed", "pandas.DataFra...
[((228, 279), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch SBIR"""'}), "(description='PyTorch SBIR')\n", (251, 279), False, 'import argparse\n'), ((801, 826), 'os.listdir', 'os.listdir', (['args.dir_path'], {}), '(args.dir_path)\n', (811, 826), False, 'import os\n'), ((2354, 2411), 'pandas.DataFrame', 'pd.DataFrame', (["{'domain': domains, 'cat': y}"], {'index': 'fpaths'}), "({'domain': domains, 'cat': y}, index=fpaths)\n", (2366, 2411), True, 'import pandas as pd\n'), ((2461, 2475), 'numpy.load', 'np.load', (['fpath'], {}), '(fpath)\n', (2468, 2475), True, 'import numpy as np\n'), ((2769, 2789), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (2783, 2789), True, 'import numpy as np\n'), ((3548, 3572), 'numpy.save', 'np.save', (['"""plop.npy"""', 'idx'], {}), "('plop.npy', idx)\n", (3555, 3572), True, 'import numpy as np\n'), ((4287, 4308), 'os.remove', 'os.remove', (['"""plop.npy"""'], {}), "('plop.npy')\n", (4296, 4308), False, 'import os\n'), ((5222, 5257), 'validate.KNN', 'KNN', (['x_src', 'x_tgt'], {'K': '(1)', 'mode': '"""ones"""'}), "(x_src, x_tgt, K=1, mode='ones')\n", (5225, 5257), False, 'from validate import retrieve, KNN, score\n'), ((5504, 5520), 'numpy.unique', 'np.unique', (['d_tgt'], {}), '(d_tgt)\n', (5513, 5520), True, 'import numpy as np\n'), ((5538, 5554), 'numpy.unique', 'np.unique', (['y_tgt'], {}), '(y_tgt)\n', (5547, 5554), True, 'import numpy as np\n'), ((5839, 5870), 'numpy.asarray', 'np.asarray', (['occ'], {'dtype': 'np.float'}), '(occ, dtype=np.float)\n', (5849, 5870), True, 'import numpy as np\n'), ((5910, 5929), 'numpy.sum', 'np.sum', (['occ'], {'axis': '(0)'}), '(occ, axis=0)\n', (5916, 5929), True, 'import numpy as np\n'), ((6483, 6501), 'numpy.asarray', 'np.asarray', (['mAP_ia'], {}), '(mAP_ia)\n', (6493, 6501), True, 'import numpy as np\n'), ((6896, 6931), 'validate.KNN', 'KNN', (['x_src', 'x_tgt'], {'K': '(1)', 'mode': '"""ones"""'}), "(x_src, x_tgt, K=1, mode='ones')\n", (6899, 6931), False, 'from validate import retrieve, KNN, score\n'), ((7643, 7665), 'validate.score', 'score', (['sk_y', 'im_y', 'idx'], {}), '(sk_y, im_y, idx)\n', (7648, 7665), False, 'from validate import retrieve, KNN, score\n'), ((8851, 8864), 'numpy.sin', 'np.sin', (['omega'], {}), '(omega)\n', (8857, 8864), True, 'import numpy as np\n'), ((844, 892), 'os.path.join', 'os.path.join', (['args.dir_path', 'path', '"""config.json"""'], {}), "(args.dir_path, path, 'config.json')\n", (856, 892), False, 'import os\n'), ((904, 925), 'os.path.isfile', 'os.path.isfile', (['fname'], {}), '(fname)\n', (918, 925), False, 'import os\n'), ((1810, 1862), 'os.path.join', 'os.path.join', (['"""aux"""', '"""data"""', "configs[key]['dataset']"], {}), "('aux', 'data', configs[key]['dataset'])\n", (1822, 1862), False, 'import os\n'), ((1880, 1931), 'data.create_multi_splits', 'create_multi_splits', (['df_dir', "configs[key]['domain']"], {}), "(df_dir, configs[key]['domain'])\n", (1899, 1931), False, 'from data import create_multi_splits\n'), ((3170, 3207), 'os.path.join', 'os.path.join', (['dirname', '"""features.npz"""'], {}), "(dirname, 'features.npz')\n", (3182, 3207), False, 'import os\n'), ((3677, 3714), 'os.path.join', 'os.path.join', (['dirname', '"""features.npz"""'], {}), "(dirname, 'features.npz')\n", (3689, 3714), False, 'import os\n'), ((4523, 4560), 'os.path.join', 'os.path.join', (['dirname', '"""features.npz"""'], {}), "(dirname, 'features.npz')\n", (4535, 4560), False, 'import os\n'), ((4577, 4591), 'numpy.load', 'np.load', (['fpath'], {}), '(fpath)\n', (4584, 4591), True, 'import numpy as np\n'), ((4972, 4991), 'numpy.asarray', 'np.asarray', (['domains'], {}), '(domains)\n', (4982, 4991), True, 'import numpy as np\n'), ((5015, 5032), 'numpy.asarray', 'np.asarray', (['feats'], {}), '(feats)\n', (5025, 5032), True, 'import numpy as np\n'), ((5054, 5072), 'numpy.asarray', 'np.asarray', (['labels'], {}), '(labels)\n', (5064, 5072), True, 'import numpy as np\n'), ((5091, 5108), 'numpy.asarray', 'np.asarray', (['feats'], {}), '(feats)\n', (5101, 5108), True, 'import numpy as np\n'), ((5131, 5149), 'numpy.asarray', 'np.asarray', (['labels'], {}), '(labels)\n', (5141, 5149), True, 'import numpy as np\n'), ((5170, 5189), 'numpy.asarray', 'np.asarray', (['domains'], {}), '(domains)\n', (5180, 5189), True, 'import numpy as np\n'), ((5351, 5364), 'validate.L2norm', 'L2norm', (['x_src'], {}), '(x_src)\n', (5357, 5364), False, 'from validate import L2norm\n'), ((5366, 5381), 'validate.L2norm', 'L2norm', (['g_src_x'], {}), '(g_src_x)\n', (5372, 5381), False, 'from validate import L2norm\n'), ((6160, 6203), 'numpy.char.equal', 'np.char.equal', (['yd_tgt[idx]', 'yd_src[:, None]'], {}), '(yd_tgt[idx], yd_src[:, None])\n', (6173, 6203), True, 'import numpy as np\n'), ((6219, 6240), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': '(10)'}), '(processes=10)\n', (6226, 6240), True, 'import multiprocessing as mp\n'), ((7029, 7042), 'validate.L2norm', 'L2norm', (['x_src'], {}), '(x_src)\n', (7035, 7042), False, 'from validate import L2norm\n'), ((7044, 7059), 'validate.L2norm', 'L2norm', (['g_src_x'], {}), '(g_src_x)\n', (7050, 7059), False, 'from validate import L2norm\n'), ((7399, 7419), 'validate.retrieve', 'retrieve', (['sk_x', 'im_x'], {}), '(sk_x, im_x)\n', (7407, 7419), False, 'from validate import retrieve, KNN, score\n'), ((7512, 7531), 'numpy.load', 'np.load', (['"""plop.npy"""'], {}), "('plop.npy')\n", (7519, 7531), True, 'import numpy as np\n'), ((7881, 7901), 'faiss.IndexFlatL2', 'faiss.IndexFlatL2', (['d'], {}), '(d)\n', (7898, 7901), False, 'import faiss\n'), ((7996, 8009), 'validate.L2norm', 'L2norm', (['query'], {}), '(query)\n', (8002, 8009), False, 'from validate import L2norm\n'), ((8028, 8043), 'validate.L2norm', 'L2norm', (['gallery'], {}), '(gallery)\n', (8034, 8043), False, 'from validate import L2norm\n'), ((8807, 8840), 'numpy.einsum', 'np.einsum', (['"""ij, ij->i"""', 'low', 'high'], {}), "('ij, ij->i', low, high)\n", (8816, 8840), True, 'import numpy as np\n'), ((2903, 2929), 'numpy.random.choice', 'np.random.choice', (['cond_idx'], {}), '(cond_idx)\n', (2919, 2929), True, 'import numpy as np\n'), ((5717, 5755), 'numpy.logical_and', 'np.logical_and', (['(d_tgt == d)', '(y_tgt == c)'], {}), '(d_tgt == d, y_tgt == c)\n', (5731, 5755), True, 'import numpy as np\n'), ((7947, 7967), 'faiss.IndexFlatIP', 'faiss.IndexFlatIP', (['d'], {}), '(d)\n', (7964, 7967), False, 'import faiss\n'), ((8360, 8417), 'numpy.logical_and', 'np.logical_and', (["(splits['domain'] == d)", "(splits['cat'] == c)"], {}), "(splits['domain'] == d, splits['cat'] == c)\n", (8374, 8417), True, 'import numpy as np\n'), ((8444, 8456), 'numpy.sum', 'np.sum', (['cond'], {}), '(cond)\n', (8450, 8456), True, 'import numpy as np\n'), ((8478, 8490), 'numpy.sum', 'np.sum', (['cond'], {}), '(cond)\n', (8484, 8490), True, 'import numpy as np\n'), ((8742, 8764), 'numpy.allclose', 'np.allclose', (['low', 'high'], {}), '(low, high)\n', (8753, 8764), True, 'import numpy as np\n'), ((985, 997), 'json.load', 'json.load', (['f'], {}), '(f)\n', (994, 997), False, 'import json\n'), ((1137, 1170), 'os.path.join', 'os.path.join', (['args.dir_path', 'path'], {}), '(args.dir_path, path)\n', (1149, 1170), False, 'import os\n'), ((1434, 1467), 'os.path.join', 'os.path.join', (['args.dir_path', 'path'], {}), '(args.dir_path, path)\n', (1446, 1467), False, 'import os\n'), ((2843, 2873), 'numpy.argwhere', 'np.argwhere', (['(y_complement == y)'], {}), '(y_complement == y)\n', (2854, 2873), True, 'import numpy as np\n'), ((5785, 5797), 'numpy.sum', 'np.sum', (['cond'], {}), '(cond)\n', (5791, 5797), True, 'import numpy as np\n'), ((6455, 6467), 'numpy.mean', 'np.mean', (['mAP'], {}), '(mAP)\n', (6462, 6467), True, 'import numpy as np\n'), ((8877, 8904), 'numpy.sin', 'np.sin', (['((1.0 - val) * omega)'], {}), '((1.0 - val) * omega)\n', (8883, 8904), True, 'import numpy as np\n'), ((8925, 8944), 'numpy.sin', 'np.sin', (['(val * omega)'], {}), '(val * omega)\n', (8931, 8944), True, 'import numpy as np\n')]
from numba import jit import numpy as np import numbers from ectools.parallelization import parallel_wrapper # kernel definitions @jit(nopython=True) def norm_kernel(distances): """gaussian kernel""" # no gamma because bandwidth is calculated elsewhere return np.sqrt(np.pi / 2) * np.exp(-distances ** 2) # list of kernels _kernel_list = { 'norm': norm_kernel } @jit(nopython=True) def _predict(X, X_t, y_t, bw, kernel): """helper function for NWKR. It is fully compiled in Numba, and it vectorizes all that is vectorizable to improve speed. Args: X: the observations to predict from X_t: training dataset observations y_t: training dataset predictions bw: bandwidth(s) - will perform broadcasting kernel: a callable that evaluates kernel densities from euclidean distances Returns: prediction_out: predictions for observations X std_out: standard deviations on predictions for observations X """ # initialize arrays for output prediction_out = np.empty(X.shape[0]) std_out = np.empty(X.shape[0]) # iterate over each row (observation requiring prediction) for k in range(X.shape[0]): # normal NWKR algorithm distances = np.sqrt((((X_t - X[k, :]) / bw) ** 2).sum(axis=1)) weights = kernel(distances) weights = weights / np.sum(weights) # normalize prediction_out[k] = np.sum(weights * y_t) std_out[k] = (np.sum(weights * (y_t ** 2)) - prediction_out[k] ** 2) ** .5 return prediction_out, std_out class NWKR(): """Nadaraya-Watson kernel regression in the style of Scikit-learn. The difference with scikit-learn's is that it supports NaN values both in the fit() and predict() methods: it will output np.nan accordingly. Another difference is that it automatically computes the standard deviations of the estimated prediction distribution. See Nad<NAME>. (1964). On Estimating Regression. Theory of Probability & Its Applications, 9(1), 141–142. https://doi.org/10.1137/1109020 <NAME>. (1964). Smooth Regression Analysis. Sankhyā: The Indian Journal of Statistics, Series A (1961-2002), 26(4), 359–372. https://doi.org/10.2307/25049340 for the definition of NWKR and <NAME>., & <NAME>. (2018). Complexity of products: the effect of data regularisation. Retrieved from http://arxiv.org/abs/1808.08249 for the standard deviations calculation. Optimized for speed with Numba. Args: kernel: must be a string with the name of one of the included kernels (see NWKR._kernel_list) or callable. bandwidth: the bandwidth that scale distances in the euclidean space of observations. must be single float or iterable of floats (for different bandwidths along different dimensions). njobs: number of CPU cores to use for computation. njobs>1 requires joblib. """ def __init__(self, kernel='norm', bandwidth=1, njobs=1): # bandwidth can also be a np.array, with multiple bw for each dimension self.bw = bandwidth self.njobs = njobs # if it's a number or a 1-d numpy array: if (isinstance(bandwidth, numbers.Number) or (isinstance(bandwidth, np.ndarray) and bandwidth.size == 1)): self.multiple_bw = False if isinstance(bandwidth, np.ndarray): # if it's 1-d numpy array, turn into a float self.bw = self.bw[0] else: self.multiple_bw = True # turn into np.array, needed later for broadcasting self.bw = np.array(self.bw) if kernel in _kernel_list: self.kernel = _kernel_list[kernel] else: if hasattr(kernel,'__call__'): self.kernel = kernel else: raise TypeError('kernel must be callable or one of included kernels (check NWKR._kernel_list)') def fit(self, X, y): """Fit using observations X and outcomes y. Args: X: a np.ndarray of floats of dimension 2 y: a np.ndarray of floats with the same number of elements as the rows of X Returns: None """ assert X.ndim == 2 assert X.shape[0] == y.size if self.multiple_bw: # check that bandwidth has same no. of elements as no. of features in X assert len(self.bw.shape) == 1 and self.bw.size == X.shape[1] # only keep complete samples keep = np.invert(np.isnan(X).sum(axis=1) > 0) & np.isfinite(y) assert keep.sum()>0 self.X_t = X[keep] self.y_t = y[keep] self.n = self.X_t.shape[0] def predict(self, X): """Predict outcomes from observations X, and also calculate standard deviations for the predictions. Args: X: a np.ndarray of floats, of dimension 2. Returns: predictions: a np.ndarray with a prediction for each row in X predictions_std: standard deviations on the predictions """ assert X.ndim == 2 assert X.shape[1] == self.X_t.shape[1] if self.njobs == 1: predictions, stds = _predict(X, self.X_t, self.y_t, self.bw, self.kernel) else: # parallelize def parallel_helper(X): return _predict(X, self.X_t, self.y_t, self.bw, self.kernel) result = parallel_wrapper(fcn=parallel_helper, iterable=np.array_split(X, self.njobs, axis=0), n_jobs=self.njobs, progress=False) predictions, stds = zip(*result) predictions = np.hstack(predictions) stds = np.hstack(stds) return predictions, stds
[ "numpy.sqrt", "numpy.hstack", "numpy.exp", "numpy.sum", "numpy.array", "numba.jit", "numpy.empty", "numpy.isfinite", "numpy.array_split", "numpy.isnan" ]
[((133, 151), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (136, 151), False, 'from numba import jit\n'), ((385, 403), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (388, 403), False, 'from numba import jit\n'), ((1049, 1069), 'numpy.empty', 'np.empty', (['X.shape[0]'], {}), '(X.shape[0])\n', (1057, 1069), True, 'import numpy as np\n'), ((1084, 1104), 'numpy.empty', 'np.empty', (['X.shape[0]'], {}), '(X.shape[0])\n', (1092, 1104), True, 'import numpy as np\n'), ((274, 292), 'numpy.sqrt', 'np.sqrt', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (281, 292), True, 'import numpy as np\n'), ((295, 318), 'numpy.exp', 'np.exp', (['(-distances ** 2)'], {}), '(-distances ** 2)\n', (301, 318), True, 'import numpy as np\n'), ((1424, 1445), 'numpy.sum', 'np.sum', (['(weights * y_t)'], {}), '(weights * y_t)\n', (1430, 1445), True, 'import numpy as np\n'), ((1367, 1382), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (1373, 1382), True, 'import numpy as np\n'), ((3594, 3611), 'numpy.array', 'np.array', (['self.bw'], {}), '(self.bw)\n', (3602, 3611), True, 'import numpy as np\n'), ((4543, 4557), 'numpy.isfinite', 'np.isfinite', (['y'], {}), '(y)\n', (4554, 4557), True, 'import numpy as np\n'), ((5673, 5695), 'numpy.hstack', 'np.hstack', (['predictions'], {}), '(predictions)\n', (5682, 5695), True, 'import numpy as np\n'), ((5715, 5730), 'numpy.hstack', 'np.hstack', (['stds'], {}), '(stds)\n', (5724, 5730), True, 'import numpy as np\n'), ((1468, 1494), 'numpy.sum', 'np.sum', (['(weights * y_t ** 2)'], {}), '(weights * y_t ** 2)\n', (1474, 1494), True, 'import numpy as np\n'), ((5490, 5527), 'numpy.array_split', 'np.array_split', (['X', 'self.njobs'], {'axis': '(0)'}), '(X, self.njobs, axis=0)\n', (5504, 5527), True, 'import numpy as np\n'), ((4512, 4523), 'numpy.isnan', 'np.isnan', (['X'], {}), '(X)\n', (4520, 4523), True, 'import numpy as np\n')]
import sys import os import numpy as np import copy import glob import shutil ''' EVLA pipeline running for mixed setups. Applies the first few steps of the pipeline up to basic flagging (shadowing, zeros, ...). The continuum and line spws are then split into their own directories. The full pipeline is then run on each. The lines do not have rflag run on them. ''' # Give the name of the ms. The folder containing the ms will be used for the # splits try: vis = sys.argv[1] path_to_pipeline = sys.argv[2] hanning_smooth = sys.argv[3] except IndexError: vis = raw_input("MS File? : ") path_to_pipeline = raw_input("Path to pipeline? : ") hanning_smooth = raw_input("Hanning smooth? : ") if vis[-1] == "/": vis = vis[:-1] if not path_to_pipeline[-1] == "/": path_to_pipeline += "/" # Chop off the .ms SDM_name = vis[:-3] SDM_name_orig = copy.copy(SDM_name) # Set Hanning smoothing if hanning_smooth == 'y': myHanning = 'y' else: myHanning = 'n' # Figure out which are the lines and which are the continuum SPWs. tb.open(vis + '/SPECTRAL_WINDOW') bandwidths = tb.getcol('TOTAL_BANDWIDTH') tb.close() tb.open(vis + '/FIELD') fields = tb.getcol('NAME') tb.close() # Drop the pol cal. fields = fields[np.where(fields != '0521+166=3C138')] # Define a threshold between expected bandwidths # Going with 10 MHz thresh_bw = 1.0e7 spws = np.arange(0, len(bandwidths)) line_spws = [str(i) for i in spws[np.where(bandwidths < thresh_bw)]] cont_spws = [str(i) for i in spws[np.where(bandwidths > thresh_bw)]] print("Line SPWs: " + str(line_spws)) print("Coninuum SPWs: " + str(cont_spws)) print("Running initial pipeline.") execfile(path_to_pipeline + "EVLA_pipeline_initial_mixed.py") print("Splitting by SPW.") os.mkdir('speclines') split(vis=vis, outputvis="speclines/"+SDM_name+".speclines.ms", spw=",".join(line_spws), datacolumn='DATA', field=",".join(fields)) os.mkdir('continuum') split(vis=vis, outputvis="continuum/"+SDM_name+".continuum.ms", spw=",".join(cont_spws), datacolumn='DATA', field=",".join(fields)) print("Running full pipeline on the spectral lines.") os.chdir("speclines") SDM_name = SDM_name_orig+".speclines" myHanning = 'n' execfile(path_to_pipeline + "EVLA_pipeline_lines.py") # It saves a bunch of plots to the parent directory. So, move them to weblog here. pngs = glob.glob("../*.png") for png in pngs: shutil.move(png, "weblog/") print("Running full pipeline on the spectral lines.") os.chdir("../continuum") SDM_name = SDM_name_orig+".continuum" myHanning = 'n' execfile(path_to_pipeline + "EVLA_pipeline_continuum.py") pngs = glob.glob("../*.png") for png in pngs: shutil.move(png, "weblog/") print("All done!")
[ "shutil.move", "numpy.where", "os.chdir", "os.mkdir", "copy.copy", "glob.glob" ]
[((876, 895), 'copy.copy', 'copy.copy', (['SDM_name'], {}), '(SDM_name)\n', (885, 895), False, 'import copy\n'), ((1760, 1781), 'os.mkdir', 'os.mkdir', (['"""speclines"""'], {}), "('speclines')\n", (1768, 1781), False, 'import os\n'), ((1922, 1943), 'os.mkdir', 'os.mkdir', (['"""continuum"""'], {}), "('continuum')\n", (1930, 1943), False, 'import os\n'), ((2139, 2160), 'os.chdir', 'os.chdir', (['"""speclines"""'], {}), "('speclines')\n", (2147, 2160), False, 'import os\n'), ((2362, 2383), 'glob.glob', 'glob.glob', (['"""../*.png"""'], {}), "('../*.png')\n", (2371, 2383), False, 'import glob\n'), ((2489, 2513), 'os.chdir', 'os.chdir', (['"""../continuum"""'], {}), "('../continuum')\n", (2497, 2513), False, 'import os\n'), ((2636, 2657), 'glob.glob', 'glob.glob', (['"""../*.png"""'], {}), "('../*.png')\n", (2645, 2657), False, 'import glob\n'), ((1249, 1285), 'numpy.where', 'np.where', (["(fields != '0521+166=3C138')"], {}), "(fields != '0521+166=3C138')\n", (1257, 1285), True, 'import numpy as np\n'), ((2405, 2432), 'shutil.move', 'shutil.move', (['png', '"""weblog/"""'], {}), "(png, 'weblog/')\n", (2416, 2432), False, 'import shutil\n'), ((2679, 2706), 'shutil.move', 'shutil.move', (['png', '"""weblog/"""'], {}), "(png, 'weblog/')\n", (2690, 2706), False, 'import shutil\n'), ((1448, 1480), 'numpy.where', 'np.where', (['(bandwidths < thresh_bw)'], {}), '(bandwidths < thresh_bw)\n', (1456, 1480), True, 'import numpy as np\n'), ((1517, 1549), 'numpy.where', 'np.where', (['(bandwidths > thresh_bw)'], {}), '(bandwidths > thresh_bw)\n', (1525, 1549), True, 'import numpy as np\n')]
# ================================================================ # Created by <NAME> on 1/31/19 # ================================================================ import numpy as np out_sdf_field01 = np.array([[-0.02499938, 0.05000062, 0.30000061, 0.20000061, 0.60000062, 0.40000063, 0.70000064, 0.70000064, 0.90000063, 0.97500062, 1., 1., 1., 1., 1., 1.], [-0.12499958, -0.04999958, 0.20000042, 0.10000042, 0.50000042, 0.25000042, 0.60000044, 0.60000044, 0.80000043, 0.87500042, 1., 1., 1., 1., 1., 1.], [-0.27499980, -0.14999978, 0.10000022, 0.00000021, 0.40000021, 0.15000021, 0.50000024, 0.50000024, 0.70000023, 0.77500021, 0.92500019, 1., 1., 1., 1., 1.], [-0.37500000, -0.17499998, 0.00000001, -0.09999999, 0.30000001, 0.05000001, 0.40000001, 0.40000001, 0.60000002, 0.67500001, 0.82499999, 0.97500002, 0.97500002, 1., 1., 1.], [-0.47500020, -0.27500018, -0.15000018, -0.20000020, 0.19999981, -0.05000019, 0.39999980, 0.29999980, 0.49999982, 0.57499981, 0.62499982, 0.87499982, 0.87499982, 1., 1., 1.], [-0.57500041, -0.37500039, -0.25000039, -0.22500040, 0.09999961, -0.15000039, 0.29999959, 0.19999960, 0.39999962, 0.47499961, 0.52499962, 0.77499962, 0.77499962, 1., 0.94999963, 1.], [-0.72500062, -0.47500059, -0.35000059, -0.32500058, -0.00000060, -0.25000060, 0.19999941, 0.09999941, 0.29999942, 0.37499940, 0.42499942, 0.67499942, 0.67499942, 0.94999939, 0.84999943, 1.], [-0.82499933, -0.49999931, -0.44999930, -0.42499930, -0.09999931, -0.34999931, 0.10000069, 0.00000069, 0.20000069, 0.27500069, 0.32500070, 0.57500070, 0.57500070, 0.85000068, 0.75000072, 1.], [-0.92499954, -0.59999949, -0.54999954, -0.52499950, -0.24999951, -0.44999951, 0.00000049, -0.09999951, 0.10000049, 0.17500049, 0.22500049, 0.47500050, 0.37500048, 0.75000048, 0.65000051, 1.], [-1., -0.69999969, -0.69999969, -0.62499970, -0.34999973, -0.54999971, -0.09999971, -0.19999972, 0.00000029, 0.07500029, 0.12500028, 0.37500030, 0.27500027, 0.65000027, 0.47500029, 0.92500031], [-1., -0.79999989, -0.79999989, -0.72499990, -0.44999993, -0.64999992, -0.19999991, -0.29999992, -0.09999992, -0.02499992, 0.02500008, 0.27500010, 0.17500009, 0.55000007, 0.37500009, 0.82500011], [-1., -0.90000010, -0.90000010, -0.82500011, -0.55000013, -0.75000012, -0.30000013, -0.40000013, -0.20000012, -0.12500012, -0.07500012, 0.17499988, 0.07499988, 0.44999987, 0.27499989, 0.72499990], [-1., -0.90000033, -1., -0.85000032, -0.65000033, -0.75000030, -0.40000033, -0.55000031, -0.30000031, -0.20000032, -0.17500032, 0.12499968, -0.02500032, 0.39999968, 0.17499968, 0.62499970], [-1., -1., -1., -0.95000052, -0.75000054, -0.85000050, -0.50000054, -0.65000051, -0.40000051, -0.30000052, -0.27500051, 0.02499948, -0.12500052, 0.29999948, 0.07499947, 0.52499950], [-1., -1., -1., -1., -0.85000074, -0.95000070, -0.60000074, -0.75000072, -0.50000072, -0.40000072, -0.37500072, -0.07500073, -0.22500072, 0.19999927, -0.02500073, 0.42499927], [-1., -1., -1., -1., -0.94999945, -1., -0.69999945, -0.84999943, -0.59999943, -0.49999943, -0.47499943, -0.17499945, -0.32499945, 0.10000056, -0.09999944, 0.32500055]], dtype=np.float32)
[ "numpy.array" ]
[((207, 3289), 'numpy.array', 'np.array', (['[[-0.02499938, 0.05000062, 0.30000061, 0.20000061, 0.60000062, 0.40000063, \n 0.70000064, 0.70000064, 0.90000063, 0.97500062, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0], [-0.12499958, -0.04999958, 0.20000042, 0.10000042, 0.50000042, \n 0.25000042, 0.60000044, 0.60000044, 0.80000043, 0.87500042, 1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0], [-0.2749998, -0.14999978, 0.10000022, 2.1e-07, \n 0.40000021, 0.15000021, 0.50000024, 0.50000024, 0.70000023, 0.77500021,\n 0.92500019, 1.0, 1.0, 1.0, 1.0, 1.0], [-0.375, -0.17499998, 1e-08, -\n 0.09999999, 0.30000001, 0.05000001, 0.40000001, 0.40000001, 0.60000002,\n 0.67500001, 0.82499999, 0.97500002, 0.97500002, 1.0, 1.0, 1.0], [-\n 0.4750002, -0.27500018, -0.15000018, -0.2000002, 0.19999981, -\n 0.05000019, 0.3999998, 0.2999998, 0.49999982, 0.57499981, 0.62499982, \n 0.87499982, 0.87499982, 1.0, 1.0, 1.0], [-0.57500041, -0.37500039, -\n 0.25000039, -0.2250004, 0.09999961, -0.15000039, 0.29999959, 0.1999996,\n 0.39999962, 0.47499961, 0.52499962, 0.77499962, 0.77499962, 1.0, \n 0.94999963, 1.0], [-0.72500062, -0.47500059, -0.35000059, -0.32500058, \n -6e-07, -0.2500006, 0.19999941, 0.09999941, 0.29999942, 0.3749994, \n 0.42499942, 0.67499942, 0.67499942, 0.94999939, 0.84999943, 1.0], [-\n 0.82499933, -0.49999931, -0.4499993, -0.4249993, -0.09999931, -\n 0.34999931, 0.10000069, 6.9e-07, 0.20000069, 0.27500069, 0.3250007, \n 0.5750007, 0.5750007, 0.85000068, 0.75000072, 1.0], [-0.92499954, -\n 0.59999949, -0.54999954, -0.5249995, -0.24999951, -0.44999951, 4.9e-07,\n -0.09999951, 0.10000049, 0.17500049, 0.22500049, 0.4750005, 0.37500048,\n 0.75000048, 0.65000051, 1.0], [-1.0, -0.69999969, -0.69999969, -\n 0.6249997, -0.34999973, -0.54999971, -0.09999971, -0.19999972, 2.9e-07,\n 0.07500029, 0.12500028, 0.3750003, 0.27500027, 0.65000027, 0.47500029, \n 0.92500031], [-1.0, -0.79999989, -0.79999989, -0.7249999, -0.44999993, \n -0.64999992, -0.19999991, -0.29999992, -0.09999992, -0.02499992, \n 0.02500008, 0.2750001, 0.17500009, 0.55000007, 0.37500009, 0.82500011],\n [-1.0, -0.9000001, -0.9000001, -0.82500011, -0.55000013, -0.75000012, -\n 0.30000013, -0.40000013, -0.20000012, -0.12500012, -0.07500012, \n 0.17499988, 0.07499988, 0.44999987, 0.27499989, 0.7249999], [-1.0, -\n 0.90000033, -1.0, -0.85000032, -0.65000033, -0.7500003, -0.40000033, -\n 0.55000031, -0.30000031, -0.20000032, -0.17500032, 0.12499968, -\n 0.02500032, 0.39999968, 0.17499968, 0.6249997], [-1.0, -1.0, -1.0, -\n 0.95000052, -0.75000054, -0.8500005, -0.50000054, -0.65000051, -\n 0.40000051, -0.30000052, -0.27500051, 0.02499948, -0.12500052, \n 0.29999948, 0.07499947, 0.5249995], [-1.0, -1.0, -1.0, -1.0, -\n 0.85000074, -0.9500007, -0.60000074, -0.75000072, -0.50000072, -\n 0.40000072, -0.37500072, -0.07500073, -0.22500072, 0.19999927, -\n 0.02500073, 0.42499927], [-1.0, -1.0, -1.0, -1.0, -0.94999945, -1.0, -\n 0.69999945, -0.84999943, -0.59999943, -0.49999943, -0.47499943, -\n 0.17499945, -0.32499945, 0.10000056, -0.09999944, 0.32500055]]'], {'dtype': 'np.float32'}), '([[-0.02499938, 0.05000062, 0.30000061, 0.20000061, 0.60000062, \n 0.40000063, 0.70000064, 0.70000064, 0.90000063, 0.97500062, 1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0], [-0.12499958, -0.04999958, 0.20000042, 0.10000042,\n 0.50000042, 0.25000042, 0.60000044, 0.60000044, 0.80000043, 0.87500042,\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [-0.2749998, -0.14999978, 0.10000022, \n 2.1e-07, 0.40000021, 0.15000021, 0.50000024, 0.50000024, 0.70000023, \n 0.77500021, 0.92500019, 1.0, 1.0, 1.0, 1.0, 1.0], [-0.375, -0.17499998,\n 1e-08, -0.09999999, 0.30000001, 0.05000001, 0.40000001, 0.40000001, \n 0.60000002, 0.67500001, 0.82499999, 0.97500002, 0.97500002, 1.0, 1.0, \n 1.0], [-0.4750002, -0.27500018, -0.15000018, -0.2000002, 0.19999981, -\n 0.05000019, 0.3999998, 0.2999998, 0.49999982, 0.57499981, 0.62499982, \n 0.87499982, 0.87499982, 1.0, 1.0, 1.0], [-0.57500041, -0.37500039, -\n 0.25000039, -0.2250004, 0.09999961, -0.15000039, 0.29999959, 0.1999996,\n 0.39999962, 0.47499961, 0.52499962, 0.77499962, 0.77499962, 1.0, \n 0.94999963, 1.0], [-0.72500062, -0.47500059, -0.35000059, -0.32500058, \n -6e-07, -0.2500006, 0.19999941, 0.09999941, 0.29999942, 0.3749994, \n 0.42499942, 0.67499942, 0.67499942, 0.94999939, 0.84999943, 1.0], [-\n 0.82499933, -0.49999931, -0.4499993, -0.4249993, -0.09999931, -\n 0.34999931, 0.10000069, 6.9e-07, 0.20000069, 0.27500069, 0.3250007, \n 0.5750007, 0.5750007, 0.85000068, 0.75000072, 1.0], [-0.92499954, -\n 0.59999949, -0.54999954, -0.5249995, -0.24999951, -0.44999951, 4.9e-07,\n -0.09999951, 0.10000049, 0.17500049, 0.22500049, 0.4750005, 0.37500048,\n 0.75000048, 0.65000051, 1.0], [-1.0, -0.69999969, -0.69999969, -\n 0.6249997, -0.34999973, -0.54999971, -0.09999971, -0.19999972, 2.9e-07,\n 0.07500029, 0.12500028, 0.3750003, 0.27500027, 0.65000027, 0.47500029, \n 0.92500031], [-1.0, -0.79999989, -0.79999989, -0.7249999, -0.44999993, \n -0.64999992, -0.19999991, -0.29999992, -0.09999992, -0.02499992, \n 0.02500008, 0.2750001, 0.17500009, 0.55000007, 0.37500009, 0.82500011],\n [-1.0, -0.9000001, -0.9000001, -0.82500011, -0.55000013, -0.75000012, -\n 0.30000013, -0.40000013, -0.20000012, -0.12500012, -0.07500012, \n 0.17499988, 0.07499988, 0.44999987, 0.27499989, 0.7249999], [-1.0, -\n 0.90000033, -1.0, -0.85000032, -0.65000033, -0.7500003, -0.40000033, -\n 0.55000031, -0.30000031, -0.20000032, -0.17500032, 0.12499968, -\n 0.02500032, 0.39999968, 0.17499968, 0.6249997], [-1.0, -1.0, -1.0, -\n 0.95000052, -0.75000054, -0.8500005, -0.50000054, -0.65000051, -\n 0.40000051, -0.30000052, -0.27500051, 0.02499948, -0.12500052, \n 0.29999948, 0.07499947, 0.5249995], [-1.0, -1.0, -1.0, -1.0, -\n 0.85000074, -0.9500007, -0.60000074, -0.75000072, -0.50000072, -\n 0.40000072, -0.37500072, -0.07500073, -0.22500072, 0.19999927, -\n 0.02500073, 0.42499927], [-1.0, -1.0, -1.0, -1.0, -0.94999945, -1.0, -\n 0.69999945, -0.84999943, -0.59999943, -0.49999943, -0.47499943, -\n 0.17499945, -0.32499945, 0.10000056, -0.09999944, 0.32500055]], dtype=\n np.float32)\n', (215, 3289), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021 <NAME> <<EMAIL>> # # MIT License # # 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 import abc import dataclasses import itertools from pathlib import Path from xml.etree import ElementTree import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader from torchvision import transforms as T class UADetracContextDetectionDataset(torch.utils.data.Dataset): """UA-DETRAC detection dataset with the additional capability of adding contextual images. If no context is specified, this class produces a dataset representation that is tantamount to that which torchvision object detection modules expect. """ @dataclasses.dataclass(frozen=True) class _SeqBoxesIndex: """An auxiliary classs to store sequence index and image index within that sequence. """ seq_idx: int image_idx: int def __init__( self, root_path, subset='train', *, past_context=0, future_context=0, context_stride=1, transforms=None ): """Constructor. Args: root_path (str): Path to the UA-DETRAC dataset. subset (str, optional): Data subset ('train' or 'test'). Defaults to 'train'. past_context (int, optional): A non-negative integer specifying the number of frames in the past. Defaults to 0. future_context (int, optional): A non-negative integer specifying the number of frames in the future. Defaults to 0. context_stride (int, optional): A positive integer representing the stride when traversing the past as well as future contextual frames. Defaults to 1. transforms (Callable, optional): Transformation to apply to individual frames. Beware that if context is required, some transformations may be nonsensical. Defaults to None. """ self._context_rel_idxs = _calc_context_rel_idxs( past_context, future_context, context_stride ) self._global_to_local_seq_image_idxs = [] self._seq_image_paths = [] self._seq_boxes = [] self.transforms = transforms self._init_data_indices(root_path, subset) def __getitem__(self, idx): """Retrieves a random sample from the dataset. Args: idx (int): Data sample index. Returns: Tuple[torch.Tensor, Dict[str, List[torch.Tensor]]]: Returns a data sample consisting of a center image in a tensor format, and target specification as a dictionary with the following content: 'boxes': A Nx4 tensor of boxes in xyxy format. 'labels': A N, tensor of labels (0 indicates background). 'context_images': A list of tensors of contextual images (including the center image). """ seq_box_idx = self._global_to_local_seq_image_idxs[idx] seq_idx, center_image_idx = seq_box_idx.seq_idx, seq_box_idx.image_idx image_file_paths = self._seq_image_paths[seq_idx] abs_context_idxs = np.clip( self._context_rel_idxs + center_image_idx, 0, len(image_file_paths) - 1 ) center_image = None context_images = [] prev_idx = -1 for context_idx in abs_context_idxs: if context_idx != prev_idx: image_file_path = image_file_paths[context_idx] image = Image.open(image_file_path) if context_idx == center_image_idx: center_image = image context_images.append(image) prev_idx = context_idx assert center_image is not None image_id = torch.as_tensor([idx], dtype=torch.int64) boxes = self._seq_boxes[seq_idx][center_image_idx] boxes = torch.as_tensor(boxes, dtype=torch.float32) areas = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) labels = torch.ones((len(boxes),), dtype=torch.int64) is_crowd = torch.zeros_like(labels) target = { 'image_id': image_id, 'boxes': boxes, 'area': areas, 'labels': labels, 'iscrowd': is_crowd, 'context_images': context_images, } if self.transforms is not None: center_image, target = self.transforms(center_image, target) return center_image, target def __len__(self): """Returns the length of the dataset. It represents the number of images (frames) of the entire dataset. Returns: int: Dataset length. """ return len(self._global_to_local_seq_image_idxs) def _init_data_indices(self, root_path, subset): """Initializes data indices to faster access. It reads image (frame) file names as well as their corresponding bounding boxes for faster access later on. Args: root_path (str): UA-DETRAC dataset root path. subset (str): Whether to read 'train' or 'test' data subset. """ images_dir, annos_dir = self._deduce_images_and_annos_paths( root_path, subset ) for seq_idx, seq_dir in enumerate(images_dir.iterdir()): xml_file_name = seq_dir.stem + '_v3.xml' xml_file_path = str(annos_dir / xml_file_name) image_boxes_map = dict(self._iter_seq_boxes(xml_file_path)) seq_image_file_paths = [] seq_image_boxes = [] image_idx_gen = itertools.count() for image_num, image_file_path in self._iter_seq_image_file_paths( seq_dir ): boxes = image_boxes_map.get(image_num) if boxes is not None: seq_image_file_paths.append(image_file_path) seq_image_boxes.append(boxes) image_idx = next(image_idx_gen) seq_boxes_idx = self._SeqBoxesIndex(seq_idx, image_idx) self._global_to_local_seq_image_idxs.append(seq_boxes_idx) self._seq_image_paths.append(seq_image_file_paths) self._seq_boxes.append(seq_image_boxes) @staticmethod def _deduce_images_and_annos_paths(root_path, subset): """Deduces paths for images and annotations. It returns the root path that contains all the sequences belonging to the specific subset. Args: root_path (str): Root directory path to the UA-DETRAC dataset. subset (str): Data subset type ('train' or 'test'). Returns: Tuple[pathlib.Path, pathlib.Path]: Directory paths for images and annotations. """ assert subset in ('train', 'test') subset = subset.capitalize() root_dir = Path(root_path) images_idr = root_dir / ('Insight-MVT_Annotation_' + subset) annos_dir = root_dir / 'DETRAC_public' / ('540p-' + subset) return images_idr, annos_dir @staticmethod def _iter_seq_image_file_paths(seq_dir): """Iterates over image file names for a specific sequence from the UA-DETRAC dataset. Args: seq_dir (pathlib.Path): Sequence directory path. Yields: Tuple[int, str]: Tuple containing image (frame) number and the corresponding file path. """ image_num_path_pairs = [ (int(p.stem[-5:]), str(p)) for p in seq_dir.iterdir() ] yield from iter(sorted(image_num_path_pairs)) @staticmethod def _iter_seq_boxes(xml_file_path): """Iterates over a sequence of bounding boxes contained within a specific XML file corresponding to some sequence from the UA-DETRAC dataset. Args: xml_file_path (str): Sequence specification XML file path. Yields: Tuple[int, List[Tuple[float, float, float, float]]]: A tuple containing the frame number and the list of bounding boxes in a xyxy format. """ tree = ElementTree.parse(xml_file_path) root = tree.getroot() for frame in root.findall('./frame'): frame_num = int(frame.attrib['num']) boxes = [] for target in frame.findall('.//target'): box_attr = target.find('box').attrib x = float(box_attr['left']) y = float(box_attr['top']) w = float(box_attr['width']) h = float(box_attr['height']) box = (x, y, x + w, y + h) boxes.append(box) yield frame_num, boxes def transform_center_and_context_images(image, target, transform): image = transform(image) context_images = target.get('context_images') or [] for i, context_image in enumerate(context_images): context_images[i] = transform(context_image) return image, target class TransformWithContext(abc.ABC): @abc.abstractmethod def __call__(self, image, target): pass class ToTensorWithContext(TransformWithContext): def __init__(self): self.to_tensor = T.ToTensor() def __call__(self, image, target): image, target = transform_center_and_context_images( image, target, self.to_tensor ) return image, target class ColorJitterWithContext(TransformWithContext): def __init__(self, brightness=0, contrast=0, saturation=0, hue=0): self.color_jitter = T.ColorJitter(brightness, contrast, saturation, hue) def __call__(self, image, target): image, target = transform_center_and_context_images( image, target, self.color_jitter ) return image, target class ComposeTransforms(TransformWithContext): def __init__(self, transforms): self.transforms = transforms def __call__(self, image, target): for transform in self.transforms: image, target = transform(image, target) return image, target def collate_context_images_batch(batch): images, targets = map(list, zip(*batch)) return images, targets def make_transforms(cfg, train=True): to_tensor = ToTensorWithContext() transforms = [to_tensor] if train: color_jitter = ColorJitterWithContext( cfg.DATASET.AUG.BRIGHTNESS, cfg.DATASET.AUG.CONTRAST, cfg.DATASET.AUG.SATURATION, cfg.DATASET.AUG.HUE ) transforms.append(color_jitter) transforms = ComposeTransforms(transforms) return transforms def make_dataset(cfg, *, train=True): transforms = make_transforms(cfg, train) subset = 'train' if train else 'test' dataset = UADetracContextDetectionDataset( cfg.DATASET.ROOT_PATH, subset, past_context=cfg.DATASET.PAST_CONTEXT, future_context=cfg.DATASET.FUTURE_CONTEXT, context_stride=cfg.DATASET.CONTEXT_STRIDE, transforms=transforms ) return dataset def make_data_loader( cfg, dataset, train=True, collate_fn=collate_context_images_batch ): pin_memory = torch.cuda.is_available() shuffle = cfg.DATA_LOADER.SHUFFLE if train else False data_loader = DataLoader( dataset, batch_size=cfg.DATA_LOADER.BATCH_SIZE, shuffle=shuffle, num_workers=cfg.DATA_LOADER.N_WORKERS, collate_fn=collate_fn, pin_memory=pin_memory ) return data_loader def _calc_context_rel_idxs(past_context, future_context, stride): assert past_context >= 0 assert future_context >= 0 assert stride > 0 past_idxs = -np.flip(np.arange(stride, past_context + 1, stride)) center_idx = np.asarray([0]) future_idxs = np.arange(stride, future_context + 1, stride) idxs = np.concatenate((past_idxs, center_idx, future_idxs)) return idxs if __name__ == '__main__': import functools import cv2 as cv from config import cfg def tensor_to_cv_image(image_tensor, max_size=None): image = image_tensor.cpu().numpy() # [C,H,W] image = np.transpose(image, (1, 2, 0)) # [H,W,C] image = image[..., ::-1] if max_size is not None: height, width, _ = image.shape max_side = max(height, width) if max_side > max_size: scale = max_size / max_side image = cv.resize( image, None, fx=scale, fy=scale, interpolation=cv.INTER_CUBIC ) return image class ImageBatchVisualizer: def __init__( self, cfg, *, max_size=None, win_name='Batch Preview', quit_key='q' ): self.past_context = cfg.DATASET.PAST_CONTEXT self.temporal_win_size = self._calc_temporal_win_size( self.past_context, cfg.DATASET.FUTURE_CONTEXT, cfg.DATASET.CONTEXT_STRIDE ) self.max_size = max_size self.win_name = win_name self.quit_key = quit_key def __enter__(self): cv.namedWindow(self.win_name) return self def __exit__(self, exc_type, exc_val, exc_tb): cv.destroyWindow(self.win_name) def preview_batch_images(self, images, targets): image_rows = [] _to_cv_image = functools.partial( tensor_to_cv_image, max_size=self.max_size ) for _, target in zip(images, targets): image_cols = list(map(_to_cv_image, target['context_images'])) image_cols_merged = np.hstack(image_cols) image_rows.append(image_cols_merged) image_final = np.vstack(image_rows) cv.imshow(self.win_name, image_final) key = cv.waitKey(0) & 0xff return key != ord(self.quit_key) @staticmethod def _calc_temporal_win_size(past_context, future_context, stride): # TODO Implement better, purely arithmetic-based solution. return len(_calc_context_rel_idxs( past_context, future_context, stride )) dataset = make_dataset(cfg) data_loader = make_data_loader(cfg, dataset) n_batches_shown = 4 with ImageBatchVisualizer(cfg, max_size=400) as visualizer: for images, targets in itertools.islice(data_loader, n_batches_shown): if not visualizer.preview_batch_images(images, targets): break
[ "torch.as_tensor", "numpy.hstack", "dataclasses.dataclass", "cv2.imshow", "torchvision.transforms.ColorJitter", "torch.cuda.is_available", "numpy.arange", "xml.etree.ElementTree.parse", "pathlib.Path", "numpy.asarray", "numpy.vstack", "numpy.concatenate", "torch.zeros_like", "torchvision.t...
[((1772, 1806), 'dataclasses.dataclass', 'dataclasses.dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (1793, 1806), False, 'import dataclasses\n'), ((12776, 12801), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (12799, 12801), False, 'import torch\n'), ((12886, 13054), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'cfg.DATA_LOADER.BATCH_SIZE', 'shuffle': 'shuffle', 'num_workers': 'cfg.DATA_LOADER.N_WORKERS', 'collate_fn': 'collate_fn', 'pin_memory': 'pin_memory'}), '(dataset, batch_size=cfg.DATA_LOADER.BATCH_SIZE, shuffle=shuffle,\n num_workers=cfg.DATA_LOADER.N_WORKERS, collate_fn=collate_fn,\n pin_memory=pin_memory)\n', (12896, 13054), False, 'from torch.utils.data import DataLoader\n'), ((13363, 13378), 'numpy.asarray', 'np.asarray', (['[0]'], {}), '([0])\n', (13373, 13378), True, 'import numpy as np\n'), ((13398, 13443), 'numpy.arange', 'np.arange', (['stride', '(future_context + 1)', 'stride'], {}), '(stride, future_context + 1, stride)\n', (13407, 13443), True, 'import numpy as np\n'), ((13458, 13510), 'numpy.concatenate', 'np.concatenate', (['(past_idxs, center_idx, future_idxs)'], {}), '((past_idxs, center_idx, future_idxs))\n', (13472, 13510), True, 'import numpy as np\n'), ((5060, 5101), 'torch.as_tensor', 'torch.as_tensor', (['[idx]'], {'dtype': 'torch.int64'}), '([idx], dtype=torch.int64)\n', (5075, 5101), False, 'import torch\n'), ((5179, 5222), 'torch.as_tensor', 'torch.as_tensor', (['boxes'], {'dtype': 'torch.float32'}), '(boxes, dtype=torch.float32)\n', (5194, 5222), False, 'import torch\n'), ((5381, 5405), 'torch.zeros_like', 'torch.zeros_like', (['labels'], {}), '(labels)\n', (5397, 5405), False, 'import torch\n'), ((8283, 8298), 'pathlib.Path', 'Path', (['root_path'], {}), '(root_path)\n', (8287, 8298), False, 'from pathlib import Path\n'), ((9592, 9624), 'xml.etree.ElementTree.parse', 'ElementTree.parse', (['xml_file_path'], {}), '(xml_file_path)\n', (9609, 9624), False, 'from xml.etree import ElementTree\n'), ((10756, 10768), 'torchvision.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (10766, 10768), True, 'from torchvision import transforms as T\n'), ((11119, 11171), 'torchvision.transforms.ColorJitter', 'T.ColorJitter', (['brightness', 'contrast', 'saturation', 'hue'], {}), '(brightness, contrast, saturation, hue)\n', (11132, 11171), True, 'from torchvision import transforms as T\n'), ((13780, 13810), 'numpy.transpose', 'np.transpose', (['image', '(1, 2, 0)'], {}), '(image, (1, 2, 0))\n', (13792, 13810), True, 'import numpy as np\n'), ((16254, 16300), 'itertools.islice', 'itertools.islice', (['data_loader', 'n_batches_shown'], {}), '(data_loader, n_batches_shown)\n', (16270, 16300), False, 'import itertools\n'), ((6948, 6965), 'itertools.count', 'itertools.count', ([], {}), '()\n', (6963, 6965), False, 'import itertools\n'), ((13300, 13343), 'numpy.arange', 'np.arange', (['stride', '(past_context + 1)', 'stride'], {}), '(stride, past_context + 1, stride)\n', (13309, 13343), True, 'import numpy as np\n'), ((14906, 14935), 'cv2.namedWindow', 'cv.namedWindow', (['self.win_name'], {}), '(self.win_name)\n', (14920, 14935), True, 'import cv2 as cv\n'), ((15040, 15071), 'cv2.destroyWindow', 'cv.destroyWindow', (['self.win_name'], {}), '(self.win_name)\n', (15056, 15071), True, 'import cv2 as cv\n'), ((15199, 15260), 'functools.partial', 'functools.partial', (['tensor_to_cv_image'], {'max_size': 'self.max_size'}), '(tensor_to_cv_image, max_size=self.max_size)\n', (15216, 15260), False, 'import functools\n'), ((15581, 15602), 'numpy.vstack', 'np.vstack', (['image_rows'], {}), '(image_rows)\n', (15590, 15602), True, 'import numpy as np\n'), ((15618, 15655), 'cv2.imshow', 'cv.imshow', (['self.win_name', 'image_final'], {}), '(self.win_name, image_final)\n', (15627, 15655), True, 'import cv2 as cv\n'), ((4792, 4819), 'PIL.Image.open', 'Image.open', (['image_file_path'], {}), '(image_file_path)\n', (4802, 4819), False, 'from PIL import Image\n'), ((14100, 14172), 'cv2.resize', 'cv.resize', (['image', 'None'], {'fx': 'scale', 'fy': 'scale', 'interpolation': 'cv.INTER_CUBIC'}), '(image, None, fx=scale, fy=scale, interpolation=cv.INTER_CUBIC)\n', (14109, 14172), True, 'import cv2 as cv\n'), ((15464, 15485), 'numpy.hstack', 'np.hstack', (['image_cols'], {}), '(image_cols)\n', (15473, 15485), True, 'import numpy as np\n'), ((15675, 15688), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (15685, 15688), True, 'import cv2 as cv\n')]
from math import sin, cos from typing import Tuple, Sequence, Union from zodipy.models import model_registry from zodipy._component_labels import ComponentLabel import numpy as np import astropy.constants as const def get_component_density_grid( component: str, model: str = "K98", earth_coords: Sequence[float] = (0, 1, 0), xy_lim: int = 5, z_lim: int = 1, n: int = 200, return_grid: bool = False, ) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]]: """Returns a 3D grid of the components density. Parameters ---------- component The component for which we grid the density. model The Interplanetary Dust Model that contains the component. xy_lim xy-limit in AU. z_lim z-limit in AU. n Number of grid points in each axis. return_grid If True, then the meshgrid is returned alongside the density_grid. Returns ------- density_grid, XX, YY, ZZ 3D grid of the density of the component. """ ipd_model = model_registry.get_model(model) component_class = ipd_model.components[ComponentLabel(component)] x_helio = np.linspace(-xy_lim, xy_lim, n) y_helio = x_helio.copy() z_helio = np.linspace(-z_lim, z_lim, n) x_prime = x_helio - component_class.x_0 y_prime = y_helio - component_class.y_0 z_prime = z_helio - component_class.z_0 XX_helio, YY_helio, ZZ_helio = np.meshgrid(x_helio, y_helio, z_helio) XX_prime, YY_prime, ZZ_prime = np.meshgrid(x_prime, y_prime, z_prime) R_prime = np.sqrt(XX_prime ** 2 + YY_prime ** 2 + ZZ_prime ** 2) Z_prime = ( XX_prime * sin(component_class.Ω) * sin(component_class.i) - YY_prime * cos(component_class.Ω) * sin(component_class.i) + ZZ_prime * cos(component_class.i) ) X_earth_prime = earth_coords - component_class.X_component[0] θ_prime = np.arctan2(YY_prime, ZZ_prime) - np.arctan2( X_earth_prime[1], X_earth_prime[0] ) density_grid = component_class.get_density( R_prime=R_prime, Z_prime=Z_prime, θ_prime=θ_prime ) # The densities in the model is given in units of 1 / AU density_grid *= const.au.value if return_grid: return density_grid, XX_helio, YY_helio, ZZ_helio return density_grid
[ "numpy.sqrt", "math.sin", "math.cos", "numpy.linspace", "numpy.meshgrid", "numpy.arctan2", "zodipy.models.model_registry.get_model", "zodipy._component_labels.ComponentLabel" ]
[((1073, 1104), 'zodipy.models.model_registry.get_model', 'model_registry.get_model', (['model'], {}), '(model)\n', (1097, 1104), False, 'from zodipy.models import model_registry\n'), ((1190, 1221), 'numpy.linspace', 'np.linspace', (['(-xy_lim)', 'xy_lim', 'n'], {}), '(-xy_lim, xy_lim, n)\n', (1201, 1221), True, 'import numpy as np\n'), ((1265, 1294), 'numpy.linspace', 'np.linspace', (['(-z_lim)', 'z_lim', 'n'], {}), '(-z_lim, z_lim, n)\n', (1276, 1294), True, 'import numpy as np\n'), ((1464, 1502), 'numpy.meshgrid', 'np.meshgrid', (['x_helio', 'y_helio', 'z_helio'], {}), '(x_helio, y_helio, z_helio)\n', (1475, 1502), True, 'import numpy as np\n'), ((1538, 1576), 'numpy.meshgrid', 'np.meshgrid', (['x_prime', 'y_prime', 'z_prime'], {}), '(x_prime, y_prime, z_prime)\n', (1549, 1576), True, 'import numpy as np\n'), ((1592, 1646), 'numpy.sqrt', 'np.sqrt', (['(XX_prime ** 2 + YY_prime ** 2 + ZZ_prime ** 2)'], {}), '(XX_prime ** 2 + YY_prime ** 2 + ZZ_prime ** 2)\n', (1599, 1646), True, 'import numpy as np\n'), ((1148, 1173), 'zodipy._component_labels.ComponentLabel', 'ComponentLabel', (['component'], {}), '(component)\n', (1162, 1173), False, 'from zodipy._component_labels import ComponentLabel\n'), ((1931, 1961), 'numpy.arctan2', 'np.arctan2', (['YY_prime', 'ZZ_prime'], {}), '(YY_prime, ZZ_prime)\n', (1941, 1961), True, 'import numpy as np\n'), ((1964, 2010), 'numpy.arctan2', 'np.arctan2', (['X_earth_prime[1]', 'X_earth_prime[0]'], {}), '(X_earth_prime[1], X_earth_prime[0])\n', (1974, 2010), True, 'import numpy as np\n'), ((1820, 1842), 'math.cos', 'cos', (['component_class.i'], {}), '(component_class.i)\n', (1823, 1842), False, 'from math import sin, cos\n'), ((1708, 1730), 'math.sin', 'sin', (['component_class.i'], {}), '(component_class.i)\n', (1711, 1730), False, 'from math import sin, cos\n'), ((1777, 1799), 'math.sin', 'sin', (['component_class.i'], {}), '(component_class.i)\n', (1780, 1799), False, 'from math import sin, cos\n'), ((1682, 1704), 'math.sin', 'sin', (['component_class.Ω'], {}), '(component_class.Ω)\n', (1685, 1704), False, 'from math import sin, cos\n'), ((1751, 1773), 'math.cos', 'cos', (['component_class.Ω'], {}), '(component_class.Ω)\n', (1754, 1773), False, 'from math import sin, cos\n')]
import matplotlib # matplotlib.use('module://matplotlib-backend-kitty') matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from zoo import Zoo from sa import _gen_point_a obj = Zoo().get('rosenbrock').make_explicit() dom = np.array(obj.domain) f = obj.f m = 50000 x_samples = [_gen_point_a(dom) for _ in range(m + 1)] delta = np.diff([f(x) for x in x_samples]) delta = np.array([d for d in delta if d > 0.]) #x = np.linspace(0, 1000, 300) c = [30, 50, 1000] fig, ax = plt.subplots(3, 1) for idx, c_i in enumerate(c): p = np.exp(-delta / c_i) ax[idx].hist(p, bins=200, color=f'C{idx}', label=f'$c={c_i}$') ax[idx].set_xlabel(r'Acceptance probability $\exp( -\Delta f / c)$') ax[idx].set_ylabel(r'Num. transitions') ax[idx].legend() plt.tight_layout() fig.savefig('figures/fig33.pdf', dpi=200) # plt.show()
[ "matplotlib.use", "zoo.Zoo", "numpy.exp", "numpy.array", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.subplots", "sa._gen_point_a" ]
[((72, 93), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (86, 93), False, 'import matplotlib\n'), ((247, 267), 'numpy.array', 'np.array', (['obj.domain'], {}), '(obj.domain)\n', (255, 267), True, 'import numpy as np\n'), ((394, 433), 'numpy.array', 'np.array', (['[d for d in delta if d > 0.0]'], {}), '([d for d in delta if d > 0.0])\n', (402, 433), True, 'import numpy as np\n'), ((495, 513), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {}), '(3, 1)\n', (507, 513), True, 'import matplotlib.pyplot as plt\n'), ((781, 799), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (797, 799), True, 'import matplotlib.pyplot as plt\n'), ((302, 319), 'sa._gen_point_a', '_gen_point_a', (['dom'], {}), '(dom)\n', (314, 319), False, 'from sa import _gen_point_a\n'), ((554, 574), 'numpy.exp', 'np.exp', (['(-delta / c_i)'], {}), '(-delta / c_i)\n', (560, 574), True, 'import numpy as np\n'), ((201, 206), 'zoo.Zoo', 'Zoo', ([], {}), '()\n', (204, 206), False, 'from zoo import Zoo\n')]